use core::slice; use std::{ ops::{Deref, DerefMut}, usize, }; use crate::allocator::ALLOCATOR; #[derive(Debug)] pub struct SharedPtr([u8; N]); impl SharedPtr { pub fn new() -> Option { let mut allocator = ALLOCATOR.lock().unwrap(); let buf = unsafe { let buf = allocator.allocate(N)?; slice::from_raw_parts_mut(buf, N) }; Some(SharedPtr(buf.try_into().expect("Should never fail"))) } pub fn get_offset(&self) -> usize { let allocator = ALLOCATOR.lock().unwrap(); unsafe { allocator.get_offset(self.as_ptr()) } } } impl Deref for SharedPtr { type Target = [u8; N]; fn deref(&self) -> &Self::Target { &self.0 } } impl<'a, const N: usize> DerefMut for SharedPtr { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl Drop for SharedPtr { fn drop(&mut self) { let mut allocator = ALLOCATOR.lock().unwrap(); unsafe { allocator.deallocate(self.0.as_mut_ptr()); } } } #[cfg(test)] mod tests { use super::SharedPtr; #[test] fn test() { let mut x = SharedPtr::<10>::new().unwrap(); x[0] = 1; assert_eq!(x[0], 1); drop(x); } #[test] fn slice() { let mut x = SharedPtr::<10>::new().unwrap(); x[0] = 1; x[1] = 2; assert_eq!(x[0..=1], [1, 2]); } }