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