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 core::cmp;
13use core::mem::MaybeUninit;
1415use crate::boxed::Box;
16use crate::io::{self, BorrowedBuf, ErrorKind, Read};
1718pub(super) struct Buffer {
19// The buffer.
20buf: Box<[MaybeUninit<u8>]>,
21// The current seek offset into `buf`, must always be <= `filled`.
22pos: usize,
23// Each call to `fill_buf` sets `filled` to indicate how many bytes at the start of `buf` are
24 // initialized with bytes from a read.
25filled: usize,
26// Whether `buf` has been fully initialized. We track this so that we can accurately tell
27 // `read_buf` how many bytes of buf are initialized, to bypass as much of its defensive
28 // initialization as possible. Calls to `fill_buf` are not required to actually fill the buffer,
29 // and omitting this is a huge perf regression for `Read` impls that do not.
30initialized: bool,
31}
3233impl Buffer {
34#[cfg(not(no_global_oom_handling))]
35 #[inline]
36pub(super) fn with_capacity(capacity: usize) -> Self {
37let buf = Box::new_uninit_slice(capacity);
38Self { buf, pos: 0, filled: 0, initialized: false }
39 }
4041#[inline]
42pub(super) fn try_with_capacity(capacity: usize) -> io::Result<Self> {
43match Box::try_new_uninit_slice(capacity) {
44Ok(buf) => Ok(Self { buf, pos: 0, filled: 0, initialized: false }),
45Err(_) => {
46Err(::core::hint::must_use(::core::io::Error::from_static_message(const {
&::core::io::SimpleMessage {
kind: ErrorKind::OutOfMemory,
message: "failed to allocate read buffer",
}
}))io::const_error!(ErrorKind::OutOfMemory, "failed to allocate read buffer"))
47 }
48 }
49 }
5051#[inline]
52pub(super) fn buffer(&self) -> &[u8] {
53// SAFETY: self.pos and self.filled are valid, and self.filled >= self.pos, and
54 // that region is initialized because those are all invariants of this type.
55unsafe { self.buf.get_unchecked(self.pos..self.filled).assume_init_ref() }
56 }
5758#[inline]
59pub(super) fn capacity(&self) -> usize {
60self.buf.len()
61 }
6263#[inline]
64pub(super) fn filled(&self) -> usize {
65self.filled
66 }
6768#[inline]
69pub(super) fn pos(&self) -> usize {
70self.pos
71 }
7273// This is only used by a test which asserts that the initialization-tracking is correct.
74pub(super) fn initialized(&self) -> bool {
75self.initialized
76 }
7778#[inline]
79pub(super) fn discard_buffer(&mut self) {
80self.pos = 0;
81self.filled = 0;
82 }
8384#[inline]
85pub(super) fn consume(&mut self, amt: usize) {
86self.pos = cmp::min(self.pos + amt, self.filled);
87 }
8889/// If there are `amt` bytes available in the buffer, pass a slice containing those bytes to
90 /// `visitor` and return true. If there are not enough bytes available, return false.
91#[inline]
92pub(super) fn consume_with<V>(&mut self, amt: usize, mut visitor: V) -> bool93where
94V: FnMut(&[u8]),
95 {
96if let Some(claimed) = self.buffer().get(..amt) {
97visitor(claimed);
98// If the indexing into self.buffer() succeeds, amt must be a valid increment.
99self.pos += amt;
100true
101} else {
102false
103}
104 }
105106#[inline]
107pub(super) fn unconsume(&mut self, amt: usize) {
108self.pos = self.pos.saturating_sub(amt);
109 }
110111/// Read more bytes into the buffer without discarding any of its contents
112pub(super) fn read_more(&mut self, mut reader: impl Read) -> io::Result<usize> {
113let mut buf = BorrowedBuf::from(&mut self.buf[self.filled..]);
114115if self.initialized {
116// SAFETY: `self.initialized` is only set after `self.buf` was
117 // fully initialized, and once `self.buf` is fully initialized
118 // no part will become uninitialized.
119unsafe { buf.set_init() };
120 }
121122 reader.read_buf(buf.unfilled())?;
123self.filled += buf.len();
124self.initialized = buf.is_init();
125Ok(buf.len())
126 }
127128/// Remove bytes that have already been read from the buffer.
129pub(super) fn backshift(&mut self) {
130self.buf.copy_within(self.pos..self.filled, 0);
131self.filled -= self.pos;
132self.pos = 0;
133 }
134135#[inline]
136pub(super) fn fill_buf(&mut self, mut reader: impl Read) -> io::Result<&[u8]> {
137// If we've reached the end of our internal buffer then we need to fetch
138 // some more data from the reader.
139 // Branch using `>=` instead of the more correct `==`
140 // to tell the compiler that the pos..cap slice is always valid.
141if self.pos >= self.filled {
142if true {
if !(self.pos == self.filled) {
::core::panicking::panic("assertion failed: self.pos == self.filled")
};
};debug_assert!(self.pos == self.filled);
143144let mut buf = BorrowedBuf::from(&mut *self.buf);
145146if self.initialized {
147// SAFETY: `self.initialized` is only set after `self.buf` was
148 // fully initialized, and once `self.buf` is fully initialized
149 // no part will become uninitialized.
150unsafe { buf.set_init() };
151 }
152153let result = reader.read_buf(buf.unfilled());
154155self.pos = 0;
156self.filled = buf.len();
157self.initialized = buf.is_init();
158159 result?;
160 }
161Ok(self.buffer())
162 }
163}