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