dummy_alloc/lib.rs
1//! Provides [`DummyAllocator`], a global allocator that fails all allocations.
2//!
3//! # Example
4//!
5//! ```no_run
6//! use std::alloc::{alloc, Layout};
7//! use dummy_alloc::DummyAllocator;
8//!
9//! // Configure it as the global allocator.
10//! #[global_allocator]
11//! static GLOBAL: DummyAllocator = DummyAllocator;
12//!
13//! let layout = Layout::new::<i32>();
14//! let ptr = unsafe { alloc(layout) };
15//! // `DummyAllocator` always returns a null pointer on allocation.
16//! assert!(ptr.is_null());
17//! ```
18//!
19//! # Similar crates
20//!
21//! [`lol_alloc`](https://crates.io/crates/lol_alloc) exports a similar
22//! `FailAllocator` that performs the same function.
23//!
24//! # Minimum supported Rust version
25//!
26//! The MSRV is currently 1.56.
27//!
28//! This may change between minor versions.
29//!
30//! # License
31//!
32//! This crate is licensed under the
33//! [Blue Oak Model License 1.0.0](https://blueoakcouncil.org/license/1.0.0).
34
35// Attributes
36#![cfg_attr(not(any(doc, test)), no_std)]
37// Lints
38#![warn(missing_docs)]
39
40extern crate alloc;
41
42use {
43 alloc::alloc::{GlobalAlloc, Layout},
44 core::ptr,
45};
46
47/// A dummy allocator.
48///
49/// Allocation will always fail by returning a null pointer. Deallocation will
50/// always do nothing.
51///
52/// # Example
53///
54/// You may use it as the global allocator like so:
55///
56/// ```no_run
57/// use dummy_alloc::DummyAllocator;
58///
59/// #[global_allocator]
60/// static GLOBAL: DummyAllocator = DummyAllocator;
61/// ```
62///
63/// See the [`alloc`](alloc::alloc) documentation for more information.
64#[derive(Copy, Clone, Debug, Default)]
65pub struct DummyAllocator;
66
67// SAFETY: Does not unwind and does not rely on allocation occurring.
68unsafe impl GlobalAlloc for DummyAllocator {
69 unsafe fn alloc(&self, _layout: Layout) -> *mut u8 {
70 ptr::null_mut()
71 }
72
73 unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) {}
74
75 unsafe fn alloc_zeroed(&self, _layout: Layout) -> *mut u8 {
76 ptr::null_mut()
77 }
78
79 unsafe fn realloc(&self, _ptr: *mut u8, _layout: Layout, _new_size: usize) -> *mut u8 {
80 ptr::null_mut()
81 }
82}