1use crate::num::NonZeroUsize;
2use crate::num::Pow2Usize;
3use super::NonNull;
4use super::AllocError;
5use super::Allocator;
6
7pub struct NopAllocator { }
8
9pub const NOP_ALLOCATOR: NopAllocator = NopAllocator { };
10
11unsafe impl Allocator for NopAllocator {
12 unsafe fn alloc(
13 &self,
14 _size: NonZeroUsize,
15 _align: Pow2Usize
16 ) -> Result<NonNull<u8>, AllocError> {
17 Err(AllocError::UnsupportedOperation)
18 }
19 unsafe fn free(
20 &self,
21 _ptr: NonNull<u8>,
22 _current_size: NonZeroUsize,
23 _align: Pow2Usize) {
24 }
25 unsafe fn grow(
26 &self,
27 _ptr: NonNull<u8>,
28 _current_size: NonZeroUsize,
29 _new_larger_size: NonZeroUsize,
30 _align: Pow2Usize
31 ) -> Result<NonNull<u8>, AllocError> {
32 Err(AllocError::UnsupportedOperation)
33 }
34 unsafe fn shrink(
35 &self,
36 _ptr: NonNull<u8>,
37 _current_size: NonZeroUsize,
38 _new_smaller_size: NonZeroUsize,
39 _align: Pow2Usize
40 ) -> Result<NonNull<u8>, AllocError> {
41 Err(AllocError::UnsupportedOperation)
42 }
43 fn supports_contains(&self) -> bool { false }
44 fn contains(&self, _ptr: NonNull<u8>) -> bool {
45 panic!("contains not supported!");
46 }
47 fn name(&self) -> &'static str { "nop-allocator" }
48}
49
50#[cfg(test)]
51mod tests {
52 use super::*;
53
54 #[test]
55 fn specific_name() {
56 assert!(NOP_ALLOCATOR.name().contains("nop"));
57 }
58
59 #[test]
60 fn alloc_not_supported() {
61 assert_eq!(unsafe { NOP_ALLOCATOR.alloc(NonZeroUsize::new(1).unwrap(), Pow2Usize::one()) }.unwrap_err(), AllocError::UnsupportedOperation);
62 }
63
64 #[test]
65 fn free_silently_completes() {
66 unsafe { NOP_ALLOCATOR.free(NonNull::dangling(), NonZeroUsize::new(1).unwrap(), Pow2Usize::one()) };
67 }
68
69 #[test]
70 fn grow_not_supported() {
71 assert_eq!(unsafe { NOP_ALLOCATOR.grow(NonNull::dangling(), NonZeroUsize::new(1).unwrap(), NonZeroUsize::new(2).unwrap(), Pow2Usize::one()) }.unwrap_err(), AllocError::UnsupportedOperation);
72 }
73
74 #[test]
75 fn shrink_not_supported() {
76 assert_eq!(unsafe { NOP_ALLOCATOR.shrink(NonNull::dangling(), NonZeroUsize::new(2).unwrap(), NonZeroUsize::new(1).unwrap(), Pow2Usize::one()) }.unwrap_err(), AllocError::UnsupportedOperation);
77 }
78
79 #[test]
80 fn contains_not_supported() {
81 assert!(!NOP_ALLOCATOR.supports_contains());
82 }
83
84 #[test]
85 #[should_panic]
86 fn calling_contains_panics() {
87 NOP_ALLOCATOR.contains(NonNull::dangling());
88 }
89}