This time there is no walkthrough. You will build a different decoder for a different format, using the same contracts, to find out which ideas you can now apply without a guide. Budget about two hours, outside Day 7's time estimate. The format is a common way to frame messages: a length, followed by that many payload octets.
The specification:
- A two-octet big-endian length, 1 to 8. Length 0 and anything above 8 are errors, detected as soon as the second length octet arrives. There is no checksum.
- The decoder is an opaque heap handle.
msg_createreturnsNULLif its allocation fails, with nothing left allocated;msg_destroyacceptsNULL. Every allocation goes through the starter'stest_alloc, so a test can make it fail. msg_feedtakes a chunk of any size and returns{status, consumed}. It stops right after one complete message (MSG_READY), returnsMSG_NEED_MOREwhen the chunk ran out mid-message, andMSG_ERRORwhen a check failed, withconsumedincluding the bad octet.- Output is a caller-owned
Message: up to eight payload octets and a size. It changes only when a call returnsMSG_READY. - Errors are sticky until
msg_reset: every feed returnsMSG_ERRORwith 0 consumed. Reset starts a new, independent stream. msg_finishsucceeds only at a message boundary; a partial message makes it fail and enters error.- Payload octets may be zero. The payload is a counted array, never a string.
The acceptance cases, which your tests must check before you look at any solution. Write xx for hexadecimal octets:
- With the allocator set to fail,
msg_createreturnsNULLand nothing is live. - The chunk
00 02 41 42 00 01 07fed in one call returnsMSG_READY, consumed 4, output41 42. Feeding the remaining three octets returnsMSG_READY, consumed 3, output07. Finish then succeeds. - After reset, the first message
00 02 41 42split into two chunks at every point before its last octet (after 0, 1, 2 or 3 octets) givesMSG_NEED_MOREwith the output untouched, thenMSG_READYwith the rest consumed and output41 42. - After reset,
00 00 41returnsMSG_ERRORwith consumed 2 and the previous output intact. A later feed of a valid message returnsMSG_ERRORwith consumed 0, and finish fails. - After reset,
00 09fails with consumed 2, and after another reset so does01 00(256, which a little-endian reader would take as 1). - After reset,
00 02 41returnsMSG_NEED_MOREwith consumed 3, and finish fails. - After reset,
00 01 00returnsMSG_READYwith a single zero octet.
The tests share one decoder, resetting it between cases, and finish by checking that destroying it brings the live count back to 0.
Predict and run
Read the program before pressing Run. Predict the output, then explain why the octets 0x41 and 0x42 have stable numeric values regardless of the character set the compiler uses.
#include <stdio.h>
int main(void) {
unsigned char payload[2] = {0x41,0x42};
printf("%u %u\n", (unsigned)payload[0],(unsigned)payload[1]);
return 0;
}Check your prediction
65 660x41 is a number, 65, written in hexadecimal. It means "A" only in ASCII and the encodings built on it. If the test had written 'A' instead, the value would be whatever the execution character set assigns to A, which is 193 in EBCDIC. Wire formats are defined in octet values, so tests should spell payloads as numbers.
What you already have
- An opaque handle with a failing create from Day 1, and a reset that create can share.
- Bytes to numbers from Day 2: a big-endian field is assembled from octets with shifts, never read from memory.
- Incremental state and a consumed count from Days 3 and 4: a decoder that remembers how far it got, and a feed that stops after one frame.
- Validate, then publish; sticky error; reset from Day 5, and sentinel outputs from Day 6, so each assertion can prove what did not change.
Plan before you type
Goals, not statements. Nothing below says how to store the state; that is the part to design.
- Decide what the decoder must remember between calls when a chunk ends after the first length octet, in the middle of the payload, or exactly at a boundary.
- Write the acceptance cases as assertions first, against functions that do not exist yet, each with a sentinel output.
- Get one case passing at a time. Run after every change, under AddressSanitizer if your toolchain has it.
- When everything passes, break one rule at a time on purpose and confirm that a test fails.
Prove it can fail
Once all assertions pass, make the length check accept 0. Case 4 should fail, because the decoder now waits for a payload of nothing instead of reporting an error. Restore it, then publish early by copying the pending message into *out on every payload octet: the split case fails, because the output changes on a call that returned MSG_NEED_MORE. Restore that, then delete the line that makes errors sticky: the "consumed 0" assertion in case 4 fails. Each broken rule should trip one of your assertions; a rule whose breakage no test notices is a missing test.
Mistakes worth checking for
- Length 9 writes past
bytes[8]. The length check was missing or used<= 9. The array sits inside the heap-allocated decoder, so the write lands on the neighboring field,pending.size, and AddressSanitizer does not see it: it only checks the edges of whole allocations. Clang's-fsanitize=boundscatches an out-of-range index into the array itself. - The second message of a chunk is lost or merged. Feed kept consuming after the first message completed. Return right after publishing.
01 00is accepted as length 1. The two length octets were combined little-endian.- A message after reset contains an old byte. Reset cleared the length state but not the pending size, so the new payload was appended after stale data.
- A zero payload octet ends the message early. Something used string logic, such as
strlenor a check for'\0'. Count octets instead. - Finish succeeds after one length octet. It looked only at the payload. A half-read length is missing data too.
Practice
Your turn
Implement the decoder against the given interface and write the tests for all seven acceptance cases. When every assertion passes, the program prints Message decoder checked. Your edits are saved in this browser, but a cleared browser or another device starts from the starter again, so copy your code somewhere safe at the end of each sitting.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
/* ---- Public interface (given) ---- */
typedef struct { unsigned char bytes[8]; size_t size; } Message;
typedef enum { MSG_NEED_MORE, MSG_READY, MSG_ERROR } MsgStatus;
typedef struct { MsgStatus status; size_t consumed; } MsgResult;
typedef struct MsgDecoder MsgDecoder;
MsgDecoder *msg_create(void);
void msg_destroy(MsgDecoder *decoder);
void msg_reset(MsgDecoder *decoder);
MsgResult msg_feed(MsgDecoder *decoder, const unsigned char *bytes, size_t size, Message *out);
int msg_finish(MsgDecoder *decoder);
/* ---- Test allocator (given): use it for every allocation ---- */
static int live = 0;
static int fail_next = 0;
static void *test_alloc(size_t size) {
if (fail_next) { fail_next = 0; return NULL; }
void *block = malloc(size);
if (block != NULL) { ++live; }
return block;
}
static void test_free(void *block) {
if (block != NULL) { --live; free(block); }
}
/* ---- Your decoder: define struct MsgDecoder and the five functions ---- */
/* ---- Your tests ---- */
int main(void) {
/* Assert every acceptance case, then: */
puts("Message decoder checked");
return 0;
}Hint 1: the idea
The decoder is in one of three places: reading the length (0 or 1 octets seen), collecting payload, or failed. A chunk can end in any of them, so each must be recorded in the struct, not in local variables of msg_feed. The length is validated the moment its second octet arrives, so the payload index can never pass 8.
Hint 2: a first step
Before any decoder code, write case 2's first assertion against a msg_feed that returns {MSG_NEED_MORE, 0}, and a create that only allocates and resets. It compiles and fails on the right line. Then make feed handle just the two length octets and the payload of that one message, without any checks, and run again.
Show one solution
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
/* ---- Public interface (given) ---- */
typedef struct { unsigned char bytes[8]; size_t size; } Message;
typedef enum { MSG_NEED_MORE, MSG_READY, MSG_ERROR } MsgStatus;
typedef struct { MsgStatus status; size_t consumed; } MsgResult;
typedef struct MsgDecoder MsgDecoder;
MsgDecoder *msg_create(void);
void msg_destroy(MsgDecoder *decoder);
void msg_reset(MsgDecoder *decoder);
MsgResult msg_feed(MsgDecoder *decoder, const unsigned char *bytes, size_t size, Message *out);
int msg_finish(MsgDecoder *decoder);
/* ---- Test allocator (given): use it for every allocation ---- */
static int live = 0;
static int fail_next = 0;
static void *test_alloc(size_t size) {
if (fail_next) { fail_next = 0; return NULL; }
void *block = malloc(size);
if (block != NULL) { ++live; }
return block;
}
static void test_free(void *block) {
if (block != NULL) { --live; free(block); }
}
/* ---- Implementation ---- */
struct MsgDecoder {
unsigned char header[2];
size_t header_used; /* 0, 1 or 2 length octets seen */
size_t expected; /* payload length, valid once header_used == 2 */
Message pending;
int failed;
};
void msg_reset(MsgDecoder *decoder) {
decoder->header_used = 0;
decoder->expected = 0;
decoder->pending.size = 0;
decoder->failed = 0;
}
MsgDecoder *msg_create(void) {
MsgDecoder *decoder = test_alloc(sizeof *decoder);
if (decoder != NULL) { msg_reset(decoder); }
return decoder;
}
void msg_destroy(MsgDecoder *decoder) { test_free(decoder); }
MsgResult msg_feed(MsgDecoder *decoder, const unsigned char *bytes, size_t size, Message *out) {
MsgResult result = {MSG_NEED_MORE, 0};
if (decoder->failed) { result.status = MSG_ERROR; return result; }
while (result.consumed < size) {
unsigned char byte = bytes[result.consumed++];
if (decoder->header_used < 2) {
decoder->header[decoder->header_used++] = byte;
if (decoder->header_used == 2) {
size_t length = ((size_t)decoder->header[0] << 8) | decoder->header[1];
if (length < 1 || length > 8) {
decoder->failed = 1;
result.status = MSG_ERROR;
return result;
}
decoder->expected = length;
decoder->pending.size = 0;
}
continue;
}
decoder->pending.bytes[decoder->pending.size++] = byte;
if (decoder->pending.size == decoder->expected) {
*out = decoder->pending;
decoder->header_used = 0;
result.status = MSG_READY;
return result;
}
}
return result;
}
int msg_finish(MsgDecoder *decoder) {
if (decoder->failed || decoder->header_used != 0) { decoder->failed = 1; return 0; }
return 1;
}
/* ---- Tests ---- */
static const Message sentinel = {{9, 9, 9, 9, 9, 9, 9, 9}, 8};
static int same(const Message *a, const Message *b) {
return a->size == b->size && memcmp(a->bytes, b->bytes, a->size) == 0;
}
int main(void) {
MsgResult r;
int ok;
/* 1: a failed create returns NULL and holds nothing. */
fail_next = 1;
MsgDecoder *none = msg_create();
assert(none == NULL && live == 0);
msg_destroy(none);
MsgDecoder *d = msg_create();
assert(d != NULL && live == 1);
/* 2: two messages in one chunk, one per call. */
const unsigned char two[7] = {0x00, 0x02, 0x41, 0x42, 0x00, 0x01, 0x07};
const Message ab = {{0x41, 0x42}, 2};
const Message seven = {{0x07}, 1};
Message out = sentinel;
r = msg_feed(d, two, 7, &out);
assert(r.status == MSG_READY && r.consumed == 4 && same(&out, &ab));
r = msg_feed(d, two + 4, 3, &out);
assert(r.status == MSG_READY && r.consumed == 3 && same(&out, &seven));
ok = msg_finish(d);
assert(ok);
/* 3: split anywhere before its last octet, the first message arrives once. */
for (size_t split = 0; split < 4; ++split) {
msg_reset(d);
out = sentinel;
r = msg_feed(d, two, split, &out);
assert(r.status == MSG_NEED_MORE && r.consumed == split && same(&out, &sentinel));
r = msg_feed(d, two + split, 4 - split, &out);
assert(r.status == MSG_READY && r.consumed == 4 - split && same(&out, &ab));
}
/* 4: length 0 fails at its second octet; the error is sticky. */
msg_reset(d);
const unsigned char zero_length[3] = {0x00, 0x00, 0x41};
r = msg_feed(d, zero_length, 3, &out);
assert(r.status == MSG_ERROR && r.consumed == 2 && same(&out, &ab));
r = msg_feed(d, two, 4, &out);
assert(r.status == MSG_ERROR && r.consumed == 0 && same(&out, &ab));
ok = msg_finish(d);
assert(!ok);
/* 5: length 9 and length 256 are too long. */
const unsigned char nine[2] = {0x00, 0x09};
const unsigned char big[2] = {0x01, 0x00};
msg_reset(d);
r = msg_feed(d, nine, 2, &out);
assert(r.status == MSG_ERROR && r.consumed == 2);
msg_reset(d);
r = msg_feed(d, big, 2, &out);
assert(r.status == MSG_ERROR && r.consumed == 2);
/* 6: a partial message fails at finish. */
msg_reset(d);
r = msg_feed(d, two, 3, &out);
assert(r.status == MSG_NEED_MORE && r.consumed == 3);
ok = msg_finish(d);
assert(!ok);
/* 7: a zero payload octet is ordinary data. */
msg_reset(d);
const unsigned char zero_byte[3] = {0x00, 0x01, 0x00};
const Message z = {{0x00}, 1};
r = msg_feed(d, zero_byte, 3, &out);
assert(r.status == MSG_READY && r.consumed == 3 && same(&out, &z));
msg_destroy(d);
assert(live == 0);
(void)r; (void)ok; (void)same; (void)ab; (void)seven; (void)z;
puts("Message decoder checked");
return 0;
}Message decoder checkedThe structure is the telemetry decoder's in miniature: state checked at the earliest octet possible, a private buffer, a single publish, a consumed count that stops at the first message, a sticky error, and a reset that create shares. same(&out, &sentinel) in the split case proves nothing was published early, and live == 0 at the end proves destroy released what create acquired. If your tests differ from these, that is expected; what matters is that each rule in the specification has an assertion that fails when the rule is broken. Close the solution and check that yours has one for each.
Completion is saved in this browser only. It does not measure mastery.