bump_scope/traits/
bump_allocator_scope.rs

1use crate::{
2    BaseAllocator, Bump, BumpAllocator, BumpScope, MinimumAlignment, SupportedMinimumAlignment, WithoutDealloc,
3    WithoutShrink,
4    traits::{assert_dyn_compatible, assert_implements},
5};
6
7/// A bump allocator scope.
8///
9/// This is a [`BumpAllocator`] which can make allocations that outlive itself.
10/// Specifically, its allocations live for the lifetime `'a`.
11///
12/// # Safety
13///
14/// This trait must only be implemented when allocations live for `'a`.
15/// For example this function must be sound:
16///
17/// ```
18/// # #![expect(dead_code)]
19/// use bump_scope::BumpAllocatorScope;
20/// use core::alloc::Layout;
21///
22/// fn allocate_zeroed_bytes<'a>(allocator: impl BumpAllocatorScope<'a>, len: usize) -> &'a [u8] {
23///     let layout = Layout::array::<u8>(len).unwrap();
24///     let ptr = allocator.allocate_zeroed(layout).unwrap();
25///     unsafe { ptr.as_ref() }
26/// }
27/// ```
28pub unsafe trait BumpAllocatorScope<'a>: BumpAllocator {}
29
30assert_dyn_compatible!(BumpAllocatorScope<'_>);
31
32assert_implements! {
33    [BumpAllocatorScope<'a> + ?Sized]
34
35    BumpScope
36
37    &Bump
38    &BumpScope
39
40    &mut Bump
41    &mut BumpScope
42
43    dyn BumpAllocatorScope
44    &dyn BumpAllocatorScope
45    &mut dyn BumpAllocatorScope
46
47    dyn MutBumpAllocatorScope
48    &dyn MutBumpAllocatorScope
49    &mut dyn MutBumpAllocatorScope
50}
51
52unsafe impl<'a, B: BumpAllocatorScope<'a> + ?Sized> BumpAllocatorScope<'a> for &B {}
53unsafe impl<'a, B: BumpAllocatorScope<'a> + ?Sized> BumpAllocatorScope<'a> for &mut B {}
54
55unsafe impl<'a, B: BumpAllocatorScope<'a>> BumpAllocatorScope<'a> for WithoutDealloc<B> {}
56unsafe impl<'a, B: BumpAllocatorScope<'a>> BumpAllocatorScope<'a> for WithoutShrink<B> {}
57
58unsafe impl<'a, A, const MIN_ALIGN: usize, const UP: bool, const GUARANTEED_ALLOCATED: bool, const DEALLOCATES: bool>
59    BumpAllocatorScope<'a> for BumpScope<'a, A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED, DEALLOCATES>
60where
61    MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
62    A: BaseAllocator<GUARANTEED_ALLOCATED>,
63{
64}
65
66unsafe impl<'a, A, const MIN_ALIGN: usize, const UP: bool, const GUARANTEED_ALLOCATED: bool, const DEALLOCATES: bool>
67    BumpAllocatorScope<'a> for &'a Bump<A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED, DEALLOCATES>
68where
69    MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
70    A: BaseAllocator<GUARANTEED_ALLOCATED>,
71{
72}
73
74unsafe impl<'a, A, const MIN_ALIGN: usize, const UP: bool, const GUARANTEED_ALLOCATED: bool, const DEALLOCATES: bool>
75    BumpAllocatorScope<'a> for &'a mut Bump<A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED, DEALLOCATES>
76where
77    MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
78    A: BaseAllocator<GUARANTEED_ALLOCATED>,
79{
80}