std1.0.0-beta-7 SafeC docs

Module io_buf

#include <std/io_buf.h> source

buffered streams over any Reader / Writer.

BufReader<R> and BufWriter<W> borrow a stream (io_traits.h's Reader / Writer: File, Pipe, TcpStream, ...) and put an IO_BUF_SIZE-byte buffer in front of it: many small reads or writes become one call on the stream. Each is a Reader / Writer itself, so read_exact, write_all, copy_stream and any generic<R: Reader> code take it like the stream it wraps.

struct TcpStream s = TcpStream::from_fd(fd);
struct BufReader<TcpStream> in = BufReader::over(&s);
struct String head = String::new();
if (in.read_until(&head, "\r\n\r\n")) { ... }   // the header block
read_exact(&in, body[0..len]);                   // bytes after it

struct BufWriter<TcpStream> out = BufWriter::over(&s);
write_all(&out, hdr[0..6]);                      // buffered
write_all(&out, payload.as_bytes());
if (out.flush() != 0) { ... }                    // one write to s

A BufWriter holds what was written until flush() (or until its buffer fills): call flush() before the stream is used directly or closed.

Structs

BufReader
BufWriter

Macros

IO_BUF_SIZE