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 bytes, 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 bytes that have been filled and
10/// the region that remains uninitialized.
11///
12/// The contents of the buffer can be visualized as:
13/// ```not_rust
14/// [ capacity ]
15/// [ len: filled and initialized | capacity - len: uninitialized ]
16/// ```
17///
18/// Note that `BorrowedBuf` does not distinguish between uninitialized data and data that was
19/// previously initialized but no longer contains valid data.
20///
21/// A `BorrowedBuf` is created around some existing data (or capacity for data) via a unique
22/// reference (`&mut`). The `BorrowedBuf` can be configured (e.g., using `clear` or `set_len`), but
23/// cannot be directly written. To write into the buffer, use `unfilled` to create a
24/// `BorrowedCursor`. The cursor has write-only access to the unfilled portion of the buffer.
25///
26/// The lifetime `'data` is a bound on the lifetime of the underlying data.
27pub struct BorrowedBuf<'data> {
28 /// The buffer's underlying data.
29 buf: &'data mut [MaybeUninit<u8>],
30 /// The length of `self.buf` which is known to be filled.
31 filled: usize,
32}
33
34impl Debug for BorrowedBuf<'_> {
35 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
36 f.debug_struct("BorrowedBuf")
37 .field("filled", &self.filled)
38 .field("capacity", &self.capacity())
39 .finish()
40 }
41}
42
43/// Creates a new `BorrowedBuf` from a fully initialized slice.
44impl<'data> From<&'data mut [u8]> for BorrowedBuf<'data> {
45 #[inline]
46 fn from(slice: &'data mut [u8]) -> BorrowedBuf<'data> {
47 BorrowedBuf {
48 // SAFETY: Always in bounds. We treat the buffer as uninitialized, even though it's
49 // already initialized.
50 buf: unsafe { (slice as *mut [u8]).as_uninit_slice_mut().unwrap() },
51 filled: 0,
52 }
53 }
54}
55
56/// Creates a new `BorrowedBuf` from an uninitialized buffer.
57///
58/// Use `set_filled` if part of the buffer is known to be already filled.
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 }
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: Always in bounds. We treat the buffer as uninitialized.
74 buf: unsafe { buf.buf.buf.get_unchecked_mut(buf.buf.filled..) },
75 filled: 0,
76 }
77 }
78}
79
80impl<'data> BorrowedBuf<'data> {
81 /// Returns the total capacity of the buffer.
82 #[inline]
83 pub fn capacity(&self) -> usize {
84 self.buf.len()
85 }
86
87 /// Returns the length of the filled part of the buffer.
88 #[inline]
89 pub fn len(&self) -> usize {
90 self.filled
91 }
92
93 /// Returns a shared reference to the filled portion of the buffer.
94 #[inline]
95 pub fn filled(&self) -> &[u8] {
96 // SAFETY: We only slice the filled part of the buffer, which is always valid
97 unsafe {
98 let buf = self.buf.get_unchecked(..self.filled);
99 buf.assume_init_ref()
100 }
101 }
102
103 /// Returns a mutable reference to the filled portion of the buffer.
104 #[inline]
105 pub fn filled_mut(&mut self) -> &mut [u8] {
106 // SAFETY: We only slice the filled part of the buffer, which is always valid
107 unsafe {
108 let buf = self.buf.get_unchecked_mut(..self.filled);
109 buf.assume_init_mut()
110 }
111 }
112
113 /// Returns a shared reference to the filled portion of the buffer with its original lifetime.
114 #[inline]
115 pub fn into_filled(self) -> &'data [u8] {
116 // SAFETY: We only slice the filled part of the buffer, which is always valid
117 unsafe {
118 let buf = self.buf.get_unchecked(..self.filled);
119 buf.assume_init_ref()
120 }
121 }
122
123 /// Returns a mutable reference to the filled portion of the buffer with its original lifetime.
124 #[inline]
125 pub fn into_filled_mut(self) -> &'data mut [u8] {
126 // SAFETY: We only slice the filled part of the buffer, which is always valid
127 unsafe {
128 let buf = self.buf.get_unchecked_mut(..self.filled);
129 buf.assume_init_mut()
130 }
131 }
132
133 /// Returns a cursor over the unfilled part of the buffer.
134 #[inline]
135 pub fn unfilled<'this>(&'this mut self) -> BorrowedCursor<'this> {
136 BorrowedCursor {
137 // SAFETY: we never assign into `BorrowedCursor::buf`, so treating its
138 // lifetime covariantly is safe.
139 buf: unsafe {
140 mem::transmute::<&'this mut BorrowedBuf<'data>, &'this mut BorrowedBuf<'this>>(self)
141 },
142 }
143 }
144
145 /// Clears the buffer, resetting the filled region to empty.
146 ///
147 /// The contents of the buffer are not modified.
148 #[inline]
149 pub fn clear(&mut self) -> &mut Self {
150 self.filled = 0;
151 self
152 }
153}
154
155/// A writeable view of the unfilled portion of a [`BorrowedBuf`].
156///
157/// Data can be written directly to the cursor by using [`append`](BorrowedCursor::append) or
158/// indirectly by getting a slice of part or all of the cursor and writing into the slice. In the
159/// indirect case, the caller must call [`advance`](BorrowedCursor::advance) after writing to inform
160/// the cursor how many bytes have been written.
161///
162/// Once data is written to the cursor, it becomes part of the filled portion of the underlying
163/// `BorrowedBuf` and can no longer be accessed or re-written by the cursor. I.e., the cursor tracks
164/// the unfilled part of the underlying `BorrowedBuf`.
165///
166/// The lifetime `'a` is a bound on the lifetime of the underlying buffer (which means it is a bound
167/// on the data in that buffer by transitivity).
168#[derive(Debug)]
169pub struct BorrowedCursor<'a> {
170 /// The underlying buffer.
171 // Safety invariant: we treat the type of buf as covariant in the lifetime of `BorrowedBuf` when
172 // we create a `BorrowedCursor`. This is only safe if we never replace `buf` by assigning into
173 // it, so don't do that!
174 buf: &'a mut BorrowedBuf<'a>,
175}
176
177impl<'a> BorrowedCursor<'a> {
178 /// Reborrows this cursor by cloning it with a smaller lifetime.
179 ///
180 /// Since a cursor maintains unique access to its underlying buffer, the borrowed cursor is
181 /// not accessible while the new cursor exists.
182 #[inline]
183 pub fn reborrow<'this>(&'this mut self) -> BorrowedCursor<'this> {
184 BorrowedCursor {
185 // SAFETY: we never assign into `BorrowedCursor::buf`, so treating its
186 // lifetime covariantly is safe.
187 buf: unsafe {
188 mem::transmute::<&'this mut BorrowedBuf<'a>, &'this mut BorrowedBuf<'this>>(
189 self.buf,
190 )
191 },
192 }
193 }
194
195 /// Returns the available space in the cursor.
196 #[inline]
197 pub fn capacity(&self) -> usize {
198 self.buf.capacity() - self.buf.filled
199 }
200
201 /// Returns the number of bytes written to the `BorrowedBuf` this cursor was created from.
202 ///
203 /// In particular, the count returned is shared by all reborrows of the cursor.
204 #[inline]
205 pub fn written(&self) -> usize {
206 self.buf.filled
207 }
208
209 /// Returns a mutable reference to the whole cursor.
210 ///
211 /// # Safety
212 ///
213 /// The caller must not uninitialize any previously initialized bytes.
214 #[inline]
215 pub unsafe fn as_mut(&mut self) -> &mut [MaybeUninit<u8>] {
216 // SAFETY: always in bounds
217 unsafe { self.buf.buf.get_unchecked_mut(self.buf.filled..) }
218 }
219
220 /// Advances the cursor by asserting that `n` bytes have been filled.
221 ///
222 /// After advancing, the `n` bytes are no longer accessible via the cursor and can only be
223 /// accessed via the underlying buffer. I.e., the buffer's filled portion grows by `n` elements
224 /// and its unfilled portion (and the capacity of this cursor) shrinks by `n` elements.
225 ///
226 /// # Safety
227 ///
228 /// The caller must ensure that the first `n` bytes of the cursor have been initialized. `n`
229 /// must not exceed the remaining capacity of this cursor.
230 #[inline]
231 pub unsafe fn advance(&mut self, n: usize) -> &mut Self {
232 self.buf.filled += n;
233 self
234 }
235
236 /// Appends data to the cursor, advancing position within its buffer.
237 ///
238 /// # Panics
239 ///
240 /// Panics if `self.capacity()` is less than `buf.len()`.
241 #[inline]
242 pub fn append(&mut self, buf: &[u8]) {
243 assert!(self.capacity() >= buf.len());
244
245 // SAFETY: we do not de-initialize any of the elements of the slice
246 unsafe {
247 self.as_mut()[..buf.len()].write_copy_of_slice(buf);
248 }
249
250 self.buf.filled += buf.len();
251 }
252
253 /// Runs the given closure with a `BorrowedBuf` containing the unfilled part
254 /// of the cursor.
255 ///
256 /// This enables inspecting what was written to the cursor.
257 ///
258 /// # Panics
259 ///
260 /// Panics if the `BorrowedBuf` given to the closure is replaced by another
261 /// one.
262 pub fn with_unfilled_buf<T>(&mut self, f: impl FnOnce(&mut BorrowedBuf<'_>) -> T) -> T {
263 let mut buf = BorrowedBuf::from(self.reborrow());
264 let prev_ptr = buf.buf as *const _;
265 let res = f(&mut buf);
266
267 // Check that the caller didn't replace the `BorrowedBuf`.
268 // This is necessary for the safety of the code below: if the check wasn't
269 // there, one could mark some bytes as initialized even though there aren't.
270 assert!(core::ptr::addr_eq(prev_ptr, buf.buf));
271
272 // SAFETY: These bytes were filled in the `BorrowedBuf`, so they're filled in the cursor
273 // too, because the buffer wasn't replaced.
274 self.buf.filled += buf.filled;
275
276 res
277 }
278}