hbutils.binary.buffer

This module provides functionality for reading and writing fixed-size binary buffers.

It defines a custom binary I/O type that handles byte buffers of a specified size, with automatic padding when writing data shorter than the buffer size.

CBufferType

class hbutils.binary.buffer.CBufferType(size: int)[source]

A binary I/O type for handling fixed-size byte buffers.

This class provides methods to read and write byte data with a predetermined size. When writing data shorter than the buffer size, it automatically pads with null bytes.

__init__(size: int)[source]

Constructor of CBufferType.

Parameters:

size (int) – Size of the buffer in bytes.

read(file: BinaryIO) bytes[source]

Read bytes value from a binary file.

Parameters:

file (BinaryIO) – Binary file object to read from. io.BytesIO is supported as well.

Returns:

Bytes value read from the file with the specified buffer size.

Return type:

bytes

property size: int

Get the size of the buffer.

Returns:

Size of the buffer in bytes.

Return type:

int

write(file: BinaryIO, val: bytearray | bytes)[source]

Write bytes value to binary IO object.

If the length of the provided value is less than the buffer size, null bytes (\x00) will be appended to reach the specified size.

Parameters:
  • file (BinaryIO) – Binary file object to write to. io.BytesIO is supported as well.

  • val (Union[bytearray, bytes]) – Bytes value to write. Must be of type bytearray or bytes.

Raises:
  • TypeError – If val is not a bytearray or bytes object.

  • ValueError – If the length of val exceeds the buffer size.

c_buffer

hbutils.binary.buffer.c_buffer(size: int) CBufferType[source]

Create a buffer type for reading and writing bytes with a given size.

This function returns a CBufferType object that can be used to read and write fixed-size byte buffers. When writing, if the data is shorter than the specified size, it will be padded with null bytes.

Parameters:

size (int) – Size of the buffer in bytes.

Returns:

A CBufferType object configured with the specified size.

Return type:

CBufferType

Examples::
>>> import io
>>> from hbutils.binary import c_buffer
>>>
>>> # Reading example
>>> with io.BytesIO(b'\xde\xad\xbe\xef\x00\x12\x34\x56\x78\x00') as file:
...     print(c_buffer(1).read(file))
...     print(c_buffer(2).read(file))
...     print(c_buffer(3).read(file))
...     print(c_buffer(4).read(file))
b'\xde'
b'\xad\xbe'
b'\xef\x00\x12'
b'4Vx\x00'
>>> 
>>> # Writing example
>>> with io.BytesIO() as file:
...     c_buffer(1).write(file, b'\xde')
...     c_buffer(2).write(file, b'\xad\xbe')
...     c_buffer(3).write(file, b'\xef\x00\x12')
...     c_buffer(4).write(file, b'4Vx')  # length is 3, will be padded to 4
...     print(file.getvalue())
b'\xde\xad\xbe\xef\x00\x124Vx\x00'