A file ends in the middle of a frame: the last write before a power cut only got five of ten bytes onto the disk. A streaming decoder fed those five bytes says NEED_MORE, which is true. But no more bytes will ever come. If nobody asks the decoder whether a partial frame is left over, the truncation is silently ignored and the report looks complete.
The decoder cannot detect this on its own. It only sees the bytes it is given; it has no idea whether the caller's file just ended, a socket closed, or the next chunk is on its way. Only the caller knows the input is over. So the library gives the caller a separate question to ask at the end: decoder_finish.
STREAM_ENDmeans the decoder is at a clean frame boundary: no partial bytes are buffered and no error occurred.DECODE_ERRORmeans a partial frame was left, or the stream already failed. A truncated stream also enters sticky error, so a later feed cannot quietly continue the half frame.
Predict and run
Read the program before pressing Run. Predict the three lines, then explain why a five-byte header followed by end of input is truncated even though every header field is valid.
#include <stdio.h>
int main(void) {
size_t partial[] = {0,3,9};
for (size_t i = 0; i < 3; ++i) { puts(partial[i] == 0 ? "Clean boundary" : "Truncated"); }
return 0;
}Check your prediction
Clean boundary
Truncated
TruncatedOnly zero buffered bytes is a clean end. Three bytes is a cut-off header; nine is a frame missing only its checksum, which is still missing data. A valid five-byte header promises four payload octets and a checksum. If the input ends there, the promise was broken, and the correct report is "truncated", not "zero readings".
An empty chunk is not the end
Why not treat decoder_feed with zero bytes as end of input? Because empty chunks happen during normal operation. A non-blocking read can return nothing simply because no data has arrived yet, and a caller's buffer management may produce an empty remainder after a frame that ended exactly at the chunk edge. The project's contract says a zero-length feed on a healthy decoder returns NEED_MORE with zero consumed and changes nothing. End of input is a separate, explicit call.
Likewise, neither chunk boundaries nor line boundaries mean anything to the protocol. The sample input file puts one frame per line for readability, but a frame split across two lines, or two frames on one line, decodes identically. The application's hex text is only a convenient way to type bytes into a browser.
Finish is a check, not a close
A clean decoder_finish does not destroy or lock the decoder. A caller may finish at the end of one file, get STREAM_END, and keep feeding the same decoder with the next file. That makes finish safe to call at any checkpoint where the caller expects a boundary. The program below runs the main cases with a compact decoder:
#include <stdio.h>
typedef enum { NEED_MORE, FRAME_READY, DECODE_ERROR, STREAM_END } Status;
typedef struct { size_t used; int failed; } Mini;
static const char *names[] = {"NEED_MORE", "FRAME_READY", "DECODE_ERROR", "STREAM_END"};
/* Counts bytes only: enough to show boundaries. */
static Status feed(Mini *d, size_t size) {
if (d->failed) { return DECODE_ERROR; }
Status last = NEED_MORE;
for (size_t i = 0; i < size; ++i) {
if (++d->used == 10) { d->used = 0; last = FRAME_READY; }
else { last = NEED_MORE; }
}
return last;
}
static Status finish(Mini *d) {
if (d->failed || d->used != 0) { d->failed = 1; return DECODE_ERROR; }
return STREAM_END;
}
int main(void) {
Mini d = {0, 0};
printf("empty feed: %s\n", names[feed(&d, 0)]);
printf("empty stream: %s\n", names[finish(&d)]);
feed(&d, 10);
printf("one frame: %s\n", names[finish(&d)]);
feed(&d, 10);
printf("finish was not a close: %s\n", names[finish(&d)]);
feed(&d, 5);
printf("header only: %s\n", names[finish(&d)]);
printf("feed after truncation: %s\n", names[feed(&d, 5)]);
return 0;
}empty feed: NEED_MORE
empty stream: STREAM_END
one frame: STREAM_END
finish was not a close: STREAM_END
header only: DECODE_ERROR
feed after truncation: DECODE_ERRORThe last line is the sticky part. Without it, a caller that ignored the finish result could feed five more bytes, and the decoder would glue them onto the stale header from the previous file, producing a reading that was never sent. Entering error on truncation turns that silent corruption into a refusal.
Empty input is a valid stream
Notice that an empty stream finishes cleanly. That is a deliberate choice: a sensor that sent nothing today is not an error, and the application reports Frames: 0. Treating empty input as truncated would make "no data" impossible to express without a special case in every caller.
Practice
Your turn
DECODE_ERROR says that a stream ended badly, not where. An operator reading a log wants to know whether the last frame was cut inside its 5-octet header or inside its payload. Write Finish finish_reason(Mini *d) that keeps the sticky rule from above but reports one of four results: STREAM_END for a clean end, CUT_IN_HEADER or CUT_IN_PAYLOAD for a truncated frame (and the decoder becomes failed), and ALREADY_FAILED for a decoder that had failed before this call. In this Mini, a frame is a 5-octet header followed by 5 more octets, and used counts the octets of the frame in progress. Print:
used 0, ok: stream end
used 3, ok: cut in header (now failed)
used 5, ok: cut in payload (now failed)
used 9, ok: cut in payload (now failed)
used 0, failed: already failed
finish twice after a cut: cut in header, then already failed#include <stdio.h>
typedef enum { STREAM_END, CUT_IN_HEADER, CUT_IN_PAYLOAD, ALREADY_FAILED } Finish;
typedef struct { size_t used; int failed; } Mini;
static const char *names[] = {"stream end", "cut in header", "cut in payload", "already failed"};
/* Write finish_reason here. */
int main(void) {
const Mini cases[5] = {{0, 0}, {3, 0}, {5, 0}, {9, 0}, {0, 1}};
/* Print one line per case, then finish one cut decoder twice. */
(void)cases; (void)names;
return 0;
}Hint 1: the idea
There are two questions, asked in order: was the decoder already unusable, and is anything left over? Only a "yes" to the second turns a healthy decoder into a failed one, and that change is what makes a second call answer differently from the first.
Hint 2: a first step
Make finish_reason report only STREAM_END or CUT_IN_HEADER at first, without touching d->failed, and run. The last line then says cut in header, then cut in header: a decoder that reports the same truncation forever, and would happily accept the next file glued onto the stale bytes. Fix that line before you split header from payload.
Show one solution
#include <stdio.h>
typedef enum { STREAM_END, CUT_IN_HEADER, CUT_IN_PAYLOAD, ALREADY_FAILED } Finish;
typedef struct { size_t used; int failed; } Mini;
static const char *names[] = {"stream end", "cut in header", "cut in payload", "already failed"};
/* A frame is a 5-octet header then 5 more octets; used counts the octets
buffered for the frame in progress. Any result but STREAM_END leaves
the decoder failed. A failed decoder reports ALREADY_FAILED. */
Finish finish_reason(Mini *d) {
if (d->failed) { return ALREADY_FAILED; }
if (d->used == 0) { return STREAM_END; }
d->failed = 1;
return d->used < 5 ? CUT_IN_HEADER : CUT_IN_PAYLOAD;
}
int main(void) {
const Mini cases[5] = {{0, 0}, {3, 0}, {5, 0}, {9, 0}, {0, 1}};
for (size_t i = 0; i < 5; ++i) {
Mini d = cases[i];
Finish f = finish_reason(&d);
printf("used %zu, %s: %s%s\n", cases[i].used, cases[i].failed ? "failed" : "ok", names[f],
d.failed && !cases[i].failed ? " (now failed)" : "");
}
Mini cut = {3, 0};
Finish first = finish_reason(&cut);
Finish second = finish_reason(&cut);
printf("finish twice after a cut: %s, then %s\n", names[first], names[second]);
return 0;
}used 0, ok: stream end
used 3, ok: cut in header (now failed)
used 5, ok: cut in payload (now failed)
used 9, ok: cut in payload (now failed)
used 0, failed: already failed
finish twice after a cut: cut in header, then already failedThe failed test comes first, so a failed decoder reports ALREADY_FAILED rather than re-diagnosing stale bytes it may not even trust. A clean end changes nothing, so finishing twice on a clean decoder would print stream end twice. A truncated end changes state exactly once, from healthy to failed, which the last line shows. The boundary between the two cut results, used < 5, is the header size; used == 5 means the header arrived and the payload did not start. The checkpoint next proves the decoder gives the same answers however the input is split into chunks.
Completion is saved in this browser only. It does not measure mastery.