feat: make size of SharedPtr dynamic

This commit is contained in:
2024-10-10 16:37:04 +02:00
parent 9b466a72bb
commit 7f46573218

View File

@@ -4,54 +4,61 @@ use std::ops::{Deref, DerefMut};
use crate::allocator::ALLOCATOR; use crate::allocator::ALLOCATOR;
#[derive(Debug)] #[derive(Debug)]
pub struct SharedPtr<const N: usize>(*mut u8); pub struct SharedPtr {
ptr: *mut u8,
size: usize
}
unsafe impl<const N: usize> Send for SharedPtr<N> {} unsafe impl Send for SharedPtr {}
unsafe impl<const N: usize> Sync for SharedPtr<N> {} unsafe impl Sync for SharedPtr {}
impl<const N: usize> SharedPtr<N> { impl SharedPtr {
pub fn new() -> Option<Self> { pub fn new(size: usize) -> Option<Self> {
let mut allocator = ALLOCATOR.lock().unwrap(); 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 { pub fn get_offset(&self) -> usize {
let allocator = ALLOCATOR.lock().unwrap(); 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<const N: usize> Deref for SharedPtr<N> { impl Deref for SharedPtr {
type Target = [u8; N]; type Target = [u8];
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
unsafe { unsafe {
slice::from_raw_parts(self.0, N) slice::from_raw_parts(self.ptr, self.size)
.try_into() .try_into()
.expect("This should never fail") .expect("This should never fail")
} }
} }
} }
impl<const N: usize> DerefMut for SharedPtr<N> { impl DerefMut for SharedPtr {
fn deref_mut(&mut self) -> &mut Self::Target { fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { unsafe {
slice::from_raw_parts_mut(self.0, N) slice::from_raw_parts_mut(self.ptr, self.size)
.try_into() .try_into()
.expect("This should never fail") .expect("This should never fail")
} }
} }
} }
impl<const N: usize> Drop for SharedPtr<N> { impl Drop for SharedPtr {
fn drop(&mut self) { fn drop(&mut self) {
let mut allocator = ALLOCATOR.lock().unwrap(); let mut allocator = ALLOCATOR.lock().unwrap();
allocator.deallocate(self.0); allocator.deallocate(self.ptr);
} }
} }
@@ -61,7 +68,7 @@ mod tests {
#[test] #[test]
fn test() { fn test() {
let mut x = SharedPtr::<10>::new().unwrap(); let mut x = SharedPtr::new(10).unwrap();
x[0] = 1; x[0] = 1;
assert_eq!(x[0], 1); assert_eq!(x[0], 1);
drop(x); drop(x);
@@ -69,7 +76,7 @@ mod tests {
#[test] #[test]
fn slice() { fn slice() {
let mut x = SharedPtr::<10>::new().unwrap(); let mut x = SharedPtr::new(10).unwrap();
x[0] = 1; x[0] = 1;
x[1] = 2; x[1] = 2;
assert_eq!(x[0..=1], [1, 2]); assert_eq!(x[0..=1], [1, 2]);