add the Mut<> type

This commit is contained in:
Intege-rs
2024-11-16 20:36:41 -05:00
parent e95a3d3557
commit f524b3c3a5
2 changed files with 32 additions and 2 deletions

View File

@@ -50,7 +50,7 @@ pub mod prelude {
pub use crate::time::dur;
pub use crate::fnv1::*;
pub use crate::pstruct::struct_offset;
pub use crate::pod::Pod;
pub use crate::pod::{Pod,Mut};
}
pub mod public {

View File

@@ -1,4 +1,5 @@
use core::mem::MaybeUninit;
use core::ops::{Deref, DerefMut};
/// Plain Old data type
pub trait Pod: Copy + 'static {
@@ -18,3 +19,32 @@ primitive!(f32, f64, usize, isize);
primitive!(());
impl<const LEN: usize, T: Pod> Pod for [T;LEN] {}
/// Type with unsafe interior mutability
/// but also with Send+Sync
///
/// internally just wraps UnsafeCell
#[repr(transparent)]
pub struct Mut<T>(core::cell::UnsafeCell<T>);
unsafe impl<T> Sync for Mut<T> {}
unsafe impl<T> Send for Mut<T> {}
impl<T: Sized> Mut<T> {
pub const fn new(value: T) -> Self {
Self(core::cell::UnsafeCell::new(value))
}
pub const fn as_ptr(&self) -> *mut T {
self.0.get()
}
}
impl<T: Pod> Mut<T> {
pub fn set(&self, value: T) { unsafe { core::ptr::write(self.as_ptr(), value) } }
pub fn get(&self) -> T { unsafe { core::ptr::read(self.as_ptr()) } }
}
impl<T> Deref for Mut<T> {
type Target = core::cell::UnsafeCell<T>;
fn deref(&self) -> &Self::Target { &self.0 }
}