Home

BufReader

BufReader is a buffered reader adaptor in Rust's standard library (std::io) that wraps another type implementing Read to provide buffered input. By storing data in an internal buffer, it reduces the number of calls to the underlying reader, improving performance when reading from files, network streams, or other slow sources. BufReader implements both Read and BufRead, making it usable wherever these traits are required.

Construction and capacity: BufReader::new(inner) creates a buffered reader with a default internal buffer size (typically around

How it works: The wrapper fills its internal buffer from the inner reader and serves subsequent reads

Methods and traits: Read is implemented by delegating to the buffer, while BufRead provides utilities for buffered

Usage and caveats: BufReader is especially beneficial for many small reads from a source, reducing system calls

8
KiB).
BufReader::with_capacity(cap,
inner)
allows
specifying
a
custom
buffer
size.
The
method
into_inner
consumes
the
BufReader
and
returns
the
underlying
reader.
from
that
buffer
until
it
is
exhausted.
Methods
like
fill_buf
and
consume
manage
the
internal
buffer
directly.
BufReader
also
exposes
standard
BufRead
operations
such
as
read_line,
read_until,
and
read_to_end,
which
operate
on
the
buffered
data.
input,
including
lines()
to
iterate
over
lines.
read_line
appends
to
a
provided
string,
including
the
newline
if
present;
lines()
yields
strings
without
trailing
newline.
The
exact
error
semantics
follow
the
underlying
reader
and
the
standard
library's
conventions.
and
latency.
It
is
not
inherently
thread-safe;
Sync/Send
depend
on
the
inner
reader.
It
is
generic
over
any
T:
Read,
enabling
use
with
files,
sockets,
or
in-memory
sources.
Example:
let
f
=
std::fs::File::open("foo.txt").unwrap();
let
mut
r
=
std::io::BufReader::new(f);
let
mut
line
=
String::new();
r.read_line(&mut
line).unwrap();