Skip to content

DataBuffer & DataReader

David edited this page Oct 5, 2018 · 2 revisions

DataBuffer & DataReader

These classes assist in the handling of binary data.

Unless explicitly stated, values are unsigned and in little-endian byte order.

DataBuffer

  • DataBuffer([data]) - creates a new buffer with (optional) initial data.
    • insert_raw(data) - inserts raw binary data into the buffer.
      • 'data' can be a bytes object, string, or a DataBuffer/DataReader object
    • insert_byte(b) - inserts a single unsigned byte into the buffer
    • insert_word(w) - inserts a 16-bit number into the buffer
    • insert_dword(d) - inserts a 32-bit number into the buffer
      • 'd' can be either an integer or a 4-length string. If a string is given it will be reversed and inserted raw into the buffer.
    • insert_long(q) - inserts a 64-bit number (or filetime) into the buffer
    • insert_string(s, [encoding]) - inserts a null-terminated string into the buffer with the specified encoding (default: utf-8)
    • insert_format(fmt, *args) - inserts data into the buffer according to struct.pack
    • clear() - clears all data from the buffer

DataReader

  • DataReader(data) - creates a buffer with the initial data for reading
    • get_raw([length]) - returns 'length' bytes from the buffer.
      • If no length is given all bytes from the current position to the end will be returned.
    • get_byte() - returns a single unsigned byte from the buffer
    • get_word() - returns a 16-bit number from the buffer
    • get_dword([as_string]) - returns a 32-bit number from the buffer.
      • If as_string is set to True then it will be returned as a DWORD-string.
    • get_long() - returns a 64-bit number from the buffer
    • get_string([encoding], [terminator]) - returns a null-terminated string from the buffer with the specified encoding.
      • If 'terminator' is specified then the it will search for a string terminated with that binary value.
    • get_format(fmt) - returns data from the buffer according to struct.unpack
    • peek([size], [position], [format]) - returns a value from the buffer without advancing the read position.
      • If none of the optional arguments are specified, a single byte will be returned.
    • eop() - returns TRUE if the read position is at the end of the buffer

format_buffer

  • format_buffer(data) - returns a packet-log style printout of the given data
    • Treating either the DataBuffer or DataReader as a string will result in this output. eg: print(DataBuffer(b'\x01'))

Implementation: https://github.com/Davnit/bncs.py/blob/master/bncs/common/buffer.py