io: add boxed module for boxed bytes like vec::zeroed...

- proxmox_io::boxed::uninitialized(len) -> Box<[u8]>
  same as vec::uninitialized, but as a box

- proxmox_io::boxed::zeroed(len) -> Box<[u8]>
  same as vec::zeroed, but as a box

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
This commit is contained in:
Wolfgang Bumiller 2022-12-07 11:20:38 +01:00
parent a7d84effc5
commit 2610208794
2 changed files with 21 additions and 0 deletions

20
proxmox-io/src/boxed.rs Normal file
View File

@ -0,0 +1,20 @@
/// Uninitialized bytes, without `MaybeUninit`.
///
/// We're talking about bytes here, which we *allocate*. That is, we call a function, get a pointer
/// to stuff, and can use it. It's not UB in that there's nothing undefined about what's going on
/// here.
pub fn uninitialized(len: usize) -> Box<[u8]> {
unsafe {
let data = std::alloc::alloc(std::alloc::Layout::array::<u8>(len).unwrap());
Box::from_raw(std::ptr::slice_from_raw_parts_mut(data, len))
}
}
/// Zero-initialized bytes, meant for large sizes to avoid busting the stack.
pub fn zeroed(len: usize) -> Box<[u8]> {
let mut bytes = uninitialized(len);
unsafe {
std::ptr::write_bytes(bytes.as_mut_ptr(), 0, bytes.len());
}
bytes
}

View File

@ -23,4 +23,5 @@ pub use std_channel_writer::StdChannelWriter;
mod byte_buffer;
pub use byte_buffer::ByteBuffer;
pub mod boxed;
pub mod vec;