diff options
author | HampusM <hampus@hampusmat.com> | 2025-03-30 16:27:27 +0200 |
---|---|---|
committer | HampusM <hampus@hampusmat.com> | 2025-03-30 16:27:27 +0200 |
commit | b336988d7d5ba3790c9d19ac4befcf5d7ee5aaad (patch) | |
tree | 38727fa291f0af93264448eb49503ace94665482 /src/util.rs | |
parent | af42d53f0f6f15da05488bf97b0989691259dcce (diff) |
feat: add remove fn
Diffstat (limited to 'src/util.rs')
-rw-r--r-- | src/util.rs | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/src/util.rs b/src/util.rs index 70e114b..8ff79c7 100644 --- a/src/util.rs +++ b/src/util.rs @@ -1,4 +1,6 @@ +use std::alloc::{alloc, dealloc, handle_alloc_error, Layout}; use std::mem::MaybeUninit; +use std::ptr::NonNull; pub trait MaybeUninitByteSlice { @@ -26,3 +28,71 @@ impl MaybeUninitByteSlice for &[MaybeUninit<u8>] unsafe { std::slice::from_raw_parts(self.as_ptr().cast::<Item>(), new_len) } } } + +#[derive(Debug)] +pub struct AnonUnique +{ + ptr: NonNull<MaybeUninit<u8>>, + layout: Layout, +} + +impl AnonUnique +{ + pub fn new_uninit(layout: Layout) -> Self + { + if layout.size() == 0 { + return Self { ptr: NonNull::dangling(), layout }; + } + + let Some(ptr) = NonNull::new(unsafe { alloc(layout) }) else { + handle_alloc_error(layout); + }; + + Self { + ptr: ptr.cast::<MaybeUninit<u8>>(), + layout, + } + } + + pub fn as_slice_mut(&mut self) -> &mut [MaybeUninit<u8>] + { + unsafe { std::slice::from_raw_parts_mut(self.ptr.as_ptr(), self.layout.size()) } + } + + pub fn as_slice(&self) -> &[MaybeUninit<u8>] + { + unsafe { std::slice::from_raw_parts(self.ptr.as_ptr(), self.layout.size()) } + } +} + +impl Drop for AnonUnique +{ + fn drop(&mut self) + { + if self.layout.size() == 0 { + return; + } + + unsafe { + dealloc(self.ptr.as_ptr().cast(), self.layout); + } + } +} + +#[derive(Debug)] +pub enum Either<A, B> +{ + A(A), + B(B), +} + +impl<A, B> Either<A, B> +{ + pub fn as_a(&self) -> Option<&A> + { + match self { + Self::A(a) => Some(a), + Self::B(_) => None, + } + } +} |