Using declarative code has many benefits. For example, the same code that can parse can also build (symmetrical), debugging and testing are much simpler (provable to some extent), creating new constructs is easy (wrapping components), and many more. If one is familiar with the C (programming language), one can think of constructs as casting from char * to struct foo * and vice versa, rather than writing code that unpacks the data.
The following example show how a TCP/IP protocol stack might be defined using Construct. Some code is omitted for brevity and simplicity. Also note that the following code is just Python code that creates objects.
First, the Ethernet header (layer 2):
Next, the IP header (layer 3):
And finally, the TCP header (layer 4):
Now define the hierarchy of the protocol stack. The following code "binds" each pair of adjacent protocols into a separate unit. Each such unit will "select" the proper next layer based on its contained protocol.
At this point, the code can parse captured TCP/IP frames into "packet" objects and build these packet objects back into binary representation.
Data::ParseBinary1 is a CPAN module that originated as a port of Construct to the Perl programming language. (see its main POD document for its inspiration). Since the initial version, some parts of the original API have been deprecated.
A port to Java is available on GitHub.2 Examples in Java, the Ethernet header (layer 2):
"Data::ParseBinary - Yet Another parser for binary structures - metacpan.org". metacpan.org. Retrieved 2023-08-29. https://metacpan.org/pod/Data::ParseBinary ↩
Ziglioli, Emanuele (2022-12-29), ZiglioUK/construct, retrieved 2023-08-29 https://github.com/ZiglioUK/construct ↩