bio
Buffered I/O - buffered reader and writer over streams, reducing syscall overhead for byte-oriented reading and writing.
Load with: use bio
What this module does
bio wraps an existing stream with a buffer so that small reads and writes
don't each go directly to the underlying stream. A buffered reader fills its internal
buffer from the stream in one shot and then serves bytes from that buffer one (or many)
at a time. A buffered writer accumulates data until its buffer is full, then flushes to
the stream in one write - with an explicit buffl call to push whatever is
left at the end.
Both reader and writer validate that the stream they're given supports the right direction
(stream.isrd / stream.iswr) via the eru error module.
Quick example
use bio
# Buffered reader - reads in chunks, serves byte by byte
r = some_readable_stream()
br = bufrd(r, 4096) # 4KB internal buffer
ch = bufr(br) # read one character
data = bufra(br, 16) # read up to 16 characters
# Buffered writer - accumulates and flushes in bulk
w = some_writable_stream()
bw = bufwr(w, 4096)
bufw(bw, "hello ")
bufw(bw, "world\n")
buffl(bw) # flush remaining bytes to stream
Functions
Buffered reader
bufrd(r, cap)
Creates a buffered reader wrapping stream r with an internal buffer capacity of cap bytes. Validates that r is a readable stream via stream.isrd - errors with "bufio: brd: bad r" if not. Returns a buffered reader object.
bufr(b)
Reads one character from the buffered reader b. If the internal buffer is exhausted, refills it by calling stream.rdall(b.r). Returns the character, or nil at EOF (when the stream returns nothing).
bufra(b, n)
Reads up to n characters from the buffered reader. Calls bufr in a loop, stopping at n characters or EOF. Returns the accumulated string (may be shorter than n at EOF).
Buffered writer
bufwr(w, cap)
Creates a buffered writer wrapping stream w with a buffer capacity of cap bytes. Validates that w is a writable stream via stream.iswr - errors with "bufio: bwr: bad w" if not. Returns a buffered writer object.
bufw(bw, s)
Appends string s to the writer's internal buffer. If the buffer length reaches or exceeds cap, automatically flushes to the underlying stream via stream.wr and clears the buffer. Returns nil.
buffl(bw)
Flushes any remaining data in the buffer to the underlying stream and clears the buffer. Call this when done writing to ensure no data is left buffered. Returns nil.
Notes
- The buffered reader refills by calling
stream.rdall- it reads all available data from the stream at once, not exactlycapbytes. - Always call
bufflon a buffered writer when done - unflushed data will be lost if you don't. - The buffered reader's
capfield is stored but is not used to limit how muchstream.rdallreturns - it describes the intended chunk size only. - Requires
trl,strm, anderu.