Skip to main content

std/io/buffered/
bufreader.rs

1mod buffer;
2
3use buffer::Buffer;
4
5use crate::fmt;
6use crate::io::{
7    self, BorrowedCursor, BufRead, DEFAULT_BUF_SIZE, IoSliceMut, Read, Seek, SeekFrom, SizeHint,
8    SpecReadByte, uninlined_slow_read_byte,
9};
10
11/// The `BufReader<R>` struct adds buffering to any reader.
12///
13/// It can be excessively inefficient to work directly with a [`Read`] instance.
14/// For example, every call to [`read`][`TcpStream::read`] on [`TcpStream`]
15/// results in a system call. A `BufReader<R>` performs large, infrequent reads on
16/// the underlying [`Read`] and maintains an in-memory buffer of the results.
17///
18/// `BufReader<R>` can improve the speed of programs that make *small* and
19/// *repeated* read calls to the same file or network socket. It does not
20/// help when reading very large amounts at once, or reading just one or a few
21/// times. It also provides no advantage when reading from a source that is
22/// already in memory, like a <code>[Vec]\<u8></code>.
23///
24/// When the `BufReader<R>` is dropped, the contents of its buffer will be
25/// discarded. Creating multiple instances of a `BufReader<R>` on the same
26/// stream can cause data loss. Reading from the underlying reader after
27/// unwrapping the `BufReader<R>` with [`BufReader::into_inner`] can also cause
28/// data loss.
29///
30/// [`TcpStream::read`]: crate::net::TcpStream::read
31/// [`TcpStream`]: crate::net::TcpStream
32///
33/// # Examples
34///
35/// ```no_run
36/// use std::io::prelude::*;
37/// use std::io::BufReader;
38/// use std::fs::File;
39///
40/// fn main() -> std::io::Result<()> {
41///     let f = File::open("log.txt")?;
42///     let mut reader = BufReader::new(f);
43///
44///     let mut line = String::new();
45///     let len = reader.read_line(&mut line)?;
46///     println!("First line is {len} bytes long");
47///     Ok(())
48/// }
49/// ```
50#[stable(feature = "rust1", since = "1.0.0")]
51#[cfg_attr(not(test), rustc_diagnostic_item = "IoBufReader")]
52pub struct BufReader<R: ?Sized> {
53    buf: Buffer,
54    inner: R,
55}
56
57impl<R: Read> BufReader<R> {
58    /// Creates a new `BufReader<R>` with a default buffer capacity. The default is currently 8 KiB,
59    /// but may change in the future.
60    ///
61    /// # Examples
62    ///
63    /// ```no_run
64    /// use std::io::BufReader;
65    /// use std::fs::File;
66    ///
67    /// fn main() -> std::io::Result<()> {
68    ///     let f = File::open("log.txt")?;
69    ///     let reader = BufReader::new(f);
70    ///     Ok(())
71    /// }
72    /// ```
73    #[stable(feature = "rust1", since = "1.0.0")]
74    pub fn new(inner: R) -> BufReader<R> {
75        BufReader::with_capacity(DEFAULT_BUF_SIZE, inner)
76    }
77
78    pub(crate) fn try_new_buffer() -> io::Result<Buffer> {
79        Buffer::try_with_capacity(DEFAULT_BUF_SIZE)
80    }
81
82    pub(crate) fn with_buffer(inner: R, buf: Buffer) -> Self {
83        Self { inner, buf }
84    }
85
86    /// Creates a new `BufReader<R>` with the specified buffer capacity.
87    ///
88    /// # Examples
89    ///
90    /// Creating a buffer with ten bytes of capacity:
91    ///
92    /// ```no_run
93    /// use std::io::BufReader;
94    /// use std::fs::File;
95    ///
96    /// fn main() -> std::io::Result<()> {
97    ///     let f = File::open("log.txt")?;
98    ///     let reader = BufReader::with_capacity(10, f);
99    ///     Ok(())
100    /// }
101    /// ```
102    #[stable(feature = "rust1", since = "1.0.0")]
103    pub fn with_capacity(capacity: usize, inner: R) -> BufReader<R> {
104        BufReader { inner, buf: Buffer::with_capacity(capacity) }
105    }
106}
107
108impl<R: Read + ?Sized> BufReader<R> {
109    /// Attempt to look ahead `n` bytes.
110    ///
111    /// `n` must be less than or equal to `capacity`.
112    ///
113    /// The returned slice may be less than `n` bytes long if
114    /// end of file is reached.
115    ///
116    /// After calling this method, you may call [`consume`](BufRead::consume)
117    /// with a value less than or equal to `n` to advance over some or all of
118    /// the returned bytes.
119    ///
120    /// ## Examples
121    ///
122    /// ```rust
123    /// #![feature(bufreader_peek)]
124    /// use std::io::{Read, BufReader};
125    ///
126    /// let mut bytes = &b"oh, hello there"[..];
127    /// let mut rdr = BufReader::with_capacity(6, &mut bytes);
128    /// assert_eq!(rdr.peek(2).unwrap(), b"oh");
129    /// let mut buf = [0; 4];
130    /// rdr.read(&mut buf[..]).unwrap();
131    /// assert_eq!(&buf, b"oh, ");
132    /// assert_eq!(rdr.peek(5).unwrap(), b"hello");
133    /// let mut s = String::new();
134    /// rdr.read_to_string(&mut s).unwrap();
135    /// assert_eq!(&s, "hello there");
136    /// assert_eq!(rdr.peek(1).unwrap().len(), 0);
137    /// ```
138    #[unstable(feature = "bufreader_peek", issue = "128405")]
139    pub fn peek(&mut self, n: usize) -> io::Result<&[u8]> {
140        assert!(n <= self.capacity());
141        while n > self.buf.buffer().len() {
142            if self.buf.pos() > 0 {
143                self.buf.backshift();
144            }
145            let new = self.buf.read_more(&mut self.inner)?;
146            if new == 0 {
147                // end of file, no more bytes to read
148                return Ok(&self.buf.buffer()[..]);
149            }
150            debug_assert_eq!(self.buf.pos(), 0);
151        }
152        Ok(&self.buf.buffer()[..n])
153    }
154}
155
156impl<R: ?Sized> BufReader<R> {
157    /// Gets a reference to the underlying reader.
158    ///
159    /// It is inadvisable to directly read from the underlying reader.
160    ///
161    /// # Examples
162    ///
163    /// ```no_run
164    /// use std::io::BufReader;
165    /// use std::fs::File;
166    ///
167    /// fn main() -> std::io::Result<()> {
168    ///     let f1 = File::open("log.txt")?;
169    ///     let reader = BufReader::new(f1);
170    ///
171    ///     let f2 = reader.get_ref();
172    ///     Ok(())
173    /// }
174    /// ```
175    #[stable(feature = "rust1", since = "1.0.0")]
176    pub fn get_ref(&self) -> &R {
177        &self.inner
178    }
179
180    /// Gets a mutable reference to the underlying reader.
181    ///
182    /// It is inadvisable to directly read from the underlying reader.
183    ///
184    /// # Examples
185    ///
186    /// ```no_run
187    /// use std::io::BufReader;
188    /// use std::fs::File;
189    ///
190    /// fn main() -> std::io::Result<()> {
191    ///     let f1 = File::open("log.txt")?;
192    ///     let mut reader = BufReader::new(f1);
193    ///
194    ///     let f2 = reader.get_mut();
195    ///     Ok(())
196    /// }
197    /// ```
198    #[stable(feature = "rust1", since = "1.0.0")]
199    pub fn get_mut(&mut self) -> &mut R {
200        &mut self.inner
201    }
202
203    /// Returns a reference to the internally buffered data.
204    ///
205    /// Unlike [`fill_buf`], this will not attempt to fill the buffer if it is empty.
206    ///
207    /// [`fill_buf`]: BufRead::fill_buf
208    ///
209    /// # Examples
210    ///
211    /// ```no_run
212    /// use std::io::{BufReader, BufRead};
213    /// use std::fs::File;
214    ///
215    /// fn main() -> std::io::Result<()> {
216    ///     let f = File::open("log.txt")?;
217    ///     let mut reader = BufReader::new(f);
218    ///     assert!(reader.buffer().is_empty());
219    ///
220    ///     if reader.fill_buf()?.len() > 0 {
221    ///         assert!(!reader.buffer().is_empty());
222    ///     }
223    ///     Ok(())
224    /// }
225    /// ```
226    #[stable(feature = "bufreader_buffer", since = "1.37.0")]
227    pub fn buffer(&self) -> &[u8] {
228        self.buf.buffer()
229    }
230
231    /// Returns the number of bytes the internal buffer can hold at once.
232    ///
233    /// # Examples
234    ///
235    /// ```no_run
236    /// use std::io::{BufReader, BufRead};
237    /// use std::fs::File;
238    ///
239    /// fn main() -> std::io::Result<()> {
240    ///     let f = File::open("log.txt")?;
241    ///     let mut reader = BufReader::new(f);
242    ///
243    ///     let capacity = reader.capacity();
244    ///     let buffer = reader.fill_buf()?;
245    ///     assert!(buffer.len() <= capacity);
246    ///     Ok(())
247    /// }
248    /// ```
249    #[stable(feature = "buffered_io_capacity", since = "1.46.0")]
250    pub fn capacity(&self) -> usize {
251        self.buf.capacity()
252    }
253
254    /// Unwraps this `BufReader<R>`, returning the underlying reader.
255    ///
256    /// Note that any leftover data in the internal buffer is lost. Therefore,
257    /// a following read from the underlying reader may lead to data loss.
258    ///
259    /// # Examples
260    ///
261    /// ```no_run
262    /// use std::io::BufReader;
263    /// use std::fs::File;
264    ///
265    /// fn main() -> std::io::Result<()> {
266    ///     let f1 = File::open("log.txt")?;
267    ///     let reader = BufReader::new(f1);
268    ///
269    ///     let f2 = reader.into_inner();
270    ///     Ok(())
271    /// }
272    /// ```
273    #[stable(feature = "rust1", since = "1.0.0")]
274    pub fn into_inner(self) -> R
275    where
276        R: Sized,
277    {
278        self.inner
279    }
280
281    /// Invalidates all data in the internal buffer.
282    #[inline]
283    pub(in crate::io) fn discard_buffer(&mut self) {
284        self.buf.discard_buffer()
285    }
286}
287
288// This is only used by a test which asserts that the initialization-tracking is correct.
289#[cfg(test)]
290impl<R: ?Sized> BufReader<R> {
291    #[allow(missing_docs)]
292    pub fn initialized(&self) -> bool {
293        self.buf.initialized()
294    }
295}
296
297impl<R: ?Sized + Seek> BufReader<R> {
298    /// Seeks relative to the current position. If the new position lies within the buffer,
299    /// the buffer will not be flushed, allowing for more efficient seeks.
300    /// This method does not return the location of the underlying reader, so the caller
301    /// must track this information themselves if it is required.
302    #[stable(feature = "bufreader_seek_relative", since = "1.53.0")]
303    pub fn seek_relative(&mut self, offset: i64) -> io::Result<()> {
304        let pos = self.buf.pos() as u64;
305        if offset < 0 {
306            if let Some(_) = pos.checked_sub((-offset) as u64) {
307                self.buf.unconsume((-offset) as usize);
308                return Ok(());
309            }
310        } else if let Some(new_pos) = pos.checked_add(offset as u64) {
311            if new_pos <= self.buf.filled() as u64 {
312                self.buf.consume(offset as usize);
313                return Ok(());
314            }
315        }
316
317        self.seek(SeekFrom::Current(offset)).map(drop)
318    }
319}
320
321#[doc(hidden)]
322#[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
323impl<R> SpecReadByte for BufReader<R>
324where
325    Self: Read,
326{
327    #[inline]
328    fn spec_read_byte(&mut self) -> Option<io::Result<u8>> {
329        let mut byte = 0;
330        if self.buf.consume_with(1, |claimed| byte = claimed[0]) {
331            return Some(Ok(byte));
332        }
333
334        // Fallback case, only reached once per buffer refill.
335        uninlined_slow_read_byte(self)
336    }
337}
338
339#[stable(feature = "rust1", since = "1.0.0")]
340impl<R: ?Sized + Read> Read for BufReader<R> {
341    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
342        // If we don't have any buffered data and we're doing a massive read
343        // (larger than our internal buffer), bypass our internal buffer
344        // entirely.
345        if self.buf.pos() == self.buf.filled() && buf.len() >= self.capacity() {
346            self.discard_buffer();
347            return self.inner.read(buf);
348        }
349        let mut rem = self.fill_buf()?;
350        let nread = rem.read(buf)?;
351        self.consume(nread);
352        Ok(nread)
353    }
354
355    fn read_buf(&mut self, mut cursor: BorrowedCursor<'_, u8>) -> io::Result<()> {
356        // If we don't have any buffered data and we're doing a massive read
357        // (larger than our internal buffer), bypass our internal buffer
358        // entirely.
359        if self.buf.pos() == self.buf.filled() && cursor.capacity() >= self.capacity() {
360            self.discard_buffer();
361            return self.inner.read_buf(cursor);
362        }
363
364        let prev = cursor.written();
365
366        let mut rem = self.fill_buf()?;
367        rem.read_buf(cursor.reborrow())?; // actually never fails
368
369        self.consume(cursor.written() - prev); //slice impl of read_buf known to never unfill buf
370
371        Ok(())
372    }
373
374    // Small read_exacts from a BufReader are extremely common when used with a deserializer.
375    // The default implementation calls read in a loop, which results in surprisingly poor code
376    // generation for the common path where the buffer has enough bytes to fill the passed-in
377    // buffer.
378    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
379        if self.buf.consume_with(buf.len(), |claimed| buf.copy_from_slice(claimed)) {
380            return Ok(());
381        }
382
383        crate::io::default_read_exact(self, buf)
384    }
385
386    fn read_buf_exact(&mut self, mut cursor: BorrowedCursor<'_, u8>) -> io::Result<()> {
387        if self.buf.consume_with(cursor.capacity(), |claimed| cursor.append(claimed)) {
388            return Ok(());
389        }
390
391        crate::io::default_read_buf_exact(self, cursor)
392    }
393
394    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
395        let total_len = bufs.iter().map(|b| b.len()).sum::<usize>();
396        if self.buf.pos() == self.buf.filled() && total_len >= self.capacity() {
397            self.discard_buffer();
398            return self.inner.read_vectored(bufs);
399        }
400        let mut rem = self.fill_buf()?;
401        let nread = rem.read_vectored(bufs)?;
402
403        self.consume(nread);
404        Ok(nread)
405    }
406
407    fn is_read_vectored(&self) -> bool {
408        self.inner.is_read_vectored()
409    }
410
411    // The inner reader might have an optimized `read_to_end`. Drain our buffer and then
412    // delegate to the inner implementation.
413    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
414        let inner_buf = self.buffer();
415        buf.try_reserve(inner_buf.len())?;
416        buf.extend_from_slice(inner_buf);
417        let nread = inner_buf.len();
418        self.discard_buffer();
419        Ok(nread + self.inner.read_to_end(buf)?)
420    }
421
422    // The inner reader might have an optimized `read_to_end`. Drain our buffer and then
423    // delegate to the inner implementation.
424    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
425        // In the general `else` case below we must read bytes into a side buffer, check
426        // that they are valid UTF-8, and then append them to `buf`. This requires a
427        // potentially large memcpy.
428        //
429        // If `buf` is empty--the most common case--we can leverage `append_to_string`
430        // to read directly into `buf`'s internal byte buffer, saving an allocation and
431        // a memcpy.
432        if buf.is_empty() {
433            // `append_to_string`'s safety relies on the buffer only being appended to since
434            // it only checks the UTF-8 validity of new data. If there were existing content in
435            // `buf` then an untrustworthy reader (i.e. `self.inner`) could not only append
436            // bytes but also modify existing bytes and render them invalid. On the other hand,
437            // if `buf` is empty then by definition any writes must be appends and
438            // `append_to_string` will validate all of the new bytes.
439            unsafe { crate::io::append_to_string(buf, |b| self.read_to_end(b)) }
440        } else {
441            // We cannot append our byte buffer directly onto the `buf` String as there could
442            // be an incomplete UTF-8 sequence that has only been partially read. We must read
443            // everything into a side buffer first and then call `from_utf8` on the complete
444            // buffer.
445            let mut bytes = Vec::new();
446            self.read_to_end(&mut bytes)?;
447            let string = crate::str::from_utf8(&bytes).map_err(|_| io::Error::INVALID_UTF8)?;
448            *buf += string;
449            Ok(string.len())
450        }
451    }
452}
453
454#[stable(feature = "rust1", since = "1.0.0")]
455impl<R: ?Sized + Read> BufRead for BufReader<R> {
456    fn fill_buf(&mut self) -> io::Result<&[u8]> {
457        self.buf.fill_buf(&mut self.inner)
458    }
459
460    fn consume(&mut self, amt: usize) {
461        self.buf.consume(amt)
462    }
463}
464
465#[stable(feature = "rust1", since = "1.0.0")]
466impl<R> fmt::Debug for BufReader<R>
467where
468    R: ?Sized + fmt::Debug,
469{
470    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
471        fmt.debug_struct("BufReader")
472            .field("reader", &&self.inner)
473            .field(
474                "buffer",
475                &format_args!("{}/{}", self.buf.filled() - self.buf.pos(), self.capacity()),
476            )
477            .finish()
478    }
479}
480
481#[stable(feature = "rust1", since = "1.0.0")]
482impl<R: ?Sized + Seek> Seek for BufReader<R> {
483    /// Seek to an offset, in bytes, in the underlying reader.
484    ///
485    /// The position used for seeking with <code>[SeekFrom::Current]\(_)</code> is the
486    /// position the underlying reader would be at if the `BufReader<R>` had no
487    /// internal buffer.
488    ///
489    /// Seeking always discards the internal buffer, even if the seek position
490    /// would otherwise fall within it. This guarantees that calling
491    /// [`BufReader::into_inner()`] immediately after a seek yields the underlying reader
492    /// at the same position.
493    ///
494    /// To seek without discarding the internal buffer, use [`BufReader::seek_relative`].
495    ///
496    /// See [`std::io::Seek`] for more details.
497    ///
498    /// Note: In the edge case where you're seeking with <code>[SeekFrom::Current]\(n)</code>
499    /// where `n` minus the internal buffer length overflows an `i64`, two
500    /// seeks will be performed instead of one. If the second seek returns
501    /// [`Err`], the underlying reader will be left at the same position it would
502    /// have if you called `seek` with <code>[SeekFrom::Current]\(0)</code>.
503    ///
504    /// [`std::io::Seek`]: Seek
505    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
506        let result: u64;
507        if let SeekFrom::Current(n) = pos {
508            let remainder = (self.buf.filled() - self.buf.pos()) as i64;
509            // it should be safe to assume that remainder fits within an i64 as the alternative
510            // means we managed to allocate 8 exbibytes and that's absurd.
511            // But it's not out of the realm of possibility for some weird underlying reader to
512            // support seeking by i64::MIN so we need to handle underflow when subtracting
513            // remainder.
514            if let Some(offset) = n.checked_sub(remainder) {
515                result = self.inner.seek(SeekFrom::Current(offset))?;
516            } else {
517                // seek backwards by our remainder, and then by the offset
518                self.inner.seek(SeekFrom::Current(-remainder))?;
519                self.discard_buffer();
520                result = self.inner.seek(SeekFrom::Current(n))?;
521            }
522        } else {
523            // Seeking with Start/End doesn't care about our buffer length.
524            result = self.inner.seek(pos)?;
525        }
526        self.discard_buffer();
527        Ok(result)
528    }
529
530    /// Returns the current seek position from the start of the stream.
531    ///
532    /// The value returned is equivalent to `self.seek(SeekFrom::Current(0))`
533    /// but does not flush the internal buffer. Due to this optimization the
534    /// function does not guarantee that calling `.into_inner()` immediately
535    /// afterwards will yield the underlying reader at the same position. Use
536    /// [`BufReader::seek`] instead if you require that guarantee.
537    ///
538    /// # Panics
539    ///
540    /// This function will panic if the position of the inner reader is smaller
541    /// than the amount of buffered data. That can happen if the inner reader
542    /// has an incorrect implementation of [`Seek::stream_position`], or if the
543    /// position has gone out of sync due to calling [`Seek::seek`] directly on
544    /// the underlying reader.
545    ///
546    /// # Example
547    ///
548    /// ```no_run
549    /// use std::{
550    ///     io::{self, BufRead, BufReader, Seek},
551    ///     fs::File,
552    /// };
553    ///
554    /// fn main() -> io::Result<()> {
555    ///     let mut f = BufReader::new(File::open("foo.txt")?);
556    ///
557    ///     let before = f.stream_position()?;
558    ///     f.read_line(&mut String::new())?;
559    ///     let after = f.stream_position()?;
560    ///
561    ///     println!("The first line was {} bytes long", after - before);
562    ///     Ok(())
563    /// }
564    /// ```
565    fn stream_position(&mut self) -> io::Result<u64> {
566        let remainder = (self.buf.filled() - self.buf.pos()) as u64;
567        self.inner.stream_position().map(|pos| {
568            pos.checked_sub(remainder).expect(
569                "overflow when subtracting remaining buffer size from inner stream position",
570            )
571        })
572    }
573
574    /// Seeks relative to the current position.
575    ///
576    /// If the new position lies within the buffer, the buffer will not be
577    /// flushed, allowing for more efficient seeks. This method does not return
578    /// the location of the underlying reader, so the caller must track this
579    /// information themselves if it is required.
580    fn seek_relative(&mut self, offset: i64) -> io::Result<()> {
581        self.seek_relative(offset)
582    }
583}
584
585#[doc(hidden)]
586#[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
587impl<T: ?Sized> SizeHint for BufReader<T> {
588    #[inline]
589    fn lower_bound(&self) -> usize {
590        SizeHint::lower_bound(self.get_ref()) + self.buffer().len()
591    }
592
593    #[inline]
594    fn upper_bound(&self) -> Option<usize> {
595        SizeHint::upper_bound(self.get_ref()).and_then(|up| self.buffer().len().checked_add(up))
596    }
597}