1 #![unstable(feature = "read_buf", issue = "78485")]
7 use crate::fmt
::{self, Debug, Formatter}
;
8 use crate::mem
::MaybeUninit
;
10 /// A wrapper around a byte buffer that is incrementally filled and initialized.
12 /// This type is a sort of "double cursor". It tracks three regions in the buffer: a region at the beginning of the
13 /// buffer that has been logically filled with data, a region that has been initialized at some point but not yet
14 /// logically filled, and a region at the end that is fully uninitialized. The filled region is guaranteed to be a
15 /// subset of the initialized region.
17 /// In summary, the contents of the buffer can be visualized as:
20 /// [ filled | unfilled ]
21 /// [ initialized | uninitialized ]
23 pub struct ReadBuf
<'a
> {
24 buf
: &'a
mut [MaybeUninit
<u8>],
29 impl Debug
for ReadBuf
<'_
> {
30 fn fmt(&self, f
: &mut Formatter
<'_
>) -> fmt
::Result
{
31 f
.debug_struct("ReadBuf")
32 .field("init", &self.initialized())
33 .field("filled", &self.filled
)
34 .field("capacity", &self.capacity())
39 impl<'a
> ReadBuf
<'a
> {
40 /// Creates a new `ReadBuf` from a fully initialized buffer.
42 pub fn new(buf
: &'a
mut [u8]) -> ReadBuf
<'a
> {
46 //SAFETY: initialized data never becoming uninitialized is an invariant of ReadBuf
47 buf
: unsafe { (buf as *mut [u8]).as_uninit_slice_mut().unwrap() }
,
53 /// Creates a new `ReadBuf` from a fully uninitialized buffer.
55 /// Use `assume_init` if part of the buffer is known to be already initialized.
57 pub fn uninit(buf
: &'a
mut [MaybeUninit
<u8>]) -> ReadBuf
<'a
> {
58 ReadBuf { buf, filled: 0, initialized: 0 }
61 /// Returns the total capacity of the buffer.
63 pub fn capacity(&self) -> usize {
67 /// Returns a shared reference to the filled portion of the buffer.
69 pub fn filled(&self) -> &[u8] {
70 //SAFETY: We only slice the filled part of the buffer, which is always valid
71 unsafe { MaybeUninit::slice_assume_init_ref(&self.buf[0..self.filled]) }
74 /// Returns a mutable reference to the filled portion of the buffer.
76 pub fn filled_mut(&mut self) -> &mut [u8] {
77 //SAFETY: We only slice the filled part of the buffer, which is always valid
78 unsafe { MaybeUninit::slice_assume_init_mut(&mut self.buf[0..self.filled]) }
81 /// Returns a shared reference to the initialized portion of the buffer.
83 /// This includes the filled portion.
85 pub fn initialized(&self) -> &[u8] {
86 //SAFETY: We only slice the initialized part of the buffer, which is always valid
87 unsafe { MaybeUninit::slice_assume_init_ref(&self.buf[0..self.initialized]) }
90 /// Returns a mutable reference to the initialized portion of the buffer.
92 /// This includes the filled portion.
94 pub fn initialized_mut(&mut self) -> &mut [u8] {
95 //SAFETY: We only slice the initialized part of the buffer, which is always valid
96 unsafe { MaybeUninit::slice_assume_init_mut(&mut self.buf[0..self.initialized]) }
99 /// Returns a mutable reference to the unfilled part of the buffer without ensuring that it has been fully
104 /// The caller must not de-initialize portions of the buffer that have already been initialized.
106 pub unsafe fn unfilled_mut(&mut self) -> &mut [MaybeUninit
<u8>] {
107 &mut self.buf
[self.filled
..]
110 /// Returns a mutable reference to the uninitialized part of the buffer.
112 /// It is safe to uninitialize any of these bytes.
114 pub fn uninitialized_mut(&mut self) -> &mut [MaybeUninit
<u8>] {
115 &mut self.buf
[self.initialized
..]
118 /// Returns a mutable reference to the unfilled part of the buffer, ensuring it is fully initialized.
120 /// Since `ReadBuf` tracks the region of the buffer that has been initialized, this is effectively "free" after
123 pub fn initialize_unfilled(&mut self) -> &mut [u8] {
124 // should optimize out the assertion
125 self.initialize_unfilled_to(self.remaining())
128 /// Returns a mutable reference to the first `n` bytes of the unfilled part of the buffer, ensuring it is
129 /// fully initialized.
133 /// Panics if `self.remaining()` is less than `n`.
135 pub fn initialize_unfilled_to(&mut self, n
: usize) -> &mut [u8] {
136 assert
!(self.remaining() >= n
);
138 let extra_init
= self.initialized
- self.filled
;
139 // If we don't have enough initialized, do zeroing
141 let uninit
= n
- extra_init
;
142 let unfilled
= &mut self.uninitialized_mut()[0..uninit
];
144 for byte
in unfilled
.iter_mut() {
148 // SAFETY: we just initialized uninit bytes, and the previous bytes were already init
154 let filled
= self.filled
;
156 &mut self.initialized_mut()[filled
..filled
+ n
]
159 /// Returns the number of bytes at the end of the slice that have not yet been filled.
161 pub fn remaining(&self) -> usize {
162 self.capacity() - self.filled
165 /// Clears the buffer, resetting the filled region to empty.
167 /// The number of initialized bytes is not changed, and the contents of the buffer are not modified.
169 pub fn clear(&mut self) -> &mut Self {
170 self.set_filled(0) // The assertion in `set_filled` is optimized out
173 /// Increases the size of the filled region of the buffer.
175 /// The number of initialized bytes is not changed.
179 /// Panics if the filled region of the buffer would become larger than the initialized region.
181 pub fn add_filled(&mut self, n
: usize) -> &mut Self {
182 self.set_filled(self.filled
+ n
)
185 /// Sets the size of the filled region of the buffer.
187 /// The number of initialized bytes is not changed.
189 /// Note that this can be used to *shrink* the filled region of the buffer in addition to growing it (for
190 /// example, by a `Read` implementation that compresses data in-place).
194 /// Panics if the filled region of the buffer would become larger than the initialized region.
196 pub fn set_filled(&mut self, n
: usize) -> &mut Self {
197 assert
!(n
<= self.initialized
);
203 /// Asserts that the first `n` unfilled bytes of the buffer are initialized.
205 /// `ReadBuf` assumes that bytes are never de-initialized, so this method does nothing when called with fewer
206 /// bytes than are already known to be initialized.
210 /// The caller must ensure that the first `n` unfilled bytes of the buffer have already been initialized.
212 pub unsafe fn assume_init(&mut self, n
: usize) -> &mut Self {
213 self.initialized
= cmp
::max(self.initialized
, self.filled
+ n
);
217 /// Appends data to the buffer, advancing the written position and possibly also the initialized position.
221 /// Panics if `self.remaining()` is less than `buf.len()`.
223 pub fn append(&mut self, buf
: &[u8]) {
224 assert
!(self.remaining() >= buf
.len());
226 // SAFETY: we do not de-initialize any of the elements of the slice
228 MaybeUninit
::write_slice(&mut self.unfilled_mut()[..buf
.len()], buf
);
231 // SAFETY: We just added the entire contents of buf to the filled section.
233 self.assume_init(buf
.len());
235 self.add_filled(buf
.len());
238 /// Returns the amount of bytes that have been filled.
240 pub fn filled_len(&self) -> usize {
244 /// Returns the amount of bytes that have been initialized.
246 pub fn initialized_len(&self) -> usize {