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