musli_core/alloc/
disabled.rs

1use core::marker::PhantomData;
2use core::ptr;
3
4use super::{Alloc, AllocError, Allocator};
5
6/// An empty buffer.
7pub struct EmptyBuf<T> {
8    _marker: PhantomData<T>,
9}
10
11impl<T> Alloc<T> for EmptyBuf<T> {
12    #[inline]
13    fn as_ptr(&self) -> *const T {
14        ptr::NonNull::dangling().as_ptr()
15    }
16
17    #[inline]
18    fn as_mut_ptr(&mut self) -> *mut T {
19        ptr::NonNull::dangling().as_ptr()
20    }
21
22    #[inline]
23    fn capacity(&self) -> usize {
24        if size_of::<T>() == 0 {
25            usize::MAX
26        } else {
27            0
28        }
29    }
30
31    #[inline]
32    fn resize(&mut self, _: usize, _: usize) -> Result<(), AllocError> {
33        Err(AllocError)
34    }
35
36    #[inline]
37    fn try_merge<B>(&mut self, _: usize, other: B, _: usize) -> Result<(), B>
38    where
39        B: Alloc<T>,
40    {
41        Err(other)
42    }
43}
44
45/// An allocator which cannot allocate anything.
46///
47/// If any operation requires allocations this will error.
48#[non_exhaustive]
49#[derive(Clone, Copy)]
50pub struct Disabled;
51
52impl Disabled {
53    /// Construct a new disabled allocator.
54    #[inline]
55    pub const fn new() -> Self {
56        Self
57    }
58}
59
60impl Default for Disabled {
61    #[inline]
62    fn default() -> Self {
63        Self::new()
64    }
65}
66
67unsafe impl Allocator for Disabled {
68    /// We can set this to `true` because the disabled allocator returns
69    /// dangling pointers which are valid in a system allocation.
70    const IS_SYSTEM: bool = true;
71
72    type Alloc<T> = EmptyBuf<T>;
73
74    #[inline]
75    fn alloc<T>(self, _: T) -> Result<Self::Alloc<T>, AllocError> {
76        Err(AllocError)
77    }
78
79    #[inline]
80    fn alloc_empty<T>(self) -> Self::Alloc<T> {
81        EmptyBuf {
82            _marker: PhantomData,
83        }
84    }
85}