From b336988d7d5ba3790c9d19ac4befcf5d7ee5aaad Mon Sep 17 00:00:00 2001 From: HampusM Date: Sun, 30 Mar 2025 16:27:27 +0200 Subject: feat: add remove fn --- src/util.rs | 70 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) (limited to 'src/util.rs') 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] unsafe { std::slice::from_raw_parts(self.as_ptr().cast::(), new_len) } } } + +#[derive(Debug)] +pub struct AnonUnique +{ + ptr: NonNull>, + 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::>(), + layout, + } + } + + pub fn as_slice_mut(&mut self) -> &mut [MaybeUninit] + { + unsafe { std::slice::from_raw_parts_mut(self.ptr.as_ptr(), self.layout.size()) } + } + + pub fn as_slice(&self) -> &[MaybeUninit] + { + 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(A), + B(B), +} + +impl Either +{ + pub fn as_a(&self) -> Option<&A> + { + match self { + Self::A(a) => Some(a), + Self::B(_) => None, + } + } +} -- cgit v1.2.3-18-g5258