composable_allocators/
base.rs

1use core::alloc::{self, Allocator};
2use core::ptr::NonNull;
3
4/// # Safety
5///
6/// The [`allows_fallback`](Fallbackable::allows_fallback) function should be pure, i.e. always return same value
7/// for same `layout`.
8///
9/// An implementer of this trait should return `true` from
10/// [`has_allocated`](Fallbackable::has_allocated)
11/// if and only if at least one of the following conditions is satisfied:
12///
13/// - the passed pointer is denoting to
14///   [currently allocated block](https://doc.rust-lang.org/core/alloc/trait.Allocator.html#currently-allocated-memory),
15///
16/// - [`allows_fallback`](Fallbackable::allows_fallback) returns false for [`Layout`](alloc::Layout) used to allocate
17///   memory block, denoting by `ptr`.
18pub unsafe trait Fallbackable: Allocator {
19    /// # Safety
20    ///
21    /// The `ptr` parameter should denote a memory block,
22    /// [currently allocated](https://doc.rust-lang.org/core/alloc/trait.Allocator.html#currently-allocated-memory)
23    /// by this or any other [`Allocator`].
24    ///
25    /// The `layout` parameter should
26    /// [fit](https://doc.rust-lang.org/core/alloc/trait.Allocator.html#memory-fitting)
27    /// the memory block denoting by `ptr`.
28    unsafe fn has_allocated(&self, ptr: NonNull<u8>, layout: alloc::Layout) -> bool;
29
30    fn allows_fallback(&self, layout: alloc::Layout) -> bool;
31}
32
33unsafe impl<'a, T: Fallbackable + ?Sized> Fallbackable for &'a T {
34    unsafe fn has_allocated(&self, ptr: NonNull<u8>, layout: alloc::Layout) -> bool {
35        (*self).has_allocated(ptr, layout)
36    }
37
38    fn allows_fallback(&self, layout: alloc::Layout) -> bool {
39        (*self).allows_fallback(layout)
40    }
41}
42
43/// # Safety
44///
45/// Allocator implementing this trait should not panic with stack unwinding.
46/// This means, either it should not initiate panic directly or indirectly,
47/// either it should be strongly linked
48/// with the standard unstable `panic_abort` crate.
49pub unsafe trait NonUnwinding: Allocator { }
50
51unsafe impl<'a, T: NonUnwinding + ?Sized> NonUnwinding for &'a T { }