Reading Fixed-Size Blocks from a Stream

A bounded read requests at most some number of bytes. Depending on the interface, a short result can require handling instead of assuming a full record.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Use a concrete payload contract
  2. Process each buffer correctly
  3. Distinguish a partial read from a truncated record
  4. Check the semantics of the specific stream

Use a concrete payload contract

A four-byte header can arrive as two bytes followed by two more on a stream. Buffer until complete or until the source reports exhaustion under that API. Length-prefixed records make the required byte count explicit.

Process each buffer correctly

On the last file block shorter than the work buffer, hash or copy only the bytes actually read. A boundary test with an input smaller than the block reveals accidental processing of unused space.[1]

Distinguish a partial read from a truncated record

A stream supplying an eight-byte header may return three bytes and then five on successive reads. A reader for this interface should gather up to the required size until it observes the stream's exhaustion or a defined error. Do not decode an incomplete header as normal data. See length-prefixed records.

Request 8 → receive 3
Request remaining 5 → receive 5
Total 8: decode header
If exhaustion occurs at total 3: report truncated header

Check the semantics of the specific stream

A nonblocking API can indicate temporarily unavailable data in a way distinct from end of stream. Test uncertainty according to that API. Include both a clean end before any bytes and missing bytes after a header begins.

References

  1. Python Software Foundation, io: Core Tools for Working with Streams ↩