gc_api/alloc/mod.rs
1use crate::error::Error;
2use std::alloc::Layout;
3use std::ptr::NonNull;
4
5pub mod access;
6pub mod api;
7pub mod marker;
8
9pub use access::*;
10pub use api::*;
11pub use marker::*;
12
13/// A marker trait which can be used to indicate a type can be allocated by an allocator.
14pub trait Alloc<T: ?Sized>: Sized {
15 /// An alternative to T that will guarentee that the created value can be accessed mutably by
16 /// [crate::alloc::access::AccessorMut]. The purpose of having this is that some GCs will have
17 /// built in locking capabilities and can avoid the need for manually using some form of lock
18 /// and having this field allows for a generic approach for switching between using an extra
19 /// lock and the regular value.
20 ///
21 /// For where `T: Sized`, it can be assumed `MutTy: From<T>`. This bound is not included since
22 /// this trait covers DSTs too and it would complicate the process for this to be required.
23 type MutTy;
24
25 type RawHandle: Sized;
26
27 type Flags;
28
29 /// Performs allocation for the specified type
30 ///
31 /// # Safety
32 /// The given layout must be a valid layout for some variation of `T`. This applies to both
33 /// `Sized` and DST `T`s.
34 unsafe fn try_alloc_layout(&mut self, layout: Layout) -> Result<Self::RawHandle, Error>;
35
36 /// Retrieves a pointer to the memory on the heap for a given handle
37 ///
38 /// # Safety
39 /// This function should only be used in a single thread context. To safely call this function,
40 /// handle should not represent an object that may be in use on another thread. The primary use
41 /// of this function is initialzing new allocations, but may also include finalizing objects
42 /// before dropping.
43 unsafe fn handle_ptr(&self, handle: &Self::RawHandle) -> NonNull<u8>;
44
45 /// Unlike handle_ptr, the purpose of this function is to also provide pointer metadata (such as
46 /// with slices). This can be helpful for dealing with some cases where some types are handled
47 /// in a different implementation.
48 ///
49 /// # Safety
50 /// This function can only be used when exclusive access is held.
51 unsafe fn handle_ref(&self, handle: &Self::RawHandle) -> &T;
52}
53
54/// This trait is a helper that can be added to trait bounds. Writing `A: AllocMut<T>` is equivalent
55/// to `A: Alloc<T> + Alloc<<Self as Alloc<T>>::MutAlternative>`
56pub trait AllocMut<T: ?Sized>: Alloc<T> + Alloc<<Self as Alloc<T>>::MutTy> {
57 type RawHandle: Sized;
58}
59
60impl<T: ?Sized, A> AllocMut<T> for A
61where
62 A: Alloc<T> + Alloc<<Self as Alloc<T>>::MutTy>,
63{
64 type RawHandle = <A as Alloc<<A as Alloc<T>>::MutTy>>::RawHandle;
65}