buf
import std::io::buf; · source
The three blocking adapters here borrow the inner reader or writer through a pointer. You keep ownership of the underlying sink and remain responsible for dropping it; wrapping and unwrapping are free. The default buffer is 8 KiB, matching stdio's block-buffered default on most Unixes.
Types
BufWriter<W>
type struct BufWriter<W> where W: Write {
writer: W*;
buffer: u8*;
capacity: u64;
length: u64;
static new(writer: W*) -> BufWriter<W>
where W: Write;
static with_capacity(writer: W*, capacity: u64) -> BufWriter<W>
where W: Write;
get_ref(&this) -> W*;
buffered(&this) -> u64;
capacity(&this) -> u64;
clear(mut &this) -> void;
flush_buffer(mut &this) -> Result<(), IoError>;
}
Wrapping a sink in a BufWriter coalesces many small writes into one syscall per buffer-full.
import std::io::buf;
mut out: Stdout = stdout();
mut buffered: BufWriter<Stdout> = BufWriter::<Stdout>::new(&out);
buffered.write(payload);
buffered.flush()?;
buffered() reports how much is waiting, clear() discards it without writing (for error paths), and flush_buffer pushes it to the sink without asking the sink to flush in turn. If you mutate through get_ref(), flush first — otherwise buffered bytes land out of order.
BufWriter::dropflushes pending bytes, so call it before the wrapped sink goes away or buffered writes are lost.
Properties
| Property | Type |
|---|---|
writer | W* |
buffer | u8* |
capacity | u64 |
length | u64 |
Constructors
static new(writer: W*) -> BufWriter<W> where W: Write;
static new(writer: W*) -> BufWriter<W> where W: Write;Wrap writer with a DEFAULT_BUFFER_SIZE-byte buffer. Panics on allocation failure.
static with_capacity(writer: W*, capacity: u64) -> BufWriter<W> where W: Write;
static with_capacity(writer: W*, capacity: u64) -> BufWriter<W> where W: Write;Wrap with an explicit buffer size. capacity == 0 is permitted but degenerate: every write hits the sink directly. Panics on allocation failure.
Methods
get_ref(&this) -> W*;
get_ref(&this) -> W*;Borrow the inner writer. Useful for operations that bypass buffering (e.g., a direct flush on the underlying fd). Callers mutating through this must call BufWriter::flush first, or buffered bytes will land out of order.
buffered(&this) -> u64;
buffered(&this) -> u64;Number of bytes currently buffered but not yet flushed.
capacity(&this) -> u64;
clear(mut &this) -> void;
clear(mut &this) -> void;Discard buffered bytes without writing them. Useful on error paths where the caller knows the output is garbage.
flush_buffer(mut &this) -> Result<(), IoError>;
flush_buffer(mut &this) -> Result<(), IoError>;Write buffered bytes to the sink and reset. Retries are delegated to the sink's write_all.
LineWriter<W>
type struct LineWriter<W> {
inner: BufWriter<W>;
static new(writer: W*) -> LineWriter<W>
where W: Write;
static with_capacity(writer: W*, capacity: u64) -> LineWriter<W>
where W: Write;
get_ref(&this) -> W*;
}
A BufWriter that flushes after any write containing \n. The right choice for interactive stdout on a TTY, where a prompt has to appear before the read that follows it.
Properties
| Property | Type |
|---|---|
inner | BufWriter<W> |
Constructors
static new(writer: W*) -> LineWriter<W> where W: Write;
static with_capacity(writer: W*, capacity: u64) -> LineWriter<W> where W: Write;
Methods
get_ref(&this) -> W*;
BufReader<R>
type struct BufReader<R> where R: Read {
reader: R*;
buffer: u8*;
capacity: u64;
position: u64;
filled: u64;
static new(reader: R*) -> BufReader<R>
where R: Read;
static with_capacity(reader: R*, capacity: u64) -> BufReader<R>
where R: Read;
get_ref(&this) -> R*;
capacity(&this) -> u64;
available(&this) -> u64;
consume(mut &this, amount: u64) -> void;
fill_buf(mut &this) -> Result<Slice<u8>, IoError>;
}
Pulls in buffer-sized chunks and serves reads from memory, and overrides read_line with a scan-and-copy fast path — the byte-at-a-time default on the trait is exact but slow on a socket or a file.
It also exposes the zero-copy parsing pair: fill_buf() returns the filled region as a Slice<u8> (empty at EOF), and consume(amount) advances past however many bytes you actually wanted. available() reports what is buffered and unread.
Properties
| Property | Type | Notes |
|---|---|---|
reader | R* | |
buffer | u8* | |
capacity | u64 | |
position | u64 | First unread byte in the buffer. |
filled | u64 | One past the last filled byte. |
Constructors
static new(reader: R*) -> BufReader<R> where R: Read;
static with_capacity(reader: R*, capacity: u64) -> BufReader<R> where R: Read;
Methods
get_ref(&this) -> R*;
capacity(&this) -> u64;
available(&this) -> u64;
available(&this) -> u64;Bytes currently buffered and unread.
consume(mut &this, amount: u64) -> void;
consume(mut &this, amount: u64) -> void;Advance the buffer cursor past amount bytes. amount must not exceed available(); a larger value is a caller bug.
fill_buf(mut &this) -> Result<Slice<u8>, IoError>;
fill_buf(mut &this) -> Result<Slice<u8>, IoError>;Fill the buffer from the source if empty, then surface the filled region. Returns an empty slice at EOF. Paired with consume for zero-copy parsing: read a prefix, decide how many bytes are actually wanted, consume that many.
Trait implementations
BufWriter
implement<W> trait Write for struct BufWriter<W> where W: Write
implement<W> trait Drop for struct BufWriter<W>
LineWriter
implement<W> trait Write for struct LineWriter<W> where W: Write
implement<W> trait Drop for struct LineWriter<W>
BufReader
implement<R> trait Read for struct BufReader<R> where R: Read
implement<R> trait Drop for struct BufReader<R>
BufStream<S>
type struct BufStream<S> {
inner: S;
rbuf: Array<u8>;
rpos: u64;
scratch: Array<u8>;
wbuf: Array<u8>;
static of(inner: S) -> BufStream<S>;
compact(mut &this) -> void;
transport(mut &this) -> S*;
}
The non-blocking counterpart, implementing AsyncRead and AsyncWrite over any AsyncTransport. Unlike the adapters above it owns its transport, because a borrowed transport cannot be held across a suspension point. of(inner) wraps an already-connected transport, and transport() surfaces it for socket options or a negotiated ALPN protocol — not for reading or writing, which would desynchronize the buffers. compact slides unconsumed bytes to the front of the read buffer; the defaults call it when they need room.
net::http::conn and net::ws::frame extend it with protocol readers as inherent methods; see conn for why they are methods rather than free functions.
Properties
| Property | Type |
|---|---|
inner | S |
rbuf | Array<u8> |
rpos | u64 |
scratch | Array<u8> |
wbuf | Array<u8> |
Constructors
static of(inner: S) -> BufStream<S>;
static of(inner: S) -> BufStream<S>;Wrap an already-connected transport.
Methods
compact(mut &this) -> void;
compact(mut &this) -> void;Drop the consumed prefix so a long-lived connection's buffer tracks what is live rather than everything ever read. Called only at the start of a fill: moving bytes at any other time would shift buffered() under a caller mid-parse. (Internal to the connection, but not private — the trait impl blocks are separate scopes and could not reach it.)
transport(mut &this) -> S*;
transport(mut &this) -> S*;The transport, for callers that need it directly (socket options, the negotiated ALPN protocol). Not for reading or writing — that would desynchronize the buffers.
Trait implementations
implement<S> trait AsyncRead for struct BufStream<S>
implement<S> trait AsyncWrite for struct BufStream<S>
implement<S> trait Drop for struct BufStream<S>
Constants
const DEFAULT_BUFFER_SIZE: u64 = 8192;
const BYTE_LF: u8 = 0x0A;
const FILL_CHUNK: u64 = 4096;type struct Name { ... }
type enum Name { ... }
type trait Name { ... }
type union Name { ... }Begins a type declaration; the keyword that follows says which kind. On its own, type Name = Existing; declares an alias.
type struct Name {
field: Type;
method(&this) -> Ret { ... }
}A value type with named fields and optional methods. Structs live on the stack and are passed by value. Fields are public by default and may carry = default values; methods take their receiver as &this, mut &this, or this.
type struct BufWriter<W> where W: Write {
writer: W*;
buffer: u8*;
capacity: u64;
length: u64;
}Coalesces writes destined for W into larger flushes. The inner writer is borrowed via pointer; the caller owns it and drops it.
type parameter Wwhere W: Write
where T: Ord + Clone, U: HashConstrains generic parameters to types that implement the listed traits, which is what makes those traits' methods callable on T. Bounds on one parameter join with +; parameters separate with ,. A where on a single method narrows the type's parameter for that method only.
type trait Write {
write_some(mut &this, bytes: Slice<u8>) -> Result<u64, IoError>;
flush(mut &this) -> Result<(), IoError>;
write<T>(mut &this, data: T) -> Result<(), IoError>;
}BufWriter.writer: W*BufWriter.buffer: u8*BufWriter.capacity: u64BufWriter.length: u64static name(param: Type) -> Ret { ... }A method that belongs to the type rather than an instance, called as Type::name(..). For structs, static new(..) returning a struct literal is the idiomatic constructor.
static BufWriter::new(writer: W*) -> BufWriter<W>
where W: WriteWrap writer with a DEFAULT_BUFFER_SIZE-byte buffer. Panics on allocation failure.
(parameter) writer: W*type struct BufWriter<W> where W: Write {
writer: W*;
buffer: u8*;
capacity: u64;
length: u64;
}Coalesces writes destined for W into larger flushes. The inner writer is borrowed via pointer; the caller owns it and drops it.
static BufWriter::with_capacity(writer: W*, capacity: u64) -> BufWriter<W>
where W: WriteWrap with an explicit buffer size. capacity == 0 is permitted but degenerate: every write hits the sink directly. Panics on allocation failure.
(parameter) capacity: u64BufWriter::get_ref(&this) -> W*Borrow the inner writer. Useful for operations that bypass buffering (e.g., a direct flush on the underlying fd). Callers mutating through this must call BufWriter::flush first, or buffered bytes will land out of order.
&this
mut &this
thisThe receiver of a method. Its first parameter declares how the method takes it: &this borrows read-only, mut &this borrows exclusively, and this / mut this move the value in and consume it. In the body, this.field reaches the members.
BufWriter::buffered(&this) -> u64Number of bytes currently buffered but not yet flushed.
BufWriter::clear(mut &this) -> voidDiscard buffered bytes without writing them. Useful on error paths where the caller knows the output is garbage.
mut &this
mut &TypeAn exclusive, mutating borrow. As a receiver, mut &this lets the method modify the fields - and callers can see that from the signature alone. As a parameter type, mut &T lets the callee mutate through the reference while the caller keeps ownership.
BufWriter::flush_buffer(mut &this) -> Result<(), IoError>Write buffered bytes to the sink and reset. Retries are delegated to the sink's write_all.
primitive ()The unit type: a value that carries no information, and the empty tuple. Distinct from void, which is the absence of a value - Result<(), E> succeeds with nothing to return. 0 bytes.
type struct IoError {
kind: IoErrorKind;
os_code: i32;
}import a::b;
import a::b::{ X, Y };
import a::b as c;
import a::b::*;Brings a module, or selected items from it, into scope. One path per declaration: use the brace form for several items, as to alias, and * for everything public (prefer the brace form; wildcards invite name collisions).
mut name: Type = value;A mutable binding, reassignable after declaration - mutability is opt-in, const is the default. At module level it declares mutable global state. Before & it marks an exclusive reference or receiver instead.
mut out: Stdouttype struct Stdout {}Handle to process standard output. Unbuffered; wrap in LineWriter<Stdout> or BufWriter<Stdout> from io::buf for the common "coalesce many small writes" case.
function stdout() -> Stdoutmut buffered: BufWriter<Stdout>static BufWriter::new(writer: W*) -> BufWriter<W>
where W: WriteWrap writer with a DEFAULT_BUFFER_SIZE-byte buffer. Panics on allocation failure.
mut out: Stdoutmut buffered: BufWriter<Stdout>BufWriter::write<T>(mut &this, data: T) -> Result<(), IoError>via trait Write
Write data in full, retrying short writes and Interrupted errors. Generic over the payload, dispatched at compile time via static match: a raw byte Slice<u8>, a Str view, a NUL-terminated C string, or a single u8.
value?Error propagation. On a Result<T, E> it yields the T of an Ok and otherwise returns the Err(e) from the enclosing function unchanged; on an Option<T> it yields the T of a Some or returns None. The enclosing function must return a matching Result / Option.
type struct LineWriter<W> {
inner: BufWriter<W>;
}A BufWriter that flushes after any write containing a \n. Appropriate for interactive stdout on a TTY, where "the user saw the line as soon as it was emitted" matters more than coalescing.
type parameter WLineWriter.inner: BufWriter<W>type parameter Wstatic LineWriter::new(writer: W*) -> LineWriter<W>
where W: Writetype struct LineWriter<W> {
inner: BufWriter<W>;
}A BufWriter that flushes after any write containing a \n. Appropriate for interactive stdout on a TTY, where "the user saw the line as soon as it was emitted" matters more than coalescing.
static LineWriter::with_capacity(writer: W*, capacity: u64) -> LineWriter<W>
where W: WriteLineWriter::get_ref(&this) -> W*type struct BufReader<R> where R: Read {
reader: R*;
buffer: u8*;
capacity: u64;
position: u64;
filled: u64;
}Pulls from R in buffer-sized chunks and serves reads from the buffer. Transforms a stream of small reads into a few large ones and makes read_line fast: no per-byte syscall.
type parameter Rwhere R: Read
type trait Read {
read(mut &this, buffer: u8*, length: u64) -> Result<u64, IoError>;
read_all(mut &this, buffer: u8*, length: u64) -> Result<u64, IoError>;
read_byte(mut &this) -> Result<Option<u8>, IoError>;
read_char(mut &this) -> Result<Option<u32>, IoError>;
read_until(mut &this, delimiter: u8, out: mut &Array<u8>) -> Result<u64, IoError>;
read_exact(mut &this, buffer: u8*, length: u64) -> Result<(), IoError>;
read_to_end(mut &this, out: mut &Array<u8>) -> Result<u64, IoError>;
read_to_string(mut &this, out: mut &String) -> Result<u64, IoError>;
read_line(mut &this, out: mut &String) -> Result<u64, IoError>;
}BufReader.reader: R*BufReader.buffer: u8*BufReader.capacity: u64BufReader.position: u64First unread byte in the buffer.
BufReader.filled: u64One past the last filled byte.
static BufReader::new(reader: R*) -> BufReader<R>
where R: Read(parameter) reader: R*type struct BufReader<R> where R: Read {
reader: R*;
buffer: u8*;
capacity: u64;
position: u64;
filled: u64;
}Pulls from R in buffer-sized chunks and serves reads from the buffer. Transforms a stream of small reads into a few large ones and makes read_line fast: no per-byte syscall.
static BufReader::with_capacity(reader: R*, capacity: u64) -> BufReader<R>
where R: ReadBufReader::get_ref(&this) -> R*BufReader::available(&this) -> u64Bytes currently buffered and unread.
BufReader::consume(mut &this, amount: u64) -> voidAdvance the buffer cursor past amount bytes. amount must not exceed available(); a larger value is a caller bug.
(parameter) amount: u64BufReader::fill_buf(mut &this) -> Result<Slice<u8>, IoError>Fill the buffer from the source if empty, then surface the filled region. Returns an empty slice at EOF. Paired with consume for zero-copy parsing: read a prefix, decide how many bytes are actually wanted, consume that many.
type struct Slice<T> {
ptr: T*;
length: u64;
}Slice<T>: a borrowed view into a contiguous sequence.
std::core::slicetype struct BufStream<S> {
inner: S;
rbuf: Array<u8>;
rpos: u64;
scratch: Array<u8>;
wbuf: Array<u8>;
}type parameter SBufStream.inner: Stype parameter SBufStream.rbuf: Array<u8>type struct Array<T, A = GlobalAlloc> where A: Allocator {
ptr: T*;
length: i64;
capacity: i64;
alloc: A;
}Array<T, A>: growable, heap-backed, contiguous sequence.
std::collections::arrayBufStream.rpos: u64BufStream.scratch: Array<u8>BufStream.wbuf: Array<u8>static BufStream::of(inner: S) -> BufStream<S>Wrap an already-connected transport.
(parameter) inner: Stype struct BufStream<S> {
inner: S;
rbuf: Array<u8>;
rpos: u64;
scratch: Array<u8>;
wbuf: Array<u8>;
}BufStream::compact(mut &this) -> voidDrop the consumed prefix so a long-lived connection's buffer tracks what is live rather than everything ever read. Called only at the start of a fill: moving bytes at any other time would shift buffered() under a caller mid-parse.
BufStream::transport(mut &this) -> S*The transport, for callers that need it directly (socket options, the negotiated ALPN protocol). Not for reading or writing — that would desynchronize the buffers.
const NAME: Type = value;At module level, a true compile-time constant, conventionally SCREAMING_SNAKE_CASE. (mut at module level declares mutable global state instead.)
const DEFAULT_BUFFER_SIZE: u64 = 8192;const BYTE_LF: u8 = 0x0A;const FILL_CHUNK: u64 = 4096;BufWriter::buffered(&this) -> u64Number of bytes currently buffered but not yet flushed.
std::io::bufBufWriter::clear(mut &this) -> voidDiscard buffered bytes without writing them. Useful on error paths where the caller knows the output is garbage.
std::io::bufBufWriter::flush_buffer(mut &this) -> Result<(), IoError>Write buffered bytes to the sink and reset. Retries are delegated to the sink's write_all.
BufWriter::get_ref(&this) -> W*Borrow the inner writer. Useful for operations that bypass buffering (e.g., a direct flush on the underlying fd). Callers mutating through this must call BufWriter::flush first, or buffered bytes will land out of order.
BufWriter.writer: W*BufWriter.buffer: u8*BufWriter.capacity: u64BufWriter.length: u64const DEFAULT_BUFFER_SIZE: u64 = 8192;static BufWriter::with_capacity(writer: W*, capacity: u64) -> BufWriter<W>
where W: WriteWrap with an explicit buffer size. capacity == 0 is permitted but degenerate: every write hits the sink directly. Panics on allocation failure.
LineWriter.inner: BufWriter<W>BufReader::read_line(mut &this, out: mut &String) -> Result<u64, IoError>via trait Read
Override the trait default; line-reading is the whole point of BufReader, so we do it the fast way: scan the filled region for \n, copy the prefix wholesale, consume, refill only if we didn't hit the newline.
BufReader::fill_buf(mut &this) -> Result<Slice<u8>, IoError>Fill the buffer from the source if empty, then surface the filled region. Returns an empty slice at EOF. Paired with consume for zero-copy parsing: read a prefix, decide how many bytes are actually wanted, consume that many.
BufReader::consume(mut &this, amount: u64) -> voidAdvance the buffer cursor past amount bytes. amount must not exceed available(); a larger value is a caller bug.
BufReader.reader: R*implement struct Name { ... }
implement trait Trait for Type { ... }
implement u64 { ... }Adds methods to a type outside its declaration. implement struct T (or enum, or a bare primitive) opens an inherent block; implement trait Tr for T supplies a trait's methods for one type. Resolution is at compile time - no dynamic dispatch.
type trait Name : Base {
method(&this, other: &This) -> Ret;
}Names a set of methods a type may implement. Inside the body This is the implementing type; methods may carry default bodies, and a trait may require a base trait (type trait Ord : Eq). Generic code asks for a trait with where T: Name.
implement trait Trait for Type { ... }Names the type a trait implementation is for. The block that follows supplies the bodies the trait requires.
language referencetype parameter Rtype trait AsyncRead {
async fill(mut &this) -> Result<u64, IoError>;
buffered(&this) -> Slice<u8>;
consume(mut &this, count: u64) -> void;
scan_for(&this, delimiter: u8, from: u64) -> u64;
take_front(mut &this, count: u64) -> Result<Array<u8>, IoError>;
async ensure(mut &this, count: u64) -> Result<(), IoError>;
async read_exact(mut &this, count: u64) -> Result<Array<u8>, IoError>;
async read_some(mut &this, limit: u64) -> Result<Array<u8>, IoError>;
async read_until(mut &this, delimiter: u8, limit: u64) -> Result<Array<u8>, IoError>;
async read_line(mut &this, limit: u64) -> Result<String, IoError>;
// … 1 more
}A byte source that buffers what it reads inside itself.
std::io::traitstype trait AsyncWrite {
pending(mut &this) -> Array<u8>*;
async flush(mut &this) -> Result<(), IoError>;
queue<T>(mut &this, data: T) -> Result<(), IoError>;
async send<T>(mut &this, data: T) -> Result<(), IoError>;
}A byte sink that buffers what it is given until told to send it.
std::io::traitstype trait AsyncTransport {
async read_into(mut &this, buf: Array<u8>) -> Transfer;
async write_from(mut &this, buf: Array<u8>) -> Transfer;
}One raw, unbuffered async byte channel: what BufStream<S> needs of a transport, and nothing more.
BufStream::transport(mut &this) -> S*The transport, for callers that need it directly (socket options, the negotiated ALPN protocol). Not for reading or writing — that would desynchronize the buffers.
std::io::bufBufStream::compact(mut &this) -> voidDrop the consumed prefix so a long-lived connection's buffer tracks what is live rather than everything ever read. Called only at the start of a fill: moving bytes at any other time would shift buffered() under a caller mid-parse.
namespace std::net::http::conn;HTTP/1.1 message framing over a buffered async connection.
module pageBufStream.rbuf: Array<u8>BufStream.rpos: u64BufStream.scratch: Array<u8>BufStream.wbuf: Array<u8>private type struct Name { ... }
private:On a field: only the declaring type's own methods may touch it (E0353). On a top-level item: confined to its own module, and naming a private type elsewhere is E0503. private: opens a block of such members.