]> git.lizzy.rs Git - rust.git/blob - library/std/src/io/buffered/bufreader.rs
Move `{core,std}::stream::Stream` to `{core,std}::async_iter::AsyncIterator`.
[rust.git] / library / std / src / io / buffered / bufreader.rs
1 use crate::cmp;
2 use crate::fmt;
3 use crate::io::{
4     self, BufRead, IoSliceMut, Read, ReadBuf, Seek, SeekFrom, SizeHint, DEFAULT_BUF_SIZE,
5 };
6 use crate::mem::MaybeUninit;
7
8 /// The `BufReader<R>` struct adds buffering to any reader.
9 ///
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.
14 ///
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>.
20 ///
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
25 /// data loss.
26 ///
27 // HACK(#78696): can't use `crate` for associated items
28 /// [`TcpStream::read`]: super::super::super::net::TcpStream::read
29 /// [`TcpStream`]: crate::net::TcpStream
30 ///
31 /// # Examples
32 ///
33 /// ```no_run
34 /// use std::io::prelude::*;
35 /// use std::io::BufReader;
36 /// use std::fs::File;
37 ///
38 /// fn main() -> std::io::Result<()> {
39 ///     let f = File::open("log.txt")?;
40 ///     let mut reader = BufReader::new(f);
41 ///
42 ///     let mut line = String::new();
43 ///     let len = reader.read_line(&mut line)?;
44 ///     println!("First line is {} bytes long", len);
45 ///     Ok(())
46 /// }
47 /// ```
48 #[stable(feature = "rust1", since = "1.0.0")]
49 pub struct BufReader<R> {
50     inner: R,
51     buf: Box<[MaybeUninit<u8>]>,
52     pos: usize,
53     cap: usize,
54     init: usize,
55 }
56
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.
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     /// Creates a new `BufReader<R>` with the specified buffer capacity.
79     ///
80     /// # Examples
81     ///
82     /// Creating a buffer with ten bytes of capacity:
83     ///
84     /// ```no_run
85     /// use std::io::BufReader;
86     /// use std::fs::File;
87     ///
88     /// fn main() -> std::io::Result<()> {
89     ///     let f = File::open("log.txt")?;
90     ///     let reader = BufReader::with_capacity(10, f);
91     ///     Ok(())
92     /// }
93     /// ```
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 }
98     }
99 }
100
101 impl<R> BufReader<R> {
102     /// Gets a reference to the underlying reader.
103     ///
104     /// It is inadvisable to directly read from the underlying reader.
105     ///
106     /// # Examples
107     ///
108     /// ```no_run
109     /// use std::io::BufReader;
110     /// use std::fs::File;
111     ///
112     /// fn main() -> std::io::Result<()> {
113     ///     let f1 = File::open("log.txt")?;
114     ///     let reader = BufReader::new(f1);
115     ///
116     ///     let f2 = reader.get_ref();
117     ///     Ok(())
118     /// }
119     /// ```
120     #[stable(feature = "rust1", since = "1.0.0")]
121     pub fn get_ref(&self) -> &R {
122         &self.inner
123     }
124
125     /// Gets a mutable reference to the underlying reader.
126     ///
127     /// It is inadvisable to directly read from the underlying reader.
128     ///
129     /// # Examples
130     ///
131     /// ```no_run
132     /// use std::io::BufReader;
133     /// use std::fs::File;
134     ///
135     /// fn main() -> std::io::Result<()> {
136     ///     let f1 = File::open("log.txt")?;
137     ///     let mut reader = BufReader::new(f1);
138     ///
139     ///     let f2 = reader.get_mut();
140     ///     Ok(())
141     /// }
142     /// ```
143     #[stable(feature = "rust1", since = "1.0.0")]
144     pub fn get_mut(&mut self) -> &mut R {
145         &mut self.inner
146     }
147
148     /// Returns a reference to the internally buffered data.
149     ///
150     /// Unlike [`fill_buf`], this will not attempt to fill the buffer if it is empty.
151     ///
152     /// [`fill_buf`]: BufRead::fill_buf
153     ///
154     /// # Examples
155     ///
156     /// ```no_run
157     /// use std::io::{BufReader, BufRead};
158     /// use std::fs::File;
159     ///
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());
164     ///
165     ///     if reader.fill_buf()?.len() > 0 {
166     ///         assert!(!reader.buffer().is_empty());
167     ///     }
168     ///     Ok(())
169     /// }
170     /// ```
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]) }
175     }
176
177     /// Returns the number of bytes the internal buffer can hold at once.
178     ///
179     /// # Examples
180     ///
181     /// ```no_run
182     /// use std::io::{BufReader, BufRead};
183     /// use std::fs::File;
184     ///
185     /// fn main() -> std::io::Result<()> {
186     ///     let f = File::open("log.txt")?;
187     ///     let mut reader = BufReader::new(f);
188     ///
189     ///     let capacity = reader.capacity();
190     ///     let buffer = reader.fill_buf()?;
191     ///     assert!(buffer.len() <= capacity);
192     ///     Ok(())
193     /// }
194     /// ```
195     #[stable(feature = "buffered_io_capacity", since = "1.46.0")]
196     pub fn capacity(&self) -> usize {
197         self.buf.len()
198     }
199
200     /// Unwraps this `BufReader<R>`, returning the underlying reader.
201     ///
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.
204     ///
205     /// # Examples
206     ///
207     /// ```no_run
208     /// use std::io::BufReader;
209     /// use std::fs::File;
210     ///
211     /// fn main() -> std::io::Result<()> {
212     ///     let f1 = File::open("log.txt")?;
213     ///     let reader = BufReader::new(f1);
214     ///
215     ///     let f2 = reader.into_inner();
216     ///     Ok(())
217     /// }
218     /// ```
219     #[stable(feature = "rust1", since = "1.0.0")]
220     pub fn into_inner(self) -> R {
221         self.inner
222     }
223
224     /// Invalidates all data in the internal buffer.
225     #[inline]
226     fn discard_buffer(&mut self) {
227         self.pos = 0;
228         self.cap = 0;
229     }
230 }
231
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;
240         if offset < 0 {
241             if let Some(new_pos) = pos.checked_sub((-offset) as u64) {
242                 self.pos = new_pos as usize;
243                 return Ok(());
244             }
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;
248                 return Ok(());
249             }
250         }
251
252         self.seek(SeekFrom::Current(offset)).map(drop)
253     }
254 }
255
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
261         // entirely.
262         if self.pos == self.cap && buf.len() >= self.buf.len() {
263             self.discard_buffer();
264             return self.inner.read(buf);
265         }
266         let nread = {
267             let mut rem = self.fill_buf()?;
268             rem.read(buf)?
269         };
270         self.consume(nread);
271         Ok(nread)
272     }
273
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
277         // entirely.
278         if self.pos == self.cap && buf.remaining() >= self.buf.len() {
279             self.discard_buffer();
280             return self.inner.read_buf(buf);
281         }
282
283         let prev = buf.filled_len();
284
285         let mut rem = self.fill_buf()?;
286         rem.read_buf(buf)?;
287
288         self.consume(buf.filled_len() - prev); //slice impl of read_buf known to never unfill buf
289
290         Ok(())
291     }
292
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
296     // buffer.
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());
301             return Ok(());
302         }
303
304         crate::io::default_read_exact(self, buf)
305     }
306
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);
312         }
313         let nread = {
314             let mut rem = self.fill_buf()?;
315             rem.read_vectored(bufs)?
316         };
317         self.consume(nread);
318         Ok(nread)
319     }
320
321     fn is_read_vectored(&self) -> bool {
322         self.inner.is_read_vectored()
323     }
324
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)?)
332     }
333
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.
340         //
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
343         // a memcpy.
344         if buf.is_empty() {
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)) }
352         } else {
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
356             // buffer.
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",
363                 )
364             })?;
365             *buf += string;
366             Ok(string.len())
367         }
368     }
369 }
370
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);
380
381             let mut readbuf = ReadBuf::uninit(&mut self.buf);
382
383             // SAFETY: `self.init` is either 0 or set to `readbuf.initialized_len()`
384             // from the last time this function was called
385             unsafe {
386                 readbuf.assume_init(self.init);
387             }
388
389             self.inner.read_buf(&mut readbuf)?;
390
391             self.cap = readbuf.filled_len();
392             self.init = readbuf.initialized_len();
393
394             self.pos = 0;
395         }
396         Ok(self.buffer())
397     }
398
399     fn consume(&mut self, amt: usize) {
400         self.pos = cmp::min(self.pos + amt, self.cap);
401     }
402 }
403
404 #[stable(feature = "rust1", since = "1.0.0")]
405 impl<R> fmt::Debug for BufReader<R>
406 where
407     R: fmt::Debug,
408 {
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()))
413             .finish()
414     }
415 }
416
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.
420     ///
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
423     /// internal buffer.
424     ///
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.
429     ///
430     /// To seek without discarding the internal buffer, use [`BufReader::seek_relative`].
431     ///
432     /// See [`std::io::Seek`] for more details.
433     ///
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>.
439     ///
440     /// [`std::io::Seek`]: Seek
441     fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
442         let 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
449             // remainder.
450             if let Some(offset) = n.checked_sub(remainder) {
451                 result = self.inner.seek(SeekFrom::Current(offset))?;
452             } else {
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))?;
457             }
458         } else {
459             // Seeking with Start/End doesn't care about our buffer length.
460             result = self.inner.seek(pos)?;
461         }
462         self.discard_buffer();
463         Ok(result)
464     }
465
466     /// Returns the current seek position from the start of the stream.
467     ///
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.
473     ///
474     /// # Panics
475     ///
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.
481     ///
482     /// # Example
483     ///
484     /// ```no_run
485     /// use std::{
486     ///     io::{self, BufRead, BufReader, Seek},
487     ///     fs::File,
488     /// };
489     ///
490     /// fn main() -> io::Result<()> {
491     ///     let mut f = BufReader::new(File::open("foo.txt")?);
492     ///
493     ///     let before = f.stream_position()?;
494     ///     f.read_line(&mut String::new())?;
495     ///     let after = f.stream_position()?;
496     ///
497     ///     println!("The first line was {} bytes long", after - before);
498     ///     Ok(())
499     /// }
500     /// ```
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",
506             )
507         })
508     }
509 }
510
511 impl<T> SizeHint for BufReader<T> {
512     #[inline]
513     fn lower_bound(&self) -> usize {
514         SizeHint::lower_bound(self.get_ref()) + self.buffer().len()
515     }
516
517     #[inline]
518     fn upper_bound(&self) -> Option<usize> {
519         SizeHint::upper_bound(self.get_ref()).and_then(|up| self.buffer().len().checked_add(up))
520     }
521 }