Skip to content

Assemble the Streaming Decoder

The Course
•
40 min study

The project has three source files, and each has exactly one job. Reading them in the order below lets you check every clause of the brief against the line that implements it.

  • telemetry.h is the contract. It declares the opaque Decoder, the Reading value, the allocator callbacks and the FeedResult, and its comments state every pointer precondition and lifetime rule. It also holds the _Static_assert on CHAR_BIT.
  • telemetry.c is the only file that completes struct Decoder. It owns the 22-byte frame buffer, the encoder and the decoder state machine.
  • main.c is an adapter. It turns hex text into bytes, calls the library, and turns results into output and an exit status. It contains no protocol knowledge at all.

Trace one frame through decoder_feed

Open telemetry.c in the playground at the end of this lesson and find decoder_feed. Its loop copies one byte per iteration into decoder->frame[decoder->used++], then asks three questions at fixed byte counts:

  1. At used == 1: is the byte 0x54? Garbage input is rejected on its first byte.
  2. At used == 5: are version and type 1, and is the big-endian length within the 16-byte limit and exactly 4? This runs before any payload byte is stored, which is what keeps used from ever exceeding 10.
  3. At used == 10: does the checksum match, and are sensor and value in range? Only then are *out = candidate; and decoder->used = 0; executed, followed by a return with FRAME_READY.

Every rejection goes through the small fail helper, which sets the sticky flag and reports how many bytes were consumed. Notice what is absent: there is no allocation, no pointer kept into bytes, and no write to *out on any path except success. Each absence is a promise from the brief.

The out == NULL || (bytes == NULL && size != 0) check at the top is defensive. Those are precondition violations, and the header says they are not allowed, but turning them into a sticky error is cheaper than debugging a crash. The check does not make passing NULL legal.

Predict and run

Read the program before pressing Run. Predict the number, then explain why the text token 54 means decimal 84 rather than decimal 54.

Predict before running C
#include <stdio.h>

int main(void) {
    unsigned high = 5, low = 4;
    printf("%u\n", high * 16 + low);
    return 0;
}
Check your prediction
Text
84

Each hex digit is worth 16 times the digit to its right, so 54 is 5 times 16 plus 4, which is 84. The token is two characters of text, '5' and '4', and the adapter must turn each character into its digit value before combining them. The character '5' has the code 53 in ASCII, not 5.

How the adapter reads tokens

main.c reads tokens with scanf("%3s", token) into char token[4]. The width 3 is deliberate. A valid token has two characters; reading at most three means a token that is too long, such as 5401, arrives as 540 with a non-null token[2], and the adapter rejects it with "Expected two hex digits per token" instead of silently splitting it into bytes. The fourth array element holds the terminator scanf always writes, so the buffer cannot overflow. Writing %s with no width would let a long token overflow token, which is a classic stack buffer overflow.

The adapter feeds one byte per call. That is the least efficient chunk size, and that is acceptable here because the library's multi-byte behavior is covered by the test suite's partition and chunk-size loops.

One exit path for cleanup

main acquires one resource, the decoder, and has six ways to fail. It uses the single-exit shape you already know from C Intermediate's cleanup lesson: exit_code = 1 at the start, goto cleanup; on every failure, exit_code = 0 only at the end of the success path, and one cleanup: block that releases everything. The decoder is created before the first goto, so decoder_destroy always receives a valid handle; had it been created later, the variable would need to start as NULL, which destroy accepts. Open main.c in the download and count the paths that reach cleanup:.

Two checks are easy to forget. The adapter tests ferror(stdin) after the loop, so a read error is not mistaken for end of input, and ferror(stdout) before exiting, so a failed write is not reported as success. Errors go to standard error and readings to standard output, so a script can capture readings separately.

Practice

Exercise

Your turn

Write int hex_digit(int ch) returning 0 to 15 or -1, and int parse_token(const char *token, unsigned char *out) returning 0 for a byte, 1 for a bad digit and 2 for a token that is not exactly two characters. *out changes only on success. Run the tokens in the starter and print:

Text
54: byte 84
ff: byte 255
0A: byte 10
G1: invalid hex token
5: expected two hex digits
540: expected two hex digits
Your workspace C
#include <stdio.h>

int main(void) {
    const char *tokens[6] = {"54", "ff", "0A", "G1", "5", "540"};
    unsigned char byte = 0;
    /* Write hex_digit and parse_token above, then print one line per token. */
    (void)tokens; (void)byte;
    return 0;
}
Hint 1: the idea

Check the length first, using the same three-character test as main.c: token[0], token[1] and token[2] tell you whether the token has fewer than, exactly, or more than two characters. Only then look at the digits.

Hint 2: a first step

Write the length test first, and print a verdict for "7", "7f" and "7f0". The characters at indexes 0, 1 and 2 decide it, and the order you test them in decides whether you ever read past the end. Write hex_digit after that, one range at a time.

Show one solution
Run the solution C
#include <stdio.h>

int hex_digit(int ch) {
    if (ch >= '0' && ch <= '9') { return ch - '0'; }
    if (ch >= 'a' && ch <= 'f') { return ch - 'a' + 10; }
    if (ch >= 'A' && ch <= 'F') { return ch - 'A' + 10; }
    return -1;
}

int parse_token(const char *token, unsigned char *out) {
    if (token[0] == '\0' || token[1] == '\0' || token[2] != '\0') { return 2; }
    int high = hex_digit(token[0]), low = hex_digit(token[1]);
    if (high < 0 || low < 0) { return 1; }
    *out = (unsigned char)(high * 16 + low);
    return 0;
}

int main(void) {
    const char *tokens[6] = {"54", "ff", "0A", "G1", "5", "540"};
    const char *errors[3] = {"", "invalid hex token", "expected two hex digits"};
    unsigned char byte = 0;
    for (size_t i = 0; i < 6; ++i) {
        int result = parse_token(tokens[i], &byte);
        if (result == 0) { printf("%s: byte %u\n", tokens[i], (unsigned)byte); }
        else { printf("%s: %s\n", tokens[i], errors[result]); }
    }
    return 0;
}
Text
54: byte 84
ff: byte 255
0A: byte 10
G1: invalid hex token
5: expected two hex digits
540: expected two hex digits

Returning -1 from hex_digit keeps "invalid" distinct from the digit 0, which a return value of 0 could not do. The 'a' to 'f' range test relies on those letters having consecutive codes. That holds in ASCII and every encoding a modern compiler uses, though the C standard guarantees consecutive codes only for the digits '0' to '9'. The same checks sit at the top of the loop in main.c, below.

Run the decoder application

Streaming telemetry decoder C
#include "telemetry.h" #include <stdio.h> /* Browser adapter: one hex octet per whitespace-separated token. Each octet is fed as one chunk; library callers can supply chunks of any length. */ static int hex_digit(int ch) { if (ch >= '0' && ch <= '9') { return ch - '0'; } if (ch >= 'a' && ch <= 'f') { return ch - 'a' + 10; } if (ch >= 'A' && ch <= 'F') { return ch - 'A' + 10; } return -1; } int main(void) { Decoder *decoder = decoder_create(telemetry_default_allocator()); if (decoder == NULL) { fputs("Decoder unavailable\n", stderr); return 1; } char token[4]; size_t frames = 0; int exit_code = 1; while (scanf("%3s", token) == 1) { if (token[0] == '\0' || token[1] == '\0' || token[2] != '\0') { fputs("Expected two hex digits per token\n", stderr); goto cleanup; } int high = hex_digit(token[0]), low = hex_digit(token[1]); if (high < 0 || low < 0) { fputs("Invalid hex token\n", stderr); goto cleanup; } unsigned char byte = (unsigned char)(high * 16 + low); Reading reading; FeedResult result = decoder_feed(decoder, &byte, 1, &reading); if (result.status == DECODE_ERROR) { fputs("Invalid frame; reset required\n", stderr); goto cleanup; } if (result.status == FRAME_READY) { printf("Sensor %u: %u\n", (unsigned)reading.sensor, (unsigned)reading.value); ++frames; } } if (ferror(stdin)) { fputs("Input error\n", stderr); goto cleanup; } if (decoder_finish(decoder) != STREAM_END) { fputs("Truncated frame\n", stderr); goto cleanup; } printf("Frames: %zu\n", frames); if (ferror(stdout)) { goto cleanup; } exit_code = 0; cleanup: decoder_destroy(decoder); return exit_code; } #include "telemetry.h" #include <stdlib.h> #include <string.h> struct Decoder { unsigned char frame[5 + TELEMETRY_PAYLOAD_LIMIT + 1]; size_t used; int failed; TelemetryAllocator allocator; }; static void *default_allocate(void *context, size_t bytes) { (void)context; return malloc(bytes); } static void default_deallocate(void *context, void *storage) { (void)context; free(storage); } TelemetryAllocator telemetry_default_allocator(void) { TelemetryAllocator allocator = {default_allocate, default_deallocate, NULL}; return allocator; } Decoder *decoder_create(TelemetryAllocator allocator) { if (allocator.allocate == NULL || allocator.deallocate == NULL) { return NULL; } Decoder *decoder = allocator.allocate(allocator.context, sizeof *decoder); if (decoder == NULL) { return NULL; } decoder->allocator = allocator; decoder_reset(decoder); return decoder; } void decoder_destroy(Decoder *decoder) { if (decoder != NULL) { decoder->allocator.deallocate(decoder->allocator.context, decoder); } } void decoder_reset(Decoder *decoder) { decoder->used = 0; decoder->failed = 0; } static unsigned long read_u16(const unsigned char *bytes) { return ((unsigned long)bytes[0] << 8) | (unsigned long)bytes[1]; } static void write_u16(unsigned char *bytes, unsigned long value) { bytes[0] = (unsigned char)(value >> 8); bytes[1] = (unsigned char)(value & 255UL); } static unsigned char checksum(const unsigned char *bytes, size_t size) { unsigned char sum = 0; for (size_t i = 0; i < size; ++i) { sum = (unsigned char)(sum + bytes[i]); } return sum; } int telemetry_encode(Reading record, unsigned char *out, size_t capacity, size_t *written) { if (out == NULL || written == NULL || capacity < TELEMETRY_FRAME_SIZE || record.sensor < 1 || record.sensor > 4095 || record.value > 10000) { return 0; } unsigned char frame[TELEMETRY_FRAME_SIZE] = {0x54, 1, 1, 0, 4, 0, 0, 0, 0, 0}; write_u16(frame + 5, record.sensor); write_u16(frame + 7, record.value); frame[9] = checksum(frame, 9); memcpy(out, frame, sizeof frame); *written = sizeof frame; return 1; } static FeedResult fail(Decoder *decoder, size_t consumed) { decoder->failed = 1; FeedResult result = {DECODE_ERROR, consumed}; return result; } FeedResult decoder_feed(Decoder *decoder, const unsigned char *bytes, size_t size, Reading *out) { if (decoder->failed) { FeedResult result = {DECODE_ERROR, 0}; return result; } if (out == NULL || (bytes == NULL && size != 0)) { return fail(decoder, 0); } size_t consumed = 0; while (consumed < size) { /* used is bounded by header validation before payload accumulation. */ decoder->frame[decoder->used++] = bytes[consumed++]; if (decoder->used == 1 && decoder->frame[0] != 0x54) { return fail(decoder, consumed); } if (decoder->used == 5) { unsigned long length = read_u16(decoder->frame + 3); if (decoder->frame[1] != 1 || decoder->frame[2] != 1 || length > TELEMETRY_PAYLOAD_LIMIT || length != 4) { return fail(decoder, consumed); } } if (decoder->used == TELEMETRY_FRAME_SIZE) { if (checksum(decoder->frame, 9) != decoder->frame[9]) { return fail(decoder, consumed); } Reading candidate = {(uint_least16_t)read_u16(decoder->frame + 5), (uint_least16_t)read_u16(decoder->frame + 7)}; if (candidate.sensor < 1 || candidate.sensor > 4095 || candidate.value > 10000) { return fail(decoder, consumed); } *out = candidate; decoder->used = 0; FeedResult result = {FRAME_READY, consumed}; return result; } } FeedResult result = {NEED_MORE, consumed}; return result; } DecodeStatus decoder_finish(Decoder *decoder) { if (decoder->failed || decoder->used != 0) { decoder->failed = 1; return DECODE_ERROR; } return STREAM_END; } #ifndef TELEMETRY_H #define TELEMETRY_H #include <limits.h> #include <stddef.h> #include <stdint.h> /* Wire octets require an 8-bit unsigned char. No native struct layout is serialized. */ _Static_assert(CHAR_BIT == 8, "Telemetry format requires 8-bit bytes"); #define TELEMETRY_PAYLOAD_LIMIT 16 #define TELEMETRY_FRAME_SIZE 10 typedef struct { uint_least16_t sensor; uint_least16_t value; } Reading; typedef enum { NEED_MORE, FRAME_READY, DECODE_ERROR, STREAM_END } DecodeStatus; typedef struct { DecodeStatus status; size_t consumed; } FeedResult; typedef void *(*AllocateFn)(void *context, size_t bytes); typedef void (*DeallocateFn)(void *context, void *storage); typedef struct { AllocateFn allocate; DeallocateFn deallocate; void *context; } TelemetryAllocator; typedef struct Decoder Decoder; TelemetryAllocator telemetry_default_allocator(void); /* allocator callbacks/context must remain valid until destroy. NULL on failure. One bounded allocation at creation; feed/reset/finish never allocate. */ Decoder *decoder_create(TelemetryAllocator allocator); void decoder_destroy(Decoder *decoder); /* NULL is allowed; other handles exactly once. */ void decoder_reset(Decoder *decoder); /* Requires non-NULL decoder/out; bytes may be NULL only for size zero. Processes at most one frame; caller advances by consumed, then feeds remaining bytes. NEED_MORE consumes all supplied bytes, FRAME_READY consumes through one checksum. Error is sticky until reset. Output changes only on FRAME_READY. Input is borrowed only during this call. Output is a caller-owned value. Decoder, input and output storage must not overlap. */ FeedResult decoder_feed(Decoder *decoder, const unsigned char *bytes, size_t size, Reading *out); /* Check end-of-input: STREAM_END on a clean boundary; partial frame becomes sticky error. A clean finish is a check, not a close: later feed is permitted. */ DecodeStatus decoder_finish(Decoder *decoder); /* Record: sensor 1..4095, value 0..10000. Encoder validates before writing. Requires non-NULL out/written and nonoverlapping record/out/written storage. Failure leaves output bytes and written unchanged. Capacity must be >=10. */ int telemetry_encode(Reading record, unsigned char *out, size_t capacity, size_t *written); #endif 54 01 01 00 04 00 01 00 19 74 54 01 01 00 04 00 02 00 28 84
Check your prediction
Text
Sensor 1: 25
Sensor 2: 40
Frames: 2

Now run the acceptance cases from the brief by editing the input. Clear it completely and confirm Frames: 0. Restore the sample and delete its final 84 to see "Truncated frame" after the first reading. Restore it again and change the first frame's checksum from 74 to 75: the error appears before any reading is printed, because the bad frame comes first. Then put GG at the start and check that the adapter rejects it before the library sees a byte.

Was this article helpful?

Your response is saved on this device.