Help C++ - Reading and writing packets
#9
Sorry for the late reply, only now I noticed your post had another question in it.

The Buffer class can be pretty much substituted by a std::string - it has the append and erase operations, you just need to add a "read position" and possibly some helper functions to read individual data types. So something like this:
class Buffer
{
public:

  Buffer():
    mReadPos(0)
  {
  }

  void restartRead()
  {
    mReadPos = 0;
  }

  void append(const char * aData, size_t aSize)
  {
    mData.append(aData, aSize);
  }

  void erase(size_t aNumBytes)
  {
    mData.erase(0, aNumBytes);
    if (mReadPos > aNumBytes)
    {
      mReadPos -= aNumBytes;
    }
    else
    {
      mReadPos = 0;
    }
  }

  UInt8 readByte()
  {
    if (mReadPos + 1 >= mData.size())
    {
      // TODO: Not enough bytes in the buffer, throw exception?
    }
    return static_cast<UInt8>(mData[mReadPos++]);
  }

  UInt16 readShort()
  {
    if (mReadPos + 2 >= mData.size()
    {
      // TODO: Not enough bytes in the buffer, throw exception?
    }
    auto oldReadPos = mReadPos;
    mReadPos += 2;
    return static_cast<UInt16>((mData[oldReadPos] << 8) | mData[oldReadPos + 1];
  }
  ...

private:

  /** The bytes in the buffer, including those already read for the current packet. */
  std::string mData;

  /** The position in mData where the next Read operation will start. */
  size_t mReadPos;
}
Reply
Thanks given by: PCPlayerLV


Messages In This Thread
RE: Help C++ - Reading and writing packets - by xoft - 10-10-2019, 05:44 PM



Users browsing this thread: 2 Guest(s)