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::MaybeUninit;
5use crate::ptr::NonNull;
6use crate::slice;
7
8/// A borrowed buffer of initially uninitialized elements, which is incrementally filled.
9///
10/// This type makes it safer to work with `MaybeUninit` buffers, such as to read into a buffer
11/// without having to initialize it first. It tracks the region of elements that have been filled
12/// and whether the unfilled region was initialized.
13///
14/// In summary, the contents of the buffer can be visualized as:
15/// ```not_rust
16/// [                capacity                ]
17/// [ filled | unfilled (may be initialized) ]
18/// ```
19///
20/// A `BorrowedBuf` is created around some existing elements (or capacity for elements) via a unique
21/// reference (`&mut`). The `BorrowedBuf` can be configured (e.g., using `clear` or `set_init`), but
22/// cannot be directly written. To write into the buffer, use `unfilled` to create a
23/// `BorrowedCursor`. The cursor has write-only access to the unfilled portion of the buffer (you
24/// can think of it as a write-only iterator).
25///
26/// The lifetime `'data` is a bound on the lifetime of the underlying elements.
27///
28/// The type is most commonly used to manage bytes, but can manage any type of elements.
29pub struct BorrowedBuf<'data, T> {
30    /// The buffer's underlying elements.
31    buf: &'data mut [MaybeUninit<T>],
32    /// The number of elements of `self.buf` that are known to be filled.
33    filled: usize,
34    /// Whether the entire unfilled part of `self.buf` has explicitly been initialized.
35    init: bool,
36}
37
38impl<T> Debug for BorrowedBuf<'_, T> {
39    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
40        BorrowedBufDebug { init: self.init, filled: self.filled, capacity: self.capacity() }.fmt(f)
41    }
42}
43
44struct BorrowedBufDebug {
45    init: bool,
46    filled: usize,
47    capacity: usize,
48}
49
50impl Debug for BorrowedBufDebug {
51    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
52        f.debug_struct("BorrowedBuf")
53            .field("init", &self.init)
54            .field("filled", &self.filled)
55            .field("capacity", &self.capacity)
56            .finish()
57    }
58}
59
60/// Creates a new `BorrowedBuf` from a fully initialized slice.
61impl<'data, T: Copy> From<&'data mut [T]> for BorrowedBuf<'data, T> {
62    #[inline]
63    fn from(slice: &'data mut [T]) -> BorrowedBuf<'data, T> {
64        BorrowedBuf {
65            // SAFETY: no initialized element is ever uninitialized as per `BorrowedBuf`'s invariant
66            buf: unsafe { &mut *(slice as *mut [T] as *mut [MaybeUninit<T>]) },
67            filled: 0,
68            init: true,
69        }
70    }
71}
72
73/// Creates a new `BorrowedBuf` from an uninitialized buffer.
74impl<'data, T: Copy> From<&'data mut [MaybeUninit<T>]> for BorrowedBuf<'data, T> {
75    #[inline]
76    fn from(buf: &'data mut [MaybeUninit<T>]) -> BorrowedBuf<'data, T> {
77        BorrowedBuf { buf, filled: 0, init: false }
78    }
79}
80
81/// Creates a new `BorrowedBuf` from a cursor.
82///
83/// Use `BorrowedCursor::with_unfilled_buf` instead for a safer alternative.
84impl<'data, T: Copy> From<BorrowedCursor<'data, T>> for BorrowedBuf<'data, T> {
85    #[inline]
86    fn from(buf: BorrowedCursor<'data, T>) -> BorrowedBuf<'data, T> {
87        let filled = buf.filled();
88        let init = buf.is_buf_init();
89        let len = buf.buf_len();
90        BorrowedBuf {
91            // SAFETY: no initialized element is ever uninitialized as per `BorrowedBuf`'s
92            // invariant, and the cursor holds the unique access to those elements for `'data`
93            buf: unsafe { slice::from_raw_parts_mut(buf.buf.as_ptr().add(filled), len - filled) },
94            filled: 0,
95            init,
96        }
97    }
98}
99
100impl<'data, T> BorrowedBuf<'data, T> {
101    /// Returns the total capacity of the buffer.
102    #[inline]
103    pub fn capacity(&self) -> usize {
104        self.buf.len()
105    }
106
107    /// Returns the length of the filled part of the buffer.
108    #[inline]
109    pub fn len(&self) -> usize {
110        self.filled
111    }
112
113    /// Returns `true` if the buffer is initialized.
114    #[unstable(feature = "borrowed_buf_init", issue = "160476")]
115    #[inline]
116    pub fn is_init(&self) -> bool {
117        self.init
118    }
119}
120
121impl<'data, T: Copy> BorrowedBuf<'data, T> {
122    /// Returns a shared reference to the filled portion of the buffer.
123    #[inline]
124    pub fn filled(&self) -> &[T] {
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.
133    #[inline]
134    pub fn filled_mut(&mut self) -> &mut [T] {
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 shared reference to the filled portion of the buffer with its original lifetime.
143    #[inline]
144    pub fn into_filled(self) -> &'data [T] {
145        // SAFETY: We only slice the filled part of the buffer, which is always valid
146        unsafe {
147            let buf = self.buf.get_unchecked(..self.filled);
148            buf.assume_init_ref()
149        }
150    }
151
152    /// Returns a mutable reference to the filled portion of the buffer with its original lifetime.
153    #[inline]
154    pub fn into_filled_mut(self) -> &'data mut [T] {
155        // SAFETY: We only slice the filled part of the buffer, which is always valid
156        unsafe {
157            let buf = self.buf.get_unchecked_mut(..self.filled);
158            buf.assume_init_mut()
159        }
160    }
161
162    /// Returns a cursor over the unfilled part of the buffer.
163    #[inline]
164    pub fn unfilled<'this>(&'this mut self) -> BorrowedCursor<'this, T> {
165        let borrowed_buf = NonNull::from_mut(self);
166        BorrowedCursor { buf: NonNull::from_mut(self.buf).cast(), borrowed_buf }
167    }
168
169    /// Clears the buffer, resetting the filled region to empty.
170    ///
171    /// The contents of the buffer are not modified.
172    #[inline]
173    pub fn clear(&mut self) -> &mut Self {
174        self.filled = 0;
175        self
176    }
177
178    /// Asserts that the unfilled part of the buffer is initialized.
179    ///
180    /// # Safety
181    ///
182    /// All the elements of the buffer must be initialized.
183    #[unstable(feature = "borrowed_buf_init", issue = "160476")]
184    #[inline]
185    pub unsafe fn set_init(&mut self) -> &mut Self {
186        self.init = true;
187        self
188    }
189}
190
191/// A writeable view of the unfilled portion of a [`BorrowedBuf`].
192///
193/// The unfilled portion may be uninitialized; see [`BorrowedBuf`] for details.
194///
195/// Data can be written directly to the cursor by using [`append`](BorrowedCursor::append) or
196/// indirectly by getting a slice of part or all of the cursor and writing into the slice. In the
197/// indirect case, the caller must call [`advance`](BorrowedCursor::advance) after writing to inform
198/// the cursor how many elements have been written.
199///
200/// Once elements are written to the cursor, they become part of the filled portion of the
201/// underlying `BorrowedBuf` and can no longer be accessed or re-written by the cursor. In other
202/// words, the cursor tracks the unfilled part of the underlying `BorrowedBuf`.
203///
204/// The lifetime `'a` is a bound on the lifetime of the underlying buffer (which means it is a bound
205/// on the elements in that buffer by transitivity).
206pub struct BorrowedCursor<'a, T> {
207    /// The start of the elements of the buffer this cursor was created from.
208    /// Safety invariant: this points to the start of the *whole* buffer of `*borrowed_buf` and is
209    /// valid for reads and writes of `(*borrowed_buf).buf.len()` elements, so that
210    /// `(*borrowed_buf).filled` indexes into it.
211    buf: NonNull<MaybeUninit<T>>,
212    /// The buffer this cursor was created from.
213    /// Safety invariants:
214    /// 1. `(*borrowed_buf).buf` is *never* accessed by the owner of the pointee while the `buf`
215    ///    field above is alive, because there is a `&mut` of the pointee while the cursor is alive.
216    /// 2. We promise to only access the `filled` and `init` fields and the metadata of the `buf`
217    ///    field through the `borrowed_buf` pointer, never triggering any retag of `buf`'s pointer,
218    ///    as the `buf` field above holds a reborrow of it and reaching the parent again would be a
219    ///    foreign access for that reborrow. This includes not making a reference to the whole
220    ///    pointee out of `borrowed_buf`, but only accessing those fields directly through pointer
221    ///    manipulation.
222    borrowed_buf: NonNull<BorrowedBuf<'a, T>>,
223}
224
225impl<T> Debug for BorrowedCursor<'_, T> {
226    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
227        let buf = BorrowedBufDebug {
228            init: self.is_buf_init(),
229            filled: self.filled(),
230            capacity: self.buf_len(),
231        };
232
233        f.debug_struct("BorrowedCursor").field("buf", &buf).finish()
234    }
235}
236
237// Helpers to access underlying buffer state.
238impl<'a, T> BorrowedCursor<'a, T> {
239    #[inline]
240    fn buf_mut(&mut self) -> &mut [MaybeUninit<T>] {
241        let len = self.buf_len();
242        // SAFETY: `buf` points to `len` elements that this cursor borrows exclusively.
243        unsafe { slice::from_raw_parts_mut(self.buf.as_ptr(), len) }
244    }
245
246    #[inline]
247    fn buf_len(&self) -> usize {
248        // SAFETY: We read just the metadata of `buf` and avoid retagging the reference.
249        unsafe {
250            let borrowed_buf = self.borrowed_buf.as_ptr();
251            let buf_ptr: *const &'a mut [MaybeUninit<T>] = &raw const (*borrowed_buf).buf;
252            // Same layout:
253            // https://doc.rust-lang.org/reference/type-layout.html#r-layout.pointer.intro
254            let buf_ptr: *const *const [MaybeUninit<T>] = buf_ptr.cast();
255            let buf: *const [MaybeUninit<T>] = *buf_ptr;
256            buf.len()
257        }
258    }
259
260    #[inline]
261    fn unfilled_slice(&mut self) -> &mut [MaybeUninit<T>] {
262        let filled = self.filled();
263        // SAFETY: always in bounds
264        unsafe { self.buf_mut().get_unchecked_mut(filled..) }
265    }
266
267    #[inline]
268    fn filled(&self) -> usize {
269        // SAFETY: We access just `filled` and avoid foreign read on `buf`.
270        unsafe { (*self.borrowed_buf.as_ptr()).filled }
271    }
272
273    #[inline]
274    fn is_buf_init(&self) -> bool {
275        // SAFETY: We access just `init` and avoid foreign read on `buf`.
276        unsafe { (*self.borrowed_buf.as_ptr()).init }
277    }
278
279    /// # Safety
280    ///
281    /// In case of `true` all the elements of the cursor must be initialized.
282    #[inline]
283    unsafe fn set_buf_init(&mut self, init: bool) {
284        // SAFETY: We access just `init` and avoid foreign read on `buf`.
285        unsafe {
286            (*self.borrowed_buf.as_ptr()).init = init;
287        }
288    }
289
290    /// # Safety
291    ///
292    /// The next `n` elements of the cursor must be initialized.
293    #[inline]
294    unsafe fn add_filled(&mut self, n: usize) {
295        // SAFETY: We access just `filled` and avoid foreign read on `buf`.
296        unsafe {
297            (*self.borrowed_buf.as_ptr()).filled += n;
298        }
299    }
300}
301
302impl<'a, T: Copy> BorrowedCursor<'a, T> {
303    /// Reborrows this cursor by cloning it with a smaller lifetime.
304    ///
305    /// Since a cursor maintains unique access to its underlying buffer, the borrowed cursor is
306    /// not accessible while the new cursor exists.
307    #[inline]
308    pub fn reborrow<'this>(&'this mut self) -> BorrowedCursor<'this, T> {
309        BorrowedCursor { buf: self.buf, borrowed_buf: self.borrowed_buf }
310    }
311
312    /// Returns the available space in the cursor.
313    #[inline]
314    pub fn capacity(&self) -> usize {
315        self.buf_len() - self.filled()
316    }
317
318    /// Returns the number of elements written to the `BorrowedBuf` this cursor was created from.
319    ///
320    /// In particular, the count returned is shared by all reborrows of the cursor.
321    #[inline]
322    pub fn written(&self) -> usize {
323        self.filled()
324    }
325
326    /// Returns `true` if the buffer is initialized.
327    #[unstable(feature = "borrowed_buf_init", issue = "160476")]
328    #[inline]
329    pub fn is_init(&self) -> bool {
330        self.is_buf_init()
331    }
332
333    /// Set the buffer as fully initialized.
334    ///
335    /// # Safety
336    ///
337    /// All the elements of the cursor must be initialized.
338    #[unstable(feature = "borrowed_buf_init", issue = "160476")]
339    #[inline]
340    pub unsafe fn set_init(&mut self) {
341        // SAFETY: the caller guarantees that all the elements of the cursor are initialized.
342        unsafe { self.set_buf_init(true) }
343    }
344
345    /// Returns a mutable reference to the whole cursor.
346    ///
347    /// # Safety
348    ///
349    /// The caller must not uninitialize any elements of the cursor if it is initialized.
350    #[inline]
351    pub unsafe fn as_mut(&mut self) -> &mut [MaybeUninit<T>] {
352        self.unfilled_slice()
353    }
354
355    /// Advances the cursor by asserting that `n` elements have been filled.
356    ///
357    /// After advancing, the `n` elements are no longer accessible via the cursor and can only be
358    /// accessed via the underlying buffer. I.e., the buffer's filled portion grows by `n` elements
359    /// and its unfilled portion (and the capacity of this cursor) shrinks by `n` elements.
360    ///
361    /// If less than `n` elements initialized (by the cursor's point of view), `set_init` should be
362    /// called first.
363    ///
364    /// # Panics
365    ///
366    /// Panics if there are less than `n` elements initialized.
367    #[unstable(feature = "borrowed_buf_init", issue = "160476")]
368    #[inline]
369    pub fn advance_checked(&mut self, n: usize) -> &mut Self {
370        // The subtraction cannot underflow by invariant of this type.
371        let init_unfilled = if self.is_buf_init() { self.buf_len() - self.filled() } else { 0 };
372        assert!(n <= init_unfilled);
373
374        // SAFETY: the next `n` elements are initialized, as asserted above.
375        unsafe { self.advance(n) };
376        self
377    }
378
379    /// Advances the cursor by asserting that `n` elements have been filled.
380    ///
381    /// After advancing, the `n` elements are no longer accessible via the cursor and can only be
382    /// accessed via the underlying buffer. I.e., the buffer's filled portion grows by `n` elements
383    /// and its unfilled portion (and the capacity of this cursor) shrinks by `n` elements.
384    ///
385    /// # Safety
386    ///
387    /// The caller must ensure that the first `n` elements of the cursor have been initialized.
388    #[inline]
389    pub unsafe fn advance(&mut self, n: usize) -> &mut Self {
390        // SAFETY: the caller guarantees that the first `n` elements of the cursor are initialized.
391        unsafe { self.add_filled(n) };
392        self
393    }
394
395    /// Append elements to the cursor, advancing position within its buffer.
396    ///
397    /// # Panics
398    ///
399    /// Panics if `self.capacity()` is less than `buf.len()`.
400    #[inline]
401    pub fn append(&mut self, buf: &[T]) {
402        assert!(self.capacity() >= buf.len());
403
404        // SAFETY: we do not de-initialize any of the elements of the slice
405        unsafe {
406            self.as_mut()[..buf.len()].write_copy_of_slice(buf);
407        }
408
409        // SAFETY: these elements have just been initialized.
410        unsafe { self.advance(buf.len()) };
411    }
412
413    /// Runs the given closure with a `BorrowedBuf` containing the unfilled part
414    /// of the cursor.
415    ///
416    /// This enables inspecting what was written to the cursor.
417    ///
418    /// # Panics
419    ///
420    /// Panics if the `BorrowedBuf` given to the closure is replaced by another
421    /// one.
422    pub fn with_unfilled_buf<R>(&mut self, f: impl FnOnce(&mut BorrowedBuf<'_, T>) -> R) -> R {
423        let mut buf = BorrowedBuf::from(self.reborrow());
424        let prev_ptr = buf.buf as *const _;
425        let res = f(&mut buf);
426
427        // Check that the caller didn't replace the `BorrowedBuf`.
428        // This is necessary for the safety of the code below: if the check wasn't
429        // there, one could mark some elements as initialized even though they aren't.
430        assert!(core::ptr::eq(prev_ptr, buf.buf));
431
432        let filled = buf.filled;
433        let init = buf.init;
434
435        // Update `init` and `filled` fields with what was written to the buffer.
436        // `self.buf.filled` was the starting length of the `BorrowedBuf`.
437        //
438        // SAFETY: These elements were initialized/filled in the `BorrowedBuf`, and therefore they
439        // are initialized/filled in the cursor too, because the buffer wasn't replaced.
440        unsafe {
441            self.set_buf_init(init);
442            self.advance(filled);
443        }
444
445        res
446    }
447}
448
449impl<'a, T: Default + Copy> BorrowedCursor<'a, T> {
450    /// Initializes all elements in the cursor with their default value and
451    /// returns them.
452    #[unstable(feature = "borrowed_buf_init", issue = "160476")]
453    #[inline]
454    pub fn ensure_init(&mut self) -> &mut [T] {
455        if !self.is_buf_init() {
456            self.unfilled_slice().write_default();
457            // SAFETY: buf is now initialized.
458            unsafe { self.set_buf_init(true) };
459        }
460
461        // SAFETY: these elements have just been initialized if they weren't before
462        unsafe { self.unfilled_slice().assume_init_mut() }
463    }
464}