1#![unstable(feature = "core_io_borrowed_buf", issue = "117693")]
2
3use crate::fmt::{self, Debug, Formatter};
4use crate::mem::{self, MaybeUninit};
5use 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.
28pub 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
37impl 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.
48impl<'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.
65impl<'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
72impl<'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`](BorrowedBuf).
143///
144/// Provides access to the initialized and uninitialized parts of the underlying `BorrowedBuf`.
145/// Data can be written directly to the cursor by using [`append`](BorrowedCursor::append) or
146/// indirectly by getting a slice of part or all of the cursor and writing into the slice. In the
147/// indirect case, the caller must call [`advance`](BorrowedCursor::advance) after writing to inform
148/// the cursor how many bytes have been written.
149///
150/// Once data is written to the cursor, it becomes part of the filled portion of the underlying
151/// `BorrowedBuf` and can no longer be accessed or re-written by the cursor. I.e., the cursor tracks
152/// the unfilled part of the underlying `BorrowedBuf`.
153///
154/// The lifetime `'a` is a bound on the lifetime of the underlying buffer (which means it is a bound
155/// on the data in that buffer by transitivity).
156#[derive(Debug)]
157pub struct BorrowedCursor<'a> {
158 /// The underlying buffer.
159 // Safety invariant: we treat the type of buf as covariant in the lifetime of `BorrowedBuf` when
160 // we create a `BorrowedCursor`. This is only safe if we never replace `buf` by assigning into
161 // it, so don't do that!
162 buf: &'a mut BorrowedBuf<'a>,
163 /// The length of the filled portion of the underlying buffer at the time of the cursor's
164 /// creation.
165 start: usize,
166}
167
168impl<'a> BorrowedCursor<'a> {
169 /// Reborrow this cursor by cloning it with a smaller lifetime.
170 ///
171 /// Since a cursor maintains unique access to its underlying buffer, the borrowed cursor is
172 /// not accessible while the new cursor exists.
173 #[inline]
174 pub fn reborrow<'this>(&'this mut self) -> BorrowedCursor<'this> {
175 BorrowedCursor {
176 // SAFETY: we never assign into `BorrowedCursor::buf`, so treating its
177 // lifetime covariantly is safe.
178 buf: unsafe {
179 mem::transmute::<&'this mut BorrowedBuf<'a>, &'this mut BorrowedBuf<'this>>(
180 self.buf,
181 )
182 },
183 start: self.start,
184 }
185 }
186
187 /// Returns the available space in the cursor.
188 #[inline]
189 pub fn capacity(&self) -> usize {
190 self.buf.capacity() - self.buf.filled
191 }
192
193 /// Returns the number of bytes written to this cursor since it was created from a `BorrowedBuf`.
194 ///
195 /// Note that if this cursor is a reborrowed clone of another, then the count returned is the
196 /// count written via either cursor, not the count since the cursor was reborrowed.
197 #[inline]
198 pub fn written(&self) -> usize {
199 self.buf.filled - self.start
200 }
201
202 /// Returns a shared reference to the initialized portion of the cursor.
203 #[inline]
204 pub fn init_ref(&self) -> &[u8] {
205 // SAFETY: We only slice the initialized part of the buffer, which is always valid
206 unsafe { MaybeUninit::slice_assume_init_ref(&self.buf.buf[self.buf.filled..self.buf.init]) }
207 }
208
209 /// Returns a mutable reference to the initialized portion of the cursor.
210 #[inline]
211 pub fn init_mut(&mut self) -> &mut [u8] {
212 // SAFETY: We only slice the initialized part of the buffer, which is always valid
213 unsafe {
214 MaybeUninit::slice_assume_init_mut(&mut self.buf.buf[self.buf.filled..self.buf.init])
215 }
216 }
217
218 /// Returns a mutable reference to the uninitialized part of the cursor.
219 ///
220 /// It is safe to uninitialize any of these bytes.
221 #[inline]
222 pub fn uninit_mut(&mut self) -> &mut [MaybeUninit<u8>] {
223 &mut self.buf.buf[self.buf.init..]
224 }
225
226 /// Returns a mutable reference to the whole cursor.
227 ///
228 /// # Safety
229 ///
230 /// The caller must not uninitialize any bytes in the initialized portion of the cursor.
231 #[inline]
232 pub unsafe fn as_mut(&mut self) -> &mut [MaybeUninit<u8>] {
233 &mut self.buf.buf[self.buf.filled..]
234 }
235
236 /// Advance the cursor by asserting that `n` bytes have been filled.
237 ///
238 /// After advancing, the `n` bytes are no longer accessible via the cursor and can only be
239 /// accessed via the underlying buffer. I.e., the buffer's filled portion grows by `n` elements
240 /// and its unfilled portion (and the capacity of this cursor) shrinks by `n` elements.
241 ///
242 /// # Safety
243 ///
244 /// The caller must ensure that the first `n` bytes of the cursor have been properly
245 /// initialised.
246 #[inline]
247 pub unsafe fn advance(&mut self, n: usize) -> &mut Self {
248 self.buf.filled += n;
249 self.buf.init = cmp::max(self.buf.init, self.buf.filled);
250 self
251 }
252
253 /// Initializes all bytes in the cursor.
254 #[inline]
255 pub fn ensure_init(&mut self) -> &mut Self {
256 let uninit = self.uninit_mut();
257 // SAFETY: 0 is a valid value for MaybeUninit<u8> and the length matches the allocation
258 // since it is comes from a slice reference.
259 unsafe {
260 ptr::write_bytes(uninit.as_mut_ptr(), 0, uninit.len());
261 }
262 self.buf.init = self.buf.capacity();
263
264 self
265 }
266
267 /// Asserts that the first `n` unfilled bytes of the cursor are initialized.
268 ///
269 /// `BorrowedBuf` assumes that bytes are never de-initialized, so this method does nothing when
270 /// called with fewer bytes than are already known to be initialized.
271 ///
272 /// # Safety
273 ///
274 /// The caller must ensure that the first `n` bytes of the buffer have already been initialized.
275 #[inline]
276 pub unsafe fn set_init(&mut self, n: usize) -> &mut Self {
277 self.buf.init = cmp::max(self.buf.init, self.buf.filled + n);
278 self
279 }
280
281 /// Appends data to the cursor, advancing position within its buffer.
282 ///
283 /// # Panics
284 ///
285 /// Panics if `self.capacity()` is less than `buf.len()`.
286 #[inline]
287 pub fn append(&mut self, buf: &[u8]) {
288 assert!(self.capacity() >= buf.len());
289
290 // SAFETY: we do not de-initialize any of the elements of the slice
291 unsafe {
292 MaybeUninit::write_slice(&mut self.as_mut()[..buf.len()], buf);
293 }
294
295 // SAFETY: We just added the entire contents of buf to the filled section.
296 unsafe {
297 self.set_init(buf.len());
298 }
299 self.buf.filled += buf.len();
300 }
301}
302