packed - acfr/comma GitHub Wiki
The packed library helps easily write strongly typed data structures to implement telecom packet layouts.
Assume that we have to send and receive a 14-bytes packet containing time updates with the following fields:
- type (timestamp type: "loc" or "utc"; string; 3 bytes)
- padding (3 bytes)
- seconds (from epoch; 4 bytes; big-endian)
- microseconds (from epoch; 4 bytes; big-endian)
#include <comma/packed/packed.h> struct time_packet : public comma::packed::struct< time_packet, 14 > { comma::packed::string< 3 > type; boost::array< comma::packed::byte, 3 > padding; comma::packed::net_uint32 seconds; comma::packed::net_uint32 microseconds; };
Now, say, we want to fill a packet and send it over a socket:
time_packet packet; packet.type = "utc"; packet.seconds = 12345; packet.microseconds = 0; ::write( socket, (char*)&packet, TimePacket::size );
Let's receive packet over a socket and retrieve the field values from the packet:
time_packet packet; ::read( socket, (char*)&packet, TimePacket::size ); std::string type = packet.type(); unsigned int seconds = packet.seconds(); unsigned int microseconds = packet.microseconds();
Thus, the assignment of a field has semantics of a normal assignment; retrieving the field value is almost as natural.
Suppose, our packet consists of a 4-byte header and 48-byte body defined elsewhere in header and body classes, using packed library:
struct header : public comma::packed::struct< header, 4 > ... struct body : public comma::packed::struct< body, 48 > ...
Let us define the packet structure:
struct packet : public comma::packed::struct< packet, header::size + body::size > { Header header; Body body; };
We can refer to the members of header and body naturally both for reading and writing:
packet p; p.header.type = "abc"; p.header.flag = 123; p.body.some_field = 55; // etc
Sending and receiving the packet with nested structures is the same as in the simple example above.
Currently, the field types implemented are:
- byte
- char
- little-endian integers
- big-endian integers
- fixed-length strings