3.9.1. Integer Atoms#
The CpIntAtomObject
is a specialized implementation for handling integers,
providing efficient mechanisms to pack and unpack sized integers. Unlike its Python
counterpart (FormatField
), this C-based class focuses solely on integer operations.
This implementation utilizes int.from_bytes
and int.to_bytes
. Direct C
calls are optimized, reducing runtime overhead compared to Python.
-
type CpIntAtomObject#
A fundamental class for managing fixed-size integers. Further recommendations for optimal use are detailed below.
-
PyObject *m_byte_count#
Represents the number of bytes in the integer. This can be accessed in Python using the attribute
nbytes
.
-
int _m_signed#
Indicates whether the integer is signed. A value of
1
means signed, and0
means unsigned.
-
int _m_little_endian#
Indicates the endianness of the integer. A value of
1
signifies little-endian, while0
signifies big-endian.
-
PyObject *m_byte_count#
-
int CpIntAtom_Pack(CpIntAtomObject *self, PyObject *value, CpLayerObject *layer)#
Packs the given value into the given layer. Returns
-1
if an error occurs.
-
PyObject *CpIntAtom_Unpack(CpIntAtomObject *self, CpLayerObject *layer)#
- Return value: New reference.
Unpacks the value from the given layer. Returns NULL if an error occurs.
-
int CpIntAtom_Check(PyObject *op)#
Checks if the given object is an
CpIntAtomObject
-
int CpIntAtom_CheckExact(PyObject *op)#
Checks if the given object is an instance of an
CpIntAtomObject
Runtime Performance
Measurements represent the accumulated runtime of one million calls to
unpack
or pack
using the corresponding implementation
in seconds.
Function |
Caterpillar [0] |
Caterpillar G [1] |
Caterpillar C [2] |
Construct [3] |
---|---|---|---|---|
|
4.002179 |
2.782663 |
0.815902 |
1.581962 |
|
3.866999 |
2.707753 |
0.926041 |
1.587046 |
The benchmark has been performed using the following code snippets:
1from caterpillar import _C, model, fields
2from construct import Int32sn
3
4# Caterpillar
5model.unpack(fields.Field(fields.int32), b"\x00\xFF\x00\xFF")
6
7# Caterpillar (Global)
8I32_G = fields.Field(fields.int32)
9model.unpack(I32_G, b"\x00\xFF\x00\xFF")
10
11# Caterpillar (C)
12_C.unpack(b"\x00\xFF\x00\xFF", _C.i32)
13
14# Construct
15Int32sn.parse(b"\x00\xFF\x00\xFF")