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, LayoutErr};
13 #[stable(feature = "alloc_layout_error", since = "1.49.0")]
14 pub use self::layout::LayoutError;
17 use crate::ptr::{self, NonNull};
19 /// The `AllocError` error indicates an allocation failure
20 /// that may be due to resource exhaustion or to
21 /// something wrong when combining the given input arguments with this
23 #[unstable(feature = "allocator_api", issue = "32838")]
24 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
25 pub struct AllocError;
27 // (we need this for downstream impl of trait Error)
28 #[unstable(feature = "allocator_api", issue = "32838")]
29 impl fmt::Display for AllocError {
30 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31 f.write_str("memory allocation failed")
35 /// An implementation of `AllocRef` can allocate, grow, shrink, and deallocate arbitrary blocks of
36 /// data described via [`Layout`][].
38 /// `AllocRef` is designed to be implemented on ZSTs, references, or smart pointers because having
39 /// an allocator like `MyAlloc([u8; N])` cannot be moved, without updating the pointers to the
42 /// Unlike [`GlobalAlloc`][], zero-sized allocations are allowed in `AllocRef`. If an underlying
43 /// allocator does not support this (like jemalloc) or return a null pointer (such as
44 /// `libc::malloc`), this must be caught by the implementation.
46 /// ### Currently allocated memory
48 /// Some of the methods require that a memory block be *currently allocated* via an allocator. This
51 /// * the starting address for that memory block was previously returned by [`alloc`], [`grow`], or
54 /// * the memory block has not been subsequently deallocated, where blocks are either deallocated
55 /// directly by being passed to [`dealloc`] or were changed by being passed to [`grow`] or
56 /// [`shrink`] that returns `Ok`. If `grow` or `shrink` have returned `Err`, the passed pointer
59 /// [`alloc`]: AllocRef::alloc
60 /// [`grow`]: AllocRef::grow
61 /// [`shrink`]: AllocRef::shrink
62 /// [`dealloc`]: AllocRef::dealloc
64 /// ### Memory fitting
66 /// Some of the methods require that a layout *fit* a memory block. What it means for a layout to
67 /// "fit" a memory block means (or equivalently, for a memory block to "fit" a layout) is that the
68 /// following conditions must hold:
70 /// * The block must be allocated with the same alignment as [`layout.align()`], and
72 /// * The provided [`layout.size()`] must fall in the range `min ..= max`, where:
73 /// - `min` is the size of the layout most recently used to allocate the block, and
74 /// - `max` is the latest actual size returned from [`alloc`], [`grow`], or [`shrink`].
76 /// [`layout.align()`]: Layout::align
77 /// [`layout.size()`]: Layout::size
81 /// * Memory blocks returned from an allocator must point to valid memory and retain their validity
82 /// until the instance and all of its clones are dropped,
84 /// * cloning or moving the allocator must not invalidate memory blocks returned from this
85 /// allocator. A cloned allocator must behave like the same allocator, and
87 /// * any pointer to a memory block which is [*currently allocated*] may be passed to any other
88 /// method of the allocator.
90 /// [*currently allocated*]: #currently-allocated-memory
91 #[unstable(feature = "allocator_api", issue = "32838")]
92 pub unsafe trait AllocRef {
93 /// Attempts to allocate a block of memory.
95 /// On success, returns a [`NonNull<[u8]>`] meeting the size and alignment guarantees of `layout`.
97 /// The returned block may have a larger size than specified by `layout.size()`, and may or may
98 /// not have its contents initialized.
100 /// [`NonNull<[u8]>`]: NonNull
104 /// Returning `Err` indicates that either memory is exhausted or `layout` does not meet
105 /// allocator's size or alignment constraints.
107 /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
108 /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
109 /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
111 /// Clients wishing to abort computation in response to an allocation error are encouraged to
112 /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
114 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
115 fn alloc(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>;
117 /// Behaves like `alloc`, but also ensures that the returned memory is zero-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 alloc_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
133 let ptr = self.alloc(layout)?;
134 // SAFETY: `alloc` returns a valid memory block
135 unsafe { ptr.as_non_null_ptr().as_ptr().write_bytes(0, ptr.len()) }
139 /// Deallocates the memory referenced by `ptr`.
143 /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator, and
144 /// * `layout` must [*fit*] that block of memory.
146 /// [*currently allocated*]: #currently-allocated-memory
147 /// [*fit*]: #memory-fitting
148 unsafe fn dealloc(&self, ptr: NonNull<u8>, layout: Layout);
150 /// Attempts to extend the memory block.
152 /// Returns a new [`NonNull<[u8]>`] containing a pointer and the actual size of the allocated
153 /// memory. The pointer is suitable for holding data described by `new_layout`. To accomplish
154 /// this, the allocator may extend the allocation referenced by `ptr` to fit the new layout.
156 /// If this returns `Ok`, then ownership of the memory block referenced by `ptr` has been
157 /// transferred to this allocator. The memory may or may not have been freed, and should be
158 /// considered unusable unless it was transferred back to the caller again via the return value
161 /// If this method returns `Err`, then ownership of the memory block has not been transferred to
162 /// this allocator, and the contents of the memory block are unaltered.
164 /// [`NonNull<[u8]>`]: NonNull
168 /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator.
169 /// * `old_layout` must [*fit*] that block of memory (The `new_layout` argument need not fit it.).
170 /// * `new_layout.size()` must be greater than or equal to `old_layout.size()`.
172 /// [*currently allocated*]: #currently-allocated-memory
173 /// [*fit*]: #memory-fitting
177 /// Returns `Err` if the new layout does not meet the allocator's size and alignment
178 /// constraints of the allocator, or if growing otherwise fails.
180 /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
181 /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
182 /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
184 /// Clients wishing to abort computation in response to an allocation error are encouraged to
185 /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
187 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
193 ) -> Result<NonNull<[u8]>, AllocError> {
195 new_layout.size() >= old_layout.size(),
196 "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
199 let new_ptr = self.alloc(new_layout)?;
201 // SAFETY: because `new_layout.size()` must be greater than or equal to
202 // `old_layout.size()`, both the old and new memory allocation are valid for reads and
203 // writes for `old_layout.size()` bytes. Also, because the old allocation wasn't yet
204 // deallocated, it cannot overlap `new_ptr`. Thus, the call to `copy_nonoverlapping` is
205 // safe. The safety contract for `dealloc` must be upheld by the caller.
207 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_layout.size());
208 self.dealloc(ptr, old_layout);
214 /// Behaves like `grow`, but also ensures that the new contents are set to zero before being
217 /// The memory block will contain the following contents after a successful call to
219 /// * Bytes `0..old_layout.size()` are preserved from the original allocation.
220 /// * Bytes `old_layout.size()..old_size` will either be preserved or zeroed, depending on
221 /// the allocator implementation. `old_size` refers to the size of the memory block prior
222 /// to the `grow_zeroed` call, which may be larger than the size that was originally
223 /// requested when it was allocated.
224 /// * Bytes `old_size..new_size` are zeroed. `new_size` refers to the size of the memory
225 /// block returned by the `grow_zeroed` call.
229 /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator.
230 /// * `old_layout` must [*fit*] that block of memory (The `new_layout` argument need not fit it.).
231 /// * `new_layout.size()` must be greater than or equal to `old_layout.size()`.
233 /// [*currently allocated*]: #currently-allocated-memory
234 /// [*fit*]: #memory-fitting
238 /// Returns `Err` if the new layout does not meet the allocator's size and alignment
239 /// constraints of the allocator, or if growing otherwise fails.
241 /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
242 /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
243 /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
245 /// Clients wishing to abort computation in response to an allocation error are encouraged to
246 /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
248 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
249 unsafe fn grow_zeroed(
254 ) -> Result<NonNull<[u8]>, AllocError> {
256 new_layout.size() >= old_layout.size(),
257 "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
260 let new_ptr = self.alloc_zeroed(new_layout)?;
262 // SAFETY: because `new_layout.size()` must be greater than or equal to
263 // `old_layout.size()`, both the old and new memory allocation are valid for reads and
264 // writes for `old_layout.size()` bytes. Also, because the old allocation wasn't yet
265 // deallocated, it cannot overlap `new_ptr`. Thus, the call to `copy_nonoverlapping` is
266 // safe. The safety contract for `dealloc` must be upheld by the caller.
268 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_layout.size());
269 self.dealloc(ptr, old_layout);
275 /// Attempts to shrink the memory block.
277 /// Returns a new [`NonNull<[u8]>`] containing a pointer and the actual size of the allocated
278 /// memory. The pointer is suitable for holding data described by `new_layout`. To accomplish
279 /// this, the allocator may shrink the allocation referenced by `ptr` to fit the new layout.
281 /// If this returns `Ok`, then ownership of the memory block referenced by `ptr` has been
282 /// transferred to this allocator. The memory may or may not have been freed, and should be
283 /// considered unusable unless it was transferred back to the caller again via the return value
286 /// If this method returns `Err`, then ownership of the memory block has not been transferred to
287 /// this allocator, and the contents of the memory block are unaltered.
289 /// [`NonNull<[u8]>`]: NonNull
293 /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator.
294 /// * `old_layout` must [*fit*] that block of memory (The `new_layout` argument need not fit it.).
295 /// * `new_layout.size()` must be smaller than or equal to `old_layout.size()`.
297 /// [*currently allocated*]: #currently-allocated-memory
298 /// [*fit*]: #memory-fitting
302 /// Returns `Err` if the new layout does not meet the allocator's size and alignment
303 /// constraints of the allocator, or if shrinking otherwise fails.
305 /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
306 /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
307 /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
309 /// Clients wishing to abort computation in response to an allocation error are encouraged to
310 /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
312 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
318 ) -> Result<NonNull<[u8]>, AllocError> {
320 new_layout.size() <= old_layout.size(),
321 "`new_layout.size()` must be smaller than or equal to `old_layout.size()`"
324 let new_ptr = self.alloc(new_layout)?;
326 // SAFETY: because `new_layout.size()` must be lower than or equal to
327 // `old_layout.size()`, both the old and new memory allocation are valid for reads and
328 // writes for `new_layout.size()` bytes. Also, because the old allocation wasn't yet
329 // deallocated, it cannot overlap `new_ptr`. Thus, the call to `copy_nonoverlapping` is
330 // safe. The safety contract for `dealloc` must be upheld by the caller.
332 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), new_layout.size());
333 self.dealloc(ptr, old_layout);
339 /// Creates a "by reference" adaptor for this instance of `AllocRef`.
341 /// The returned adaptor also implements `AllocRef` and will simply borrow this.
343 fn by_ref(&self) -> &Self {
348 #[unstable(feature = "allocator_api", issue = "32838")]
349 unsafe impl<A> AllocRef for &A
351 A: AllocRef + ?Sized,
354 fn alloc(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
355 (**self).alloc(layout)
359 fn alloc_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
360 (**self).alloc_zeroed(layout)
364 unsafe fn dealloc(&self, ptr: NonNull<u8>, layout: Layout) {
365 // SAFETY: the safety contract must be upheld by the caller
366 unsafe { (**self).dealloc(ptr, layout) }
375 ) -> Result<NonNull<[u8]>, AllocError> {
376 // SAFETY: the safety contract must be upheld by the caller
377 unsafe { (**self).grow(ptr, old_layout, new_layout) }
381 unsafe fn grow_zeroed(
386 ) -> Result<NonNull<[u8]>, AllocError> {
387 // SAFETY: the safety contract must be upheld by the caller
388 unsafe { (**self).grow_zeroed(ptr, old_layout, new_layout) }
397 ) -> Result<NonNull<[u8]>, AllocError> {
398 // SAFETY: the safety contract must be upheld by the caller
399 unsafe { (**self).shrink(ptr, old_layout, new_layout) }