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
225// SAFETY: A `BorrowedCursor<'a, T>` is a unique borrow of a `BorrowedBuf<'a, T>`, which is a
226// `&'a mut [MaybeUninit<T>]` and two `Copy` fields. The `buf` raw pointer is used like
227// `&mut [MaybeUninit<T>]` so `T: Send` -> `Send` and is: `T: Sync` -> `Sync`, and the
228// `borrowed_buf` only touches two `Copy` fields, without depending of `T`.
229unsafe impl<T: Send> Send for BorrowedCursor<'_, T> {}
230// SAFETY: See the `Send` impl above.
231unsafe impl<T: Sync> Sync for BorrowedCursor<'_, T> {}
232
233impl<T> Debug for BorrowedCursor<'_, T> {
234 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
235 let buf = BorrowedBufDebug {
236 init: self.is_buf_init(),
237 filled: self.filled(),
238 capacity: self.buf_len(),
239 };
240
241 f.debug_struct("BorrowedCursor").field("buf", &buf).finish()
242 }
243}
244
245// Helpers to access underlying buffer state.
246impl<'a, T> BorrowedCursor<'a, T> {
247 #[inline]
248 fn buf_mut(&mut self) -> &mut [MaybeUninit<T>] {
249 let len = self.buf_len();
250 // SAFETY: `buf` points to `len` elements that this cursor borrows exclusively.
251 unsafe { slice::from_raw_parts_mut(self.buf.as_ptr(), len) }
252 }
253
254 #[inline]
255 fn buf_len(&self) -> usize {
256 // SAFETY: We read just the metadata of `buf` and avoid retagging the reference.
257 unsafe {
258 let borrowed_buf = self.borrowed_buf.as_ptr();
259 let buf_ptr: *const &'a mut [MaybeUninit<T>] = &raw const (*borrowed_buf).buf;
260 // Same layout:
261 // https://doc.rust-lang.org/reference/type-layout.html#r-layout.pointer.intro
262 let buf_ptr: *const *const [MaybeUninit<T>] = buf_ptr.cast();
263 let buf: *const [MaybeUninit<T>] = *buf_ptr;
264 buf.len()
265 }
266 }
267
268 #[inline]
269 fn unfilled_slice(&mut self) -> &mut [MaybeUninit<T>] {
270 let filled = self.filled();
271 // SAFETY: always in bounds
272 unsafe { self.buf_mut().get_unchecked_mut(filled..) }
273 }
274
275 #[inline]
276 fn filled(&self) -> usize {
277 // SAFETY: We access just `filled` and avoid foreign read on `buf`.
278 unsafe { (*self.borrowed_buf.as_ptr()).filled }
279 }
280
281 #[inline]
282 fn is_buf_init(&self) -> bool {
283 // SAFETY: We access just `init` and avoid foreign read on `buf`.
284 unsafe { (*self.borrowed_buf.as_ptr()).init }
285 }
286
287 /// # Safety
288 ///
289 /// In case of `true` all the elements of the cursor must be initialized.
290 #[inline]
291 unsafe fn set_buf_init(&mut self, init: bool) {
292 // SAFETY: We access just `init` and avoid foreign read on `buf`.
293 unsafe {
294 (*self.borrowed_buf.as_ptr()).init = init;
295 }
296 }
297
298 /// # Safety
299 ///
300 /// The next `n` elements of the cursor must be initialized.
301 #[inline]
302 unsafe fn add_filled(&mut self, n: usize) {
303 // SAFETY: We access just `filled` and avoid foreign read on `buf`.
304 unsafe {
305 (*self.borrowed_buf.as_ptr()).filled += n;
306 }
307 }
308}
309
310impl<'a, T: Copy> BorrowedCursor<'a, T> {
311 /// Reborrows this cursor by cloning it with a smaller lifetime.
312 ///
313 /// Since a cursor maintains unique access to its underlying buffer, the borrowed cursor is
314 /// not accessible while the new cursor exists.
315 #[inline]
316 pub fn reborrow<'this>(&'this mut self) -> BorrowedCursor<'this, T> {
317 BorrowedCursor { buf: self.buf, borrowed_buf: self.borrowed_buf }
318 }
319
320 /// Returns the available space in the cursor.
321 #[inline]
322 pub fn capacity(&self) -> usize {
323 self.buf_len() - self.filled()
324 }
325
326 /// Returns the number of elements written to the `BorrowedBuf` this cursor was created from.
327 ///
328 /// In particular, the count returned is shared by all reborrows of the cursor.
329 #[inline]
330 pub fn written(&self) -> usize {
331 self.filled()
332 }
333
334 /// Returns `true` if the buffer is initialized.
335 #[unstable(feature = "borrowed_buf_init", issue = "160476")]
336 #[inline]
337 pub fn is_init(&self) -> bool {
338 self.is_buf_init()
339 }
340
341 /// Set the buffer as fully initialized.
342 ///
343 /// # Safety
344 ///
345 /// All the elements of the cursor must be initialized.
346 #[unstable(feature = "borrowed_buf_init", issue = "160476")]
347 #[inline]
348 pub unsafe fn set_init(&mut self) {
349 // SAFETY: the caller guarantees that all the elements of the cursor are initialized.
350 unsafe { self.set_buf_init(true) }
351 }
352
353 /// Returns a mutable reference to the whole cursor.
354 ///
355 /// # Safety
356 ///
357 /// The caller must not uninitialize any elements of the cursor if it is initialized.
358 #[inline]
359 pub unsafe fn as_mut(&mut self) -> &mut [MaybeUninit<T>] {
360 self.unfilled_slice()
361 }
362
363 /// Advances the cursor by asserting that `n` elements have been filled.
364 ///
365 /// After advancing, the `n` elements are no longer accessible via the cursor and can only be
366 /// accessed via the underlying buffer. I.e., the buffer's filled portion grows by `n` elements
367 /// and its unfilled portion (and the capacity of this cursor) shrinks by `n` elements.
368 ///
369 /// If less than `n` elements initialized (by the cursor's point of view), `set_init` should be
370 /// called first.
371 ///
372 /// # Panics
373 ///
374 /// Panics if there are less than `n` elements initialized.
375 #[unstable(feature = "borrowed_buf_init", issue = "160476")]
376 #[inline]
377 pub fn advance_checked(&mut self, n: usize) -> &mut Self {
378 // The subtraction cannot underflow by invariant of this type.
379 let init_unfilled = if self.is_buf_init() { self.buf_len() - self.filled() } else { 0 };
380 assert!(n <= init_unfilled);
381
382 // SAFETY: the next `n` elements are initialized, as asserted above.
383 unsafe { self.advance(n) };
384 self
385 }
386
387 /// Advances the cursor by asserting that `n` elements have been filled.
388 ///
389 /// After advancing, the `n` elements are no longer accessible via the cursor and can only be
390 /// accessed via the underlying buffer. I.e., the buffer's filled portion grows by `n` elements
391 /// and its unfilled portion (and the capacity of this cursor) shrinks by `n` elements.
392 ///
393 /// # Safety
394 ///
395 /// The caller must ensure that the first `n` elements of the cursor have been initialized.
396 #[inline]
397 pub unsafe fn advance(&mut self, n: usize) -> &mut Self {
398 // SAFETY: the caller guarantees that the first `n` elements of the cursor are initialized.
399 unsafe { self.add_filled(n) };
400 self
401 }
402
403 /// Append elements to the cursor, advancing position within its buffer.
404 ///
405 /// # Panics
406 ///
407 /// Panics if `self.capacity()` is less than `buf.len()`.
408 #[inline]
409 pub fn append(&mut self, buf: &[T]) {
410 assert!(self.capacity() >= buf.len());
411
412 // SAFETY: we do not de-initialize any of the elements of the slice
413 unsafe {
414 self.as_mut()[..buf.len()].write_copy_of_slice(buf);
415 }
416
417 // SAFETY: these elements have just been initialized.
418 unsafe { self.advance(buf.len()) };
419 }
420
421 /// Runs the given closure with a `BorrowedBuf` containing the unfilled part
422 /// of the cursor.
423 ///
424 /// This enables inspecting what was written to the cursor.
425 ///
426 /// # Panics
427 ///
428 /// Panics if the `BorrowedBuf` given to the closure is replaced by another
429 /// one.
430 pub fn with_unfilled_buf<R>(&mut self, f: impl FnOnce(&mut BorrowedBuf<'_, T>) -> R) -> R {
431 let mut buf = BorrowedBuf::from(self.reborrow());
432 let prev_ptr = buf.buf as *const _;
433 let res = f(&mut buf);
434
435 // Check that the caller didn't replace the `BorrowedBuf`.
436 // This is necessary for the safety of the code below: if the check wasn't
437 // there, one could mark some elements as initialized even though they aren't.
438 assert!(core::ptr::eq(prev_ptr, buf.buf));
439
440 let filled = buf.filled;
441 let init = buf.init;
442
443 // Update `init` and `filled` fields with what was written to the buffer.
444 // `self.buf.filled` was the starting length of the `BorrowedBuf`.
445 //
446 // SAFETY: These elements were initialized/filled in the `BorrowedBuf`, and therefore they
447 // are initialized/filled in the cursor too, because the buffer wasn't replaced.
448 unsafe {
449 self.set_buf_init(init);
450 self.advance(filled);
451 }
452
453 res
454 }
455}
456
457impl<'a, T: Default + Copy> BorrowedCursor<'a, T> {
458 /// Initializes all elements in the cursor with their default value and
459 /// returns them.
460 #[unstable(feature = "borrowed_buf_init", issue = "160476")]
461 #[inline]
462 pub fn ensure_init(&mut self) -> &mut [T] {
463 if !self.is_buf_init() {
464 self.unfilled_slice().write_default();
465 // SAFETY: buf is now initialized.
466 unsafe { self.set_buf_init(true) };
467 }
468
469 // SAFETY: these elements have just been initialized if they weren't before
470 unsafe { self.unfilled_slice().assume_init_mut() }
471 }
472}