1 //! Memory allocation APIs
3 #![stable(feature = "alloc_module", since = "1.28.0")]
8 #[stable(feature = "global_alloc", since = "1.28.0")]
9 pub use self::global::GlobalAlloc;
10 #[stable(feature = "alloc_layout", since = "1.28.0")]
11 pub use self::layout::Layout;
12 #[stable(feature = "alloc_layout", since = "1.28.0")]
15 note = "Name does not follow std convention, use LayoutError",
16 suggestion = "LayoutError"
18 #[allow(deprecated, deprecated_in_future)]
19 pub use self::layout::LayoutErr;
21 #[stable(feature = "alloc_layout_error", since = "1.50.0")]
22 pub use self::layout::LayoutError;
24 use crate::error::Error;
26 use crate::ptr::{self, NonNull};
28 /// The `AllocError` error indicates an allocation failure
29 /// that may be due to resource exhaustion or to
30 /// something wrong when combining the given input arguments with this
32 #[unstable(feature = "allocator_api", issue = "32838")]
33 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
34 pub struct AllocError;
37 feature = "allocator_api",
38 reason = "the precise API and guarantees it provides may be tweaked.",
41 impl Error for AllocError {}
43 // (we need this for downstream impl of trait Error)
44 #[unstable(feature = "allocator_api", issue = "32838")]
45 impl fmt::Display for AllocError {
46 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47 f.write_str("memory allocation failed")
51 /// An implementation of `Allocator` can allocate, grow, shrink, and deallocate arbitrary blocks of
52 /// data described via [`Layout`][].
54 /// `Allocator` is designed to be implemented on ZSTs, references, or smart pointers because having
55 /// an allocator like `MyAlloc([u8; N])` cannot be moved, without updating the pointers to the
58 /// Unlike [`GlobalAlloc`][], zero-sized allocations are allowed in `Allocator`. If an underlying
59 /// allocator does not support this (like jemalloc) or return a null pointer (such as
60 /// `libc::malloc`), this must be caught by the implementation.
62 /// ### Currently allocated memory
64 /// Some of the methods require that a memory block be *currently allocated* via an allocator. This
67 /// * the starting address for that memory block was previously returned by [`allocate`], [`grow`], or
70 /// * the memory block has not been subsequently deallocated, where blocks are either deallocated
71 /// directly by being passed to [`deallocate`] or were changed by being passed to [`grow`] or
72 /// [`shrink`] that returns `Ok`. If `grow` or `shrink` have returned `Err`, the passed pointer
75 /// [`allocate`]: Allocator::allocate
76 /// [`grow`]: Allocator::grow
77 /// [`shrink`]: Allocator::shrink
78 /// [`deallocate`]: Allocator::deallocate
80 /// ### Memory fitting
82 /// Some of the methods require that a layout *fit* a memory block. What it means for a layout to
83 /// "fit" a memory block means (or equivalently, for a memory block to "fit" a layout) is that the
84 /// following conditions must hold:
86 /// * The block must be allocated with the same alignment as [`layout.align()`], and
88 /// * The provided [`layout.size()`] must fall in the range `min ..= max`, where:
89 /// - `min` is the size of the layout most recently used to allocate the block, and
90 /// - `max` is the latest actual size returned from [`allocate`], [`grow`], or [`shrink`].
92 /// [`layout.align()`]: Layout::align
93 /// [`layout.size()`]: Layout::size
97 /// * Memory blocks returned from an allocator must point to valid memory and retain their validity
98 /// until the instance and all of its clones are dropped,
100 /// * cloning or moving the allocator must not invalidate memory blocks returned from this
101 /// allocator. A cloned allocator must behave like the same allocator, and
103 /// * any pointer to a memory block which is [*currently allocated*] may be passed to any other
104 /// method of the allocator.
106 /// [*currently allocated*]: #currently-allocated-memory
107 #[unstable(feature = "allocator_api", issue = "32838")]
109 pub unsafe trait Allocator {
110 /// Attempts to allocate a block of memory.
112 /// On success, returns a [`NonNull<[u8]>`][NonNull] meeting the size and alignment guarantees of `layout`.
114 /// The returned block may have a larger size than specified by `layout.size()`, and may or may
115 /// not have its contents initialized.
119 /// Returning `Err` indicates that either memory is exhausted or `layout` does not meet
120 /// allocator's size or alignment constraints.
122 /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
123 /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
124 /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
126 /// Clients wishing to abort computation in response to an allocation error are encouraged to
127 /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
129 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
130 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>;
132 /// Behaves like `allocate`, but also ensures that the returned memory is zero-initialized.
136 /// Returning `Err` indicates that either memory is exhausted or `layout` does not meet
137 /// allocator's size or alignment constraints.
139 /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
140 /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
141 /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
143 /// Clients wishing to abort computation in response to an allocation error are encouraged to
144 /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
146 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
147 fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
148 let ptr = self.allocate(layout)?;
149 // SAFETY: `alloc` returns a valid memory block
150 unsafe { ptr.as_non_null_ptr().as_ptr().write_bytes(0, ptr.len()) }
154 /// Deallocates the memory referenced by `ptr`.
158 /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator, and
159 /// * `layout` must [*fit*] that block of memory.
161 /// [*currently allocated*]: #currently-allocated-memory
162 /// [*fit*]: #memory-fitting
163 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout);
165 /// Attempts to extend the memory block.
167 /// Returns a new [`NonNull<[u8]>`][NonNull] containing a pointer and the actual size of the allocated
168 /// memory. The pointer is suitable for holding data described by `new_layout`. To accomplish
169 /// this, the allocator may extend the allocation referenced by `ptr` to fit the new layout.
171 /// If this returns `Ok`, then ownership of the memory block referenced by `ptr` has been
172 /// transferred to this allocator. Any access to the old `ptr` is Undefined Behavior, even if the
173 /// allocation was grown in-place. The newly returned pointer is the only valid pointer
174 /// for accessing this memory now.
176 /// If this method returns `Err`, then ownership of the memory block has not been transferred to
177 /// this allocator, and the contents of the memory block are unaltered.
181 /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator.
182 /// * `old_layout` must [*fit*] that block of memory (The `new_layout` argument need not fit it.).
183 /// * `new_layout.size()` must be greater than or equal to `old_layout.size()`.
185 /// Note that `new_layout.align()` need not be the same as `old_layout.align()`.
187 /// [*currently allocated*]: #currently-allocated-memory
188 /// [*fit*]: #memory-fitting
192 /// Returns `Err` if the new layout does not meet the allocator's size and alignment
193 /// constraints of the allocator, or if growing otherwise fails.
195 /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
196 /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
197 /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
199 /// Clients wishing to abort computation in response to an allocation error are encouraged to
200 /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
202 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
208 ) -> Result<NonNull<[u8]>, AllocError> {
210 new_layout.size() >= old_layout.size(),
211 "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
214 let new_ptr = self.allocate(new_layout)?;
216 // SAFETY: because `new_layout.size()` must be greater than or equal to
217 // `old_layout.size()`, both the old and new memory allocation are valid for reads and
218 // writes for `old_layout.size()` bytes. Also, because the old allocation wasn't yet
219 // deallocated, it cannot overlap `new_ptr`. Thus, the call to `copy_nonoverlapping` is
220 // safe. The safety contract for `dealloc` must be upheld by the caller.
222 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_layout.size());
223 self.deallocate(ptr, old_layout);
229 /// Behaves like `grow`, but also ensures that the new contents are set to zero before being
232 /// The memory block will contain the following contents after a successful call to
234 /// * Bytes `0..old_layout.size()` are preserved from the original allocation.
235 /// * Bytes `old_layout.size()..old_size` will either be preserved or zeroed, depending on
236 /// the allocator implementation. `old_size` refers to the size of the memory block prior
237 /// to the `grow_zeroed` call, which may be larger than the size that was originally
238 /// requested when it was allocated.
239 /// * Bytes `old_size..new_size` are zeroed. `new_size` refers to the size of the memory
240 /// block returned by the `grow_zeroed` call.
244 /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator.
245 /// * `old_layout` must [*fit*] that block of memory (The `new_layout` argument need not fit it.).
246 /// * `new_layout.size()` must be greater than or equal to `old_layout.size()`.
248 /// Note that `new_layout.align()` need not be the same as `old_layout.align()`.
250 /// [*currently allocated*]: #currently-allocated-memory
251 /// [*fit*]: #memory-fitting
255 /// Returns `Err` if the new layout does not meet the allocator's size and alignment
256 /// constraints of the allocator, or if growing otherwise fails.
258 /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
259 /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
260 /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
262 /// Clients wishing to abort computation in response to an allocation error are encouraged to
263 /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
265 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
266 unsafe fn grow_zeroed(
271 ) -> Result<NonNull<[u8]>, AllocError> {
273 new_layout.size() >= old_layout.size(),
274 "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
277 let new_ptr = self.allocate_zeroed(new_layout)?;
279 // SAFETY: because `new_layout.size()` must be greater than or equal to
280 // `old_layout.size()`, both the old and new memory allocation are valid for reads and
281 // writes for `old_layout.size()` bytes. Also, because the old allocation wasn't yet
282 // deallocated, it cannot overlap `new_ptr`. Thus, the call to `copy_nonoverlapping` is
283 // safe. The safety contract for `dealloc` must be upheld by the caller.
285 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_layout.size());
286 self.deallocate(ptr, old_layout);
292 /// Attempts to shrink the memory block.
294 /// Returns a new [`NonNull<[u8]>`][NonNull] containing a pointer and the actual size of the allocated
295 /// memory. The pointer is suitable for holding data described by `new_layout`. To accomplish
296 /// this, the allocator may shrink the allocation referenced by `ptr` to fit the new layout.
298 /// If this returns `Ok`, then ownership of the memory block referenced by `ptr` has been
299 /// transferred to this allocator. Any access to the old `ptr` is Undefined Behavior, even if the
300 /// allocation was shrunk in-place. The newly returned pointer is the only valid pointer
301 /// for accessing this memory now.
303 /// If this method returns `Err`, then ownership of the memory block has not been transferred to
304 /// this allocator, and the contents of the memory block are unaltered.
308 /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator.
309 /// * `old_layout` must [*fit*] that block of memory (The `new_layout` argument need not fit it.).
310 /// * `new_layout.size()` must be smaller than or equal to `old_layout.size()`.
312 /// Note that `new_layout.align()` need not be the same as `old_layout.align()`.
314 /// [*currently allocated*]: #currently-allocated-memory
315 /// [*fit*]: #memory-fitting
319 /// Returns `Err` if the new layout does not meet the allocator's size and alignment
320 /// constraints of the allocator, or if shrinking otherwise fails.
322 /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
323 /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
324 /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
326 /// Clients wishing to abort computation in response to an allocation error are encouraged to
327 /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
329 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
335 ) -> Result<NonNull<[u8]>, AllocError> {
337 new_layout.size() <= old_layout.size(),
338 "`new_layout.size()` must be smaller than or equal to `old_layout.size()`"
341 let new_ptr = self.allocate(new_layout)?;
343 // SAFETY: because `new_layout.size()` must be lower than or equal to
344 // `old_layout.size()`, both the old and new memory allocation are valid for reads and
345 // writes for `new_layout.size()` bytes. Also, because the old allocation wasn't yet
346 // deallocated, it cannot overlap `new_ptr`. Thus, the call to `copy_nonoverlapping` is
347 // safe. The safety contract for `dealloc` must be upheld by the caller.
349 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), new_layout.size());
350 self.deallocate(ptr, old_layout);
356 /// Creates a "by reference" adapter for this instance of `Allocator`.
358 /// The returned adapter also implements `Allocator` and will simply borrow this.
360 fn by_ref(&self) -> &Self
368 #[unstable(feature = "allocator_api", issue = "32838")]
369 unsafe impl<A> Allocator for &A
371 A: Allocator + ?Sized,
374 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
375 (**self).allocate(layout)
379 fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
380 (**self).allocate_zeroed(layout)
384 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
385 // SAFETY: the safety contract must be upheld by the caller
386 unsafe { (**self).deallocate(ptr, layout) }
395 ) -> Result<NonNull<[u8]>, AllocError> {
396 // SAFETY: the safety contract must be upheld by the caller
397 unsafe { (**self).grow(ptr, old_layout, new_layout) }
401 unsafe fn grow_zeroed(
406 ) -> Result<NonNull<[u8]>, AllocError> {
407 // SAFETY: the safety contract must be upheld by the caller
408 unsafe { (**self).grow_zeroed(ptr, old_layout, new_layout) }
417 ) -> Result<NonNull<[u8]>, AllocError> {
418 // SAFETY: the safety contract must be upheld by the caller
419 unsafe { (**self).shrink(ptr, old_layout, new_layout) }