From 7f46573218dc46417608a700a6146950dfea1442 Mon Sep 17 00:00:00 2001 From: Aaron Kaiser Date: Thu, 10 Oct 2024 16:37:04 +0200 Subject: [PATCH] feat: make size of SharedPtr dynamic --- src/sharedptr.rs | 41 ++++++++++++++++++++++++----------------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/src/sharedptr.rs b/src/sharedptr.rs index 278192f..fe0cbd7 100644 --- a/src/sharedptr.rs +++ b/src/sharedptr.rs @@ -4,54 +4,61 @@ use std::ops::{Deref, DerefMut}; use crate::allocator::ALLOCATOR; #[derive(Debug)] -pub struct SharedPtr(*mut u8); +pub struct SharedPtr { + ptr: *mut u8, + size: usize +} -unsafe impl Send for SharedPtr {} -unsafe impl Sync for SharedPtr {} +unsafe impl Send for SharedPtr {} +unsafe impl Sync for SharedPtr {} -impl SharedPtr { - pub fn new() -> Option { +impl SharedPtr { + pub fn new(size: usize) -> Option { let mut allocator = ALLOCATOR.lock().unwrap(); - let buf = allocator.allocate(N)?; + let buf = allocator.allocate(size)?; - Some(SharedPtr(buf)) + Some(SharedPtr{ptr: buf, size}) } pub fn get_offset(&self) -> usize { let allocator = ALLOCATOR.lock().unwrap(); - unsafe { allocator.get_offset(self.as_ptr()) } + unsafe { allocator.get_offset(self.ptr) } + } + + pub fn get_size(&self) -> usize { + self.size } } -impl Deref for SharedPtr { - type Target = [u8; N]; +impl Deref for SharedPtr { + type Target = [u8]; fn deref(&self) -> &Self::Target { unsafe { - slice::from_raw_parts(self.0, N) + slice::from_raw_parts(self.ptr, self.size) .try_into() .expect("This should never fail") } } } -impl DerefMut for SharedPtr { +impl DerefMut for SharedPtr { fn deref_mut(&mut self) -> &mut Self::Target { unsafe { - slice::from_raw_parts_mut(self.0, N) + slice::from_raw_parts_mut(self.ptr, self.size) .try_into() .expect("This should never fail") } } } -impl Drop for SharedPtr { +impl Drop for SharedPtr { fn drop(&mut self) { let mut allocator = ALLOCATOR.lock().unwrap(); - allocator.deallocate(self.0); + allocator.deallocate(self.ptr); } } @@ -61,7 +68,7 @@ mod tests { #[test] fn test() { - let mut x = SharedPtr::<10>::new().unwrap(); + let mut x = SharedPtr::new(10).unwrap(); x[0] = 1; assert_eq!(x[0], 1); drop(x); @@ -69,7 +76,7 @@ mod tests { #[test] fn slice() { - let mut x = SharedPtr::<10>::new().unwrap(); + let mut x = SharedPtr::new(10).unwrap(); x[0] = 1; x[1] = 2; assert_eq!(x[0..=1], [1, 2]);