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 reason = "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;
25 use crate::ptr::{self, NonNull};
27 /// The `AllocError` error indicates an allocation failure
28 /// that may be due to resource exhaustion or to
29 /// something wrong when combining the given input arguments with this
31 #[unstable(feature = "allocator_api", issue = "32838")]
32 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
33 pub struct AllocError;
35 // (we need this for downstream impl of trait Error)
36 #[unstable(feature = "allocator_api", issue = "32838")]
37 impl fmt::Display for AllocError {
38 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39 f.write_str("memory allocation failed")
43 /// An implementation of `Allocator` can allocate, grow, shrink, and deallocate arbitrary blocks of
44 /// data described via [`Layout`][].
46 /// `Allocator` is designed to be implemented on ZSTs, references, or smart pointers because having
47 /// an allocator like `MyAlloc([u8; N])` cannot be moved, without updating the pointers to the
50 /// Unlike [`GlobalAlloc`][], zero-sized allocations are allowed in `Allocator`. If an underlying
51 /// allocator does not support this (like jemalloc) or return a null pointer (such as
52 /// `libc::malloc`), this must be caught by the implementation.
54 /// ### Currently allocated memory
56 /// Some of the methods require that a memory block be *currently allocated* via an allocator. This
59 /// * the starting address for that memory block was previously returned by [`allocate`], [`grow`], or
62 /// * the memory block has not been subsequently deallocated, where blocks are either deallocated
63 /// directly by being passed to [`deallocate`] or were changed by being passed to [`grow`] or
64 /// [`shrink`] that returns `Ok`. If `grow` or `shrink` have returned `Err`, the passed pointer
67 /// [`allocate`]: Allocator::allocate
68 /// [`grow`]: Allocator::grow
69 /// [`shrink`]: Allocator::shrink
70 /// [`deallocate`]: Allocator::deallocate
72 /// ### Memory fitting
74 /// Some of the methods require that a layout *fit* a memory block. What it means for a layout to
75 /// "fit" a memory block means (or equivalently, for a memory block to "fit" a layout) is that the
76 /// following conditions must hold:
78 /// * The block must be allocated with the same alignment as [`layout.align()`], and
80 /// * The provided [`layout.size()`] must fall in the range `min ..= max`, where:
81 /// - `min` is the size of the layout most recently used to allocate the block, and
82 /// - `max` is the latest actual size returned from [`allocate`], [`grow`], or [`shrink`].
84 /// [`layout.align()`]: Layout::align
85 /// [`layout.size()`]: Layout::size
89 /// * Memory blocks returned from an allocator must point to valid memory and retain their validity
90 /// until the instance and all of its clones are dropped,
92 /// * cloning or moving the allocator must not invalidate memory blocks returned from this
93 /// allocator. A cloned allocator must behave like the same allocator, and
95 /// * any pointer to a memory block which is [*currently allocated*] may be passed to any other
96 /// method of the allocator.
98 /// [*currently allocated*]: #currently-allocated-memory
99 #[unstable(feature = "allocator_api", issue = "32838")]
100 pub unsafe trait Allocator {
101 /// Attempts to allocate a block of memory.
103 /// On success, returns a [`NonNull<[u8]>`][NonNull] meeting the size and alignment guarantees of `layout`.
105 /// The returned block may have a larger size than specified by `layout.size()`, and may or may
106 /// not have its contents initialized.
110 /// Returning `Err` indicates that either memory is exhausted or `layout` does not meet
111 /// allocator's size or alignment constraints.
113 /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
114 /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
115 /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
117 /// Clients wishing to abort computation in response to an allocation error are encouraged to
118 /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
120 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
121 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>;
123 /// Behaves like `allocate`, but also ensures that the returned memory is zero-initialized.
127 /// Returning `Err` indicates that either memory is exhausted or `layout` does not meet
128 /// allocator's size or alignment constraints.
130 /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
131 /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
132 /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
134 /// Clients wishing to abort computation in response to an allocation error are encouraged to
135 /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
137 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
138 fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
139 let ptr = self.allocate(layout)?;
140 // SAFETY: `alloc` returns a valid memory block
141 unsafe { ptr.as_non_null_ptr().as_ptr().write_bytes(0, ptr.len()) }
145 /// Deallocates the memory referenced by `ptr`.
149 /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator, and
150 /// * `layout` must [*fit*] that block of memory.
152 /// [*currently allocated*]: #currently-allocated-memory
153 /// [*fit*]: #memory-fitting
154 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout);
156 /// Attempts to extend the memory block.
158 /// Returns a new [`NonNull<[u8]>`][NonNull] containing a pointer and the actual size of the allocated
159 /// memory. The pointer is suitable for holding data described by `new_layout`. To accomplish
160 /// this, the allocator may extend the allocation referenced by `ptr` to fit the new layout.
162 /// If this returns `Ok`, then ownership of the memory block referenced by `ptr` has been
163 /// transferred to this allocator. The memory may or may not have been freed, and should be
164 /// considered unusable unless it was transferred back to the caller again via the return value
167 /// If this method returns `Err`, then ownership of the memory block has not been transferred to
168 /// this allocator, and the contents of the memory block are unaltered.
172 /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator.
173 /// * `old_layout` must [*fit*] that block of memory (The `new_layout` argument need not fit it.).
174 /// * `new_layout.size()` must be greater than or equal to `old_layout.size()`.
176 /// Note that `new_layout.align()` need not be the same as `old_layout.align()`.
178 /// [*currently allocated*]: #currently-allocated-memory
179 /// [*fit*]: #memory-fitting
183 /// Returns `Err` if the new layout does not meet the allocator's size and alignment
184 /// constraints of the allocator, or if growing otherwise fails.
186 /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
187 /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
188 /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
190 /// Clients wishing to abort computation in response to an allocation error are encouraged to
191 /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
193 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
199 ) -> Result<NonNull<[u8]>, AllocError> {
201 new_layout.size() >= old_layout.size(),
202 "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
205 let new_ptr = self.allocate(new_layout)?;
207 // SAFETY: because `new_layout.size()` must be greater than or equal to
208 // `old_layout.size()`, both the old and new memory allocation are valid for reads and
209 // writes for `old_layout.size()` bytes. Also, because the old allocation wasn't yet
210 // deallocated, it cannot overlap `new_ptr`. Thus, the call to `copy_nonoverlapping` is
211 // safe. The safety contract for `dealloc` must be upheld by the caller.
213 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_layout.size());
214 self.deallocate(ptr, old_layout);
220 /// Behaves like `grow`, but also ensures that the new contents are set to zero before being
223 /// The memory block will contain the following contents after a successful call to
225 /// * Bytes `0..old_layout.size()` are preserved from the original allocation.
226 /// * Bytes `old_layout.size()..old_size` will either be preserved or zeroed, depending on
227 /// the allocator implementation. `old_size` refers to the size of the memory block prior
228 /// to the `grow_zeroed` call, which may be larger than the size that was originally
229 /// requested when it was allocated.
230 /// * Bytes `old_size..new_size` are zeroed. `new_size` refers to the size of the memory
231 /// block returned by the `grow_zeroed` call.
235 /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator.
236 /// * `old_layout` must [*fit*] that block of memory (The `new_layout` argument need not fit it.).
237 /// * `new_layout.size()` must be greater than or equal to `old_layout.size()`.
239 /// Note that `new_layout.align()` need not be the same as `old_layout.align()`.
241 /// [*currently allocated*]: #currently-allocated-memory
242 /// [*fit*]: #memory-fitting
246 /// Returns `Err` if the new layout does not meet the allocator's size and alignment
247 /// constraints of the allocator, or if growing otherwise fails.
249 /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
250 /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
251 /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
253 /// Clients wishing to abort computation in response to an allocation error are encouraged to
254 /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
256 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
257 unsafe fn grow_zeroed(
262 ) -> Result<NonNull<[u8]>, AllocError> {
264 new_layout.size() >= old_layout.size(),
265 "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
268 let new_ptr = self.allocate_zeroed(new_layout)?;
270 // SAFETY: because `new_layout.size()` must be greater than or equal to
271 // `old_layout.size()`, both the old and new memory allocation are valid for reads and
272 // writes for `old_layout.size()` bytes. Also, because the old allocation wasn't yet
273 // deallocated, it cannot overlap `new_ptr`. Thus, the call to `copy_nonoverlapping` is
274 // safe. The safety contract for `dealloc` must be upheld by the caller.
276 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_layout.size());
277 self.deallocate(ptr, old_layout);
283 /// Attempts to shrink the memory block.
285 /// Returns a new [`NonNull<[u8]>`][NonNull] containing a pointer and the actual size of the allocated
286 /// memory. The pointer is suitable for holding data described by `new_layout`. To accomplish
287 /// this, the allocator may shrink the allocation referenced by `ptr` to fit the new layout.
289 /// If this returns `Ok`, then ownership of the memory block referenced by `ptr` has been
290 /// transferred to this allocator. The memory may or may not have been freed, and should be
291 /// considered unusable unless it was transferred back to the caller again via the return value
294 /// If this method returns `Err`, then ownership of the memory block has not been transferred to
295 /// this allocator, and the contents of the memory block are unaltered.
299 /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator.
300 /// * `old_layout` must [*fit*] that block of memory (The `new_layout` argument need not fit it.).
301 /// * `new_layout.size()` must be smaller than or equal to `old_layout.size()`.
303 /// Note that `new_layout.align()` need not be the same as `old_layout.align()`.
305 /// [*currently allocated*]: #currently-allocated-memory
306 /// [*fit*]: #memory-fitting
310 /// Returns `Err` if the new layout does not meet the allocator's size and alignment
311 /// constraints of the allocator, or if shrinking otherwise fails.
313 /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
314 /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
315 /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
317 /// Clients wishing to abort computation in response to an allocation error are encouraged to
318 /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
320 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
326 ) -> Result<NonNull<[u8]>, AllocError> {
328 new_layout.size() <= old_layout.size(),
329 "`new_layout.size()` must be smaller than or equal to `old_layout.size()`"
332 let new_ptr = self.allocate(new_layout)?;
334 // SAFETY: because `new_layout.size()` must be lower than or equal to
335 // `old_layout.size()`, both the old and new memory allocation are valid for reads and
336 // writes for `new_layout.size()` bytes. Also, because the old allocation wasn't yet
337 // deallocated, it cannot overlap `new_ptr`. Thus, the call to `copy_nonoverlapping` is
338 // safe. The safety contract for `dealloc` must be upheld by the caller.
340 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), new_layout.size());
341 self.deallocate(ptr, old_layout);
347 /// Creates a "by reference" adapter for this instance of `Allocator`.
349 /// The returned adapter also implements `Allocator` and will simply borrow this.
351 fn by_ref(&self) -> &Self
359 #[unstable(feature = "allocator_api", issue = "32838")]
360 unsafe impl<A> Allocator for &A
362 A: Allocator + ?Sized,
365 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
366 (**self).allocate(layout)
370 fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
371 (**self).allocate_zeroed(layout)
375 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
376 // SAFETY: the safety contract must be upheld by the caller
377 unsafe { (**self).deallocate(ptr, layout) }
386 ) -> Result<NonNull<[u8]>, AllocError> {
387 // SAFETY: the safety contract must be upheld by the caller
388 unsafe { (**self).grow(ptr, old_layout, new_layout) }
392 unsafe fn grow_zeroed(
397 ) -> Result<NonNull<[u8]>, AllocError> {
398 // SAFETY: the safety contract must be upheld by the caller
399 unsafe { (**self).grow_zeroed(ptr, old_layout, new_layout) }
408 ) -> Result<NonNull<[u8]>, AllocError> {
409 // SAFETY: the safety contract must be upheld by the caller
410 unsafe { (**self).shrink(ptr, old_layout, new_layout) }