binobj.helpers module

Various helper functions for stream I/O.

iter_bytes(stream: BinaryIO, max_bytes: int | None = None) Iterator[bytes]

Wrap a stream in an iterator that yields individual bytes, not lines.

Parameters:
  • stream – A stream opened in binary mode.

  • max_bytes (int) – The maximum number of bytes to read.

New in version 0.2.1.

peek_bytes(stream: BinaryIO, count: int, short_read_okay: bool = True) bytes

Read the next count bytes in the stream without moving the stream pointer.

New in version 0.9.0.

read_int(stream: BinaryIO, n_bytes: int, signed: bool = True, endian: typing_extensions.Literal[little, big] | None = None) int

Read an integer from the given byte stream.

Parameters:
  • stream (BinaryIO) – The stream to read from.

  • n_bytes (int) – The number of bytes to read for this integer.

  • signed (bool) – If True, interpret this integer as a two’s-complement signed integer. Otherwise, interpret it as an unsigned integer.

  • endian (str) – The endianness of the integer, either big or little. If not given, will default to the system’s native byte order as given by sys.byteorder.

Returns:

The integer loaded from the byte stream.

Return type:

int

Raises:

UnexpectedEOFError – The end of the stream was hit before n_bytes bytes were read.

write_int(stream: BinaryIO, value: int, n_bytes: int, signed: bool = True, endian: typing_extensions.Literal[little, big] | None = None) None

Write an integer to a stream.

Parameters:
  • stream (BinaryIO) – The stream to write the integer to.

  • value (int) – The integer to dump into the stream.

  • n_bytes (int) – The number of bytes the integer should take up. Exactly this many bytes will be written into the stream, so ensure that there’s enough bits to represent value.

  • signed (bool) – If True, write this integer in two’s-complement format. Otherwise, write it as an unsigned integer. A negative value will trigger an OverflowError if this is False.

  • endian (str) – The endianness to use when writing the integer, either “big” or “little”. If not given, will default to the system’s native byte order as given by sys.byteorder.

Raises:

OverflowErrorvalue can’t be represented only by n_bytes bytes. The number is too big, or it’s negative and signed is False.