Implement Message Framing Readers for TCP Sockets
Context
You are given a TCP socket. Each call to recv(k) may return any number of bytes up to k; in blocking mode, a return of 0 indicates EOF (peer closed). You must not assume a recv will return the full amount requested. Messages may arrive in pieces or back-to-back. Implement a reader that maintains an internal buffer across calls and extracts exactly one message per API call.
Use any mainstream language; Python 3 is acceptable for clarity and unit-testing.
Requirements
Build two variants backed by an internal buffer that persists across calls:
-
Length-prefixed messages
-
The protocol is: a 4-byte big-endian unsigned integer N, followed by exactly N bytes of payload.
-
API: readMessage() returns exactly one payload as bytes (or string, if you choose), blocking until complete or raising on EOF/error.
-
Newline-delimited messages
-
Messages are delimited by '\n'. Treat an optional preceding '\r' (CRLF) as part of the delimiter and return the line without it.
-
API: readLine() returns exactly one line (without the delimiter), blocking until complete or raising on EOF/error.
Both variants must:
-
Maintain an internal buffer across calls.
-
Correctly handle partial reads, back-to-back messages, and EOF.
-
Provide reasonable guardrails (e.g., a max message/line size to avoid unbounded memory growth) and clear error signaling when constraints are violated.
Also provide:
-
Unit tests covering partial reads, back-to-back messages, empty message/line, EOF during header/body, and size limit violations.
-
Time and space complexity analysis, including any amortization arguments.