From f524b3c3a55fc2dc60d7301b34e02a4e7cd94207 Mon Sep 17 00:00:00 2001 From: Intege-rs Date: Sat, 16 Nov 2024 20:36:41 -0500 Subject: [PATCH] add the Mut<> type --- sub/core/src/lib.rs | 2 +- sub/core/src/pod.rs | 32 +++++++++++++++++++++++++++++++- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/sub/core/src/lib.rs b/sub/core/src/lib.rs index be64942..bf11b8d 100644 --- a/sub/core/src/lib.rs +++ b/sub/core/src/lib.rs @@ -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 { diff --git a/sub/core/src/pod.rs b/sub/core/src/pod.rs index 0e1f4d4..9e3be71 100644 --- a/sub/core/src/pod.rs +++ b/sub/core/src/pod.rs @@ -1,4 +1,5 @@ use core::mem::MaybeUninit; +use core::ops::{Deref, DerefMut}; /// Plain Old data type pub trait Pod: Copy + 'static { @@ -17,4 +18,33 @@ primitive!(i8, i16, i32, i64, i128); primitive!(f32, f64, usize, isize); primitive!(()); -impl Pod for [T;LEN] {} \ No newline at end of file +impl Pod for [T;LEN] {} + + +/// Type with unsafe interior mutability +/// but also with Send+Sync +/// +/// internally just wraps UnsafeCell +#[repr(transparent)] +pub struct Mut(core::cell::UnsafeCell); +unsafe impl Sync for Mut {} +unsafe impl Send for Mut {} + +impl Mut { + 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 Mut { + 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 Deref for Mut { + type Target = core::cell::UnsafeCell; + fn deref(&self) -> &Self::Target { &self.0 } +} \ No newline at end of file