zeropool/allocator.rs
1//! Pluggable buffer allocation backend.
2//!
3//! [`ZeroPool`](crate::ZeroPool) delegates raw buffer creation to an [`Allocator`].
4//! The default [`HeapAllocator`] returns zero-initialized heap buffers.
5//! Implement the trait for custom strategies (page-aligned, huge pages, etc.).
6
7/// Controls how the pool creates raw byte buffers.
8///
9/// # Contract
10///
11/// - `allocate(capacity)` must return a `Vec<u8>` with `len() >= capacity`.
12/// - The first `capacity` bytes must be initialized to zero.
13/// - The returned `Vec` must have `capacity() >= len()`.
14/// - The `Vec` must be deallocatable by the standard global allocator.
15///
16/// # Example
17///
18/// ```
19/// use zeropool::{Allocator, ZeroPool};
20///
21/// struct PrefaultAllocator;
22///
23/// impl Allocator for PrefaultAllocator {
24/// fn allocate(&self, capacity: usize) -> Vec<u8> {
25/// vec![0; capacity]
26/// }
27/// }
28///
29/// let pool = ZeroPool::new().allocator(PrefaultAllocator);
30/// ```
31pub trait Allocator: Send + Sync + 'static {
32 /// Allocate a zero-initialized buffer with at least `capacity` bytes.
33 fn allocate(&self, capacity: usize) -> Vec<u8>;
34}
35
36/// Standard heap allocation via `vec![0; capacity]`.
37///
38/// This is the default safe allocator used by [`ZeroPool`](crate::ZeroPool).
39#[derive(Debug, Clone, Copy, Default)]
40pub struct HeapAllocator;
41
42impl Allocator for HeapAllocator {
43 #[inline]
44 fn allocate(&self, capacity: usize) -> Vec<u8> {
45 vec![0; capacity]
46 }
47}
48
49impl std::fmt::Debug for dyn Allocator {
50 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51 f.write_str("dyn Allocator")
52 }
53}