Files
shared_memory_heap/src/sharedptr.rs
Aaron Kaiser 43aa454a29 chore: The slice test encounters a weird error that looks like rust is doing something weird
---- sharedptr::tests::slice stdout ----
thread 'sharedptr::tests::slice' panicked at src/allocator.rs:106:9:
assertion `left == right` failed
  left: true
 right: true
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
2024-05-06 14:13:07 +02:00

75 lines
1.5 KiB
Rust

use core::slice;
use std::{
ops::{Deref, DerefMut},
usize,
};
use crate::allocator::ALLOCATOR;
#[derive(Debug)]
pub struct SharedPtr<const N: usize>([u8; N]);
impl<const N: usize> SharedPtr<N> {
pub fn new() -> Option<Self> {
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<const N: usize> Deref for SharedPtr<N> {
type Target = [u8; N];
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'a, const N: usize> DerefMut for SharedPtr<N> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<const N: usize> Drop for SharedPtr<N> {
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]);
}
}