BufReader
is a buffered I/O wrapper that works with any stream type
implementing the stream-read and stream-write interfaces.
Interfaces
Implement these for your stream type to use BufReader:
(definterface stream-read (Fn [&a &(Array Byte) Int] Int))
(definterface stream-write (Fn [&a &(Array Byte)] Int))
(definterface stream-close (Fn [a] ()))
Usage
; Wrap a TcpStream (if socket library implements the interfaces)
(let [br (BufReader.wrap stream)]
(do
(match (BufReader.read-line &br)
(Result.Success line) (println* &line)
(Result.Error e) (IO.errorln &e))
(BufReader.delete br)))
flush
(Fn [(Ref BufReader a)] (Result () String))
(flush br)
sends all buffered write data. Returns (Result () String).
On error the buffer keeps exactly the bytes the stream did not accept, so
calling flush again resumes instead of re-sending the accepted prefix.
read-append
(Fn [(Ref BufReader a), (Ref (Array Byte) b)] (Result Int String))
(read-append br buf)
reads available data and appends to the byte buffer.
Returns (Result Int String) with the number of bytes read; 0 means the
stream ended. Nothing is appended when the read fails.
read-line
(Fn [(Ref BufReader a)] (Result String String))
(read-line br)
reads until a newline character, returning the line including
the delimiter. Returns (Result String String).
A stream that ends before the newline yields the buffered remainder as a short
line; if nothing is buffered the result is Error "connection closed". A
stream that fails yields Error "read error" and consumes nothing, so a
later call resumes from the same place.
read-n
(Fn [(Ref BufReader a), Int] (Result (Array Byte) String))
(read-n br n)
reads exactly n bytes. Returns (Result (Array Byte) String).
A stream that ends early yields the bytes it did produce; if that is none the
result is Error "connection closed". A stream that fails yields
Error "read error" and the bytes already copied out are gone — unlike
read-line, a partial read-n cannot be resumed.
An n below 1 is Error "invalid count" and reads nothing.
read-until
(Fn [(Ref BufReader a), Char] (Result String String))
(read-until br delim)
reads until the given delimiter byte. Returns (Result String String).
Ends and fails exactly like read-line, which is this function with \n.
write
(Fn [(Ref BufReader a), (Ref String b)] Int)
(write br data)
buffers string data for writing. Call flush to send.
Returns the number of bytes buffered, or -1 if the write buffer could not
grow, in which case nothing was buffered.
write-bytes
(Fn [(Ref BufReader a), (Ref (Array Byte) b)] Int)
(write-bytes br data)
buffers binary data for writing. Call flush to send.
Returns the number of bytes buffered, or -1 if the write buffer could not
grow, in which case nothing was buffered.