A market data feed sends big-endian messages with a 2 byte length, a 1 byte type and then a body. You want to parse with no copying. State the three correctness problems with casting the receive buffer to a struct pointer, and describe the parser you would write instead.
A market data feed sends big-endian messages with a 2 byte length, a 1 byte type and then a body. You want to parse with no copying. State the three correctness problems with casting the receive buffer to a struct pointer, and describe the parser you would write instead.
Approach: Consider the byte order on the wire against the host, the alignment the struct requires against where a message happens to start, and what the compiler may assume about a pointer of that type.
The three problems are byte order, since the wire is big-endian and the host is little-endian so every multi-byte field needs a swap; alignment, since a message can begin at any offset in the buffer and forming a struct pointer at an unaligned address is undefined behaviour even where the hardware tolerates the load; and strict aliasing, since reading through a struct pointer aimed at a character buffer is undefined and the optimiser may reorder or cache around it. Write field accessors that memcpy each field out at its documented offset and byte swap it, which compiles to one load and one swap instruction at -O2 and copies nothing beyond that field. Keep a packed struct only as documentation of the layout, never as the access path, and static assert its size against the wire size. Hold each message as a pointer and a length into the receive buffer so the body is never duplicated, which is what makes the parsing zero copy.
Follow-up: What changes if a variable length field sits before the one you need, and how do you keep access to later fields constant time?
Key concepts: byte order, alignment, strict aliasing, zero copy parsing.