twizzler/alloc/
global.rs

1use std::alloc::Layout;
2
3use twizzler_abi::object::ObjID;
4
5use super::Allocator;
6use crate::ptr::{GlobalPtr, Ref};
7
8/// A global pointer that owns the memory it points to, and will free it on drop.
9pub struct OwnedGlobalPtr<T, A: Allocator> {
10    global: GlobalPtr<T>,
11    alloc: A,
12}
13
14impl<T, A: Allocator> Drop for OwnedGlobalPtr<T, A> {
15    fn drop(&mut self) {
16        let layout = Layout::new::<T>();
17        unsafe { self.alloc.dealloc(self.global().cast(), layout) };
18    }
19}
20
21impl<T, A: Allocator> OwnedGlobalPtr<T, A> {
22    pub fn global(&self) -> GlobalPtr<T> {
23        self.global
24    }
25
26    pub unsafe fn from_global(global: GlobalPtr<T>, alloc: A) -> Self {
27        Self { global, alloc }
28    }
29
30    pub fn resolve<'a>(&'a self) -> Ref<'a, T> {
31        unsafe { self.global.resolve() }
32    }
33
34    pub fn allocator(&self) -> &A {
35        &self.alloc
36    }
37
38    /// Returns the object ID of the global pointer.
39    pub fn id(&self) -> ObjID {
40        self.global().id()
41    }
42
43    /// Returns the offset of the global pointer.
44    pub fn offset(&self) -> u64 {
45        self.global().offset()
46    }
47}