A caller hands the decoder a 25-byte chunk. Inside it are two complete frames and the first five bytes of a third. What should one call return? It has room for exactly one Reading in the caller's output, so it cannot return both frames at once. If it decoded both and kept only the second, the first reading would be lost. If it returned the first and silently threw away the rest of the chunk, the second frame would be lost.
The project's answer is a small contract with two parts: a status and a count.
typedef enum { NEED_MORE, FRAME_READY, DECODE_ERROR, STREAM_END } DecodeStatus;
typedef struct { DecodeStatus status; size_t consumed; } FeedResult;
FeedResult decoder_feed(Decoder *decoder, const unsigned char *bytes, size_t size, Reading *out);decoder_feed processes at most one frame per call. The consumed field tells the caller exactly how many input bytes the decoder used, so the caller can advance its pointer and call again with the remainder. Each status pins down what consumed means:
- FRAME_READY:
outholds a new reading, andconsumedends immediately after that frame's checksum byte. Bytes after it were not looked at. - NEED_MORE: every supplied byte was consumed and buffered, and
outis unchanged. - DECODE_ERROR:
consumedruns through the byte that exposed the problem. On later calls the decoder is in sticky error and consumes zero.
Predict and run
Read the program before pressing Run. Predict the output, then explain what would happen if the caller passed all twenty bytes again instead.
#include <stdio.h>
int main(void) {
size_t size = 20, consumed = 10;
printf("Remaining: %zu\n", size - consumed);
return 0;
}Check your prediction
Remaining: 10The caller supplied 20 bytes and the decoder used 10 for one frame, so 10 bytes are still the caller's responsibility. Passing all twenty bytes again would decode the first frame a second time and report a duplicate reading. Passing nothing would lose the second frame. Only bytes + consumed with size - consumed is correct.
Why one frame per call
Returning one frame at a time keeps the output simple: a single caller-owned Reading, no array to size and no callback whose lifetime must be specified. It also gives the caller control. A caller can stop after any frame to write it to disk, apply backpressure, or decide it has seen enough, and the unconsumed bytes are still in its own buffer.
The zero-progress trap
A loop that advances by consumed must also stop when progress is impossible. In sticky error, decoder_feed returns DECODE_ERROR with consumed 0 forever. A caller that only checks offset < size would spin on that call without end:
while (offset < size) {
FeedResult r = decoder_feed(decoder, bytes + offset, size - offset, &out);
offset += r.consumed; /* stays the same in sticky error: infinite loop */
}The contract makes this the caller's responsibility: stop on DECODE_ERROR. A defensive caller can also assert r.consumed <= size - offset before advancing, which catches a decoder bug that over-reports progress and would otherwise push offset past the end of the buffer.
The caller loop
Here is a decoder with the project's contract and a caller that drains a chunk containing two frames plus a partial third. The loop is the pattern every user of the library must follow:
#include <stdio.h>
typedef enum { NEED_MORE, FRAME_READY, DECODE_ERROR } Status;
typedef struct { Status status; size_t consumed; } FeedResult;
typedef struct { unsigned char frame[22]; size_t used; int failed; } Decoder;
static FeedResult feed(Decoder *d, const unsigned char *bytes, size_t size, unsigned *sensor) {
FeedResult r = {NEED_MORE, 0};
if (d->failed) { r.status = DECODE_ERROR; return r; }
while (r.consumed < size) {
d->frame[d->used++] = bytes[r.consumed++];
if ((d->used == 1 && d->frame[0] != 0x54) || (d->used == 5 && d->frame[4] != 4)) {
d->failed = 1; r.status = DECODE_ERROR; return r;
}
if (d->used == 10) {
*sensor = ((unsigned)d->frame[5] << 8) | d->frame[6];
d->used = 0; r.status = FRAME_READY; return r;
}
}
return r;
}
int main(void) {
static const char *names[] = {"NEED_MORE", "FRAME_READY", "DECODE_ERROR"};
const unsigned char chunk[25] = {
0x54, 1, 1, 0, 4, 0, 1, 0, 25, 0x74,
0x54, 1, 1, 0, 4, 0, 2, 0, 40, 0x84,
0x54, 1, 1, 0, 4};
Decoder d = {{0}, 0, 0};
size_t offset = 0;
int call = 0;
while (offset < sizeof chunk) {
unsigned sensor = 0;
FeedResult r = feed(&d, chunk + offset, sizeof chunk - offset, &sensor);
printf("call %d: %s, consumed %zu", ++call, names[r.status], r.consumed);
if (r.status == FRAME_READY) { printf(", sensor %u", sensor); }
printf("\n");
if (r.status == DECODE_ERROR) { break; }
offset += r.consumed;
}
printf("decoder holds %zu partial bytes\n", d.used);
return 0;
}call 1: FRAME_READY, consumed 10, sensor 1
call 2: FRAME_READY, consumed 10, sensor 2
call 3: NEED_MORE, consumed 5
decoder holds 5 partial bytesThe third call consumed all five remaining bytes and buffered them. When the next chunk arrives, the decoder continues the third frame at byte 6 without the caller needing to remember anything. (This compact decoder checks only magic and length to keep the example short; the project checks every field.)
Practice
Your turn
Using the feed from the example, write size_t drain(Decoder *d, const unsigned char *bytes, size_t size) that prints each reading, stops on the first error and prints how many bytes had been accepted, and returns the frame count. It must also stop, rather than loop, if a call reports more bytes than remain. Feed two valid frames followed by a stray 0x00 byte. Print:
frame: sensor 1
frame: sensor 2
error after 21 bytes
frames: 2#include <stdio.h>
typedef enum { NEED_MORE, FRAME_READY, DECODE_ERROR } Status;
typedef struct { Status status; size_t consumed; } FeedResult;
typedef struct { unsigned char frame[22]; size_t used; int failed; } Decoder;
static FeedResult feed(Decoder *d, const unsigned char *bytes, size_t size, unsigned *sensor) {
FeedResult r = {NEED_MORE, 0};
if (d->failed) { r.status = DECODE_ERROR; return r; }
while (r.consumed < size) {
d->frame[d->used++] = bytes[r.consumed++];
if ((d->used == 1 && d->frame[0] != 0x54) || (d->used == 5 && d->frame[4] != 4)) {
d->failed = 1; r.status = DECODE_ERROR; return r;
}
if (d->used == 10) {
*sensor = ((unsigned)d->frame[5] << 8) | d->frame[6];
d->used = 0; r.status = FRAME_READY; return r;
}
}
return r;
}
int main(void) {
const unsigned char stream[21] = {
0x54, 1, 1, 0, 4, 0, 1, 0, 25, 0x74,
0x54, 1, 1, 0, 4, 0, 2, 0, 40, 0x84, 0x00};
Decoder d = {{0}, 0, 0};
/* Write drain above and call it here. */
(void)stream; (void)d;
return 0;
}Hint 1: the idea
The error message reports offset + r.consumed, the bytes accepted including the one that exposed the problem. Every other status advances offset and continues.
Hint 2: a first step
Write the loop with just two things: the guard that stops a result claiming more bytes than are left, and the line that advances offset. Run it on the valid stream and check it reaches the end. Then add the statuses one at a time, the error first.
Show one solution
#include <stdio.h>
typedef enum { NEED_MORE, FRAME_READY, DECODE_ERROR } Status;
typedef struct { Status status; size_t consumed; } FeedResult;
typedef struct { unsigned char frame[22]; size_t used; int failed; } Decoder;
static FeedResult feed(Decoder *d, const unsigned char *bytes, size_t size, unsigned *sensor) {
FeedResult r = {NEED_MORE, 0};
if (d->failed) { r.status = DECODE_ERROR; return r; }
while (r.consumed < size) {
d->frame[d->used++] = bytes[r.consumed++];
if ((d->used == 1 && d->frame[0] != 0x54) || (d->used == 5 && d->frame[4] != 4)) {
d->failed = 1; r.status = DECODE_ERROR; return r;
}
if (d->used == 10) {
*sensor = ((unsigned)d->frame[5] << 8) | d->frame[6];
d->used = 0; r.status = FRAME_READY; return r;
}
}
return r;
}
size_t drain(Decoder *d, const unsigned char *bytes, size_t size) {
size_t offset = 0, frames = 0;
while (offset < size) {
unsigned sensor = 0;
FeedResult r = feed(d, bytes + offset, size - offset, &sensor);
if (r.consumed > size - offset) { break; } /* decoder bug: over-reported progress */
if (r.status == DECODE_ERROR) {
printf("error after %zu bytes\n", offset + r.consumed);
break;
}
if (r.status == FRAME_READY) { printf("frame: sensor %u\n", sensor); ++frames; }
offset += r.consumed;
}
return frames;
}
int main(void) {
const unsigned char stream[21] = {
0x54, 1, 1, 0, 4, 0, 1, 0, 25, 0x74,
0x54, 1, 1, 0, 4, 0, 2, 0, 40, 0x84, 0x00};
Decoder d = {{0}, 0, 0};
printf("frames: %zu\n", drain(&d, stream, sizeof stream));
return 0;
}frame: sensor 1
frame: sensor 2
error after 21 bytes
frames: 2The loop has exactly two exits besides running out of input, and both are for conditions where progress cannot continue. Because the error consumed the stray byte, the report says 21, pointing at the culprit. Notice the two readings were already printed before the error: streaming output is not all-or-nothing, and the project's application behaves the same way. Next, you decide what it means for the input to end cleanly.
Completion is saved in this browser only. It does not measure mastery.