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 #[cfg(not(bootstrap))]
25 use crate::error::Error;
27 use crate::ptr::{self, NonNull};
29 /// The `AllocError` error indicates an allocation failure
30 /// that may be due to resource exhaustion or to
31 /// something wrong when combining the given input arguments with this
33 #[unstable(feature = "allocator_api", issue = "32838")]
34 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
35 pub struct AllocError;
37 #[cfg(not(bootstrap))]
39 feature = "allocator_api",
40 reason = "the precise API and guarantees it provides may be tweaked.",
43 impl Error for AllocError {}
45 // (we need this for downstream impl of trait Error)
46 #[unstable(feature = "allocator_api", issue = "32838")]
47 impl fmt::Display for AllocError {
48 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49 f.write_str("memory allocation failed")
53 /// An implementation of `Allocator` can allocate, grow, shrink, and deallocate arbitrary blocks of
54 /// data described via [`Layout`][].
56 /// `Allocator` is designed to be implemented on ZSTs, references, or smart pointers because having
57 /// an allocator like `MyAlloc([u8; N])` cannot be moved, without updating the pointers to the
60 /// Unlike [`GlobalAlloc`][], zero-sized allocations are allowed in `Allocator`. If an underlying
61 /// allocator does not support this (like jemalloc) or return a null pointer (such as
62 /// `libc::malloc`), this must be caught by the implementation.
64 /// ### Currently allocated memory
66 /// Some of the methods require that a memory block be *currently allocated* via an allocator. This
69 /// * the starting address for that memory block was previously returned by [`allocate`], [`grow`], or
72 /// * the memory block has not been subsequently deallocated, where blocks are either deallocated
73 /// directly by being passed to [`deallocate`] or were changed by being passed to [`grow`] or
74 /// [`shrink`] that returns `Ok`. If `grow` or `shrink` have returned `Err`, the passed pointer
77 /// [`allocate`]: Allocator::allocate
78 /// [`grow`]: Allocator::grow
79 /// [`shrink`]: Allocator::shrink
80 /// [`deallocate`]: Allocator::deallocate
82 /// ### Memory fitting
84 /// Some of the methods require that a layout *fit* a memory block. What it means for a layout to
85 /// "fit" a memory block means (or equivalently, for a memory block to "fit" a layout) is that the
86 /// following conditions must hold:
88 /// * The block must be allocated with the same alignment as [`layout.align()`], and
90 /// * The provided [`layout.size()`] must fall in the range `min ..= max`, where:
91 /// - `min` is the size of the layout most recently used to allocate the block, and
92 /// - `max` is the latest actual size returned from [`allocate`], [`grow`], or [`shrink`].
94 /// [`layout.align()`]: Layout::align
95 /// [`layout.size()`]: Layout::size
99 /// * Memory blocks returned from an allocator must point to valid memory and retain their validity
100 /// until the instance and all of its clones are dropped,
102 /// * cloning or moving the allocator must not invalidate memory blocks returned from this
103 /// allocator. A cloned allocator must behave like the same allocator, and
105 /// * any pointer to a memory block which is [*currently allocated*] may be passed to any other
106 /// method of the allocator.
108 /// [*currently allocated*]: #currently-allocated-memory
109 #[unstable(feature = "allocator_api", issue = "32838")]
111 pub unsafe trait Allocator {
112 /// Attempts to allocate a block of memory.
114 /// On success, returns a [`NonNull<[u8]>`][NonNull] meeting the size and alignment guarantees of `layout`.
116 /// The returned block may have a larger size than specified by `layout.size()`, and may or may
117 /// not have its contents initialized.
121 /// Returning `Err` indicates that either memory is exhausted or `layout` does not meet
122 /// allocator's size or alignment constraints.
124 /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
125 /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
126 /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
128 /// Clients wishing to abort computation in response to an allocation error are encouraged to
129 /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
131 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
132 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>;
134 /// Behaves like `allocate`, but also ensures that the returned memory is zero-initialized.
138 /// Returning `Err` indicates that either memory is exhausted or `layout` does not meet
139 /// allocator's size or alignment constraints.
141 /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
142 /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
143 /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
145 /// Clients wishing to abort computation in response to an allocation error are encouraged to
146 /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
148 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
149 fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
150 let ptr = self.allocate(layout)?;
151 // SAFETY: `alloc` returns a valid memory block
152 unsafe { ptr.as_non_null_ptr().as_ptr().write_bytes(0, ptr.len()) }
156 /// Deallocates the memory referenced by `ptr`.
160 /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator, and
161 /// * `layout` must [*fit*] that block of memory.
163 /// [*currently allocated*]: #currently-allocated-memory
164 /// [*fit*]: #memory-fitting
165 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout);
167 /// Attempts to extend the memory block.
169 /// Returns a new [`NonNull<[u8]>`][NonNull] containing a pointer and the actual size of the allocated
170 /// memory. The pointer is suitable for holding data described by `new_layout`. To accomplish
171 /// this, the allocator may extend the allocation referenced by `ptr` to fit the new layout.
173 /// If this returns `Ok`, then ownership of the memory block referenced by `ptr` has been
174 /// transferred to this allocator. The memory may or may not have been freed, and should be
175 /// considered unusable.
177 /// If this method returns `Err`, then ownership of the memory block has not been transferred to
178 /// this allocator, and the contents of the memory block are unaltered.
182 /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator.
183 /// * `old_layout` must [*fit*] that block of memory (The `new_layout` argument need not fit it.).
184 /// * `new_layout.size()` must be greater than or equal to `old_layout.size()`.
186 /// Note that `new_layout.align()` need not be the same as `old_layout.align()`.
188 /// [*currently allocated*]: #currently-allocated-memory
189 /// [*fit*]: #memory-fitting
193 /// Returns `Err` if the new layout does not meet the allocator's size and alignment
194 /// constraints of the allocator, or if growing otherwise fails.
196 /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
197 /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
198 /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
200 /// Clients wishing to abort computation in response to an allocation error are encouraged to
201 /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
203 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
209 ) -> Result<NonNull<[u8]>, AllocError> {
211 new_layout.size() >= old_layout.size(),
212 "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
215 let new_ptr = self.allocate(new_layout)?;
217 // SAFETY: because `new_layout.size()` must be greater than or equal to
218 // `old_layout.size()`, both the old and new memory allocation are valid for reads and
219 // writes for `old_layout.size()` bytes. Also, because the old allocation wasn't yet
220 // deallocated, it cannot overlap `new_ptr`. Thus, the call to `copy_nonoverlapping` is
221 // safe. The safety contract for `dealloc` must be upheld by the caller.
223 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_layout.size());
224 self.deallocate(ptr, old_layout);
230 /// Behaves like `grow`, but also ensures that the new contents are set to zero before being
233 /// The memory block will contain the following contents after a successful call to
235 /// * Bytes `0..old_layout.size()` are preserved from the original allocation.
236 /// * Bytes `old_layout.size()..old_size` will either be preserved or zeroed, depending on
237 /// the allocator implementation. `old_size` refers to the size of the memory block prior
238 /// to the `grow_zeroed` call, which may be larger than the size that was originally
239 /// requested when it was allocated.
240 /// * Bytes `old_size..new_size` are zeroed. `new_size` refers to the size of the memory
241 /// block returned by the `grow_zeroed` call.
245 /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator.
246 /// * `old_layout` must [*fit*] that block of memory (The `new_layout` argument need not fit it.).
247 /// * `new_layout.size()` must be greater than or equal to `old_layout.size()`.
249 /// Note that `new_layout.align()` need not be the same as `old_layout.align()`.
251 /// [*currently allocated*]: #currently-allocated-memory
252 /// [*fit*]: #memory-fitting
256 /// Returns `Err` if the new layout does not meet the allocator's size and alignment
257 /// constraints of the allocator, or if growing otherwise fails.
259 /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
260 /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
261 /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
263 /// Clients wishing to abort computation in response to an allocation error are encouraged to
264 /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
266 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
267 unsafe fn grow_zeroed(
272 ) -> Result<NonNull<[u8]>, AllocError> {
274 new_layout.size() >= old_layout.size(),
275 "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
278 let new_ptr = self.allocate_zeroed(new_layout)?;
280 // SAFETY: because `new_layout.size()` must be greater than or equal to
281 // `old_layout.size()`, both the old and new memory allocation are valid for reads and
282 // writes for `old_layout.size()` bytes. Also, because the old allocation wasn't yet
283 // deallocated, it cannot overlap `new_ptr`. Thus, the call to `copy_nonoverlapping` is
284 // safe. The safety contract for `dealloc` must be upheld by the caller.
286 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_layout.size());
287 self.deallocate(ptr, old_layout);
293 /// Attempts to shrink the memory block.
295 /// Returns a new [`NonNull<[u8]>`][NonNull] containing a pointer and the actual size of the allocated
296 /// memory. The pointer is suitable for holding data described by `new_layout`. To accomplish
297 /// this, the allocator may shrink the allocation referenced by `ptr` to fit the new layout.
299 /// If this returns `Ok`, then ownership of the memory block referenced by `ptr` has been
300 /// transferred to this allocator. The memory may or may not have been freed, and should be
301 /// considered unusable.
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) }