Debian Codegraph @

docs/userguide.rst

raw
1 User Guide
2 ==========
3
4 Core concepts
5 -------------
6
7 *bpack* is a lightweight Python package intended to help users to
8
9 * describe binary data structures
10 * encode/decode binary data to/from Python object
11
12
13 Descriptors
14 ~~~~~~~~~~~
15
16 The user can define binary data structure in a declarative way, as follows:
17
18 .. testcode::
19
20 import bpack
21
22 @bpack.descriptor
23 class BinaryRecord:
24 field_1: float = bpack.field(size=8)
25 field_2: int = bpack.field(size=4, signed=True)
26
27 Key concepts for definition of binary data structures are
28
29 * the declaration of the data structure by means of the
30 :func:`bpack.descriptors.descriptor` class decorator.
31 It allows to specify the main properties of the data structure.
32 * the specification of the characteristics of each field, mainly the data
33 type, the size and (optionally) the offset with respect to the beginning
34 of the record. This can be done using the :func:`bpack.descriptors.field`
35 factory function.
36
37 In the above example the ``BinaryRecord`` has been defined to have two fields:
38
39 :field_1:
40 a double precision floating point (8 bytes)
41 :field_2:
42 a 32bit signed integer (4 bytes)
43
44 ``size`` is expressed in bytes in this case.
45
46 The offset of the fields have not been explicitly specified so they are
47 computed automatically.
48
49 In the example ``field_1`` has ``offset=0``, while ``field_2`` has
50 ``offset=8`` i.e. data belonging to ``field_2`` immediately follow the ones
51 of the previous field.
52
53 The design is strongly inspired to the one of the :mod:`dataclasses` package
54 of the Python standard library.
55
56
57 Codecs
58 ~~~~~~
59
60 Once a binary structure is defined, the *bpack* package allows to
61 automatically generate :class:`Codec` objects that are able
62 to convert binary data into a Python objects and vice versa:
63
64 .. testcode::
65
66 import bpack.st
67
68 binary_data = b"\x18-DT\xfb!\t@\x15\xcd[\x07"
69
70 codec = bpack.st.Codec(BinaryRecord)
71 record = codec.decode(binary_data)
72
73 assert record.field_1 == 3.141592653589793
74 assert record.field_2 == 123456789
75
76 print(record)
77
78 .. testoutput::
79
80 BinaryRecord(field_1=3.141592653589793, field_2=123456789)
81
82 .. testcode::
83
84 encoded_data = codec.encode(record)
85 assert binary_data == encoded_data
86
87 print("binary_data: ", binary_data)
88 print("encoded_data:", encoded_data)
89
90 .. testoutput::
91
92 binary_data: b'\x18-DT\xfb!\t@\x15\xcd[\x07'
93 encoded_data: b'\x18-DT\xfb!\t@\x15\xcd[\x07'
94
95 In the example above it has been used the :class:`bpack.st.Codec` class
96 from the :mod:`bpack.st` module.
97
98 Please note that the decoder class (:class:`bpack.st.Codec`)
99
100 * takes in input the *descriptor* (i.e. the type) of the binary data
101 structure, and
102 * return a *codec* object which is capable to encode/decode only binary data
103 organized according to the *descriptor* received at the instantiation
104 time. If one need to encode/decode a differed data structure than it is
105 necessary to instantiate a different codec.
106
107 The :mod:`bpack.st` module used in the example is just one of the, so called,
108 *backends* available in *bpack*.
109
110 See the Backends_ section below for more details.
111
112
113 Binary data structures declaration
114 ----------------------------------
115
116 As anticipated above the declaration of a binary data structure and
117 its main properties is done using the :func:`bpack.descriptors.descriptor`
118 class decorator.
119
120
121 Bit vs byte structures
122 ~~~~~~~~~~~~~~~~~~~~~~
123
124 One of the properties that the :func:`bpack.descriptors.descriptor`
125 class decorator allows to specify is *baseunits*.
126 It allows to specify the elementary units used to describe the binary
127 structure itself.
128 A structure can be described in terms of *bytes* or in terms of *bits*,
129 i.e. if field size and offsets have to be intended as number of bytes of
130 as number of bits.
131
132 This is an important distinction for two reasons:
133
134 * it is fundamental for *decoders* (see below) to know much data have to be
135 converted and where this data are exactly located in a string of bytes
136 * not all *backends* are capable of decoding both kinds of structures
137
138 .. note::
139
140 Currently available *backends* do not support nested data structures
141 (see `Record nesting`_) described using different *baseunits*
142 (see :ref:`Limitations`).
143
144 *Baseunits* can be specified as follows:
145
146 .. testcode::
147
148 @bpack.descriptor(baseunits=bpack.EBaseUnits.BITS)
149 class BitRecord:
150 field_1: bool = bpack.field(size=1)
151 field_2: int = bpack.field(size=3)
152 field_3: int = bpack.field(size=4)
153
154
155 The ``baseunits`` parameter has been specified as a parameter of the
156 :func:`bpack.descriptors.descriptor` class decorator and its possible values
157 are enumerated by the :class:`bpack.enums.EBaseUnits` :class:`enum.Enum`:
158
159 * :data:`bpack.enums.EBaseUnits.BITS`, or
160 * :data:`bpack.enums.EBaseUnits.BYTES`
161
162 If the ``baseunits`` parameter is not specified than it is assumed to be
163 equal to :data:`bpack.enums.EBaseUnits.BYTES` by default.
164
165 Please note that the entire data structure of the above example is only
166 8 bits (1 byte) large.
167
168 .. note::
169
170 Please note that *baseunits* and many of the function and method parameters
171 whose valued is supposed to be an :class:`enum.Enum` can also accept a
172 string value.
173 E.g. the above example can also be written as follows:
174
175 .. testcode::
176
177 @bpack.descriptor(baseunits="bits")
178 class BitRecord:
179 field_1: bool = bpack.field(size=1)
180 field_2: int = bpack.field(size=3)
181 field_3: int = bpack.field(size=4)
182
183 Please refer to the specific enum documentation (in this case
184 :class:`bpack.enums.EBaseUnits`) to know which are string values
185 corresponding to the desired enumerated value.
186
187
188 Specifying bit/byte order
189 ~~~~~~~~~~~~~~~~~~~~~~~~~
190
191 Other important parameters for the :func:`bpack.descriptors.descriptor`
192 class decorator are:
193
194 :byteorder:
195 whose possible values are described by :class:`bpack.enums.EByteOrder`.
196 By the fault the native byte order is assumed.
197 :bitorder:
198 whose possible values are described by :class:`bpack.enums.EBitOrder`.
199 The *bitorder* parameter shall always be set to ``None`` the if
200 *baseunits* value is :data:`bpack.enums.EBaseUnits.BYTES`.
201
202 Both this parameters describe the internal organization of binary data
203 of each field.
204
205
206 Descriptor size
207 ~~~~~~~~~~~~~~~
208
209 The :func:`bpack.descriptors.descriptor` class decorator also allows to
210 specify *explicitly* the overall size of the binary data structure:
211
212 .. testcode::
213
214 @bpack.descriptor(baseunits="bits", size=8)
215 class BinaryRecord:
216 field_1: bool = bpack.field(size=1)
217 field_2: int = bpack.field(size=3)
218
219 In this case the the overall size of ``BitRecord`` is 8 bits (1 bytes)
220
221 .. doctest::
222
223 >>> bpack.calcsize(BinaryRecord)
224 8
225
226 even if the sum of sizes of all fields is only 4 bits.
227
228 Usually explicitly specifying the *size* of a binary data structure is not
229 necessary because the *bpack* is able to compute it automatically by looking
230 at the size of fields.
231
232 In some cases, anyway, it can be useful to specify it, e.g. when one want to
233 use a descriptor like the one defined in the above example as field of
234 a larger descriptor (see `Record nesting`_).
235 In this case it is important tho know the correct size of each field in
236 order to be able to automatically compute the *offset* of the following
237 ones.
238
239
240 Fields specification
241 --------------------
242
243 As anticipated in the previous section there are three main elements that
244 the *bpack* package need to know about fields in order to have a complete
245 description of a binary data structure:
246
247 * the field data **type**,
248 * the field **size** (expressed in *baseunits*,
249 see `Bit vs byte structures`_), and
250 * the field **offset** with respect to the beginning of the binary data
251 structure (also in this case expressed in *baseunits*,
252 see `Bit vs byte structures`_)
253
254 .. testcode::
255
256 @bpack.descriptor
257 class BinaryRecord:
258 field: int = bpack.field(size=4, offset=0)
259
260 Please note, anyway, that in some case it is possible to infer some of the
261 above information from the context so it is not always necessary to specify
262 all of them explicitly. More details will be provided in the following.
263
264 As shown in the example above the main way to specify a field descriptor is
265 to use the :func:`bpack.descriptors.field` factory function together with
266 Python type annotations to specify the data type.
267
268
269 Type
270 ~~~~
271
272 The data type of a field is the only parameter that is always mandatory,
273 and also it is the only parameter that is not specified by means of the
274 :func:`bpack.descriptors.field` factory function.
275 Rather it is specified using the standard Python syntax for type annotations.
276
277 Currently supported data types are:
278
279 :basic types:
280 basic Python types like ``bool``, ``int``, ``float``, ``bytes``, ``str``
281 (``complex`` is not supported currently)
282 :enums:
283 enumeration types defined using the :mod:`enum` module of the standard
284 Python library.
285 Please refer to the `Enumeration fields`_ section for more details about
286 features and limitations
287 :sequences:
288 used to define fields containing a sequence of homogeneous values
289 (i.e. values having the same data type). A *sequence* data type in *bpack*
290 can be defined using the standard type annotations classes like
291 :class:`typing.Sequence` or :class:`typing.List`, or directly `list[...]`.
292 Please refer to the `Sequence fields`_ section for more details about
293 features and limitations
294 :descriptors:
295 i.e. any binary data structure defined using the
296 :func:`bpack.descriptors.descriptor` class decorator
297 (see also `Record nesting`_)
298 :type annotations:
299 annotated data types defined by means of the :class:`bpack.typing.T`
300 type annotation. Please refer to the `Special type annotations`_ section
301 for a more detailed description
302
303 .. note::
304
305 The ``str`` type in Python is used to represent unicode strings.
306 The conversion of this kind of strings from/to binary format requires
307 some form of decoding/encoding.
308 *Bpack* codecs (see `Data codecs`_) convert ``str`` data from/to
309 ``bytes`` strings using the "UTF-8" encoding.
310
311 Please note that the *size* of a ``str`` field still describes the
312 number of bits/bytes in its binary representation, not the length
313 of the string (which in principle could require a number of bytes
314 larger that the number of characters).
315
316
317 Size
318 ~~~~
319
320 The field *size* is specified as a positive integer in *baseunits*
321 (see the `Bit vs byte structures`_ section).
322
323 It is a fundamental information and it must be always specified by means
324 of the :func:`bpack.descriptors.field` factory function unless it is
325 absolutely clear and unambiguous how to determine the fields size from
326 the data type.
327
328 This is only possible in the following cases:
329
330 * the data type is ``bool`` in which case the size is assumed to be ``1``
331 (at the moment no other basic type has a default size associated)
332 * the data type is a record descriptor, in which case the field size is
333 computed as follows:
334
335 .. testcode::
336
337 bpack.calcsize(BinaryRecord, units=bpack.baseunits(BinaryRecord))
338
339 * the data type is specified using special type annotations also including
340 size information:
341
342 .. testcode::
343
344 from bpack import T
345
346 @bpack.descriptor
347 class BinaryRecord:
348 field: T["u3"]
349
350 The ``T["u3"]`` type annotation specifier defines an unsigned integer type
351 (``u``) having size 3 (for the specific example this means 3 bytes).
352 Please refer to the `Special type annotations`_ section for more details.
353
354 Please note that the size of the field must not necessarily correspond to
355 the size of one of the data types supported by the platform.
356 In the example above it has been specified a type ``T["u3"]`` which
357 corresponds to a 24 bits unsigned integer. It is represented using a standard
358 Python ``int`` in the Python code but the binary representation will always
359 take only 3 bytes.
360
361
362 Offset
363 ~~~~~~
364
365 The field *offset* is specified as a not-negative integer in *baseunits*
366 (see the `Bit vs byte structures`_ section), and it represent the amount
367 of *baseunits* from the beginning of the record to the beginning of the field.
368
369 It is a fundamental information and it can be specified by means of the
370 :func:`bpack.descriptors.field` factory function.
371
372 The *bpack* package, anyway, implements a mechanism to automatically compute
373 the field offset exploiting information of the other fields in the record.
374 For this reason it is necessary to specify the field *offset* explicitly only
375 in very specific cases.
376
377 For example the *verbose* definition of a record with 5 integer fields
378 looks like the following:
379
380 .. testcode::
381
382 @bpack.descriptor
383 class BinaryRecord:
384 field_1: int = bpack.field(size=4, offset=0)
385 field_2: int = bpack.field(size=4, offset=4)
386 field_3: int = bpack.field(size=4, offset=8)
387 field_4: int = bpack.field(size=4, offset=12)
388 field_5: int = bpack.field(size=4, offset=16)
389
390 If not specified, the offset of the first field is assumed to be ``0``,
391 and the offset of the following fields is assumed to be equal to the
392 offset of the previous field plus the size of the previous field itself::
393
394 field[n].offset = field[n - 1].offset + field[n - 1].size
395
396 In short the automatic offset computation works assuming that all fields
397 are stored contiguously and without holes.
398
399 .. testcode::
400
401 @bpack.descriptor
402 class BinaryRecord:
403 field_1: int = bpack.field(size=4) # offset = 0 first field
404 field_2: int = bpack.field(size=4) # offset = 4
405 # field_1.offset + field_1.size
406 field_3: int = bpack.field(size=4) # offset = 8
407 # field_2.offset + field_2.size
408 field_4: int = bpack.field(size=4) # offset = 12
409 # field_3.offset + field_3.size
410 field_5: int = bpack.field(size=4) # offset = 16
411 # field_4.offset + field_4.size
412
413 Now suppose that the user is not interested in the field n. 2 and wants to
414 remove it from the descriptor. This creates a *gap* in the binary data
415 which makes not possible to exploit the automatic offset computation
416 mechanism:
417
418 .. testcode::
419
420 @bpack.descriptor
421 class BinaryRecord:
422 field_1: int = bpack.field(size=4) # offset = 0 first field
423 # field_2: int = bpack.field(size=4)
424 field_3: int = bpack.field(size=4) # offset = 4 != 8 NOT CORRECT
425 field_4: int = bpack.field(size=4) # offset = 8 != 12 NOT CORRECT
426 field_5: int = bpack.field(size=4) # offset = 12 != 16 NOT CORRECT
427
428 The automatic computation of the offset fails, in this case, because of the
429 missing information about ``field_2``.
430 Indeed, since ``field_2`` has not been specified, for the computation of
431 the offset of ``field_3`` *bpack* assumes that the previous field is
432 ``field_1`` and performs the computation accordingly::
433
434 field_3.offest = fielf_1.offset + field_i.size == 4 != 8 # INCORRECT
435
436 The incorrect offset of ``field_3`` causes the incorrect computation of the
437 offset all the fields that follow.
438
439 One option to recover the correct behavior (without falling back to the
440 *verbose* description shown at the beginning of the section) is to specify
441 explicitly **only** the offset of the first field after the gap:
442
443 .. testcode::
444
445 @bpack.descriptor
446 class BinaryRecord:
447 field_1: int = bpack.field(size=4) # offset = 0 first field
448 # field_2: int = bpack.field(size=4)
449 field_3: int = bpack.field(size=4, offset=8)
450 field_4: int = bpack.field(size=4) # offset = 12
451 field_5: int = bpack.field(size=4) # offset = 16
452
453 In this way the correct offset can be computed automatically for all fields
454 but the one(s) immediately following a *gap* in the data descriptor.
455
456
457 Signed integer types
458 ~~~~~~~~~~~~~~~~~~~~
459
460 Only for integer types, it is possible to specify if the integer value is
461 *signed* or not.
462 Although this distinction is not relevant in the Python code, it is necessary
463 to have this information when data have to be stored in binary form.
464
465 .. testcode::
466
467 @bpack.descriptor
468 class BinaryRecord:
469 field: int = bpack.field(size=4, offset=0, signed=True)
470
471 If *signed* is not specified for a field having an integer type, then it
472 is assumed to be ``False`` (*unsigned*).
473
474 The *signed* parameter is ignored if the data type is not ``int``.
475
476
477 Default values
478 ~~~~~~~~~~~~~~
479
480 The :func:`bpack.descriptors.field` factory function also allows to specify
481 default values using the ``default`` parameter:
482
483 .. testcode::
484
485 @bpack.descriptor
486 class BinaryRecord:
487 field: int = bpack.field(size=4, default=0)
488
489 This allows to instantiate the record without specifying the value of each
490 field:
491
492 .. doctest::
493
494 >>> BinaryRecord()
495 BinaryRecord(field=0)
496
497 In cases in which the :func:`bpack.descriptors.field` factory function
498 is not used for field definition, the default value can be specified by
499 direct assignment:
500
501 .. testcode::
502
503 @bpack.descriptor
504 class BinaryRecord:
505 field_1: bool = False
506 field_2: bpack.T["i4"] = 33
507
508 .. note::
509
510 No check is performed by *bpack* to ensure that the default value
511 specified for a field is consistent with the corresponding data type.
512
513
514 Enumeration fields
515 ------------------
516
517 The *bpack* package supports direct mapping of integer types, strings of
518 ``bytes`` and Python ``str`` (unicode) into enumerated values of Python
519 :class:`Enum` types (including also :class:`IntEnum` and :class:`IntFlag`).
520
521 Example:
522
523 .. testcode::
524
525 import enum
526
527 class EColor(enum.IntEnum):
528 RED = 1
529 GREEN = 2
530 BLUE = 3
531 BLACK = 10
532 WHITE = 11
533
534 @bpack.descriptor(baseunits="bits")
535 class BinaryRecord:
536 foreground: EColor = bpack.field(size=4, default=EColor.BLACK)
537 background: EColor = bpack.field(size=4, default=EColor.WHITE)
538
539 record = BinaryRecord()
540 print(record)
541
542 .. testoutput::
543
544 BinaryRecord(foreground=<EColor.BLACK: 10>, background=<EColor.WHITE: 11>)
545
546 The ``EColor`` enum values are lower that 16 so they can be represented
547 with only 4 bits.
548
549 In particular the binary representation of ``BLACK`` and ``WHITE`` is:
550
551 .. doctest::
552
553 >>> format(EColor.BLACK, "04b")
554 '1010'
555 >>> format(EColor.WHITE, "04b")
556 '1011'
557
558 and the binary string representing the above defined binary record is:
559
560 .. testcode::
561
562 data = bytes([0b10101011])
563 print(data)
564
565 .. testoutput::
566
567 b'\xab'
568
569 The data string can be decoded using the :mod:`bpack.bs` backend that is
570 suitable to handle binary data structures with ``bits`` as *baseunits*:
571
572 .. testcode::
573
574 import bpack.bs
575
576 decoder = bpack.bs.Decoder(BinaryRecord)
577 record = decoder.decode(data)
578 print(record)
579
580 .. testoutput::
581
582 BinaryRecord(foreground=<EColor.BLACK: 10>, background=<EColor.WHITE: 11>)
583
584 The result is directly mapped into Python enum values: ``EColor:BLACK`` and
585 ``EColor:WHITE``.
586
587 .. note::
588
589 The :class:`Enum` sub-classes are accepted as field type only if all
590 the enumeration values have the same type (``int``, ``bytes`` or ``str``).
591
592 Example::
593
594 import enum
595 import bpack
596
597
598 class EType(enum.Enum):
599 A = "A"
600 B = 2
601
602
603 @bpack.descriptor(baseunits=bpack.EBaseUnits.BITS)
604 class Record:
605 field: EType = bpack.field(size=8, default=EType.A) # ERROR!
606
607 The above code will result in the following error::
608
609 1 @bpack.descriptor(baseunits=bpack.EBaseUnits.BITS)
610 2 class Record:
611 3 field: EType = bpack.field(size=8, default=EType.A)
612
613 [...]
614
615 TypeError: only Enum with homogeneous values are supported
616
617 Sequence fields
618 ---------------
619
620 *bpack* provides a basic support to homogeneous *sequence* fields i.e.
621 fields containing a sequence of values having the same data type.
622
623 The sequence is specified using the standard Python type annotation classes
624 :class:`typing.Sequence` or :class:`typing.List`, or directly using the
625 `list[...]` notation.
626
627 The data type of a sequence item can be any of the basic data types described
628 in `Type`_.
629
630 .. testcode::
631
632 from typing import Sequence
633
634 @bpack.descriptor
635 class BinaryRecord:
636 sequence: Sequence[int] = bpack.field(size=1, repeat=2)
637 list_: list[float] = bpack.field(size=4, repeat=3)
638
639 Please note that the *size* parameter of the :func:`bpack.descriptors.field`
640 factory function describes the size of the sequence *item*, while the *repeat*
641 parameter described the number of elements in the *sequence*.
642
643 The :mod:`bpack.bs` and :mod:`bpack.st` backend map ``Sequence[T]`` onto
644 Python :class:`tuple` instances and ``List[T]`` or ``list[T]`` onto
645 :class:`list` instances.
646 The :mod:`bpack.np` instead maps all kind of sequences onto
647 :class:`numpy.ndarray` instances.
648
649
650 Record nesting
651 --------------
652
653 Descriptors of binary structures (record types) can have fields that are
654 binary structure descriptors in their turn (sub-records).
655
656 Example:
657
658 .. testcode::
659
660 @bpack.descriptor
661 class SubRecord:
662 field_21: int = bpack.field(size=2, default=1)
663 field_22: int = bpack.field(size=2, default=2)
664
665 @bpack.descriptor
666 class Record:
667 field_1: int = bpack.field(size=4, default=0)
668 field_2: SubRecord = bpack.field(default_factory=SubRecord)
669
670 print(Record())
671
672 .. testoutput::
673
674 Record(field_1=0, field_2=SubRecord(field_21=1, field_22=2))
675
676
677 Decoding of the ``Record`` structure will automatically decode also data
678 belonging to the sub-record and assign to ``field_2`` a ``SubRecord``
679 instance.
680
681
682 Special type annotations
683 ------------------------
684
685 Using the :func:`bpack.descriptors.field` factory function to define fields
686 can be sometime very verbose and boring.
687
688 The *bpack* package provides a typing annotation helper,
689 :class:`bpack.typing.T`, that allows to specify basic types annotated
690 with additional information like the *size* or the *signed* attribute for
691 integers.
692 This helps to reduce the amount of typesetting required to specify a
693 binary structure.
694
695 The :class:`bpack.typing.T` type annotation class takes in input a string
696 argument and converts it into an annotated basic type.
697
698 .. doctest::
699
700 >>> T["u4"] # doctest: +NORMALIZE_WHITESPACE
701 typing.Annotated[int, TypeParams(byteorder=None, type='int',
702 size=4, signed=False)]
703
704 The resulting type annotation is a :class:`typing.Annotated` basic type
705 with attached a :class:`bpack.typing.TypeParams` instance.
706
707 This allows `bpack` to retrieve the information necessary to specify a field.
708
709 For example the following descriptor:
710
711 .. testcode::
712
713 @bpack.descriptor
714 class BinaryRecord:
715 field_1: int = bpack.field(size=4, signed=True, default=0)
716 field_2: int = bpack.field(size=4, signed=False, default=1)
717
718 Can be specified in a more synthetic form as follows:
719
720
721 .. testcode::
722
723 @bpack.descriptor
724 class BinaryRecord:
725 field_1: T["i4"] = 0
726 field_2: T["u4"] = 1
727
728 String descriptors, or *typestr*, are compatible with numpy (a sub-set
729 of the one used in the numpy `array interface`_).
730
731 The *typestr* string format consists of 3 parts:
732
733 * an (optional) character describing the bit/byte order of the data
734
735 - ``<``: little-endian,
736 - ``>``: big-endian,
737 - ``|``: not-relevant
738
739 * a character code giving the basic type of the array, and
740 * an integer providing the number of bits/bytes used by the type
741
742 The basic type character codes are:
743
744 * ``i``: sighed integer
745 * ``u``: unsigned integer
746 * ``f``: float
747 * ``c``: complex (**currently not supported**)
748 * ``S``: bytes (string)
749
750 .. note::
751
752 Although the *typestr* format allows to specify the bit/byte *order*
753 of the datatype it is usually not necessary to do it because
754 descriptor object already have this information.
755
756 .. seealso::
757
758 :func:`bpack.typing.str_to_type_params`, :class:`bpack.typing.TypeParams`,
759 https://numpy.org/doc/stable/reference/arrays.dtypes.html and
760 https://numpy.org/doc/stable/reference/arrays.interface.html
761
762 .. _`array interface`: https://numpy.org/doc/stable/reference/arrays.interface.html
763
764
765 Data codecs
766 -----------
767
768 Backends
769 ~~~~~~~~
770
771 Backends provide encoding/decoding capabilities for binary data
772 *descriptors* exploiting external packages to do the low level job.
773
774 Currently *bpack* provides the following backends:
775
776 * :mod:`bpack.st` backend, based on the :mod:`struct` package, and
777 * :mod:`bpack.bs` backend, based on the bitstruct_ package to decode
778 binary data described at bit level, i.e. with fields that can have size
779 expressed in terms of number of bits (also smaller that 8).
780 * :mod:`bpack.np` backend, based on numpy_ (limited encoding capabilities)
781
782 Additionally a :mod:`bpack.ba` backend, feature incomplete, is also provided
783 mainly for benchmarking purposes. The :mod:`bpack.ba` backend is based on the
784 bitarray_ package.
785
786 .. _bitstruct: https://github.com/eerimoq/bitstruct
787 .. _bitarray: https://github.com/ilanschnell/bitarray
788 .. _numpy: https://numpy.org
789
790
791 Codec objects
792 ~~~~~~~~~~~~~
793
794 Each backend provides a ``Codec`` class that can be used to instantiate
795 a *codec* objects.
796
797 Please refer to the `Codecs`_ section for a description of basic concepts
798 of how decoders work.
799
800 Decoders are instantiated passing to the ``Codec`` class a binary data
801 record *descriptor*.
802 Each *codec* has
803
804 * a ``descriptor`` property, by which it is possible to access the *descriptor*
805 associated to the ``Codec`` instance
806 * a ``baseunits`` property, that indicates the kind of *descriptors* supported
807 by the ``Decoder`` class
808 * a ``decode(data: bytes)`` method, that takes in input a string of
809 :class:`bytes` and returns an instance of the record type specified
810 at the instantiation of the *codec* object
811 * a ``encode(record)`` method, that takes in input an instance of the record
812 type specified at the instantiation of the *codec* object (a Python object)
813 and returns a string of :class:`bytes`
814
815 Details on the ``Codec`` API can be found in:
816
817 * :class:`bpack.bs.Codec`,
818 * :class:`bpack.np.Codec`,
819 * :class:`bpack.st.Codec`
820
821 .. note::
822
823 the :mod:`bpack.ba` backend does not provides encoding capabilities
824 so no :class:`bpack.ba.Codec` class exists.
825 A :class:`bpack.ba.Decoder` class exists instead providing only decoding
826 capabilities.
827
828
829 Codec decorator
830 ~~~~~~~~~~~~~~~
831
832 Each backend provides also a ``@codec`` decorator the can be used to
833 add to a *descriptor* direct decoding capabilities.
834 In particular the ``frombytes(data: bytes)`` class method and the
835 ``tobytes()`` method are added to the *descriptor* to be able to write code
836 as the following:
837
838
839 .. testcode::
840
841 import bpack
842 import bpack.st
843
844 @bpack.st.codec
845 @bpack.descriptor
846 class BinaryRecord:
847 field_1: float = bpack.field(size=8)
848 field_2: int = bpack.field(size=4, signed=True)
849
850 binary_data = b"\x18-DT\xfb!\t@\x15\xcd[\x07"
851 record = BinaryRecord.frombytes(binary_data)
852
853 print(record)
854
855 .. testoutput::
856
857 BinaryRecord(field_1=3.141592653589793, field_2=123456789)
858
859 .. testcode::
860
861 encoded_data = record.tobytes()
862 assert binary_data == encoded_data
863
864 print(encoded_data)
865
866 .. testoutput::
867
868 b'\x18-DT\xfb!\t@\x15\xcd[\x07'