Module io_traits
byte-stream traits.
std's blocking byte streams share one read/write shape, so the loops every caller needs around them (read until full, write until done, copy one stream into another) are written once here. One trait per capability, composed into the roles generic code asks for:
Reader read(buf): File, Pipe, TcpStream, TlsStream, BufReader<R>
Writer write(buf): File, Pipe, TcpStream, TlsStream, BufWriter<W>
Seekable seek(off, whence) / tell(): File
Flusher flush(): File, BufWriter<W>
Stream Reader + Writer: File, Pipe, TcpStream
SeekableStream Stream + Seekable: File
File (io_file.h) f.read / f.write on an open file
Pipe (ipc/pipe.h) read end / write end of an anonymous pipe
TcpStream (http/http.h) a connected, blocking TCP socket
BufReader / BufWriter (io_buf.h) buffering over any Reader / Writer
Traits are structural: a type conforms by having the methods, so your own stream works with read_exact / write_all / copy_stream (and with any generic<R: Reader> code) as soon as it defines read or write with these signatures. Each call is resolved at compile time (no dispatch at run time).
?&File in = File::open("in.bin", "rb");
struct Pipe p; p.init();
...
long long n = copy_stream(f, &p); // R = File, W = Pipe
if (!write_all(&p, hdr[0..16])) { ... }
Not conforming, on purpose:
WsConn (http/websocket.h) message-based: recv() yields whole frames.
TcpConn (net/tcp.h) a freestanding, non-blocking segment buffer:
read() returning 0 means "nothing yet", not
EOF, so the loops below would misread it.
Traits
| Reader | |
| Writer | |
| Seekable | |
| Flusher | |
| Stream | |
| SeekableStream |
Functions
| read_exact | Fills buf completely, looping over short reads. 1 when all buf.len bytes arrived; 0 when the stream ended or failed first (buf then holds what did arrive). |
| write_all | Writes all of buf, looping over short writes. 1 on success, 0 if the stream failed (or accepted nothing) first. |
| copy_stream | Copies r into w until r's end. Returns the byte count copied, or -1 if a read or write failed (what was copied before stays written). |
| stream_size | The stream's length in bytes (its end offset), leaving the position where it was; -1 on error. |