How to add up BytesBuffer (haxe.io.BytesBuffer)

I would like to add two haxe.io.BytesBuffer:
buf1 should be added to buf2.
My code:

var buf1 = new haxe.io.BytesBuffer();
var buf2 = new haxe.io.BytesBuffer();
buf2.addBytes( buf1.getBytes(), buf2.length, buf1.length );

In words:

  • Add buf1 to buf2 at the end of buf2 ( “buf2.length” ).
  • Append “buf1.length” bytes to buf2.

However I get a ValueException instead.


Why adding buffers?
This should then allow me to add up data, even by just recalling the code:

var buf1 = new haxe.io.BytesBuffer();
var buf2 = new haxe.io.BytesBuffer();
buf2.addBytes( buf1.getBytes(), buf2.length, buf1.length );
buf2.addBytes( buf1.getBytes(), buf2.length, buf1.length );
buf2.addBytes( buf1.getBytes(), buf2.length, buf1.length );
buf2.addBytes( buf1.getBytes(), buf2.length, buf1.length );
...

I’m having a hard time finding more about dealing with byte data in general and the docs seem short on that. I appreciate if you have any suggestions for reading/articles. Thank you! :slight_smile:

This? Try Haxe ! ?

EDIT: if the idea is to read the string out of the buffer later based on the length, then you’ll need the length to be first (not last) in order to know how many bytes to read out:

import haxe.io.BytesBuffer;
import haxe.io.BytesInput;

class Test {
  static function main() {
    var buf1 = new BytesBuffer();
    buf1.addString("this is buffer1");
    
    var buf2 = new BytesBuffer();
    buf2.addInt32(buf1.length);
    buf2.add(buf1.getBytes());
    
    trace(buf2.getBytes().toString());
    trace(buf2.getBytes().toHex());
    
    var bi = new BytesInput(buf2.getBytes());
    var len = bi.readInt32();
    trace(len);
    var data = bi.read(len);
    trace(data.toString());
  }
}
2 Likes

Hey, Ian! Thank you a lot for this interesting sample!
It took me quite a while to get Why would you write a length value in your buffer? until I realised this allows your bi BytesInput to regain strings/messages within the buffer later on :smiley: (when it gets longer and there are multiple data types “lumped” together within the buffer).

1 Like