Skip to content

Commit 4dde290

Browse files
committed
feat: add initialized_unfilled to ReadBufCursor
1 parent aecf5ab commit 4dde290

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

‎src/rt/io.rs‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -382,6 +382,39 @@ impl ReadBufCursor<'_> {
382382
}
383383
self.buf.filled = end;
384384
}
385+
386+
/// Returns a mutable reference to the unfilled part of the buffer, ensuring it is fully initialized.
387+
#[inline]
388+
pub fn initialize_unfilled(&mut self) -> &mut [u8] {
389+
self.initialize_unfilled_to(self.remaining())
390+
}
391+
392+
/// Returns a mutable reference to the first `n` bytes of the unfilled part of the buffer, ensuring it is
393+
/// fully initialized.
394+
///
395+
/// # Panics
396+
///
397+
/// Panics if `self.remaining()` is less than `n`.
398+
#[inline]
399+
pub fn initialize_unfilled_to(&mut self, n: usize) -> &mut [u8] {
400+
assert!(self.remaining() >= n, "n overflows remaining");
401+
402+
// This can't overflow as the assert above would have panicked otherwise.
403+
let end = self.buf.filled + n;
404+
405+
if self.buf.init < end {
406+
unsafe {
407+
self.buf.raw[self.buf.init..end]
408+
.as_mut_ptr()
409+
.write_bytes(0, end - self.buf.init);
410+
}
411+
self.buf.init = end;
412+
}
413+
414+
let slice = &mut self.buf.raw[self.buf.filled..end];
415+
416+
unsafe { &mut *(slice as *mut [MaybeUninit<u8>] as *mut [u8]) }
417+
}
385418
}
386419

387420
macro_rules! deref_async_read {

0 commit comments

Comments
 (0)