blink_alloc/
api.rs

1use allocator_api2::alloc::Allocator;
2
3/// Extension trait for [`Allocator`] that defines blink allocator API.
4/// Blink-allocators are allocators with cheap allocation
5/// and potentially no-op deallocation.
6/// Blink-allocator *can* reuse deallocated memory, but not required to.
7/// Typically deallocation is either no-op or processed only if deallocating
8/// the very last allocated memory block.
9/// The [`reset`][BlinkAllocator::reset]
10/// method deallocates all memory allocated from this instance at once.
11///
12/// Additional guarantees are provided that
13///
14/// * [`Allocator::shrink`] will always succeed and never move memory
15/// when `ptr` is already aligned to `new_layout.align()`.
16///
17/// # Safety
18///
19/// Draws most requirements from [`Allocator`] super-trait.
20/// The [`reset`][BlinkAllocator::reset] method
21/// may invalidate currently allocated memory if allocator is not cloneable.
22pub unsafe trait BlinkAllocator: Allocator {
23    /// Resets allocator potentially invalidating all allocations
24    /// made from this instance.
25    /// This is no-op if allocator is [`Clone`][core::clone::Clone]
26    /// (typically shared reference to blink-allocator).
27    ///
28    /// # Safety
29    ///
30    /// Caller must guarantee that all allocations made from this instance
31    /// won't be used after this call.
32    /// The potential invalid memory access will happen through
33    /// raw pointer and requires `unsafe`.
34    ///
35    /// This method requires mutable borrow of the blink-allocator
36    /// and so cannot be called while collection types reference it.
37    /// So it is safe to use reference to blink allocator as allocator type
38    /// for, say, [`Vec`] and later then call `reset` safely.
39    /// The `Vec` would have to be dropped (or forgotten) before calling `reset`
40    /// due to mutable borrow.
41    ///
42    /// [`Vec`]: alloc::vec::Vec
43    fn reset(&mut self);
44}
45
46unsafe impl<A> BlinkAllocator for &A
47where
48    A: BlinkAllocator,
49{
50    #[inline]
51    fn reset(&mut self) {}
52}
53
54unsafe impl<'a, A> BlinkAllocator for &'a mut A
55where
56    &'a mut A: Allocator,
57    A: BlinkAllocator,
58{
59    #[inline]
60    fn reset(&mut self) {
61        A::reset(self);
62    }
63}