core/io/borrowed_buf.rs
1#![unstable(feature = "core_io_borrowed_buf", issue = "117693")]
2
3use crate::fmt::{self, Debug, Formatter};
4use crate::mem::{self, MaybeUninit};
5use crate::{cmp, ptr};
6
7/// A borrowed byte buffer which is incrementally filled and initialized.
8///
9/// This type is a sort of "double cursor". It tracks three regions in the buffer: a region at the beginning of the
10/// buffer that has been logically filled with data, a region that has been initialized at some point but not yet
11/// logically filled, and a region at the end that is fully uninitialized. The filled region is guaranteed to be a
12/// subset of the initialized region.
13///
14/// In summary, the contents of the buffer can be visualized as:
15/// ```not_rust
16/// [ capacity ]
17/// [ filled | unfilled ]
18/// [ initialized | uninitialized ]
19/// ```
20///
21/// A `BorrowedBuf` is created around some existing data (or capacity for data) via a unique reference
22/// (`&mut`). The `BorrowedBuf` can be configured (e.g., using `clear` or `set_init`), but cannot be
23/// directly written. To write into the buffer, use `unfilled` to create a `BorrowedCursor`. The cursor
24/// has write-only access to the unfilled portion of the buffer (you can think of it as a
25/// write-only iterator).
26///
27/// The lifetime `'data` is a bound on the lifetime of the underlying data.
28pub struct BorrowedBuf<'data> {
29 /// The buffer's underlying data.
30 buf: &'data mut [MaybeUninit<u8>],
31 /// The length of `self.buf` which is known to be filled.
32 filled: usize,
33 /// The length of `self.buf` which is known to be initialized.
34 init: usize,
35}
36
37impl Debug for BorrowedBuf<'_> {
38 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
39 f.debug_struct("BorrowedBuf")
40 .field("init", &self.init)
41 .field("filled", &self.filled)
42 .field("capacity", &self.capacity())
43 .finish()
44 }
45}
46
47/// Creates a new `BorrowedBuf` from a fully initialized slice.
48impl<'data> From<&'data mut [u8]> for BorrowedBuf<'data> {
49 #[inline]
50 fn from(slice: &'data mut [u8]) -> BorrowedBuf<'data> {
51 let len = slice.len();
52
53 BorrowedBuf {
54 // SAFETY: initialized data never becoming uninitialized is an invariant of BorrowedBuf
55 buf: unsafe { (slice as *mut [u8]).as_uninit_slice_mut().unwrap() },
56 filled: 0,
57 init: len,
58 }
59 }
60}
61
62/// Creates a new `BorrowedBuf` from an uninitialized buffer.
63///
64/// Use `set_init` if part of the buffer is known to be already initialized.
65impl<'data> From<&'data mut [MaybeUninit<u8>]> for BorrowedBuf<'data> {
66 #[inline]
67 fn from(buf: &'data mut [MaybeUninit<u8>]) -> BorrowedBuf<'data> {
68 BorrowedBuf { buf, filled: 0, init: 0 }
69 }
70}
71
72impl<'data> BorrowedBuf<'data> {
73 /// Returns the total capacity of the buffer.
74 #[inline]
75 pub fn capacity(&self) -> usize {
76 self.buf.len()
77 }
78
79 /// Returns the length of the filled part of the buffer.
80 #[inline]
81 pub fn len(&self) -> usize {
82 self.filled
83 }
84
85 /// Returns the length of the initialized part of the buffer.
86 #[inline]
87 pub fn init_len(&self) -> usize {
88 self.init
89 }
90
91 /// Returns a shared reference to the filled portion of the buffer.
92 #[inline]
93 pub fn filled(&self) -> &[u8] {
94 // SAFETY: We only slice the filled part of the buffer, which is always valid
95 unsafe {
96 let buf = self.buf.get_unchecked(..self.filled);
97 buf.assume_init_ref()
98 }
99 }
100
101 /// Returns a mutable reference to the filled portion of the buffer.
102 #[inline]
103 pub fn filled_mut(&mut self) -> &mut [u8] {
104 // SAFETY: We only slice the filled part of the buffer, which is always valid
105 unsafe {
106 let buf = self.buf.get_unchecked_mut(..self.filled);
107 buf.assume_init_mut()
108 }
109 }
110
111 /// Returns a shared reference to the filled portion of the buffer with its original lifetime.
112 #[inline]
113 pub fn into_filled(self) -> &'data [u8] {
114 // SAFETY: We only slice the filled part of the buffer, which is always valid
115 unsafe {
116 let buf = self.buf.get_unchecked(..self.filled);
117 buf.assume_init_ref()
118 }
119 }
120
121 /// Returns a mutable reference to the filled portion of the buffer with its original lifetime.
122 #[inline]
123 pub fn into_filled_mut(self) -> &'data mut [u8] {
124 // SAFETY: We only slice the filled part of the buffer, which is always valid
125 unsafe {
126 let buf = self.buf.get_unchecked_mut(..self.filled);
127 buf.assume_init_mut()
128 }
129 }
130
131 /// Returns a cursor over the unfilled part of the buffer.
132 #[inline]
133 pub fn unfilled<'this>(&'this mut self) -> BorrowedCursor<'this> {
134 BorrowedCursor {
135 start: self.filled,
136 // SAFETY: we never assign into `BorrowedCursor::buf`, so treating its
137 // lifetime covariantly is safe.
138 buf: unsafe {
139 mem::transmute::<&'this mut BorrowedBuf<'data>, &'this mut BorrowedBuf<'this>>(self)
140 },
141 }
142 }
143
144 /// Clears the buffer, resetting the filled region to empty.
145 ///
146 /// The number of initialized bytes is not changed, and the contents of the buffer are not modified.
147 #[inline]
148 pub fn clear(&mut self) -> &mut Self {
149 self.filled = 0;
150 self
151 }
152
153 /// Asserts that the first `n` bytes of the buffer are initialized.
154 ///
155 /// `BorrowedBuf` assumes that bytes are never de-initialized, so this method does nothing when called with fewer
156 /// bytes than are already known to be initialized.
157 ///
158 /// # Safety
159 ///
160 /// The caller must ensure that the first `n` unfilled bytes of the buffer have already been initialized.
161 #[inline]
162 pub unsafe fn set_init(&mut self, n: usize) -> &mut Self {
163 self.init = cmp::max(self.init, n);
164 self
165 }
166}
167
168/// A writeable view of the unfilled portion of a [`BorrowedBuf`].
169///
170/// The unfilled portion consists of an initialized and an uninitialized part; see [`BorrowedBuf`]
171/// for details.
172///
173/// Data can be written directly to the cursor by using [`append`](BorrowedCursor::append) or
174/// indirectly by getting a slice of part or all of the cursor and writing into the slice. In the
175/// indirect case, the caller must call [`advance`](BorrowedCursor::advance) after writing to inform
176/// the cursor how many bytes have been written.
177///
178/// Once data is written to the cursor, it becomes part of the filled portion of the underlying
179/// `BorrowedBuf` and can no longer be accessed or re-written by the cursor. I.e., the cursor tracks
180/// the unfilled part of the underlying `BorrowedBuf`.
181///
182/// The lifetime `'a` is a bound on the lifetime of the underlying buffer (which means it is a bound
183/// on the data in that buffer by transitivity).
184#[derive(Debug)]
185pub struct BorrowedCursor<'a> {
186 /// The underlying buffer.
187 // Safety invariant: we treat the type of buf as covariant in the lifetime of `BorrowedBuf` when
188 // we create a `BorrowedCursor`. This is only safe if we never replace `buf` by assigning into
189 // it, so don't do that!
190 buf: &'a mut BorrowedBuf<'a>,
191 /// The length of the filled portion of the underlying buffer at the time of the cursor's
192 /// creation.
193 start: usize,
194}
195
196impl<'a> BorrowedCursor<'a> {
197 /// Reborrows this cursor by cloning it with a smaller lifetime.
198 ///
199 /// Since a cursor maintains unique access to its underlying buffer, the borrowed cursor is
200 /// not accessible while the new cursor exists.
201 #[inline]
202 pub fn reborrow<'this>(&'this mut self) -> BorrowedCursor<'this> {
203 BorrowedCursor {
204 // SAFETY: we never assign into `BorrowedCursor::buf`, so treating its
205 // lifetime covariantly is safe.
206 buf: unsafe {
207 mem::transmute::<&'this mut BorrowedBuf<'a>, &'this mut BorrowedBuf<'this>>(
208 self.buf,
209 )
210 },
211 start: self.start,
212 }
213 }
214
215 /// Returns the available space in the cursor.
216 #[inline]
217 pub fn capacity(&self) -> usize {
218 self.buf.capacity() - self.buf.filled
219 }
220
221 /// Returns the number of bytes written to this cursor since it was created from a `BorrowedBuf`.
222 ///
223 /// Note that if this cursor is a reborrowed clone of another, then the count returned is the
224 /// count written via either cursor, not the count since the cursor was reborrowed.
225 #[inline]
226 pub fn written(&self) -> usize {
227 self.buf.filled - self.start
228 }
229
230 /// Returns a shared reference to the initialized portion of the cursor.
231 #[inline]
232 pub fn init_ref(&self) -> &[u8] {
233 // SAFETY: We only slice the initialized part of the buffer, which is always valid
234 unsafe {
235 let buf = self.buf.buf.get_unchecked(self.buf.filled..self.buf.init);
236 buf.assume_init_ref()
237 }
238 }
239
240 /// Returns a mutable reference to the initialized portion of the cursor.
241 #[inline]
242 pub fn init_mut(&mut self) -> &mut [u8] {
243 // SAFETY: We only slice the initialized part of the buffer, which is always valid
244 unsafe {
245 let buf = self.buf.buf.get_unchecked_mut(self.buf.filled..self.buf.init);
246 buf.assume_init_mut()
247 }
248 }
249
250 /// Returns a mutable reference to the uninitialized part of the cursor.
251 ///
252 /// It is safe to uninitialize any of these bytes.
253 #[inline]
254 pub fn uninit_mut(&mut self) -> &mut [MaybeUninit<u8>] {
255 // SAFETY: always in bounds
256 unsafe { self.buf.buf.get_unchecked_mut(self.buf.init..) }
257 }
258
259 /// Returns a mutable reference to the whole cursor.
260 ///
261 /// # Safety
262 ///
263 /// The caller must not uninitialize any bytes in the initialized portion of the cursor.
264 #[inline]
265 pub unsafe fn as_mut(&mut self) -> &mut [MaybeUninit<u8>] {
266 // SAFETY: always in bounds
267 unsafe { self.buf.buf.get_unchecked_mut(self.buf.filled..) }
268 }
269
270 /// Advances the cursor by asserting that `n` bytes have been filled.
271 ///
272 /// After advancing, the `n` bytes are no longer accessible via the cursor and can only be
273 /// accessed via the underlying buffer. I.e., the buffer's filled portion grows by `n` elements
274 /// and its unfilled portion (and the capacity of this cursor) shrinks by `n` elements.
275 ///
276 /// If less than `n` bytes initialized (by the cursor's point of view), `set_init` should be
277 /// called first.
278 ///
279 /// # Panics
280 ///
281 /// Panics if there are less than `n` bytes initialized.
282 #[inline]
283 pub fn advance(&mut self, n: usize) -> &mut Self {
284 let filled = self.buf.filled.strict_add(n);
285 assert!(filled <= self.buf.init);
286
287 self.buf.filled = filled;
288 self
289 }
290
291 /// Advances the cursor by asserting that `n` bytes have been filled.
292 ///
293 /// After advancing, the `n` bytes are no longer accessible via the cursor and can only be
294 /// accessed via the underlying buffer. I.e., the buffer's filled portion grows by `n` elements
295 /// and its unfilled portion (and the capacity of this cursor) shrinks by `n` elements.
296 ///
297 /// # Safety
298 ///
299 /// The caller must ensure that the first `n` bytes of the cursor have been properly
300 /// initialised.
301 #[inline]
302 pub unsafe fn advance_unchecked(&mut self, n: usize) -> &mut Self {
303 self.buf.filled += n;
304 self.buf.init = cmp::max(self.buf.init, self.buf.filled);
305 self
306 }
307
308 /// Initializes all bytes in the cursor.
309 #[inline]
310 pub fn ensure_init(&mut self) -> &mut Self {
311 let uninit = self.uninit_mut();
312 // SAFETY: 0 is a valid value for MaybeUninit<u8> and the length matches the allocation
313 // since it is comes from a slice reference.
314 unsafe {
315 ptr::write_bytes(uninit.as_mut_ptr(), 0, uninit.len());
316 }
317 self.buf.init = self.buf.capacity();
318
319 self
320 }
321
322 /// Asserts that the first `n` unfilled bytes of the cursor are initialized.
323 ///
324 /// `BorrowedBuf` assumes that bytes are never de-initialized, so this method does nothing when
325 /// called with fewer bytes than are already known to be initialized.
326 ///
327 /// # Safety
328 ///
329 /// The caller must ensure that the first `n` bytes of the buffer have already been initialized.
330 #[inline]
331 pub unsafe fn set_init(&mut self, n: usize) -> &mut Self {
332 self.buf.init = cmp::max(self.buf.init, self.buf.filled + n);
333 self
334 }
335
336 /// Appends data to the cursor, advancing position within its buffer.
337 ///
338 /// # Panics
339 ///
340 /// Panics if `self.capacity()` is less than `buf.len()`.
341 #[inline]
342 pub fn append(&mut self, buf: &[u8]) {
343 assert!(self.capacity() >= buf.len());
344
345 // SAFETY: we do not de-initialize any of the elements of the slice
346 unsafe {
347 self.as_mut()[..buf.len()].write_copy_of_slice(buf);
348 }
349
350 // SAFETY: We just added the entire contents of buf to the filled section.
351 unsafe {
352 self.set_init(buf.len());
353 }
354 self.buf.filled += buf.len();
355 }
356}