musli/alloc/
disabled.rs

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