Hardware interview practice
Decode a compact hardware trace stream
Firmware receives a byte stream of typed trace records from a debug buffer and must reject damaged framing without publishing partial records. Implement the C trace decoder with a validate-then-decode pass.
Starting point
Question code
struct TraceRec { uint8_t type; uint32_t value; };
enum TrDec { TD_OK, TD_BAD_ARG, TD_FORMAT, TD_NO_SPACE };
TrDec decode_trace(const uint8_t *in, size_t len, TraceRec *out,
size_t cap, size_t *count);Reviewed example
Work through one case
Input
bytes = {0x00, 0x7F, 0x40, 0x34, 0x12, 0xC0}, cap = 2.Expected output
Return TD_OK with records {(0, 0x7F), (1, 0x1234)} and count = 2.The first header carries one byte, the second carries a two-byte little-endian value, and the final 0xC0 is a valid terminator.
What to cover
Requirements
- Require count; in may be null only when len=0, and out may be null only when cap=0. Bad arguments return TD_BAD_ARG and preserve out and *count.
- Legal headers are 0x00, 0x40, 0x80, and 0xC0. Their types are 0, 1, 2, and 3; types 0, 1, and 2 carry respectively 1, 2, and 4 little-endian payload bytes, while type 3 is the end marker and has no payload.
- Validate the entire stream first: it must contain one end marker as its final byte, every payload must be complete, and no other header value is legal. TD_FORMAT preserves out and *count.
- Let needed exclude the end marker. If needed>cap, set *count=needed, preserve out, and return TD_NO_SPACE; otherwise decode all records, set *count=needed, and return TD_OK.
