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
//! Core allocator abstraction.
//!
//! This module defines the [`Allocator`] trait — the single interface that
//! every allocator in the crate implements and that every collection depends on.
//!
//! The design is deliberately minimal: two methods (`alloc` / `dealloc`) that
//! mirror the semantics of `posix_memalign` / `free` while being safe to
//! compose behind higher-level wrappers.
use Layout;
use NonNull;
/// Low-level memory allocator interface.
///
/// Inspired by the explicit allocation model of Zig, this trait decouples
/// collections from any concrete or global allocator. Callers retain full
/// control over *which* memory region is used and *when* it is released.
///
/// # Implementing `Allocator`
///
/// An implementation must uphold the following invariants:
///
/// * A successful call to [`alloc`](Allocator::alloc) returns a pointer that is
/// valid for `layout.size()` bytes and aligned to at least `layout.align()`.
/// * The returned memory may contain arbitrary (uninitialized) bytes.
/// * The allocated block remains valid until an explicit call to
/// [`dealloc`](Allocator::dealloc) with the *exact same pointer and layout*.
/// * Calling `dealloc` with a pointer that was not obtained from the same
/// allocator instance, or with a mismatched layout, is undefined behaviour.
/// Blanket implementation of [`Allocator`] for shared references.
///
/// This allows passing `&A` (or `&dyn Allocator`) into collections that are
/// generic over `A: Allocator`, avoiding the need to move ownership of the
/// allocator into every container.
///
/// # Example
///
/// ```rust,ignore
/// let sys = SystemAllocator;
/// let vec: ExVec<u32> = ExVec::new(&sys); // &SystemAllocator implements Allocator
/// ```