From 26102087942b5b352a70d5eecad99ee5c53dec36 Mon Sep 17 00:00:00 2001 From: Wolfgang Bumiller Date: Wed, 7 Dec 2022 11:20:38 +0100 Subject: [PATCH] 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 --- proxmox-io/src/boxed.rs | 20 ++++++++++++++++++++ proxmox-io/src/lib.rs | 1 + 2 files changed, 21 insertions(+) create mode 100644 proxmox-io/src/boxed.rs diff --git a/proxmox-io/src/boxed.rs b/proxmox-io/src/boxed.rs new file mode 100644 index 00000000..7af51cfc --- /dev/null +++ b/proxmox-io/src/boxed.rs @@ -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::(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 +} diff --git a/proxmox-io/src/lib.rs b/proxmox-io/src/lib.rs index a32c0105..e6cc0beb 100644 --- a/proxmox-io/src/lib.rs +++ b/proxmox-io/src/lib.rs @@ -23,4 +23,5 @@ pub use std_channel_writer::StdChannelWriter; mod byte_buffer; pub use byte_buffer::ByteBuffer; +pub mod boxed; pub mod vec;