STL without memcpy

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Esam
    New Member
    • Sep 2006
    • 2

    STL without memcpy

    I wanted to write a quick test program to send a message with variable length fields in the message. Typically I would use some sort of dynamically allocated c-like buffer and just memcpy the elements of different sized into their proper positions. For example:

    Code:
    char Buffer[8192];
    unsigned short count = 512;
    char temp_char = 3, temp_char2 = 255;
    
    *(unsigned short*)(&Buffer[0]) = 1;  
    *(unsigned short*)(&Buffer[2]) = count;
    Buffer[4] = temp_char;
    Buffer[5] = temp_char2;
    I would like to use the STL to do this a little more elegantly and c++-ish, but I don't know how to go about doing it the best way. I could do something like this:
    Code:
    deque<char> Buffer(8192);
    deque<char>::iterator buff_iter = Buffer.begin();
    unsigned short count = 512;
    char temp_char = 3, temp_char2 = 255;
    
    *buff_iter = 0; // High Byte
    buff_iter++;
    *buff_iter = 1; // Low Byte
    buff_iter++;
    
    *buff_iter = ((count >> 8) & 0xFF); // High Byte
    buff_iter++;
    *buff_iter = (count & 0xFF); // Low Byte
    buff_iter++;
    
    *buff_iter = temp_char;
    buff_iter++;
    *buff_iter = temp_char2;
    However, that seems worse to me. Could someone give me some ideas on a good way to handle packing data words of different sizes into an STL container?

    Thanks!

    Btw... I didn't actually attempt to compile this so it may not be 100% syntactically correct.
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Rather than just instanciating a variable of type deque(char) you could create a subclass of that type and add you own methods to insert data

    Code:
    class message : public deque<char>
    {
    public:
        message();
        message(int defaultBufferSize);
        ~message();
    
        AddChar(unsigned char data);
        AddShort(unsigned short data);
        AddString(string data);
    
        // etc
    }
    Then your main cod becomes

    Code:
    message Buffer(8192);
    unsigned short count = 512;
    char temp_char = 3, temp_char2 = 255;
    
    Buffer.AddShort(1);
    Buffer.AddShort(count);
    Buffer.AddChar(temp_char);
    Buffer.AddChar(temp_char2);
    If you wished rather than add methods you could override the += operator giving

    Code:
    message Buffer(8192);
    unsigned short count = 512;
    char temp_char = 3, temp_char2 = 255;
    
    Buffer += (unsigned short)1;
    Buffer += count;
    Buffer += temp_char;
    Buffer += temp_char2;
    I have left you to actually implement the functions/operators.

    Comment

    • Esam
      New Member
      • Sep 2006
      • 2

      #3
      Hey that's a good idea, thanks!

      Comment

      Working...