|
| 1 | +.. _first_steps-inline-syntax: |
| 2 | + |
| 3 | +Inline Syntax |
| 4 | +============= |
| 5 | + |
| 6 | +In addition to the standard methods for packing and unpacking data, *Caterpillar* also |
| 7 | +supports an **inline syntax** feature that allows for more concise and expressive data |
| 8 | +parsing. This syntax uses Python's overloaded left-shift operator (``<<``) to easily |
| 9 | +unpack data from a bytes object or a stream, making the code both compact and readable. |
| 10 | + |
| 11 | +Unpacking Data Inline |
| 12 | +^^^^^^^^^^^^^^^^^^^^^^ |
| 13 | + |
| 14 | +With the inline syntax, you can unpack binary data into a struct directly using the |
| 15 | +left-shift operator. This operator is a shorthand for calling the ``from_bytes`` method, |
| 16 | +which means you don't need to explicitly invoke a function to parse your data. |
| 17 | + |
| 18 | +.. code-block:: python |
| 19 | +
|
| 20 | + from io import BytesIO |
| 21 | + from caterpillar.py import uint8 |
| 22 | +
|
| 23 | + # data can be unpacked INLINE using a special operator |
| 24 | + data = b"\x00\x00\x01\xff" |
| 25 | +
|
| 26 | + # If using on a static bytes object, the struct will always begin at offset zero |
| 27 | + value1 = uint8 << data |
| 28 | + value2 = uint8 << data |
| 29 | + assert value1 == value2 |
| 30 | +
|
| 31 | +
|
| 32 | +In the example above, the binary data is unpacked into the :data:`~caterpillar.fields.uint8` struct. |
| 33 | +The left-shift operator (``<<``) reads the data starting at the beginning of the byte stream and |
| 34 | +automatically handles the parsing for you. |
| 35 | + |
| 36 | +When using a stream, the operator will start unpacking from the current position in the stream. This |
| 37 | +is useful for processing data incrementally or when you want to track your stream's current position |
| 38 | +manually. |
| 39 | + |
| 40 | +>>> stream = BytesIO(data) |
| 41 | +>>> stream.seek(2) # Move the stream position to byte index 2 |
| 42 | +>>> uint8 << stream |
| 43 | +1 |
| 44 | + |
| 45 | +Wrapper methods |
| 46 | +^^^^^^^^^^^^^^^ |
| 47 | + |
| 48 | +Instead of using the special operator, all struct classes in *Caterpillar* also provide the typical |
| 49 | +wrapper functions for packing and unpacking: |
| 50 | + |
| 51 | +>>> # Instead of using the special operator, all default struct classes provide |
| 52 | +>>> # wrapper functions for packing and unpacking: |
| 53 | +>>> uint8.from_bytes(data) |
| 54 | +0 |
| 55 | +>>> uint8.to_bytes(0xFF) |
| 56 | +b"\0xFF" |
| 57 | + |
| 58 | +This inline syntax feature is great for simplifying your code when dealing with binary data, making the |
| 59 | +code both more readable and intuitive. |
0 commit comments