4 self, BufRead, IoSliceMut, Read, ReadBuf, Seek, SeekFrom, SizeHint, DEFAULT_BUF_SIZE,
6 use crate::mem::MaybeUninit;
8 /// The `BufReader<R>` struct adds buffering to any reader.
10 /// It can be excessively inefficient to work directly with a [`Read`] instance.
11 /// For example, every call to [`read`][`TcpStream::read`] on [`TcpStream`]
12 /// results in a system call. A `BufReader<R>` performs large, infrequent reads on
13 /// the underlying [`Read`] and maintains an in-memory buffer of the results.
15 /// `BufReader<R>` can improve the speed of programs that make *small* and
16 /// *repeated* read calls to the same file or network socket. It does not
17 /// help when reading very large amounts at once, or reading just one or a few
18 /// times. It also provides no advantage when reading from a source that is
19 /// already in memory, like a <code>[Vec]\<u8></code>.
21 /// When the `BufReader<R>` is dropped, the contents of its buffer will be
22 /// discarded. Creating multiple instances of a `BufReader<R>` on the same
23 /// stream can cause data loss. Reading from the underlying reader after
24 /// unwrapping the `BufReader<R>` with [`BufReader::into_inner`] can also cause
27 // HACK(#78696): can't use `crate` for associated items
28 /// [`TcpStream::read`]: super::super::super::net::TcpStream::read
29 /// [`TcpStream`]: crate::net::TcpStream
34 /// use std::io::prelude::*;
35 /// use std::io::BufReader;
36 /// use std::fs::File;
38 /// fn main() -> std::io::Result<()> {
39 /// let f = File::open("log.txt")?;
40 /// let mut reader = BufReader::new(f);
42 /// let mut line = String::new();
43 /// let len = reader.read_line(&mut line)?;
44 /// println!("First line is {} bytes long", len);
48 #[stable(feature = "rust1", since = "1.0.0")]
49 pub struct BufReader<R> {
51 buf: Box<[MaybeUninit<u8>]>,
57 impl<R: Read> BufReader<R> {
58 /// Creates a new `BufReader<R>` with a default buffer capacity. The default is currently 8 KB,
59 /// but may change in the future.
64 /// use std::io::BufReader;
65 /// use std::fs::File;
67 /// fn main() -> std::io::Result<()> {
68 /// let f = File::open("log.txt")?;
69 /// let reader = BufReader::new(f);
73 #[stable(feature = "rust1", since = "1.0.0")]
74 pub fn new(inner: R) -> BufReader<R> {
75 BufReader::with_capacity(DEFAULT_BUF_SIZE, inner)
78 /// Creates a new `BufReader<R>` with the specified buffer capacity.
82 /// Creating a buffer with ten bytes of capacity:
85 /// use std::io::BufReader;
86 /// use std::fs::File;
88 /// fn main() -> std::io::Result<()> {
89 /// let f = File::open("log.txt")?;
90 /// let reader = BufReader::with_capacity(10, f);
94 #[stable(feature = "rust1", since = "1.0.0")]
95 pub fn with_capacity(capacity: usize, inner: R) -> BufReader<R> {
96 let buf = Box::new_uninit_slice(capacity);
97 BufReader { inner, buf, pos: 0, cap: 0, init: 0 }
101 impl<R> BufReader<R> {
102 /// Gets a reference to the underlying reader.
104 /// It is inadvisable to directly read from the underlying reader.
109 /// use std::io::BufReader;
110 /// use std::fs::File;
112 /// fn main() -> std::io::Result<()> {
113 /// let f1 = File::open("log.txt")?;
114 /// let reader = BufReader::new(f1);
116 /// let f2 = reader.get_ref();
120 #[stable(feature = "rust1", since = "1.0.0")]
121 pub fn get_ref(&self) -> &R {
125 /// Gets a mutable reference to the underlying reader.
127 /// It is inadvisable to directly read from the underlying reader.
132 /// use std::io::BufReader;
133 /// use std::fs::File;
135 /// fn main() -> std::io::Result<()> {
136 /// let f1 = File::open("log.txt")?;
137 /// let mut reader = BufReader::new(f1);
139 /// let f2 = reader.get_mut();
143 #[stable(feature = "rust1", since = "1.0.0")]
144 pub fn get_mut(&mut self) -> &mut R {
148 /// Returns a reference to the internally buffered data.
150 /// Unlike [`fill_buf`], this will not attempt to fill the buffer if it is empty.
152 /// [`fill_buf`]: BufRead::fill_buf
157 /// use std::io::{BufReader, BufRead};
158 /// use std::fs::File;
160 /// fn main() -> std::io::Result<()> {
161 /// let f = File::open("log.txt")?;
162 /// let mut reader = BufReader::new(f);
163 /// assert!(reader.buffer().is_empty());
165 /// if reader.fill_buf()?.len() > 0 {
166 /// assert!(!reader.buffer().is_empty());
171 #[stable(feature = "bufreader_buffer", since = "1.37.0")]
172 pub fn buffer(&self) -> &[u8] {
173 // SAFETY: self.cap is always <= self.init, so self.buf[self.pos..self.cap] is always init
174 unsafe { MaybeUninit::slice_assume_init_ref(&self.buf[self.pos..self.cap]) }
177 /// Returns the number of bytes the internal buffer can hold at once.
182 /// use std::io::{BufReader, BufRead};
183 /// use std::fs::File;
185 /// fn main() -> std::io::Result<()> {
186 /// let f = File::open("log.txt")?;
187 /// let mut reader = BufReader::new(f);
189 /// let capacity = reader.capacity();
190 /// let buffer = reader.fill_buf()?;
191 /// assert!(buffer.len() <= capacity);
195 #[stable(feature = "buffered_io_capacity", since = "1.46.0")]
196 pub fn capacity(&self) -> usize {
200 /// Unwraps this `BufReader<R>`, returning the underlying reader.
202 /// Note that any leftover data in the internal buffer is lost. Therefore,
203 /// a following read from the underlying reader may lead to data loss.
208 /// use std::io::BufReader;
209 /// use std::fs::File;
211 /// fn main() -> std::io::Result<()> {
212 /// let f1 = File::open("log.txt")?;
213 /// let reader = BufReader::new(f1);
215 /// let f2 = reader.into_inner();
219 #[stable(feature = "rust1", since = "1.0.0")]
220 pub fn into_inner(self) -> R {
224 /// Invalidates all data in the internal buffer.
226 fn discard_buffer(&mut self) {
232 impl<R: Seek> BufReader<R> {
233 /// Seeks relative to the current position. If the new position lies within the buffer,
234 /// the buffer will not be flushed, allowing for more efficient seeks.
235 /// This method does not return the location of the underlying reader, so the caller
236 /// must track this information themselves if it is required.
237 #[stable(feature = "bufreader_seek_relative", since = "1.53.0")]
238 pub fn seek_relative(&mut self, offset: i64) -> io::Result<()> {
239 let pos = self.pos as u64;
241 if let Some(new_pos) = pos.checked_sub((-offset) as u64) {
242 self.pos = new_pos as usize;
245 } else if let Some(new_pos) = pos.checked_add(offset as u64) {
246 if new_pos <= self.cap as u64 {
247 self.pos = new_pos as usize;
252 self.seek(SeekFrom::Current(offset)).map(drop)
256 #[stable(feature = "rust1", since = "1.0.0")]
257 impl<R: Read> Read for BufReader<R> {
258 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
259 // If we don't have any buffered data and we're doing a massive read
260 // (larger than our internal buffer), bypass our internal buffer
262 if self.pos == self.cap && buf.len() >= self.buf.len() {
263 self.discard_buffer();
264 return self.inner.read(buf);
267 let mut rem = self.fill_buf()?;
274 fn read_buf(&mut self, buf: &mut ReadBuf<'_>) -> io::Result<()> {
275 // If we don't have any buffered data and we're doing a massive read
276 // (larger than our internal buffer), bypass our internal buffer
278 if self.pos == self.cap && buf.remaining() >= self.buf.len() {
279 self.discard_buffer();
280 return self.inner.read_buf(buf);
283 let prev = buf.filled_len();
285 let mut rem = self.fill_buf()?;
288 self.consume(buf.filled_len() - prev); //slice impl of read_buf known to never unfill buf
293 // Small read_exacts from a BufReader are extremely common when used with a deserializer.
294 // The default implementation calls read in a loop, which results in surprisingly poor code
295 // generation for the common path where the buffer has enough bytes to fill the passed-in
297 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
298 if self.buffer().len() >= buf.len() {
299 buf.copy_from_slice(&self.buffer()[..buf.len()]);
300 self.consume(buf.len());
304 crate::io::default_read_exact(self, buf)
307 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
308 let total_len = bufs.iter().map(|b| b.len()).sum::<usize>();
309 if self.pos == self.cap && total_len >= self.buf.len() {
310 self.discard_buffer();
311 return self.inner.read_vectored(bufs);
314 let mut rem = self.fill_buf()?;
315 rem.read_vectored(bufs)?
321 fn is_read_vectored(&self) -> bool {
322 self.inner.is_read_vectored()
325 // The inner reader might have an optimized `read_to_end`. Drain our buffer and then
326 // delegate to the inner implementation.
327 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
328 let nread = self.cap - self.pos;
329 buf.extend_from_slice(&self.buffer());
330 self.discard_buffer();
331 Ok(nread + self.inner.read_to_end(buf)?)
334 // The inner reader might have an optimized `read_to_end`. Drain our buffer and then
335 // delegate to the inner implementation.
336 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
337 // In the general `else` case below we must read bytes into a side buffer, check
338 // that they are valid UTF-8, and then append them to `buf`. This requires a
339 // potentially large memcpy.
341 // If `buf` is empty--the most common case--we can leverage `append_to_string`
342 // to read directly into `buf`'s internal byte buffer, saving an allocation and
345 // `append_to_string`'s safety relies on the buffer only being appended to since
346 // it only checks the UTF-8 validity of new data. If there were existing content in
347 // `buf` then an untrustworthy reader (i.e. `self.inner`) could not only append
348 // bytes but also modify existing bytes and render them invalid. On the other hand,
349 // if `buf` is empty then by definition any writes must be appends and
350 // `append_to_string` will validate all of the new bytes.
351 unsafe { crate::io::append_to_string(buf, |b| self.read_to_end(b)) }
353 // We cannot append our byte buffer directly onto the `buf` String as there could
354 // be an incomplete UTF-8 sequence that has only been partially read. We must read
355 // everything into a side buffer first and then call `from_utf8` on the complete
357 let mut bytes = Vec::new();
358 self.read_to_end(&mut bytes)?;
359 let string = crate::str::from_utf8(&bytes).map_err(|_| {
360 io::Error::new_const(
361 io::ErrorKind::InvalidData,
362 &"stream did not contain valid UTF-8",
371 #[stable(feature = "rust1", since = "1.0.0")]
372 impl<R: Read> BufRead for BufReader<R> {
373 fn fill_buf(&mut self) -> io::Result<&[u8]> {
374 // If we've reached the end of our internal buffer then we need to fetch
375 // some more data from the underlying reader.
376 // Branch using `>=` instead of the more correct `==`
377 // to tell the compiler that the pos..cap slice is always valid.
378 if self.pos >= self.cap {
379 debug_assert!(self.pos == self.cap);
381 let mut readbuf = ReadBuf::uninit(&mut self.buf);
383 // SAFETY: `self.init` is either 0 or set to `readbuf.initialized_len()`
384 // from the last time this function was called
386 readbuf.assume_init(self.init);
389 self.inner.read_buf(&mut readbuf)?;
391 self.cap = readbuf.filled_len();
392 self.init = readbuf.initialized_len();
399 fn consume(&mut self, amt: usize) {
400 self.pos = cmp::min(self.pos + amt, self.cap);
404 #[stable(feature = "rust1", since = "1.0.0")]
405 impl<R> fmt::Debug for BufReader<R>
409 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
410 fmt.debug_struct("BufReader")
411 .field("reader", &self.inner)
412 .field("buffer", &format_args!("{}/{}", self.cap - self.pos, self.buf.len()))
417 #[stable(feature = "rust1", since = "1.0.0")]
418 impl<R: Seek> Seek for BufReader<R> {
419 /// Seek to an offset, in bytes, in the underlying reader.
421 /// The position used for seeking with <code>[SeekFrom::Current]\(_)</code> is the
422 /// position the underlying reader would be at if the `BufReader<R>` had no
425 /// Seeking always discards the internal buffer, even if the seek position
426 /// would otherwise fall within it. This guarantees that calling
427 /// [`BufReader::into_inner()`] immediately after a seek yields the underlying reader
428 /// at the same position.
430 /// To seek without discarding the internal buffer, use [`BufReader::seek_relative`].
432 /// See [`std::io::Seek`] for more details.
434 /// Note: In the edge case where you're seeking with <code>[SeekFrom::Current]\(n)</code>
435 /// where `n` minus the internal buffer length overflows an `i64`, two
436 /// seeks will be performed instead of one. If the second seek returns
437 /// [`Err`], the underlying reader will be left at the same position it would
438 /// have if you called `seek` with <code>[SeekFrom::Current]\(0)</code>.
440 /// [`std::io::Seek`]: Seek
441 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
443 if let SeekFrom::Current(n) = pos {
444 let remainder = (self.cap - self.pos) as i64;
445 // it should be safe to assume that remainder fits within an i64 as the alternative
446 // means we managed to allocate 8 exbibytes and that's absurd.
447 // But it's not out of the realm of possibility for some weird underlying reader to
448 // support seeking by i64::MIN so we need to handle underflow when subtracting
450 if let Some(offset) = n.checked_sub(remainder) {
451 result = self.inner.seek(SeekFrom::Current(offset))?;
453 // seek backwards by our remainder, and then by the offset
454 self.inner.seek(SeekFrom::Current(-remainder))?;
455 self.discard_buffer();
456 result = self.inner.seek(SeekFrom::Current(n))?;
459 // Seeking with Start/End doesn't care about our buffer length.
460 result = self.inner.seek(pos)?;
462 self.discard_buffer();
466 /// Returns the current seek position from the start of the stream.
468 /// The value returned is equivalent to `self.seek(SeekFrom::Current(0))`
469 /// but does not flush the internal buffer. Due to this optimization the
470 /// function does not guarantee that calling `.into_inner()` immediately
471 /// afterwards will yield the underlying reader at the same position. Use
472 /// [`BufReader::seek`] instead if you require that guarantee.
476 /// This function will panic if the position of the inner reader is smaller
477 /// than the amount of buffered data. That can happen if the inner reader
478 /// has an incorrect implementation of [`Seek::stream_position`], or if the
479 /// position has gone out of sync due to calling [`Seek::seek`] directly on
480 /// the underlying reader.
486 /// io::{self, BufRead, BufReader, Seek},
490 /// fn main() -> io::Result<()> {
491 /// let mut f = BufReader::new(File::open("foo.txt")?);
493 /// let before = f.stream_position()?;
494 /// f.read_line(&mut String::new())?;
495 /// let after = f.stream_position()?;
497 /// println!("The first line was {} bytes long", after - before);
501 fn stream_position(&mut self) -> io::Result<u64> {
502 let remainder = (self.cap - self.pos) as u64;
503 self.inner.stream_position().map(|pos| {
504 pos.checked_sub(remainder).expect(
505 "overflow when subtracting remaining buffer size from inner stream position",
511 impl<T> SizeHint for BufReader<T> {
513 fn lower_bound(&self) -> usize {
514 SizeHint::lower_bound(self.get_ref()) + self.buffer().len()
518 fn upper_bound(&self) -> Option<usize> {
519 SizeHint::upper_bound(self.get_ref()).and_then(|up| self.buffer().len().checked_add(up))