Skip to main content

Capacity, input status and recovery

What this concept is​

A line reader needs a contract for capacity, terminators, rejected input and source position. A boolean success flag hides distinctions that callers need to recover correctly.

Why it matters here​

The lab stores at most capacity minus one bytes and keeps one slot for the terminator. It separates a valid blank line, end before any content, an overlong line, embedded NUL and a source error. This makes boundary behavior inspectable before learning heap allocation.

Concrete example​

With capacity 4, abc followed by newline succeeds; abcd is rejected. The rejected line is consumed through newline/end, so the next call starts at the next line. Capacity 1 can represent a blank line but no content. If a source error occurs after two bytes, return an error and clear the first output byte. Do not present the partial prefix as success.

Common confusion / misconception​

Bounded storage is not bounded running time: draining a source that never supplies newline or end can run indefinitely. Byte counts are not Unicode character counts. Our lab preserves carriage return as ordinary content and rejects embedded NUL rather than pretending the prefix is the entire line.

How to use it​

Read reader.h before implementing. Keep the source result in int, distinguish bytes from negative status sentinels, and validate zero capacity before subtracting one. Track whether any input occurred separately from the number of stored bytes. On rejection, continue draining unless an input error occurs. The buffer and source context are borrowed for this call.

Check yourself​

Why does capacity minus one underflow when capacity is zero? Why can an overlong line leave the next call in the wrong place? Which status wins if a NUL-containing line later hits an input error?

Mini drill or application​

For capacity 2, trace a, NUL, b, newline, q, newline. Expect NUL rejection then a successful q line. Inject an error before the newline and explain why recovery is no longer promised.

Read this only if stuck​

The C Programming Language for arrays and stdio. Use the lab contract as the authority for this exercise’s rejection and recovery policies.