2.1.1.2Class ByteBuf

Flexible memory buffer optimized for binary mangling

Class ByteBuf( [sizeOrObject],[extrasizeOrAdopt] )
sizeOrObject
extrasizeOrAdopt

A ByteBuf is a growable memory buffer with methods to read and write primitive datatypes and strings. It supports streaming data in and out as well as random access.

For convenience, it can be converted to a MemBuf, at your option with zero cost.

Endianness can optionally be changed, by default it stores data in native endian of the host machine.

The constructor takes the following parameters:

Anything else passed into the constructor will raise a ParamError. Note that the constructor does not set/copy read or write positions or anything else.

Example code for basic usage:


    bb = ByteBuf(30)                    // create a ByteBuf with an initial capacity of 30 bytes
    bb.setEndian(ByteBuf.LITTLE_ENDIAN) // we store everything as little endian
    bb.w16(0, 42, -16)                  // append 2 uint16 and 1 int16
    bb.wf(0.5)                          // append a float
    bb.write("Hello world")             // append a string, char size 1
    // .. write more data ..
    // now final buffer size is known 
    bb.setEndian(ByteBuf.BIG_ENDIAN)    // the next written bytes are stored in network byte order
    bb.wpos(0).w16(bb.size())           // seek back to start and put total size there, in big endian
    mb = bb.toMemBuf()
    // -- encrypt everything except the first 2 bytes and send via network --
    
    ....
    // -- receive membuf on the other side --
    bb = ByteBuf(mb, true)              // wrap a ByteBuf around the MemBuf, without copying occupied memory
    bb.setEndian(ByteBuf.BIG_ENDIAN)    // read in network byte order
    size = bb.r16()                     // read total size
    bb.setEndian(ByteBuf.LITTLE_ENDIAN) // rest of the buffer is in little endian
    // -- decrypt remaining (size - 2) bytes --
    a = bb.r16()                        // = 42
    b = bb.r16(true)                    // (this is a signed short) = -16
    f = bb.rf()                         // = ~ 0.5 (maybe slight precision loss)
    s = bb.readString()                 // string is null terminated, and char size 1  
    // .. read remaining data ..
Properties
BIG_ENDIAN
LITTLE_ENDIAN
NATIVE_ENDIAN
REVERSE_ENDIAN

Properties

BIG_ENDIAN

LITTLE_ENDIAN

NATIVE_ENDIAN

REVERSE_ENDIAN

Made with http://www.falconpl.org