Skip to main content

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