Skip to main content

ax_io/buffered/bufreader/
mod.rs

1mod buffer;
2
3#[cfg(feature = "alloc")]
4use alloc::{string::String, vec::Vec};
5use core::{fmt, io::BorrowedCursor};
6
7use self::buffer::Buffer;
8#[cfg(feature = "alloc")]
9use crate::Error;
10use crate::{BufRead, DEFAULT_BUF_SIZE, IoBuf, Read, Result, Seek, SeekFrom};
11
12/// The `BufReader<R>` struct adds buffering to any reader.
13///
14/// See [`std::io::BufReader`] for more details.
15pub struct BufReader<R: ?Sized> {
16    buf: Buffer,
17    inner: R,
18}
19
20impl<R: Read> BufReader<R> {
21    /// Creates a new `BufReader<R>` with the specified buffer capacity.
22    pub fn with_capacity(capacity: usize, inner: R) -> BufReader<R> {
23        BufReader {
24            buf: Buffer::with_capacity(capacity),
25            inner,
26        }
27    }
28
29    /// Creates a new `BufReader<R>` with a default buffer capacity.
30    pub fn new(inner: R) -> BufReader<R> {
31        BufReader::with_capacity(DEFAULT_BUF_SIZE, inner)
32    }
33}
34
35impl<R: ?Sized> BufReader<R> {
36    /// Gets a reference to the underlying reader.
37    ///
38    /// It is inadvisable to directly read from the underlying reader.
39    pub fn get_ref(&self) -> &R {
40        &self.inner
41    }
42
43    /// Gets a mutable reference to the underlying reader.
44    ///
45    /// It is inadvisable to directly read from the underlying reader.
46    pub fn get_mut(&mut self) -> &mut R {
47        &mut self.inner
48    }
49
50    /// Returns a reference to the internally buffered data.
51    ///
52    /// Unlike [`fill_buf`], this will not attempt to fill the buffer if it is empty.
53    ///
54    /// [`fill_buf`]: BufRead::fill_buf
55    pub fn buffer(&self) -> &[u8] {
56        self.buf.buffer()
57    }
58
59    /// Returns the number of bytes the internal buffer can hold at once.
60    pub fn capacity(&self) -> usize {
61        self.buf.capacity()
62    }
63
64    #[doc(hidden)]
65    pub fn initialized(&self) -> bool {
66        self.buf.initialized()
67    }
68
69    /// Unwraps this `BufReader<R>`, returning the underlying reader.
70    ///
71    /// Note that any leftover data in the internal buffer is lost. Therefore,
72    /// a following read from the underlying reader may lead to data loss.
73    pub fn into_inner(self) -> R
74    where
75        R: Sized,
76    {
77        self.inner
78    }
79
80    /// Invalidates all data in the internal buffer.
81    #[inline]
82    pub(crate) fn discard_buffer(&mut self) {
83        self.buf.discard_buffer()
84    }
85
86    #[inline]
87    pub(crate) fn consume(&mut self, amt: usize) {
88        self.buf.consume(amt)
89    }
90}
91
92impl<R: Read + ?Sized> BufReader<R> {
93    /// Attempt to look ahead `n` bytes.
94    ///
95    /// `n` must be less than or equal to `capacity`.
96    ///
97    /// The returned slice may be less than `n` bytes long if
98    /// end of file is reached.
99    ///
100    /// After calling this method, you may call [`consume`](BufRead::consume)
101    /// with a value less than or equal to `n` to advance over some or all of
102    /// the returned bytes.
103    pub fn peek(&mut self, n: usize) -> Result<&[u8]> {
104        assert!(n <= self.capacity());
105        while n > self.buf.buffer().len() {
106            if self.buf.pos() > 0 {
107                self.buf.backshift();
108            }
109            let new = self.buf.read_more(&mut self.inner)?;
110            if new == 0 {
111                // end of file, no more bytes to read
112                return Ok(self.buf.buffer());
113            }
114            debug_assert_eq!(self.buf.pos(), 0);
115        }
116        Ok(&self.buf.buffer()[..n])
117    }
118}
119
120impl<R> fmt::Debug for BufReader<R>
121where
122    R: ?Sized + fmt::Debug,
123{
124    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
125        fmt.debug_struct("BufReader")
126            .field("reader", &&self.inner)
127            .field(
128                "buffer",
129                &format_args!("{}/{}", self.buf.filled() - self.buf.pos(), self.capacity()),
130            )
131            .finish()
132    }
133}
134
135impl<R: ?Sized + Read> Read for BufReader<R> {
136    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
137        // If we don't have any buffered data and we're doing a massive read
138        // (larger than our internal buffer), bypass our internal buffer
139        // entirely.
140        if self.buf.pos() == self.buf.filled() && buf.len() >= self.capacity() {
141            self.discard_buffer();
142            return self.inner.read(buf);
143        }
144        let mut rem = self.fill_buf()?;
145        let nread = rem.read(buf)?;
146        self.consume(nread);
147        Ok(nread)
148    }
149
150    fn read_buf(&mut self, mut cursor: BorrowedCursor<'_>) -> Result<()> {
151        // If we don't have any buffered data and we're doing a massive read
152        // (larger than our internal buffer), bypass our internal buffer
153        // entirely.
154        if self.buf.pos() == self.buf.filled() && cursor.capacity() >= self.capacity() {
155            self.discard_buffer();
156            return self.inner.read_buf(cursor);
157        }
158
159        let prev = cursor.written();
160
161        let mut rem = self.fill_buf()?;
162        rem.read_buf(cursor.reborrow())?; // actually never fails
163
164        self.consume(cursor.written() - prev); // slice impl of read_buf known to never unfill buf
165
166        Ok(())
167    }
168
169    // Small read_exacts from a BufReader are extremely common when used with a deserializer.
170    // The default implementation calls read in a loop, which results in surprisingly poor code
171    // generation for the common path where the buffer has enough bytes to fill the passed-in
172    // buffer.
173    fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
174        if self
175            .buf
176            .consume_with(buf.len(), |claimed| buf.copy_from_slice(claimed))
177        {
178            return Ok(());
179        }
180
181        crate::default_read_exact(self, buf)
182    }
183
184    fn read_buf_exact(&mut self, mut cursor: BorrowedCursor<'_>) -> Result<()> {
185        if self
186            .buf
187            .consume_with(cursor.capacity(), |claimed| cursor.append(claimed))
188        {
189            return Ok(());
190        }
191
192        crate::default_read_buf_exact(self, cursor)
193    }
194
195    // The inner reader might have an optimized `read_to_end`. Drain our buffer and then
196    // delegate to the inner implementation.
197    #[cfg(feature = "alloc")]
198    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
199        let inner_buf = self.buffer();
200        buf.try_reserve(inner_buf.len())
201            .map_err(|_| Error::NoMemory)?;
202        buf.extend_from_slice(inner_buf);
203        let nread = inner_buf.len();
204        self.discard_buffer();
205        Ok(nread + self.inner.read_to_end(buf)?)
206    }
207
208    // The inner reader might have an optimized `read_to_end`. Drain our buffer and then
209    // delegate to the inner implementation.
210    #[cfg(feature = "alloc")]
211    fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
212        // In the general `else` case below we must read bytes into a side buffer, check
213        // that they are valid UTF-8, and then append them to `buf`. This requires a
214        // potentially large memcpy.
215        //
216        // If `buf` is empty--the most common case--we can leverage `append_to_string`
217        // to read directly into `buf`'s internal byte buffer, saving an allocation and
218        // a memcpy.
219
220        if buf.is_empty() {
221            // `append_to_string`'s safety relies on the buffer only being appended to since
222            // it only checks the UTF-8 validity of new data. If there were existing content in
223            // `buf` then an untrustworthy reader (i.e. `self.inner`) could not only append
224            // bytes but also modify existing bytes and render them invalid. On the other hand,
225            // if `buf` is empty then by definition any writes must be appends and
226            // `append_to_string` will validate all of the new bytes.
227            unsafe { crate::append_to_string(buf, |b| self.read_to_end(b)) }
228        } else {
229            // We cannot append our byte buffer directly onto the `buf` String as there could
230            // be an incomplete UTF-8 sequence that has only been partially read. We must read
231            // everything into a side buffer first and then call `from_utf8` on the complete
232            // buffer.
233            let mut bytes = Vec::new();
234            self.read_to_end(&mut bytes)?;
235            let string = str::from_utf8(&bytes).map_err(|_| Error::IllegalBytes)?;
236            *buf += string;
237            Ok(string.len())
238        }
239    }
240}
241
242impl<R: ?Sized + Read> BufRead for BufReader<R> {
243    fn fill_buf(&mut self) -> Result<&[u8]> {
244        self.buf.fill_buf(&mut self.inner)
245    }
246
247    fn consume(&mut self, amt: usize) {
248        self.buf.consume(amt)
249    }
250}
251
252impl<R: ?Sized + Seek> Seek for BufReader<R> {
253    /// Seek to an offset, in bytes, in the underlying reader.
254    ///
255    /// The position used for seeking with <code>[SeekFrom::Current]\(_)</code> is the
256    /// position the underlying reader would be at if the `BufReader<R>` had no
257    /// internal buffer.
258    ///
259    /// Seeking always discards the internal buffer, even if the seek position
260    /// would otherwise fall within it. This guarantees that calling
261    /// [`BufReader::into_inner()`] immediately after a seek yields the underlying reader
262    /// at the same position.
263    ///
264    /// To seek without discarding the internal buffer, use [`BufReader::seek_relative`].
265    ///
266    /// See [`Seek`] for more details.
267    ///
268    /// Note: In the edge case where you're seeking with <code>[SeekFrom::Current]\(n)</code>
269    /// where `n` minus the internal buffer length overflows an `i64`, two
270    /// seeks will be performed instead of one. If the second seek returns
271    /// [`Err`], the underlying reader will be left at the same position it would
272    /// have if you called `seek` with <code>[SeekFrom::Current]\(0)</code>.
273    fn seek(&mut self, pos: SeekFrom) -> Result<u64> {
274        let result: u64;
275        if let SeekFrom::Current(n) = pos {
276            let remainder = (self.buf.filled() - self.buf.pos()) as i64;
277            // it should be safe to assume that remainder fits within an i64 as the alternative
278            // means we managed to allocate 8 exbibytes and that's absurd.
279            // But it's not out of the realm of possibility for some weird underlying reader to
280            // support seeking by i64::MIN so we need to handle underflow when subtracting
281            // remainder.
282            if let Some(offset) = n.checked_sub(remainder) {
283                result = self.inner.seek(SeekFrom::Current(offset))?;
284            } else {
285                // seek backwards by our remainder, and then by the offset
286                self.inner.seek(SeekFrom::Current(-remainder))?;
287                self.discard_buffer();
288                result = self.inner.seek(SeekFrom::Current(n))?;
289            }
290        } else {
291            // Seeking with Start/End doesn't care about our buffer length.
292            result = self.inner.seek(pos)?;
293        }
294        self.discard_buffer();
295        Ok(result)
296    }
297
298    /// Returns the current seek position from the start of the stream.
299    ///
300    /// The value returned is equivalent to `self.seek(SeekFrom::Current(0))`
301    /// but does not flush the internal buffer. Due to this optimization the
302    /// function does not guarantee that calling `.into_inner()` immediately
303    /// afterwards will yield the underlying reader at the same position. Use
304    /// [`BufReader::seek`] instead if you require that guarantee.
305    ///
306    /// # Panics
307    ///
308    /// This function will panic if the position of the inner reader is smaller
309    /// than the amount of buffered data. That can happen if the inner reader
310    /// has an incorrect implementation of [`Seek::stream_position`], or if the
311    /// position has gone out of sync due to calling [`Seek::seek`] directly on
312    /// the underlying reader.
313    fn stream_position(&mut self) -> Result<u64> {
314        let remainder = (self.buf.filled() - self.buf.pos()) as u64;
315        self.inner.stream_position().map(|pos| {
316            pos.checked_sub(remainder).expect(
317                "overflow when subtracting remaining buffer size from inner stream position",
318            )
319        })
320    }
321
322    /// Seeks relative to the current position.
323    ///
324    /// If the new position lies within the buffer, the buffer will not be
325    /// flushed, allowing for more efficient seeks. This method does not return
326    /// the location of the underlying reader, so the caller must track this
327    /// information themselves if it is required.
328    fn seek_relative(&mut self, offset: i64) -> Result<()> {
329        let pos = self.buf.pos() as u64;
330        if offset < 0 {
331            if pos.checked_sub((-offset) as u64).is_some() {
332                self.buf.unconsume((-offset) as usize);
333                return Ok(());
334            }
335        } else if let Some(new_pos) = pos.checked_add(offset as u64)
336            && new_pos <= self.buf.filled() as u64
337        {
338            self.buf.consume(offset as usize);
339            return Ok(());
340        }
341
342        self.seek(SeekFrom::Current(offset)).map(drop)
343    }
344}
345
346impl<R: ?Sized + IoBuf> IoBuf for BufReader<R> {
347    #[inline]
348    fn remaining(&self) -> usize {
349        self.inner.remaining() + self.buf.filled() - self.buf.pos()
350    }
351}