You are implementing a parser in C# that reads a binary stream containing a sequence of records.
An interviewer provides these helper functions (you may not change their behavior):
// Reads up to n bytes from the underlying stream asynchronously.
// Returns an empty array when the stream is at EOF.
Task<byte[]> ReadAsync(int n);
// Decodes exactly 4 bytes into an Int32 length.
Task<int> DecodeInt(byte[] fourBytes);
// Decodes a byte sequence into one object instance.
Task<object> DecodeObject(byte[] bytes);
The stream format is:
-
Repeatedly:
-
Read
4 bytes
→ decode as an
int L
(the length of the next object payload in bytes)
-
Read
L bytes
→ decode into an
object
-
Continue until EOF is reached cleanly.
Task
Implement Task<List<object>> ReadAllObjectsAsync() that reads the entire stream and returns the decoded objects in order.
Requirements
-
Must handle
partial reads
(i.e.,
ReadAsync(n)
may return fewer than
n
bytes).
-
If EOF occurs in the middle of a record (e.g., only 2 of 4 length bytes are available, or payload is truncated), treat it as an error (you may throw).
-
Assume
L >= 0
. You may define reasonable upper bounds/guards if you want.