1 | #![unstable (feature = "core_io_borrowed_buf" , issue = "117693" )] |
2 | |
3 | use crate::fmt::{self, Debug, Formatter}; |
4 | use crate::mem::{self, MaybeUninit}; |
5 | use crate::{cmp, ptr}; |
6 | |
7 | /// A borrowed byte buffer which is incrementally filled and initialized. |
8 | /// |
9 | /// This type is a sort of "double cursor". It tracks three regions in the buffer: a region at the beginning of the |
10 | /// buffer that has been logically filled with data, a region that has been initialized at some point but not yet |
11 | /// logically filled, and a region at the end that is fully uninitialized. The filled region is guaranteed to be a |
12 | /// subset of the initialized region. |
13 | /// |
14 | /// In summary, the contents of the buffer can be visualized as: |
15 | /// ```not_rust |
16 | /// [ capacity ] |
17 | /// [ filled | unfilled ] |
18 | /// [ initialized | uninitialized ] |
19 | /// ``` |
20 | /// |
21 | /// A `BorrowedBuf` is created around some existing data (or capacity for data) via a unique reference |
22 | /// (`&mut`). The `BorrowedBuf` can be configured (e.g., using `clear` or `set_init`), but cannot be |
23 | /// directly written. To write into the buffer, use `unfilled` to create a `BorrowedCursor`. The cursor |
24 | /// has write-only access to the unfilled portion of the buffer (you can think of it as a |
25 | /// write-only iterator). |
26 | /// |
27 | /// The lifetime `'data` is a bound on the lifetime of the underlying data. |
28 | pub struct BorrowedBuf<'data> { |
29 | /// The buffer's underlying data. |
30 | buf: &'data mut [MaybeUninit<u8>], |
31 | /// The length of `self.buf` which is known to be filled. |
32 | filled: usize, |
33 | /// The length of `self.buf` which is known to be initialized. |
34 | init: usize, |
35 | } |
36 | |
37 | impl Debug for BorrowedBuf<'_> { |
38 | fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { |
39 | f&mut DebugStruct<'_, '_>.debug_struct("BorrowedBuf" ) |
40 | .field("init" , &self.init) |
41 | .field("filled" , &self.filled) |
42 | .field(name:"capacity" , &self.capacity()) |
43 | .finish() |
44 | } |
45 | } |
46 | |
47 | /// Create a new `BorrowedBuf` from a fully initialized slice. |
48 | impl<'data> From<&'data mut [u8]> for BorrowedBuf<'data> { |
49 | #[inline ] |
50 | fn from(slice: &'data mut [u8]) -> BorrowedBuf<'data> { |
51 | let len: usize = slice.len(); |
52 | |
53 | BorrowedBuf { |
54 | // SAFETY: initialized data never becoming uninitialized is an invariant of BorrowedBuf |
55 | buf: unsafe { (slice as *mut [u8]).as_uninit_slice_mut().unwrap() }, |
56 | filled: 0, |
57 | init: len, |
58 | } |
59 | } |
60 | } |
61 | |
62 | /// Create a new `BorrowedBuf` from an uninitialized buffer. |
63 | /// |
64 | /// Use `set_init` if part of the buffer is known to be already initialized. |
65 | impl<'data> From<&'data mut [MaybeUninit<u8>]> for BorrowedBuf<'data> { |
66 | #[inline ] |
67 | fn from(buf: &'data mut [MaybeUninit<u8>]) -> BorrowedBuf<'data> { |
68 | BorrowedBuf { buf, filled: 0, init: 0 } |
69 | } |
70 | } |
71 | |
72 | impl<'data> BorrowedBuf<'data> { |
73 | /// Returns the total capacity of the buffer. |
74 | #[inline ] |
75 | pub fn capacity(&self) -> usize { |
76 | self.buf.len() |
77 | } |
78 | |
79 | /// Returns the length of the filled part of the buffer. |
80 | #[inline ] |
81 | pub fn len(&self) -> usize { |
82 | self.filled |
83 | } |
84 | |
85 | /// Returns the length of the initialized part of the buffer. |
86 | #[inline ] |
87 | pub fn init_len(&self) -> usize { |
88 | self.init |
89 | } |
90 | |
91 | /// Returns a shared reference to the filled portion of the buffer. |
92 | #[inline ] |
93 | pub fn filled(&self) -> &[u8] { |
94 | // SAFETY: We only slice the filled part of the buffer, which is always valid |
95 | unsafe { MaybeUninit::slice_assume_init_ref(&self.buf[0..self.filled]) } |
96 | } |
97 | |
98 | /// Returns a mutable reference to the filled portion of the buffer. |
99 | #[inline ] |
100 | pub fn filled_mut(&mut self) -> &mut [u8] { |
101 | // SAFETY: We only slice the filled part of the buffer, which is always valid |
102 | unsafe { MaybeUninit::slice_assume_init_mut(&mut self.buf[0..self.filled]) } |
103 | } |
104 | |
105 | /// Returns a cursor over the unfilled part of the buffer. |
106 | #[inline ] |
107 | pub fn unfilled<'this>(&'this mut self) -> BorrowedCursor<'this> { |
108 | BorrowedCursor { |
109 | start: self.filled, |
110 | // SAFETY: we never assign into `BorrowedCursor::buf`, so treating its |
111 | // lifetime covariantly is safe. |
112 | buf: unsafe { |
113 | mem::transmute::<&'this mut BorrowedBuf<'data>, &'this mut BorrowedBuf<'this>>(self) |
114 | }, |
115 | } |
116 | } |
117 | |
118 | /// Clears the buffer, resetting the filled region to empty. |
119 | /// |
120 | /// The number of initialized bytes is not changed, and the contents of the buffer are not modified. |
121 | #[inline ] |
122 | pub fn clear(&mut self) -> &mut Self { |
123 | self.filled = 0; |
124 | self |
125 | } |
126 | |
127 | /// Asserts that the first `n` bytes of the buffer are initialized. |
128 | /// |
129 | /// `BorrowedBuf` assumes that bytes are never de-initialized, so this method does nothing when called with fewer |
130 | /// bytes than are already known to be initialized. |
131 | /// |
132 | /// # Safety |
133 | /// |
134 | /// The caller must ensure that the first `n` unfilled bytes of the buffer have already been initialized. |
135 | #[inline ] |
136 | pub unsafe fn set_init(&mut self, n: usize) -> &mut Self { |
137 | self.init = cmp::max(self.init, n); |
138 | self |
139 | } |
140 | } |
141 | |
142 | /// A writeable view of the unfilled portion of a [`BorrowedBuf`]. |
143 | /// |
144 | /// The unfilled portion consists of an initialized and an uninitialized part; see [`BorrowedBuf`] |
145 | /// for details. |
146 | /// |
147 | /// Data can be written directly to the cursor by using [`append`](BorrowedCursor::append) or |
148 | /// indirectly by getting a slice of part or all of the cursor and writing into the slice. In the |
149 | /// indirect case, the caller must call [`advance`](BorrowedCursor::advance) after writing to inform |
150 | /// the cursor how many bytes have been written. |
151 | /// |
152 | /// Once data is written to the cursor, it becomes part of the filled portion of the underlying |
153 | /// `BorrowedBuf` and can no longer be accessed or re-written by the cursor. I.e., the cursor tracks |
154 | /// the unfilled part of the underlying `BorrowedBuf`. |
155 | /// |
156 | /// The lifetime `'a` is a bound on the lifetime of the underlying buffer (which means it is a bound |
157 | /// on the data in that buffer by transitivity). |
158 | #[derive (Debug)] |
159 | pub struct BorrowedCursor<'a> { |
160 | /// The underlying buffer. |
161 | // Safety invariant: we treat the type of buf as covariant in the lifetime of `BorrowedBuf` when |
162 | // we create a `BorrowedCursor`. This is only safe if we never replace `buf` by assigning into |
163 | // it, so don't do that! |
164 | buf: &'a mut BorrowedBuf<'a>, |
165 | /// The length of the filled portion of the underlying buffer at the time of the cursor's |
166 | /// creation. |
167 | start: usize, |
168 | } |
169 | |
170 | impl<'a> BorrowedCursor<'a> { |
171 | /// Reborrow this cursor by cloning it with a smaller lifetime. |
172 | /// |
173 | /// Since a cursor maintains unique access to its underlying buffer, the borrowed cursor is |
174 | /// not accessible while the new cursor exists. |
175 | #[inline ] |
176 | pub fn reborrow<'this>(&'this mut self) -> BorrowedCursor<'this> { |
177 | BorrowedCursor { |
178 | // SAFETY: we never assign into `BorrowedCursor::buf`, so treating its |
179 | // lifetime covariantly is safe. |
180 | buf: unsafe { |
181 | mem::transmute::<&'this mut BorrowedBuf<'a>, &'this mut BorrowedBuf<'this>>( |
182 | self.buf, |
183 | ) |
184 | }, |
185 | start: self.start, |
186 | } |
187 | } |
188 | |
189 | /// Returns the available space in the cursor. |
190 | #[inline ] |
191 | pub fn capacity(&self) -> usize { |
192 | self.buf.capacity() - self.buf.filled |
193 | } |
194 | |
195 | /// Returns the number of bytes written to this cursor since it was created from a `BorrowedBuf`. |
196 | /// |
197 | /// Note that if this cursor is a reborrowed clone of another, then the count returned is the |
198 | /// count written via either cursor, not the count since the cursor was reborrowed. |
199 | #[inline ] |
200 | pub fn written(&self) -> usize { |
201 | self.buf.filled - self.start |
202 | } |
203 | |
204 | /// Returns a shared reference to the initialized portion of the cursor. |
205 | #[inline ] |
206 | pub fn init_ref(&self) -> &[u8] { |
207 | // SAFETY: We only slice the initialized part of the buffer, which is always valid |
208 | unsafe { MaybeUninit::slice_assume_init_ref(&self.buf.buf[self.buf.filled..self.buf.init]) } |
209 | } |
210 | |
211 | /// Returns a mutable reference to the initialized portion of the cursor. |
212 | #[inline ] |
213 | pub fn init_mut(&mut self) -> &mut [u8] { |
214 | // SAFETY: We only slice the initialized part of the buffer, which is always valid |
215 | unsafe { |
216 | MaybeUninit::slice_assume_init_mut(&mut self.buf.buf[self.buf.filled..self.buf.init]) |
217 | } |
218 | } |
219 | |
220 | /// Returns a mutable reference to the uninitialized part of the cursor. |
221 | /// |
222 | /// It is safe to uninitialize any of these bytes. |
223 | #[inline ] |
224 | pub fn uninit_mut(&mut self) -> &mut [MaybeUninit<u8>] { |
225 | &mut self.buf.buf[self.buf.init..] |
226 | } |
227 | |
228 | /// Returns a mutable reference to the whole cursor. |
229 | /// |
230 | /// # Safety |
231 | /// |
232 | /// The caller must not uninitialize any bytes in the initialized portion of the cursor. |
233 | #[inline ] |
234 | pub unsafe fn as_mut(&mut self) -> &mut [MaybeUninit<u8>] { |
235 | &mut self.buf.buf[self.buf.filled..] |
236 | } |
237 | |
238 | /// Advance the cursor by asserting that `n` bytes have been filled. |
239 | /// |
240 | /// After advancing, the `n` bytes are no longer accessible via the cursor and can only be |
241 | /// accessed via the underlying buffer. I.e., the buffer's filled portion grows by `n` elements |
242 | /// and its unfilled portion (and the capacity of this cursor) shrinks by `n` elements. |
243 | /// |
244 | /// If less than `n` bytes initialized (by the cursor's point of view), `set_init` should be |
245 | /// called first. |
246 | /// |
247 | /// # Panics |
248 | /// |
249 | /// Panics if there are less than `n` bytes initialized. |
250 | #[inline ] |
251 | pub fn advance(&mut self, n: usize) -> &mut Self { |
252 | let filled = self.buf.filled.strict_add(n); |
253 | assert!(filled <= self.buf.init); |
254 | |
255 | self.buf.filled = filled; |
256 | self |
257 | } |
258 | |
259 | /// Advance the cursor by asserting that `n` bytes have been filled. |
260 | /// |
261 | /// After advancing, the `n` bytes are no longer accessible via the cursor and can only be |
262 | /// accessed via the underlying buffer. I.e., the buffer's filled portion grows by `n` elements |
263 | /// and its unfilled portion (and the capacity of this cursor) shrinks by `n` elements. |
264 | /// |
265 | /// # Safety |
266 | /// |
267 | /// The caller must ensure that the first `n` bytes of the cursor have been properly |
268 | /// initialised. |
269 | #[inline ] |
270 | pub unsafe fn advance_unchecked(&mut self, n: usize) -> &mut Self { |
271 | self.buf.filled += n; |
272 | self.buf.init = cmp::max(self.buf.init, self.buf.filled); |
273 | self |
274 | } |
275 | |
276 | /// Initializes all bytes in the cursor. |
277 | #[inline ] |
278 | pub fn ensure_init(&mut self) -> &mut Self { |
279 | let uninit = self.uninit_mut(); |
280 | // SAFETY: 0 is a valid value for MaybeUninit<u8> and the length matches the allocation |
281 | // since it is comes from a slice reference. |
282 | unsafe { |
283 | ptr::write_bytes(uninit.as_mut_ptr(), 0, uninit.len()); |
284 | } |
285 | self.buf.init = self.buf.capacity(); |
286 | |
287 | self |
288 | } |
289 | |
290 | /// Asserts that the first `n` unfilled bytes of the cursor are initialized. |
291 | /// |
292 | /// `BorrowedBuf` assumes that bytes are never de-initialized, so this method does nothing when |
293 | /// called with fewer bytes than are already known to be initialized. |
294 | /// |
295 | /// # Safety |
296 | /// |
297 | /// The caller must ensure that the first `n` bytes of the buffer have already been initialized. |
298 | #[inline ] |
299 | pub unsafe fn set_init(&mut self, n: usize) -> &mut Self { |
300 | self.buf.init = cmp::max(self.buf.init, self.buf.filled + n); |
301 | self |
302 | } |
303 | |
304 | /// Appends data to the cursor, advancing position within its buffer. |
305 | /// |
306 | /// # Panics |
307 | /// |
308 | /// Panics if `self.capacity()` is less than `buf.len()`. |
309 | #[inline ] |
310 | pub fn append(&mut self, buf: &[u8]) { |
311 | assert!(self.capacity() >= buf.len()); |
312 | |
313 | // SAFETY: we do not de-initialize any of the elements of the slice |
314 | unsafe { |
315 | MaybeUninit::copy_from_slice(&mut self.as_mut()[..buf.len()], buf); |
316 | } |
317 | |
318 | // SAFETY: We just added the entire contents of buf to the filled section. |
319 | unsafe { |
320 | self.set_init(buf.len()); |
321 | } |
322 | self.buf.filled += buf.len(); |
323 | } |
324 | } |
325 | |