blink_alloc/
api.rs

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