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