1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
use crate::{AllocateAll, Owns, ReallocateInPlace};
use core::{
    alloc::{AllocError, AllocRef, Layout},
    ptr::NonNull,
};

/// An emphatically empty implementation of `AllocRef`.
///
/// Although it has no direct use, it is useful as a "terminator" in composite allocators
/// or for disabling the global allocator.
///
/// # Examples
///
/// The `Null` will always return `Err`:
///
/// ```rust
/// #![feature(allocator_api)]
///
/// use alloc_compose::Null;
/// use std::alloc::{AllocRef, Global, Layout};
///
/// let memory = Null.alloc(Layout::new::<u32>());
/// assert!(memory.is_err())
/// ```
///
/// Even if a zero-sized allocation is requested:
///
/// ```rust
/// # #![feature(allocator_api)]
/// # use alloc_compose::Null;
/// # use std::alloc::{AllocRef, Global, Layout};
/// let memory = Null.alloc(Layout::new::<()>());
/// assert!(memory.is_err())
/// ```
///
/// ## Disabling the global allocator
///
/// ```rust, no_run
/// use alloc_compose::Null;
///
/// #[global_allocator]
/// static A: Null = Null;
/// ```
#[derive(Debug, Copy, Clone)]
pub struct Null;

unsafe impl AllocRef for Null {
    /// Will always return `Err(AllocErr)`.
    fn alloc(&self, _layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
        Err(AllocError)
    }

    /// Will always return `Err(AllocErr)`.
    fn alloc_zeroed(&self, _layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
        Err(AllocError)
    }

    /// Must not be called, as allocation always fails.
    unsafe fn dealloc(&self, _ptr: NonNull<u8>, _layout: Layout) {
        unreachable!("Null::dealloc must never be called as allocation always fails")
    }

    /// Must not be called, as allocation always fails.
    unsafe fn grow(
        &self,
        _ptr: NonNull<u8>,
        _old_layout: Layout,
        _new_layout: Layout,
    ) -> Result<NonNull<[u8]>, AllocError> {
        unreachable!("Null::grow must never be called as allocation always fails")
    }

    /// Must not be called, as allocation always fails.
    unsafe fn grow_zeroed(
        &self,
        _ptr: NonNull<u8>,
        _old_layout: Layout,
        _new_layout: Layout,
    ) -> Result<NonNull<[u8]>, AllocError> {
        unreachable!("Null::grow_zeroed must never be called as allocation always fails")
    }

    /// Must not be called, as allocation always fails.
    unsafe fn shrink(
        &self,
        _ptr: NonNull<u8>,
        _old_layout: Layout,
        _new_layout: Layout,
    ) -> Result<NonNull<[u8]>, AllocError> {
        unreachable!("Null::shrink must never be called as allocation always fails")
    }
}

unsafe impl AllocateAll for Null {
    fn allocate_all(&self) -> Result<NonNull<[u8]>, AllocError> {
        Err(AllocError)
    }

    fn allocate_all_zeroed(&self) -> Result<NonNull<[u8]>, AllocError> {
        Err(AllocError)
    }

    fn deallocate_all(&self) {}

    fn capacity(&self) -> usize {
        0
    }

    fn capacity_left(&self) -> usize {
        0
    }
}

unsafe impl ReallocateInPlace for Null {
    /// Must not be called, as allocation always fails.
    unsafe fn grow_in_place(
        &self,
        _ptr: NonNull<u8>,
        _old_layout: Layout,
        _new_layout: Layout,
    ) -> Result<usize, AllocError> {
        unreachable!("Null::grow_in_place must never be called as allocation always fails")
    }

    /// Must not be called, as allocation always fails.
    unsafe fn grow_in_place_zeroed(
        &self,
        _ptr: NonNull<u8>,
        _old_layout: Layout,
        _new_layout: Layout,
    ) -> Result<usize, AllocError> {
        unreachable!("Null::grow_in_place_zeroed must never be called as allocation always fails")
    }

    /// Must not be called, as allocation always fails.
    unsafe fn shrink_in_place(
        &self,
        _ptr: NonNull<u8>,
        _old_layout: Layout,
        _new_layout: Layout,
    ) -> Result<usize, AllocError> {
        unreachable!("Null::shrink_in_place must never be called as allocation always fails")
    }
}

impl Owns for Null {
    /// Will always return `false.
    fn owns(&self, _memory: NonNull<[u8]>) -> bool {
        false
    }
}

impl_global_alloc!(Null);

#[cfg(test)]
mod tests {
    #![allow(clippy::wildcard_imports)]
    use super::*;

    #[test]
    #[should_panic(expected = "unreachable")]
    fn dealloc() {
        unsafe { Null.dealloc(NonNull::dangling(), Layout::new::<()>()) };
    }

    #[test]
    fn alloc() {
        assert!(Null.alloc(Layout::new::<u32>()).is_err());
        assert!(Null.alloc_zeroed(Layout::new::<u32>()).is_err());
        assert!(Null.allocate_all().is_err());
        assert!(Null.allocate_all_zeroed().is_err());
        assert_eq!(Null.capacity(), 0);
        assert_eq!(Null.capacity_left(), 0);
        Null.deallocate_all();
    }

    #[test]
    #[should_panic(expected = "unreachable")]
    fn grow() {
        unsafe {
            let _ = Null.grow(
                NonNull::dangling(),
                Layout::new::<()>(),
                Layout::new::<()>(),
            );
        };
    }

    #[test]
    #[should_panic(expected = "unreachable")]
    fn grow_zeroed() {
        unsafe {
            let _ = Null.grow_zeroed(
                NonNull::dangling(),
                Layout::new::<()>(),
                Layout::new::<()>(),
            );
        };
    }

    #[test]
    #[should_panic(expected = "unreachable")]
    fn grow_in_place() {
        unsafe {
            let _ = Null.grow_in_place(
                NonNull::dangling(),
                Layout::new::<()>(),
                Layout::new::<()>(),
            );
        };
    }

    #[test]
    #[should_panic(expected = "unreachable")]
    fn grow_in_place_zeroed() {
        unsafe {
            let _ = Null.grow_in_place_zeroed(
                NonNull::dangling(),
                Layout::new::<()>(),
                Layout::new::<()>(),
            );
        };
    }

    #[test]
    #[should_panic(expected = "unreachable")]
    fn shrink() {
        unsafe {
            let _ = Null.shrink(
                NonNull::dangling(),
                Layout::new::<()>(),
                Layout::new::<()>(),
            );
        };
    }

    #[test]
    #[should_panic(expected = "unreachable")]
    fn shrink_in_place() {
        unsafe {
            let _ = Null.shrink_in_place(
                NonNull::dangling(),
                Layout::new::<()>(),
                Layout::new::<()>(),
            );
        };
    }

    #[test]
    fn owns() {
        assert!(!Null.owns(NonNull::slice_from_raw_parts(NonNull::dangling(), 0)));
    }

    #[test]
    fn debug() {
        assert_eq!(alloc::format!("{:?}", Null), "Null");
    }
}