Skip to content

Make Decoder States Explicit

The Course
•
40 min study

Day 3's decoder needed all ten bytes in one call. Real input does not cooperate. A serial port delivers whatever arrived in the last millisecond, a socket read returns anywhere from one byte to a full buffer, and a file reader works in fixed blocks that ignore frame boundaries. A frame can arrive as 3 bytes, then 6, then 1. A decoder that only works on whole frames forces every caller to reassemble frames first, which means every caller re-implements the hardest part of the decoder.

A streaming decoder accepts bytes in any split. Between calls it remembers two things: the bytes of the current frame received so far, and what validation comes next. That memory is its state. Making the states explicit, and the transitions between them, is what makes the decoder testable: for every state and every possible next byte, you can say exactly what should happen.

The telemetry decoder has three conceptual phases:

  • Header: fewer than 5 bytes buffered. The magic byte is checked as soon as it arrives.
  • Payload: 5 to 9 bytes buffered. The header has been validated; the payload and checksum are still arriving.
  • Failed: a check failed. Every later byte is refused until reset.

A successful tenth byte publishes the reading and returns to an empty header phase, ready for the next frame.

Predict and run

Read the program before pressing Run. Predict both lines, then say which phase each count corresponds to.

Predict before running C
#include <stdio.h>

int main(void) {
    size_t used = 0;
    for (int chunk = 0; chunk < 2; ++chunk) { used += 5; printf("%zu\n", used); }
    return 0;
}
Check your prediction
Text
5
10

After five bytes the header is complete and can be validated, so the decoder moves to the payload phase. Five bytes is enough to know the frame's shape but not enough to publish anything: the sensor, value and checksum are still missing. At ten bytes the frame is complete, the checksum and domain checks run, and on success used goes back to 0.

Derive the phase instead of storing it

You could store an enum Phase alongside used and failed. The project deliberately does not. If the phase is stored separately, the code must update two fields in step on every transition, and one forgotten update creates a state that means nothing, such as "phase is header, but 7 bytes are buffered". Deriving the phase from used and failed makes that state impossible to represent:

C
typedef enum { PHASE_HEADER, PHASE_PAYLOAD, PHASE_FAILED } Phase;
Phase phase_of(size_t used, int failed) {
    if (failed) { return PHASE_FAILED; }
    return used < 5 ? PHASE_HEADER : PHASE_PAYLOAD;
}

The rule generalizes: store the minimum facts, compute everything else. Fewer independent fields means fewer combinations to test and fewer ways for them to disagree.

Validate at the exact byte that makes a check possible

The decoder runs each check at the earliest moment it has the data. Magic at byte 1 means a stream of random bytes is rejected immediately instead of after ten bytes. The header at byte 5 means an oversized length is rejected before any payload byte is stored. The checksum and domain at byte 10 come last because they need everything. The program below pushes the fixture one byte at a time and reports each transition:

Push one byte at a time C
#include <stdio.h>

typedef struct { unsigned char frame[22]; size_t used; int failed; } Mini;

/* Returns -1 on error, 0 if more bytes are needed, 1 when a frame is ready. */
static int push(Mini *d, unsigned char byte, unsigned *sensor, unsigned *value) {
    if (d->failed) { return -1; }
    d->frame[d->used++] = byte;
    if (d->used == 1 && d->frame[0] != 0x54) { d->failed = 1; return -1; }
    if (d->used == 5) {
        unsigned long length = ((unsigned long)d->frame[3] << 8) | d->frame[4];
        if (d->frame[1] != 1 || d->frame[2] != 1 || length != 4) { d->failed = 1; return -1; }
    }
    if (d->used == 10) {
        unsigned char sum = 0;
        for (size_t i = 0; i < 9; ++i) { sum = (unsigned char)(sum + d->frame[i]); }
        if (sum != d->frame[9]) { d->failed = 1; return -1; }
        *sensor = ((unsigned)d->frame[5] << 8) | d->frame[6];
        *value = ((unsigned)d->frame[7] << 8) | d->frame[8];
        d->used = 0;
        return 1;
    }
    return 0;
}

int main(void) {
    const unsigned char fixture[10] = {0x54, 1, 1, 0, 4, 0, 1, 0, 25, 0x74};
    Mini d = {{0}, 0, 0};
    unsigned sensor = 0, value = 0;
    for (size_t i = 0; i < 10; ++i) {
        int result = push(&d, fixture[i], &sensor, &value);
        if (i == 0 || i == 4 || result != 0) {
            printf("byte %zu: result %d, used %zu\n", i + 1, result, d.used);
        }
    }
    printf("reading: sensor %u, value %u\n", sensor, value);
    const unsigned char noise[2] = {0x00, 0x54};
    Mini fresh = {{0}, 0, 0};
    int first = push(&fresh, noise[0], &sensor, &value);
    int second = push(&fresh, noise[1], &sensor, &value);
    printf("noise: %d then %d\n", first, second);
    return 0;
}
Text
byte 1: result 0, used 1
byte 5: result 0, used 5
byte 10: result 1, used 0
reading: sensor 1, value 25
noise: -1 then -1

Look at the last line of output. The noise stream fails on its first byte, and the following 0x54, which looks like a valid start, is refused too. That is the terminal error state from Day 3: once the stream is known to be bad, the decoder does not guess where the next frame might begin. The used index is safe to increment without its own check because the header check at byte 5 guarantees the frame never grows past 10, well inside the 22-byte buffer.

The two noise pushes are separate statements on purpose. Had they both been arguments to one printf, C would not specify which runs first, and pushing 0x54 before 0x00 would print a different result. When calls change shared state, give each its own statement.

Practice

Exercise

Your turn

A progress display wants more than "header or payload": it wants to show which part of the frame comes next and how many octets are still needed, including the moment when only the checksum is missing. The starter contains the push and feed from above. Without adding any field to Mini, write Phase phase_of(const Mini *d) with four phases (header, payload, checksum, failed) and size_t needed(const Mini *d), the octets still needed to complete the current frame (0 for a failed decoder). The starter feeds the fixture in chunks of 3, 4, 2 and 1 octets, then a header with version 2. Print:

Text
after 3: header, needs 7
after 7: payload, needs 3
after 9: checksum, needs 1
after 10: header, needs 10
reading 1 25
bad version: failed, needs 0
next push: -1
Your workspace C
#include <stdio.h>

typedef struct { unsigned char frame[22]; size_t used; int failed; } Mini;
typedef enum { PHASE_HEADER, PHASE_PAYLOAD, PHASE_CHECKSUM, PHASE_FAILED } Phase;
static const char *phase_names[] = {"header", "payload", "checksum", "failed"};

/* The push from above, with the length octets compared directly. */
static int push(Mini *d, unsigned char byte, unsigned *sensor, unsigned *value) {
    if (d->failed) { return -1; }
    d->frame[d->used++] = byte;
    if (d->used == 1 && d->frame[0] != 0x54) { d->failed = 1; return -1; }
    if (d->used == 5 && (d->frame[1] != 1 || d->frame[2] != 1 || d->frame[3] != 0 || d->frame[4] != 4)) {
        d->failed = 1; return -1;
    }
    if (d->used == 10) {
        unsigned char sum = 0;
        for (size_t i = 0; i < 9; ++i) { sum = (unsigned char)(sum + d->frame[i]); }
        if (sum != d->frame[9]) { d->failed = 1; return -1; }
        *sensor = ((unsigned)d->frame[5] << 8) | d->frame[6];
        *value = ((unsigned)d->frame[7] << 8) | d->frame[8];
        d->used = 0;
        return 1;
    }
    return 0;
}

static int feed(Mini *d, const unsigned char *bytes, size_t size, unsigned *sensor, unsigned *value) {
    int result = 0;
    for (size_t i = 0; i < size && result == 0; ++i) { result = push(d, bytes[i], sensor, value); }
    return result;
}

/* Write phase_of and needed here. */

static void show(const char *label, const Mini *d) {
    printf("%s: %s, needs %zu\n", label, phase_names[phase_of(d)], needed(d));
}

int main(void) {
    const unsigned char fixture[10] = {0x54, 1, 1, 0, 4, 0, 1, 0, 25, 0x74};
    const unsigned char bad[5] = {0x54, 2, 1, 0, 4};
    Mini d = {{0}, 0, 0};
    unsigned sensor = 0, value = 0;
    feed(&d, fixture, 3, &sensor, &value);
    show("after 3", &d);
    feed(&d, fixture + 3, 4, &sensor, &value);
    show("after 7", &d);
    feed(&d, fixture + 7, 2, &sensor, &value);
    show("after 9", &d);
    if (feed(&d, fixture + 9, 1, &sensor, &value) == 1) {
        show("after 10", &d);
        printf("reading %u %u\n", sensor, value);
    }
    d = (Mini){{0}, 0, 0};
    feed(&d, bad, 5, &sensor, &value);
    show("bad version", &d);
    printf("next push: %d\n", push(&d, 0x54, &sensor, &value));
    return 0;
}
Hint 1: the idea

Everything the display needs is already implied by failed and used: storing a phase or a countdown would only add fields that can disagree with them. Write down which values of used mean "the next byte is part of the payload" and which mean "the next byte is the checksum".

Hint 2: a first step

Write phase_of with the failed case and the header case only, returning PHASE_PAYLOAD for everything else, and write needed. Run it: only the after 9 line is wrong. With 9 octets buffered, which octet comes next?

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

typedef struct { unsigned char frame[22]; size_t used; int failed; } Mini;
typedef enum { PHASE_HEADER, PHASE_PAYLOAD, PHASE_CHECKSUM, PHASE_FAILED } Phase;
static const char *phase_names[] = {"header", "payload", "checksum", "failed"};

/* The push from above, with the length octets compared directly. */
static int push(Mini *d, unsigned char byte, unsigned *sensor, unsigned *value) {
    if (d->failed) { return -1; }
    d->frame[d->used++] = byte;
    if (d->used == 1 && d->frame[0] != 0x54) { d->failed = 1; return -1; }
    if (d->used == 5 && (d->frame[1] != 1 || d->frame[2] != 1 || d->frame[3] != 0 || d->frame[4] != 4)) {
        d->failed = 1; return -1;
    }
    if (d->used == 10) {
        unsigned char sum = 0;
        for (size_t i = 0; i < 9; ++i) { sum = (unsigned char)(sum + d->frame[i]); }
        if (sum != d->frame[9]) { d->failed = 1; return -1; }
        *sensor = ((unsigned)d->frame[5] << 8) | d->frame[6];
        *value = ((unsigned)d->frame[7] << 8) | d->frame[8];
        d->used = 0;
        return 1;
    }
    return 0;
}

static int feed(Mini *d, const unsigned char *bytes, size_t size, unsigned *sensor, unsigned *value) {
    int result = 0;
    for (size_t i = 0; i < size && result == 0; ++i) { result = push(d, bytes[i], sensor, value); }
    return result;
}

/* Which part of a 10-octet frame the next byte belongs to. */
Phase phase_of(const Mini *d) {
    if (d->failed) { return PHASE_FAILED; }
    if (d->used < 5) { return PHASE_HEADER; }
    if (d->used < 9) { return PHASE_PAYLOAD; }
    return PHASE_CHECKSUM;
}

/* Octets still needed to complete the current frame; 0 for a failed decoder. */
size_t needed(const Mini *d) {
    return d->failed ? 0 : 10 - d->used;
}

static void show(const char *label, const Mini *d) {
    printf("%s: %s, needs %zu\n", label, phase_names[phase_of(d)], needed(d));
}

int main(void) {
    const unsigned char fixture[10] = {0x54, 1, 1, 0, 4, 0, 1, 0, 25, 0x74};
    const unsigned char bad[5] = {0x54, 2, 1, 0, 4};
    Mini d = {{0}, 0, 0};
    unsigned sensor = 0, value = 0;
    feed(&d, fixture, 3, &sensor, &value);
    show("after 3", &d);
    feed(&d, fixture + 3, 4, &sensor, &value);
    show("after 7", &d);
    feed(&d, fixture + 7, 2, &sensor, &value);
    show("after 9", &d);
    if (feed(&d, fixture + 9, 1, &sensor, &value) == 1) {
        show("after 10", &d);
        printf("reading %u %u\n", sensor, value);
    }
    d = (Mini){{0}, 0, 0};
    feed(&d, bad, 5, &sensor, &value);
    show("bad version", &d);
    printf("next push: %d\n", push(&d, 0x54, &sensor, &value));
    return 0;
}
Text
after 3: header, needs 7
after 7: payload, needs 3
after 9: checksum, needs 1
after 10: header, needs 10
reading 1 25
bad version: failed, needs 0
next push: -1

used counts octets already buffered, so the phase describes the next octet: indexes 5 to 8 are payload, and with 9 buffered the next one is the checksum. After a complete frame used is back to 0, so the display shows a fresh header with 10 octets needed. A failed decoder needs nothing, because no octet will ever be accepted again, which the next push: -1 line confirms. Splitting the frame into chunks of 3, 4, 2 and 1 changed nothing about the reading, the property Day 4's checkpoint tests for every split. Next, the decoder's public function has to tell its caller how many bytes of each chunk it actually used.

Was this article helpful?

Your response is saved on this device.