Jump to content

[ByteBuffer] read<T>() function


Guest Toinan67
 Share

Recommended Posts

Hi !

It's been a very long time since i posted, i'm pleased to be back :)

I have a question about the ByteBuffer class, which is the parent class of WorldPacket.

If i understood correctly, when you do this :

uint32 value;

packet >> value;

You get into that function :

       ByteBuffer &operator>>(uint32 &value)
       {
           value = read<uint32>();
           return *this;
       }

Which ultimately calls that function :

template <typename T> T read(size_t pos) const
       {
           if(pos + sizeof(T) > size())
               throw ByteBufferException(false, pos, sizeof(T), size());
           T val = *((T const*)&_storage[pos]);
           EndianConvert(val);
           return val;
       }

_storage is a vector<uint8>.

I have a problem with :

T val = *((T const*)&_storage[pos]);

(sorry about the code display, it seems like there is some troubles)

So basically we're storing a uint32 in a uint8 ?!

Then why do we use uint32? Why not using uint8 everywhere?

And why is this line so complicated? Why not :

T val = _storage[pos];

I hope i've been clear :)

Thank you!

Link to comment
Share on other sites

_storage is byte "array" by default. such arrays in memory are located as continuous set of bytes. _storage as value is a pointer to it's first element

if uint8 storage[n]; then storage == &storage[0] which means that storage val points to the head of that array

when accessing _storage[pos] you access *(_storage + pos), which means byte number 'pos' since address of _storage.

by casting *((T const*)&_storage[pos] you say that &_storage[pos] is pointer not to uint8 but to value type T*, and it would 'grab' nearest bytes depending on T size

Link to comment
Share on other sites

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue. Privacy Policy Terms of Use