5 self, BufRead, IoSliceMut, Read, ReadBuf, Seek, SeekFrom, SizeHint, DEFAULT_BUF_SIZE,
9 /// The `BufReader<R>` struct adds buffering to any reader.
11 /// It can be excessively inefficient to work directly with a [`Read`] instance.
12 /// For example, every call to [`read`][`TcpStream::read`] on [`TcpStream`]
13 /// results in a system call. A `BufReader<R>` performs large, infrequent reads on
14 /// the underlying [`Read`] and maintains an in-memory buffer of the results.
16 /// `BufReader<R>` can improve the speed of programs that make *small* and
17 /// *repeated* read calls to the same file or network socket. It does not
18 /// help when reading very large amounts at once, or reading just one or a few
19 /// times. It also provides no advantage when reading from a source that is
20 /// already in memory, like a <code>[Vec]\<u8></code>.
22 /// When the `BufReader<R>` is dropped, the contents of its buffer will be
23 /// discarded. Creating multiple instances of a `BufReader<R>` on the same
24 /// stream can cause data loss. Reading from the underlying reader after
25 /// unwrapping the `BufReader<R>` with [`BufReader::into_inner`] can also cause
28 // HACK(#78696): can't use `crate` for associated items
29 /// [`TcpStream::read`]: super::super::super::net::TcpStream::read
30 /// [`TcpStream`]: crate::net::TcpStream
35 /// use std::io::prelude::*;
36 /// use std::io::BufReader;
37 /// use std::fs::File;
39 /// fn main() -> std::io::Result<()> {
40 /// let f = File::open("log.txt")?;
41 /// let mut reader = BufReader::new(f);
43 /// let mut line = String::new();
44 /// let len = reader.read_line(&mut line)?;
45 /// println!("First line is {len} bytes long");
49 #[stable(feature = "rust1", since = "1.0.0")]
50 pub struct BufReader<R> {
55 impl<R: Read> BufReader<R> {
56 /// Creates a new `BufReader<R>` with a default buffer capacity. The default is currently 8 KB,
57 /// but may change in the future.
62 /// use std::io::BufReader;
63 /// use std::fs::File;
65 /// fn main() -> std::io::Result<()> {
66 /// let f = File::open("log.txt")?;
67 /// let reader = BufReader::new(f);
71 #[stable(feature = "rust1", since = "1.0.0")]
72 pub fn new(inner: R) -> BufReader<R> {
73 BufReader::with_capacity(DEFAULT_BUF_SIZE, inner)
76 /// Creates a new `BufReader<R>` with the specified buffer capacity.
80 /// Creating a buffer with ten bytes of capacity:
83 /// use std::io::BufReader;
84 /// use std::fs::File;
86 /// fn main() -> std::io::Result<()> {
87 /// let f = File::open("log.txt")?;
88 /// let reader = BufReader::with_capacity(10, f);
92 #[stable(feature = "rust1", since = "1.0.0")]
93 pub fn with_capacity(capacity: usize, inner: R) -> BufReader<R> {
94 BufReader { inner, buf: Buffer::with_capacity(capacity) }
98 impl<R> BufReader<R> {
99 /// Gets a reference to the underlying reader.
101 /// It is inadvisable to directly read from the underlying reader.
106 /// use std::io::BufReader;
107 /// use std::fs::File;
109 /// fn main() -> std::io::Result<()> {
110 /// let f1 = File::open("log.txt")?;
111 /// let reader = BufReader::new(f1);
113 /// let f2 = reader.get_ref();
117 #[stable(feature = "rust1", since = "1.0.0")]
118 pub fn get_ref(&self) -> &R {
122 /// Gets a mutable reference to the underlying reader.
124 /// It is inadvisable to directly read from the underlying reader.
129 /// use std::io::BufReader;
130 /// use std::fs::File;
132 /// fn main() -> std::io::Result<()> {
133 /// let f1 = File::open("log.txt")?;
134 /// let mut reader = BufReader::new(f1);
136 /// let f2 = reader.get_mut();
140 #[stable(feature = "rust1", since = "1.0.0")]
141 pub fn get_mut(&mut self) -> &mut R {
145 /// Returns a reference to the internally buffered data.
147 /// Unlike [`fill_buf`], this will not attempt to fill the buffer if it is empty.
149 /// [`fill_buf`]: BufRead::fill_buf
154 /// use std::io::{BufReader, BufRead};
155 /// use std::fs::File;
157 /// fn main() -> std::io::Result<()> {
158 /// let f = File::open("log.txt")?;
159 /// let mut reader = BufReader::new(f);
160 /// assert!(reader.buffer().is_empty());
162 /// if reader.fill_buf()?.len() > 0 {
163 /// assert!(!reader.buffer().is_empty());
168 #[stable(feature = "bufreader_buffer", since = "1.37.0")]
169 pub fn buffer(&self) -> &[u8] {
173 /// Returns the number of bytes the internal buffer can hold at once.
178 /// use std::io::{BufReader, BufRead};
179 /// use std::fs::File;
181 /// fn main() -> std::io::Result<()> {
182 /// let f = File::open("log.txt")?;
183 /// let mut reader = BufReader::new(f);
185 /// let capacity = reader.capacity();
186 /// let buffer = reader.fill_buf()?;
187 /// assert!(buffer.len() <= capacity);
191 #[stable(feature = "buffered_io_capacity", since = "1.46.0")]
192 pub fn capacity(&self) -> usize {
196 /// Unwraps this `BufReader<R>`, returning the underlying reader.
198 /// Note that any leftover data in the internal buffer is lost. Therefore,
199 /// a following read from the underlying reader may lead to data loss.
204 /// use std::io::BufReader;
205 /// use std::fs::File;
207 /// fn main() -> std::io::Result<()> {
208 /// let f1 = File::open("log.txt")?;
209 /// let reader = BufReader::new(f1);
211 /// let f2 = reader.into_inner();
215 #[stable(feature = "rust1", since = "1.0.0")]
216 pub fn into_inner(self) -> R {
220 /// Invalidates all data in the internal buffer.
222 fn discard_buffer(&mut self) {
223 self.buf.discard_buffer()
227 impl<R: Seek> BufReader<R> {
228 /// Seeks relative to the current position. If the new position lies within the buffer,
229 /// the buffer will not be flushed, allowing for more efficient seeks.
230 /// This method does not return the location of the underlying reader, so the caller
231 /// must track this information themselves if it is required.
232 #[stable(feature = "bufreader_seek_relative", since = "1.53.0")]
233 pub fn seek_relative(&mut self, offset: i64) -> io::Result<()> {
234 let pos = self.buf.pos() as u64;
236 if let Some(_) = pos.checked_sub((-offset) as u64) {
237 self.buf.unconsume((-offset) as usize);
240 } else if let Some(new_pos) = pos.checked_add(offset as u64) {
241 if new_pos <= self.buf.filled() as u64 {
242 self.buf.consume(offset as usize);
247 self.seek(SeekFrom::Current(offset)).map(drop)
251 #[stable(feature = "rust1", since = "1.0.0")]
252 impl<R: Read> Read for BufReader<R> {
253 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
254 // If we don't have any buffered data and we're doing a massive read
255 // (larger than our internal buffer), bypass our internal buffer
257 if self.buf.pos() == self.buf.filled() && buf.len() >= self.capacity() {
258 self.discard_buffer();
259 return self.inner.read(buf);
262 let mut rem = self.fill_buf()?;
269 fn read_buf(&mut self, buf: &mut ReadBuf<'_>) -> io::Result<()> {
270 // If we don't have any buffered data and we're doing a massive read
271 // (larger than our internal buffer), bypass our internal buffer
273 if self.buf.pos() == self.buf.filled() && buf.remaining() >= self.capacity() {
274 self.discard_buffer();
275 return self.inner.read_buf(buf);
278 let prev = buf.filled_len();
280 let mut rem = self.fill_buf()?;
283 self.consume(buf.filled_len() - prev); //slice impl of read_buf known to never unfill buf
288 // Small read_exacts from a BufReader are extremely common when used with a deserializer.
289 // The default implementation calls read in a loop, which results in surprisingly poor code
290 // generation for the common path where the buffer has enough bytes to fill the passed-in
292 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
293 if self.buf.consume_with(buf.len(), |claimed| buf.copy_from_slice(claimed)) {
297 crate::io::default_read_exact(self, buf)
300 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
301 let total_len = bufs.iter().map(|b| b.len()).sum::<usize>();
302 if self.buf.pos() == self.buf.filled() && total_len >= self.capacity() {
303 self.discard_buffer();
304 return self.inner.read_vectored(bufs);
307 let mut rem = self.fill_buf()?;
308 rem.read_vectored(bufs)?
314 fn is_read_vectored(&self) -> bool {
315 self.inner.is_read_vectored()
318 // The inner reader might have an optimized `read_to_end`. Drain our buffer and then
319 // delegate to the inner implementation.
320 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
321 let inner_buf = self.buffer();
322 buf.extend_from_slice(inner_buf);
323 let nread = inner_buf.len();
324 self.discard_buffer();
325 Ok(nread + self.inner.read_to_end(buf)?)
328 // The inner reader might have an optimized `read_to_end`. Drain our buffer and then
329 // delegate to the inner implementation.
330 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
331 // In the general `else` case below we must read bytes into a side buffer, check
332 // that they are valid UTF-8, and then append them to `buf`. This requires a
333 // potentially large memcpy.
335 // If `buf` is empty--the most common case--we can leverage `append_to_string`
336 // to read directly into `buf`'s internal byte buffer, saving an allocation and
339 // `append_to_string`'s safety relies on the buffer only being appended to since
340 // it only checks the UTF-8 validity of new data. If there were existing content in
341 // `buf` then an untrustworthy reader (i.e. `self.inner`) could not only append
342 // bytes but also modify existing bytes and render them invalid. On the other hand,
343 // if `buf` is empty then by definition any writes must be appends and
344 // `append_to_string` will validate all of the new bytes.
345 unsafe { crate::io::append_to_string(buf, |b| self.read_to_end(b)) }
347 // We cannot append our byte buffer directly onto the `buf` String as there could
348 // be an incomplete UTF-8 sequence that has only been partially read. We must read
349 // everything into a side buffer first and then call `from_utf8` on the complete
351 let mut bytes = Vec::new();
352 self.read_to_end(&mut bytes)?;
353 let string = crate::str::from_utf8(&bytes).map_err(|_| {
355 io::ErrorKind::InvalidData,
356 "stream did not contain valid UTF-8",
365 #[stable(feature = "rust1", since = "1.0.0")]
366 impl<R: Read> BufRead for BufReader<R> {
367 fn fill_buf(&mut self) -> io::Result<&[u8]> {
368 self.buf.fill_buf(&mut self.inner)
371 fn consume(&mut self, amt: usize) {
372 self.buf.consume(amt)
376 #[stable(feature = "rust1", since = "1.0.0")]
377 impl<R> fmt::Debug for BufReader<R>
381 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
382 fmt.debug_struct("BufReader")
383 .field("reader", &self.inner)
386 &format_args!("{}/{}", self.buf.filled() - self.buf.pos(), self.capacity()),
392 #[stable(feature = "rust1", since = "1.0.0")]
393 impl<R: Seek> Seek for BufReader<R> {
394 /// Seek to an offset, in bytes, in the underlying reader.
396 /// The position used for seeking with <code>[SeekFrom::Current]\(_)</code> is the
397 /// position the underlying reader would be at if the `BufReader<R>` had no
400 /// Seeking always discards the internal buffer, even if the seek position
401 /// would otherwise fall within it. This guarantees that calling
402 /// [`BufReader::into_inner()`] immediately after a seek yields the underlying reader
403 /// at the same position.
405 /// To seek without discarding the internal buffer, use [`BufReader::seek_relative`].
407 /// See [`std::io::Seek`] for more details.
409 /// Note: In the edge case where you're seeking with <code>[SeekFrom::Current]\(n)</code>
410 /// where `n` minus the internal buffer length overflows an `i64`, two
411 /// seeks will be performed instead of one. If the second seek returns
412 /// [`Err`], the underlying reader will be left at the same position it would
413 /// have if you called `seek` with <code>[SeekFrom::Current]\(0)</code>.
415 /// [`std::io::Seek`]: Seek
416 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
418 if let SeekFrom::Current(n) = pos {
419 let remainder = (self.buf.filled() - self.buf.pos()) as i64;
420 // it should be safe to assume that remainder fits within an i64 as the alternative
421 // means we managed to allocate 8 exbibytes and that's absurd.
422 // But it's not out of the realm of possibility for some weird underlying reader to
423 // support seeking by i64::MIN so we need to handle underflow when subtracting
425 if let Some(offset) = n.checked_sub(remainder) {
426 result = self.inner.seek(SeekFrom::Current(offset))?;
428 // seek backwards by our remainder, and then by the offset
429 self.inner.seek(SeekFrom::Current(-remainder))?;
430 self.discard_buffer();
431 result = self.inner.seek(SeekFrom::Current(n))?;
434 // Seeking with Start/End doesn't care about our buffer length.
435 result = self.inner.seek(pos)?;
437 self.discard_buffer();
441 /// Returns the current seek position from the start of the stream.
443 /// The value returned is equivalent to `self.seek(SeekFrom::Current(0))`
444 /// but does not flush the internal buffer. Due to this optimization the
445 /// function does not guarantee that calling `.into_inner()` immediately
446 /// afterwards will yield the underlying reader at the same position. Use
447 /// [`BufReader::seek`] instead if you require that guarantee.
451 /// This function will panic if the position of the inner reader is smaller
452 /// than the amount of buffered data. That can happen if the inner reader
453 /// has an incorrect implementation of [`Seek::stream_position`], or if the
454 /// position has gone out of sync due to calling [`Seek::seek`] directly on
455 /// the underlying reader.
461 /// io::{self, BufRead, BufReader, Seek},
465 /// fn main() -> io::Result<()> {
466 /// let mut f = BufReader::new(File::open("foo.txt")?);
468 /// let before = f.stream_position()?;
469 /// f.read_line(&mut String::new())?;
470 /// let after = f.stream_position()?;
472 /// println!("The first line was {} bytes long", after - before);
476 fn stream_position(&mut self) -> io::Result<u64> {
477 let remainder = (self.buf.filled() - self.buf.pos()) as u64;
478 self.inner.stream_position().map(|pos| {
479 pos.checked_sub(remainder).expect(
480 "overflow when subtracting remaining buffer size from inner stream position",
486 impl<T> SizeHint for BufReader<T> {
488 fn lower_bound(&self) -> usize {
489 SizeHint::lower_bound(self.get_ref()) + self.buffer().len()
493 fn upper_bound(&self) -> Option<usize> {
494 SizeHint::upper_bound(self.get_ref()).and_then(|up| self.buffer().len().checked_add(up))