1//! An encapsulation of `BufReader`'s buffer management logic.
2//!
3//! This module factors out the basic functionality of `BufReader` in order to protect two core
4//! invariants:
5//! * `filled` bytes of `buf` are always initialized
6//! * `pos` is always <= `filled`
7//! Since this module encapsulates the buffer management logic, we can ensure that the range
8//! `pos..filled` is always a valid index into the initialized region of the buffer. This means
9//! that user code which wants to do reads from a `BufReader` via `buffer` + `consume` can do so
10//! without encountering any runtime bounds checks.
1112use crate::cmp;
13use crate::io::{self, BorrowedBuf, ErrorKind, Read};
14use crate::mem::MaybeUninit;
1516pub struct Buffer {
17// The buffer.
18buf: Box<[MaybeUninit<u8>]>,
19// The current seek offset into `buf`, must always be <= `filled`.
20pos: usize,
21// Each call to `fill_buf` sets `filled` to indicate how many bytes at the start of `buf` are
22 // initialized with bytes from a read.
23filled: usize,
24// Whether `buf` has been fully initialized. We track this so that we can accurately tell
25 // `read_buf` how many bytes of buf are initialized, to bypass as much of its defensive
26 // initialization as possible. Calls to `fill_buf` are not required to actually fill the buffer,
27 // and omitting this is a huge perf regression for `Read` impls that do not.
28initialized: bool,
29}
3031impl Buffer {
32#[inline]
33pub fn with_capacity(capacity: usize) -> Self {
34let buf = Box::new_uninit_slice(capacity);
35Self { buf, pos: 0, filled: 0, initialized: false }
36 }
3738#[inline]
39pub fn try_with_capacity(capacity: usize) -> io::Result<Self> {
40match Box::try_new_uninit_slice(capacity) {
41Ok(buf) => Ok(Self { buf, pos: 0, filled: 0, initialized: false }),
42Err(_) => {
43Err(crate::hint::must_use(crate::io::Error::from_static_message(const {
&crate::io::SimpleMessage {
kind: ErrorKind::OutOfMemory,
message: "failed to allocate read buffer",
}
}))io::const_error!(ErrorKind::OutOfMemory, "failed to allocate read buffer"))
44 }
45 }
46 }
4748#[inline]
49pub fn buffer(&self) -> &[u8] {
50// SAFETY: self.pos and self.filled are valid, and self.filled >= self.pos, and
51 // that region is initialized because those are all invariants of this type.
52unsafe { self.buf.get_unchecked(self.pos..self.filled).assume_init_ref() }
53 }
5455#[inline]
56pub fn capacity(&self) -> usize {
57self.buf.len()
58 }
5960#[inline]
61pub fn filled(&self) -> usize {
62self.filled
63 }
6465#[inline]
66pub fn pos(&self) -> usize {
67self.pos
68 }
6970// This is only used by a test which asserts that the initialization-tracking is correct.
71#[cfg(test)]
72pub fn initialized(&self) -> bool {
73self.initialized
74 }
7576#[inline]
77pub fn discard_buffer(&mut self) {
78self.pos = 0;
79self.filled = 0;
80 }
8182#[inline]
83pub fn consume(&mut self, amt: usize) {
84self.pos = cmp::min(self.pos + amt, self.filled);
85 }
8687/// If there are `amt` bytes available in the buffer, pass a slice containing those bytes to
88 /// `visitor` and return true. If there are not enough bytes available, return false.
89#[inline]
90pub fn consume_with<V>(&mut self, amt: usize, mut visitor: V) -> bool91where
92V: FnMut(&[u8]),
93 {
94if let Some(claimed) = self.buffer().get(..amt) {
95visitor(claimed);
96// If the indexing into self.buffer() succeeds, amt must be a valid increment.
97self.pos += amt;
98true
99} else {
100false
101}
102 }
103104#[inline]
105pub fn unconsume(&mut self, amt: usize) {
106self.pos = self.pos.saturating_sub(amt);
107 }
108109/// Read more bytes into the buffer without discarding any of its contents
110pub fn read_more(&mut self, mut reader: impl Read) -> io::Result<usize> {
111let mut buf = BorrowedBuf::from(&mut self.buf[self.filled..]);
112113if self.initialized {
114// SAFETY: `self.initialized` is only set after `self.buf` was
115 // fully initialized, and once `self.buf` is fully initialized
116 // no part will become uninitialized.
117unsafe { buf.set_init() };
118 }
119120 reader.read_buf(buf.unfilled())?;
121self.filled += buf.len();
122self.initialized = buf.is_init();
123Ok(buf.len())
124 }
125126/// Remove bytes that have already been read from the buffer.
127pub fn backshift(&mut self) {
128self.buf.copy_within(self.pos..self.filled, 0);
129self.filled -= self.pos;
130self.pos = 0;
131 }
132133#[inline]
134pub fn fill_buf(&mut self, mut reader: impl Read) -> io::Result<&[u8]> {
135// If we've reached the end of our internal buffer then we need to fetch
136 // some more data from the reader.
137 // Branch using `>=` instead of the more correct `==`
138 // to tell the compiler that the pos..cap slice is always valid.
139if self.pos >= self.filled {
140if true {
if !(self.pos == self.filled) {
::core::panicking::panic("assertion failed: self.pos == self.filled")
};
};debug_assert!(self.pos == self.filled);
141142let mut buf = BorrowedBuf::from(&mut *self.buf);
143144if self.initialized {
145// SAFETY: `self.initialized` is only set after `self.buf` was
146 // fully initialized, and once `self.buf` is fully initialized
147 // no part will become uninitialized.
148unsafe { buf.set_init() };
149 }
150151let result = reader.read_buf(buf.unfilled());
152153self.pos = 0;
154self.filled = buf.len();
155self.initialized = buf.is_init();
156157 result?;
158 }
159Ok(self.buffer())
160 }
161}