dummy-alloc 1.0.0

Global allocator that fails all allocations
Documentation
//! Provides [`DummyAllocator`], a global allocator that fails all allocations.
//!
//! # Example
//!
//! ```no_run
//! use std::alloc::{alloc, Layout};
//! use dummy_alloc::DummyAllocator;
//!
//! // Configure it as the global allocator.
//! #[global_allocator]
//! static GLOBAL: DummyAllocator = DummyAllocator;
//!
//! let layout = Layout::new::<i32>();
//! let ptr = unsafe { alloc(layout) };
//! // `DummyAllocator` always returns a null pointer on allocation.
//! assert!(ptr.is_null());
//! ```
//!
//! # Similar crates
//!
//! [`lol_alloc`](https://crates.io/crates/lol_alloc) exports a similar
//! `FailAllocator` that performs the same function.
//!
//! # Minimum supported Rust version
//!
//! The MSRV is currently 1.56.
//!
//! This may change between minor versions.
//!
//! # License
//!
//! This crate is licensed under the
//! [Blue Oak Model License 1.0.0](https://blueoakcouncil.org/license/1.0.0).

// Attributes
#![cfg_attr(not(any(doc, test)), no_std)]
// Lints
#![warn(missing_docs)]

extern crate alloc;

use {
	alloc::alloc::{GlobalAlloc, Layout},
	core::ptr,
};

/// A dummy allocator.
///
/// Allocation will always fail by returning a null pointer. Deallocation will
/// always do nothing.
///
/// # Example
///
/// You may use it as the global allocator like so:
///
/// ```no_run
/// use dummy_alloc::DummyAllocator;
///
/// #[global_allocator]
/// static GLOBAL: DummyAllocator = DummyAllocator;
/// ```
///
/// See the [`alloc`](alloc::alloc) documentation for more information.
#[derive(Copy, Clone, Debug, Default)]
pub struct DummyAllocator;

// SAFETY: Does not unwind and does not rely on allocation occurring.
unsafe impl GlobalAlloc for DummyAllocator {
	unsafe fn alloc(&self, _layout: Layout) -> *mut u8 {
		ptr::null_mut()
	}

	unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) {}

	unsafe fn alloc_zeroed(&self, _layout: Layout) -> *mut u8 {
		ptr::null_mut()
	}

	unsafe fn realloc(&self, _ptr: *mut u8, _layout: Layout, _new_size: usize) -> *mut u8 {
		ptr::null_mut()
	}
}