buffer - Memory buffer manager¶
Overview¶
firebird.base.buffer
¶
This module provides a MemoryBuffer class for managing raw memory buffers,
offering a convenient and consistent API for reading and writing various data types
(integers of different sizes, strings with different termination/prefixing styles, raw bytes).
It's particularly useful for tasks involving binary data serialization/deserialization,
such as implementing network protocols or handling custom file formats.
The underlying memory storage can be customized via a BufferFactory. Two factories
are provided:
BytesBufferFactory: Uses Python's built-inbytearray.CTypesBufferFactory: Usesctypes.create_string_bufferfor potentially different memory characteristics or C-level interoperability.
Example
from firebird.base.buffer import MemoryBuffer, ByteOrder
# Create a buffer (default uses bytearray)
buf = MemoryBuffer(10) # Initial size 10 bytes
# Write data
buf.write_short(258) # Write 2 bytes (0x0102 in little-endian)
buf.write_pascal_string("Hi") # Write 1 byte length (2) + "Hi"
buf.write(b'\x0A\x0B') # Write raw bytes
# Reset position to read
buf.pos = 0
# Read data
num = buf.read_short()
s = buf.read_pascal_string()
extra = buf.read(2)
print(f"Number: {num}") # Output: Number: 258
print(f"String: '{s}'") # Output: String: 'Hi'
print(f"Extra bytes: {extra}") # Output: Extra bytes: b'\n\x0b'
print(f"Final position: {buf.pos}") # Output: Final position: 7
print(f"Raw buffer: {buf.get_raw()}") # Output: Raw buffer: bytearray(b'\x02\x01\x02Hi\n\x0b\x00\x00\x00')
MemoryBuffer starts with a capacity and a position of zero. Writes advance pos;
set it back to zero before reading the data you wrote. Number reads and writes use
the selected byte order:
from firebird.base.buffer import MemoryBuffer
from firebird.base.types import ByteOrder
buffer = MemoryBuffer(4, byteorder=ByteOrder.BIG)
buffer.write_short(0x1234)
buffer.write(b"OK")
assert buffer.pos == 4
assert bytes(buffer.get_raw()) == b"\x12\x34OK"
buffer.pos = 0
assert buffer.read_short() == 0x1234
assert bytes(buffer.read(2)) == b"OK"
assert buffer.pos == 4
get_raw() returns the storage content as bytes or a bytearray regardless of the
chosen buffer factory. A buffer's capacity may exceed the amount of data written,
so use pos to track where the next read or write takes place.
MemoryBuffer¶
firebird.base.buffer.MemoryBuffer
¶
Generic memory buffer manager.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
init
|
int | bytes
|
Must be an integer which specifies the size of the array, or a |
required |
size
|
int | None
|
Size of the array. The argument value is used only when |
None
|
factory
|
type[BufferFactory]
|
Factory object used to create/resize the internal memory buffer. |
BytesBufferFactory
|
eof_marker
|
int | None
|
Value that indicates the end of data. Could be None. |
None
|
max_size
|
int | Sentinel
|
If specified, the buffer couldn't grow beyond specified number of bytes. |
UNLIMITED
|
byteorder
|
ByteOrder
|
The byte order used to read/write numbers. |
LITTLE
|
- Modules types - Common data types ByteOrder
Source code in firebird/base/buffer.py
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 | |
buffer_size: int
property
¶
Current allocated buffer size in bytes.
byteorder: ByteOrder
instance-attribute
¶
The byte order used to read/write numbers [default: LITTLE].
eof_marker: int
instance-attribute
¶
Value that indicates the end of data. Could be None.
factory: BufferFactory
instance-attribute
¶
Buffer factory instance used by manager [default: BytesBufferFactory].
last_data: int
property
¶
Index of the last non-zero byte in the buffer (-1 if all zeros).
max_size: int | Sentinel
instance-attribute
¶
The buffer couldn't grow beyond specified number of bytes [default: UNLIMITED].
pos: int
instance-attribute
¶
Current position in buffer, i.e. the next read/writen byte would be at this position.
raw: bytearray
instance-attribute
¶
The memory buffer. The actual data type of buffer depends on buffer factory,
but it must provide direct acces to cells, slices and length like bytearray.
clear() -> None
¶
get_raw() -> bytes | bytearray
¶
Return the underlying buffer's content as bytes or bytearray.
Use this method for generic access to the raw buffer content instead of
accessing the raw attribute directly, as the type of raw can vary
depending on the buffer factory used.
Returns:
| Type | Description |
|---|---|
bytes | bytearray
|
The raw content of the buffer. |
Source code in firebird/base/buffer.py
is_eof() -> bool
¶
Check if the current position is at or past the end of data.
End of data is defined as being beyond the buffer's current length,
or positioned exactly on a byte matching self.eof_marker (if defined).
Returns:
| Type | Description |
|---|---|
bool
|
True if at end-of-data, False otherwise. |
Source code in firebird/base/buffer.py
read(size: int = -1) -> bytes
¶
Read specified number of bytes from current position, or all remaining data.
Advances the position by the number of bytes read.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size
|
int
|
Number of bytes to read. If negative, reads all data from the current position to the end of the buffer. |
-1
|
Returns: The bytes read.
Raises:
| Type | Description |
|---|---|
BufferError
|
If |
Source code in firebird/base/buffer.py
read_bigint(*, signed: bool = False) -> int
¶
read_byte(*, signed: bool = False) -> int
¶
read_bytes() -> bytes | bytearray
¶
Read content of binary cluster (2 bytes data length followed by data).
Returns:
| Type | Description |
|---|---|
bytes | bytearray
|
The bytes read. |
Raises:
| Type | Description |
|---|---|
BufferError
|
If the end of the buffer is reached before end of data. |
Source code in firebird/base/buffer.py
read_int(*, signed: bool = False) -> int
¶
read_number(size: int, *, signed: bool = False) -> int
¶
Read a number of size bytes from current position using self.byteorder.
Advances the position by size.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size
|
int
|
The number of bytes representing the number. |
required |
signed
|
bool
|
Whether to interpret the bytes as a signed integer. |
False
|
Returns:
| Type | Description |
|---|---|
int
|
The integer value read. |
Raises:
| Type | Description |
|---|---|
BufferError
|
When |
Source code in firebird/base/buffer.py
read_pascal_string(*, encoding: str = 'ascii', errors: str = 'strict') -> str
¶
Read Pascal string (1 byte length followed by string data).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
encoding
|
str
|
Encoding to use for decoding. |
'ascii'
|
errors
|
str
|
Decoding error handling scheme. |
'strict'
|
Returns:
| Type | Description |
|---|---|
str
|
The decoded string. |
Raises:
| Type | Description |
|---|---|
BufferError
|
If the end of the buffer is reached before end of string. |
UnicodeDecodeError
|
If the read bytes cannot be decoded using |
Source code in firebird/base/buffer.py
read_short(*, signed: bool = False) -> int
¶
read_sized_int(*, signed: bool = False) -> int
¶
read_sized_string(*, encoding: str = 'ascii', errors: str = 'strict') -> str
¶
Read sized string (2 byte length followed by data).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
encoding
|
str
|
Encoding to use for decoding. |
'ascii'
|
errors
|
str
|
Decoding error handling scheme. |
'strict'
|
Returns:
| Type | Description |
|---|---|
str
|
The decoded string. |
Raises:
| Type | Description |
|---|---|
BufferError
|
If the end of the buffer is reached before end of string. |
UnicodeDecodeError
|
If the read bytes cannot be decoded using |
Source code in firebird/base/buffer.py
read_string(*, encoding: str = 'ascii', errors: str = 'strict') -> str
¶
Read bytes until a null terminator (0x00) is found, decode, and return string.
Advances the position past the null terminator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
encoding
|
str
|
Encoding to use for decoding. |
'ascii'
|
errors
|
str
|
Decoding error handling scheme. |
'strict'
|
Returns:
| Type | Description |
|---|---|
str
|
The decoded string (excluding the null terminator). |
Raises:
| Type | Description |
|---|---|
BufferError
|
If the end of the buffer is reached before a null terminator. |
UnicodeDecodeError
|
If the read bytes cannot be decoded using |
Source code in firebird/base/buffer.py
resize(size: int) -> None
¶
Resize buffer to the specified length. Content is preserved up to the minimum of the old and new sizes. New space is uninitialized (depends on factory).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size
|
int
|
The new size in bytes. |
required |
Raises:
| Type | Description |
|---|---|
BufferError
|
On attempt to resize beyond |
Source code in firebird/base/buffer.py
write(data: bytes) -> None
¶
Write raw bytes at the current position and advance position.
Ensures buffer has enough space, resizing if necessary and allowed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
bytes
|
The bytes to write. |
required |
Raises:
| Type | Description |
|---|---|
BufferError
|
If resizing is needed but exceeds |
Source code in firebird/base/buffer.py
write_bigint(value: int) -> None
¶
Write 8 byte number (c_ulonglong).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
int
|
The integer value to write. |
required |
Raises:
| Type | Description |
|---|---|
BufferError
|
If resizing is needed but exceeds |
Source code in firebird/base/buffer.py
write_byte(byte: int) -> None
¶
write_int(value: int) -> None
¶
Write 4 byte number (c_uint).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
int
|
The integer value to write. |
required |
Raises:
| Type | Description |
|---|---|
BufferError
|
If resizing is needed but exceeds |
write_number(value: int, size: int, *, signed: bool = False) -> None
¶
Write number with specified size (in bytes).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
int
|
The integer value to write. |
required |
size
|
int
|
Value size in bytes. |
required |
signed
|
bool
|
Write as signed or unsigned integer. |
False
|
Raises:
| Type | Description |
|---|---|
BufferError
|
If resizing is needed but exceeds |
Source code in firebird/base/buffer.py
write_pascal_string(value: str, *, encoding: str = 'ascii', errors: str = 'strict') -> None
¶
Write Pascal string (2 byte length followed by data).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
The string to write. |
required |
encoding
|
str
|
Encoding to use. |
'ascii'
|
errors
|
str
|
Encoding error handling scheme. |
'strict'
|
Raises:
| Type | Description |
|---|---|
BufferError
|
If resizing is needed but exceeds |
Source code in firebird/base/buffer.py
write_short(value: int) -> None
¶
Write 2 byte number (c_ushort).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
int
|
The integer value to write. |
required |
Raises:
| Type | Description |
|---|---|
BufferError
|
If resizing is needed but exceeds |
Source code in firebird/base/buffer.py
write_sized_string(value: str, *, encoding: str = 'ascii', errors: str = 'strict') -> None
¶
Write sized string (2 byte length followed by data).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
The string to write. |
required |
encoding
|
str
|
Encoding to use. |
'ascii'
|
errors
|
str
|
Encoding error handling scheme. |
'strict'
|
Raises:
| Type | Description |
|---|---|
BufferError
|
If resizing is needed but exceeds |
Source code in firebird/base/buffer.py
write_string(value: str, *, encoding: str = 'ascii', errors: str = 'strict') -> None
¶
Encode string, write bytes followed by a null terminator (0x00).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
The string to write. |
required |
encoding
|
str
|
Encoding to use. |
'ascii'
|
errors
|
str
|
Encoding error handling scheme. |
'strict'
|
Raises:
| Type | Description |
|---|---|
BufferError
|
If resizing is needed but exceeds |
UnicodeEncodeError
|
If |
Source code in firebird/base/buffer.py
Buffer factories¶
firebird.base.buffer.BufferFactory
¶
Bases: Protocol
Protocol defining the interface for creating and managing memory buffers.
Allows MemoryBuffer to work with different underlying buffer types
(like bytearray or ctypes arrays).
Source code in firebird/base/buffer.py
clear(buffer: Any) -> None
¶
Fill the buffer entirely with null bytes (zeros).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
buffer
|
Any
|
A memory buffer previously created by this factory's |
required |
create(init_or_size: int | bytes, size: int | None = None) -> Any
¶
Create and return a mutable byte buffer object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
init_or_size
|
int | bytes
|
An integer specifying the buffer size, or a bytes object for initializing the buffer content. |
required |
size
|
int | None
|
Optional integer size, primarily used when |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The created mutable buffer object (e.g., bytearray or a ctypes array of characters). |
Source code in firebird/base/buffer.py
get_raw(buffer: Any) -> bytes | bytearray
¶
Return the buffer's content as a standard bytes or bytearray.
This method is necessary to provide a consistent way to access the raw
byte sequence, as the buffer object returned by create might be of a
different type (e.g., ctypes arrays have a raw attribute).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
buffer
|
Any
|
A memory buffer previously created by this factory's |
required |
Returns:
| Type | Description |
|---|---|
bytes | bytearray
|
The raw byte content of the buffer. |
Source code in firebird/base/buffer.py
firebird.base.buffer.BytesBufferFactory
¶
Buffer factory using Python's bytearray for storage.
Source code in firebird/base/buffer.py
clear(buffer: bytearray) -> None
¶
create(init_or_size: int | bytes, size: int | None = None) -> bytearray
¶
This function creates a mutable character buffer. The returned object is a bytearray.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
init_or_size
|
int | bytes
|
Must be an integer which specifies the size of the array, or a bytes object which will be used to initialize the array items. |
required |
size
|
int | None
|
Size of the array. |
None
|
Important
Although arguments are the same as for ctypes.create_string_buffer, the behavior is different when new buffer is initialized from bytes:
- If there are more bytes than specified
size, this function copies onlysizebytes into new buffer. The ctypes.create_string_buffer raises an excpetion. - Unlike ctypes.create_string_buffer when
sizeis NOT specified, the buffer is NOT made one item larger than its length so that the last element in the array is a NUL termination character.
Source code in firebird/base/buffer.py
firebird.base.buffer.CTypesBufferFactory
¶
Buffer factory using ctypes.create_string_buffer (array of c_char).
Source code in firebird/base/buffer.py
clear(buffer: bytearray, init: int = 0) -> None
¶
create(init_or_size: int | bytes, size: int | None = None) -> bytearray
¶
This function creates a ctypes mutable character buffer. The returned object is an array of ctypes.c_char.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
init_or_size
|
int | bytes
|
Must be an integer which specifies the size of the array, or a bytes object which will be used to initialize the array items. |
required |
size
|
int | None
|
Size of the array. |
None
|
Important
Although arguments are the same as for ctypes.create_string_buffer, the behavior is different when new buffer is initialized from bytes:
- If there are more bytes than specified
size, this function copies onlysizebytes into new buffer. The ctypes.create_string_buffer raises an excpetion. - Unlike ctypes.create_string_buffer when
sizeis NOT specified, the buffer is NOT made one item larger than its length so that the last element in the array is a NUL termination character.
Source code in firebird/base/buffer.py
Functions¶
firebird.base.buffer.safe_ord(byte: bytes | int) -> int
¶
Return the integer ordinal of a byte, or the integer itself.
Handles inputs that might already be integers (e.g., from iterating
over a bytes object) or single-character bytes objects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
byte
|
bytes | int
|
A single-character bytes object or an integer. |
required |
Returns:
| Type | Description |
|---|---|
int
|
The integer value. |