1 //! Memory allocation APIs
3 // ignore-tidy-undocumented-unsafe
5 #![stable(feature = "alloc_module", since = "1.28.0")]
10 use crate::num::NonZeroUsize;
11 use crate::ptr::{self, NonNull};
14 /// Represents the combination of a starting address and
15 /// a total capacity of the returned block.
16 #[unstable(feature = "allocator_api", issue = "32838")]
18 pub struct Excess(pub NonNull<u8>, pub usize);
20 const fn size_align<T>() -> (usize, usize) {
21 (mem::size_of::<T>(), mem::align_of::<T>())
24 /// Layout of a block of memory.
26 /// An instance of `Layout` describes a particular layout of memory.
27 /// You build a `Layout` up as an input to give to an allocator.
29 /// All layouts have an associated non-negative size and a
30 /// power-of-two alignment.
32 /// (Note however that layouts are *not* required to have positive
33 /// size, even though many allocators require that all memory
34 /// requests have positive size. A caller to the `AllocRef::alloc`
35 /// method must either ensure that conditions like this are met, or
36 /// use specific allocators with looser requirements.)
37 #[stable(feature = "alloc_layout", since = "1.28.0")]
38 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
39 #[lang = "alloc_layout"]
41 // size of the requested block of memory, measured in bytes.
44 // alignment of the requested block of memory, measured in bytes.
45 // we ensure that this is always a power-of-two, because API's
46 // like `posix_memalign` require it and it is a reasonable
47 // constraint to impose on Layout constructors.
49 // (However, we do not analogously require `align >= sizeof(void*)`,
50 // even though that is *also* a requirement of `posix_memalign`.)
55 /// Constructs a `Layout` from a given `size` and `align`,
56 /// or returns `LayoutErr` if any of the following conditions
59 /// * `align` must not be zero,
61 /// * `align` must be a power of two,
63 /// * `size`, when rounded up to the nearest multiple of `align`,
64 /// must not overflow (i.e., the rounded value must be less than
66 #[stable(feature = "alloc_layout", since = "1.28.0")]
67 #[rustc_const_unstable(feature = "const_alloc_layout", issue = "67521")]
69 pub const fn from_size_align(size: usize, align: usize) -> Result<Self, LayoutErr> {
70 if !align.is_power_of_two() {
71 return Err(LayoutErr { private: () });
74 // (power-of-two implies align != 0.)
76 // Rounded up size is:
77 // size_rounded_up = (size + align - 1) & !(align - 1);
79 // We know from above that align != 0. If adding (align - 1)
80 // does not overflow, then rounding up will be fine.
82 // Conversely, &-masking with !(align - 1) will subtract off
83 // only low-order-bits. Thus if overflow occurs with the sum,
84 // the &-mask cannot subtract enough to undo that overflow.
86 // Above implies that checking for summation overflow is both
87 // necessary and sufficient.
88 if size > usize::MAX - (align - 1) {
89 return Err(LayoutErr { private: () });
92 unsafe { Ok(Layout::from_size_align_unchecked(size, align)) }
95 /// Creates a layout, bypassing all checks.
99 /// This function is unsafe as it does not verify the preconditions from
100 /// [`Layout::from_size_align`](#method.from_size_align).
101 #[stable(feature = "alloc_layout", since = "1.28.0")]
102 #[rustc_const_stable(feature = "alloc_layout", since = "1.28.0")]
104 pub const unsafe fn from_size_align_unchecked(size: usize, align: usize) -> Self {
105 Layout { size_: size, align_: NonZeroUsize::new_unchecked(align) }
108 /// The minimum size in bytes for a memory block of this layout.
109 #[stable(feature = "alloc_layout", since = "1.28.0")]
110 #[rustc_const_unstable(feature = "const_alloc_layout", issue = "67521")]
112 pub const fn size(&self) -> usize {
116 /// The minimum byte alignment for a memory block of this layout.
117 #[stable(feature = "alloc_layout", since = "1.28.0")]
118 #[rustc_const_unstable(feature = "const_alloc_layout", issue = "67521")]
120 pub const fn align(&self) -> usize {
124 /// Constructs a `Layout` suitable for holding a value of type `T`.
125 #[stable(feature = "alloc_layout", since = "1.28.0")]
126 #[rustc_const_stable(feature = "alloc_layout_const_new", since = "1.42.0")]
128 pub const fn new<T>() -> Self {
129 let (size, align) = size_align::<T>();
130 // Note that the align is guaranteed by rustc to be a power of two and
131 // the size+align combo is guaranteed to fit in our address space. As a
132 // result use the unchecked constructor here to avoid inserting code
133 // that panics if it isn't optimized well enough.
134 unsafe { Layout::from_size_align_unchecked(size, align) }
137 /// Produces layout describing a record that could be used to
138 /// allocate backing structure for `T` (which could be a trait
139 /// or other unsized type like a slice).
140 #[stable(feature = "alloc_layout", since = "1.28.0")]
142 pub fn for_value<T: ?Sized>(t: &T) -> Self {
143 let (size, align) = (mem::size_of_val(t), mem::align_of_val(t));
144 // See rationale in `new` for why this is using an unsafe variant below
145 debug_assert!(Layout::from_size_align(size, align).is_ok());
146 unsafe { Layout::from_size_align_unchecked(size, align) }
149 /// Creates a layout describing the record that can hold a value
150 /// of the same layout as `self`, but that also is aligned to
151 /// alignment `align` (measured in bytes).
153 /// If `self` already meets the prescribed alignment, then returns
156 /// Note that this method does not add any padding to the overall
157 /// size, regardless of whether the returned layout has a different
158 /// alignment. In other words, if `K` has size 16, `K.align_to(32)`
159 /// will *still* have size 16.
161 /// Returns an error if the combination of `self.size()` and the given
162 /// `align` violates the conditions listed in
163 /// [`Layout::from_size_align`](#method.from_size_align).
164 #[unstable(feature = "alloc_layout_extra", issue = "55724")]
166 pub fn align_to(&self, align: usize) -> Result<Self, LayoutErr> {
167 Layout::from_size_align(self.size(), cmp::max(self.align(), align))
170 /// Returns the amount of padding we must insert after `self`
171 /// to ensure that the following address will satisfy `align`
172 /// (measured in bytes).
174 /// e.g., if `self.size()` is 9, then `self.padding_needed_for(4)`
175 /// returns 3, because that is the minimum number of bytes of
176 /// padding required to get a 4-aligned address (assuming that the
177 /// corresponding memory block starts at a 4-aligned address).
179 /// The return value of this function has no meaning if `align` is
180 /// not a power-of-two.
182 /// Note that the utility of the returned value requires `align`
183 /// to be less than or equal to the alignment of the starting
184 /// address for the whole allocated block of memory. One way to
185 /// satisfy this constraint is to ensure `align <= self.align()`.
186 #[unstable(feature = "alloc_layout_extra", issue = "55724")]
187 #[rustc_const_unstable(feature = "const_alloc_layout", issue = "67521")]
189 pub const fn padding_needed_for(&self, align: usize) -> usize {
190 let len = self.size();
192 // Rounded up value is:
193 // len_rounded_up = (len + align - 1) & !(align - 1);
194 // and then we return the padding difference: `len_rounded_up - len`.
196 // We use modular arithmetic throughout:
198 // 1. align is guaranteed to be > 0, so align - 1 is always
201 // 2. `len + align - 1` can overflow by at most `align - 1`,
202 // so the &-mask with `!(align - 1)` will ensure that in the
203 // case of overflow, `len_rounded_up` will itself be 0.
204 // Thus the returned padding, when added to `len`, yields 0,
205 // which trivially satisfies the alignment `align`.
207 // (Of course, attempts to allocate blocks of memory whose
208 // size and padding overflow in the above manner should cause
209 // the allocator to yield an error anyway.)
211 let len_rounded_up = len.wrapping_add(align).wrapping_sub(1) & !align.wrapping_sub(1);
212 len_rounded_up.wrapping_sub(len)
215 /// Creates a layout by rounding the size of this layout up to a multiple
216 /// of the layout's alignment.
218 /// This is equivalent to adding the result of `padding_needed_for`
219 /// to the layout's current size.
220 #[unstable(feature = "alloc_layout_extra", issue = "55724")]
222 pub fn pad_to_align(&self) -> Layout {
223 let pad = self.padding_needed_for(self.align());
224 // This cannot overflow. Quoting from the invariant of Layout:
225 // > `size`, when rounded up to the nearest multiple of `align`,
226 // > must not overflow (i.e., the rounded value must be less than
228 let new_size = self.size() + pad;
230 Layout::from_size_align(new_size, self.align()).unwrap()
233 /// Creates a layout describing the record for `n` instances of
234 /// `self`, with a suitable amount of padding between each to
235 /// ensure that each instance is given its requested size and
236 /// alignment. On success, returns `(k, offs)` where `k` is the
237 /// layout of the array and `offs` is the distance between the start
238 /// of each element in the array.
240 /// On arithmetic overflow, returns `LayoutErr`.
241 #[unstable(feature = "alloc_layout_extra", issue = "55724")]
243 pub fn repeat(&self, n: usize) -> Result<(Self, usize), LayoutErr> {
244 // Warning, removing the checked_add here led to segfaults in #67174. Further
245 // analysis in #69225 seems to indicate that this is an LTO-related
246 // miscompilation, so #67174 might be able to be reapplied in the future.
247 let padded_size = self
249 .checked_add(self.padding_needed_for(self.align()))
250 .ok_or(LayoutErr { private: () })?;
251 let alloc_size = padded_size.checked_mul(n).ok_or(LayoutErr { private: () })?;
254 // self.align is already known to be valid and alloc_size has been
256 Ok((Layout::from_size_align_unchecked(alloc_size, self.align()), padded_size))
260 /// Creates a layout describing the record for `self` followed by
261 /// `next`, including any necessary padding to ensure that `next`
262 /// will be properly aligned. Note that the resulting layout will
263 /// satisfy the alignment properties of both `self` and `next`.
265 /// The resulting layout will be the same as that of a C struct containing
266 /// two fields with the layouts of `self` and `next`, in that order.
268 /// Returns `Some((k, offset))`, where `k` is layout of the concatenated
269 /// record and `offset` is the relative location, in bytes, of the
270 /// start of the `next` embedded within the concatenated record
271 /// (assuming that the record itself starts at offset 0).
273 /// On arithmetic overflow, returns `LayoutErr`.
274 #[unstable(feature = "alloc_layout_extra", issue = "55724")]
276 pub fn extend(&self, next: Self) -> Result<(Self, usize), LayoutErr> {
277 let new_align = cmp::max(self.align(), next.align());
278 let pad = self.padding_needed_for(next.align());
280 let offset = self.size().checked_add(pad).ok_or(LayoutErr { private: () })?;
281 let new_size = offset.checked_add(next.size()).ok_or(LayoutErr { private: () })?;
283 let layout = Layout::from_size_align(new_size, new_align)?;
287 /// Creates a layout describing the record for `n` instances of
288 /// `self`, with no padding between each instance.
290 /// Note that, unlike `repeat`, `repeat_packed` does not guarantee
291 /// that the repeated instances of `self` will be properly
292 /// aligned, even if a given instance of `self` is properly
293 /// aligned. In other words, if the layout returned by
294 /// `repeat_packed` is used to allocate an array, it is not
295 /// guaranteed that all elements in the array will be properly
298 /// On arithmetic overflow, returns `LayoutErr`.
299 #[unstable(feature = "alloc_layout_extra", issue = "55724")]
301 pub fn repeat_packed(&self, n: usize) -> Result<Self, LayoutErr> {
302 let size = self.size().checked_mul(n).ok_or(LayoutErr { private: () })?;
303 Layout::from_size_align(size, self.align())
306 /// Creates a layout describing the record for `self` followed by
307 /// `next` with no additional padding between the two. Since no
308 /// padding is inserted, the alignment of `next` is irrelevant,
309 /// and is not incorporated *at all* into the resulting layout.
311 /// On arithmetic overflow, returns `LayoutErr`.
312 #[unstable(feature = "alloc_layout_extra", issue = "55724")]
314 pub fn extend_packed(&self, next: Self) -> Result<Self, LayoutErr> {
315 let new_size = self.size().checked_add(next.size()).ok_or(LayoutErr { private: () })?;
316 Layout::from_size_align(new_size, self.align())
319 /// Creates a layout describing the record for a `[T; n]`.
321 /// On arithmetic overflow, returns `LayoutErr`.
322 #[unstable(feature = "alloc_layout_extra", issue = "55724")]
324 pub fn array<T>(n: usize) -> Result<Self, LayoutErr> {
325 Layout::new::<T>().repeat(n).map(|(k, offs)| {
326 debug_assert!(offs == mem::size_of::<T>());
332 /// The parameters given to `Layout::from_size_align`
333 /// or some other `Layout` constructor
334 /// do not satisfy its documented constraints.
335 #[stable(feature = "alloc_layout", since = "1.28.0")]
336 #[derive(Clone, PartialEq, Eq, Debug)]
337 pub struct LayoutErr {
341 // (we need this for downstream impl of trait Error)
342 #[stable(feature = "alloc_layout", since = "1.28.0")]
343 impl fmt::Display for LayoutErr {
344 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
345 f.write_str("invalid parameters to Layout::from_size_align")
349 /// The `AllocErr` error indicates an allocation failure
350 /// that may be due to resource exhaustion or to
351 /// something wrong when combining the given input arguments with this
353 #[unstable(feature = "allocator_api", issue = "32838")]
354 #[derive(Clone, PartialEq, Eq, Debug)]
357 // (we need this for downstream impl of trait Error)
358 #[unstable(feature = "allocator_api", issue = "32838")]
359 impl fmt::Display for AllocErr {
360 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
361 f.write_str("memory allocation failed")
365 /// The `CannotReallocInPlace` error is used when [`grow_in_place`] or
366 /// [`shrink_in_place`] were unable to reuse the given memory block for
367 /// a requested layout.
369 /// [`grow_in_place`]: ./trait.AllocRef.html#method.grow_in_place
370 /// [`shrink_in_place`]: ./trait.AllocRef.html#method.shrink_in_place
371 #[unstable(feature = "allocator_api", issue = "32838")]
372 #[derive(Clone, PartialEq, Eq, Debug)]
373 pub struct CannotReallocInPlace;
375 #[unstable(feature = "allocator_api", issue = "32838")]
376 impl CannotReallocInPlace {
377 pub fn description(&self) -> &str {
378 "cannot reallocate allocator's memory in place"
382 // (we need this for downstream impl of trait Error)
383 #[unstable(feature = "allocator_api", issue = "32838")]
384 impl fmt::Display for CannotReallocInPlace {
385 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
386 write!(f, "{}", self.description())
390 /// A memory allocator that can be registered as the standard library’s default
391 /// through the `#[global_allocator]` attribute.
393 /// Some of the methods require that a memory block be *currently
394 /// allocated* via an allocator. This means that:
396 /// * the starting address for that memory block was previously
397 /// returned by a previous call to an allocation method
398 /// such as `alloc`, and
400 /// * the memory block has not been subsequently deallocated, where
401 /// blocks are deallocated either by being passed to a deallocation
402 /// method such as `dealloc` or by being
403 /// passed to a reallocation method that returns a non-null pointer.
409 /// use std::alloc::{GlobalAlloc, Layout, alloc};
410 /// use std::ptr::null_mut;
412 /// struct MyAllocator;
414 /// unsafe impl GlobalAlloc for MyAllocator {
415 /// unsafe fn alloc(&self, _layout: Layout) -> *mut u8 { null_mut() }
416 /// unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) {}
419 /// #[global_allocator]
420 /// static A: MyAllocator = MyAllocator;
424 /// assert!(alloc(Layout::new::<u32>()).is_null())
431 /// The `GlobalAlloc` trait is an `unsafe` trait for a number of reasons, and
432 /// implementors must ensure that they adhere to these contracts:
434 /// * It's undefined behavior if global allocators unwind. This restriction may
435 /// be lifted in the future, but currently a panic from any of these
436 /// functions may lead to memory unsafety.
438 /// * `Layout` queries and calculations in general must be correct. Callers of
439 /// this trait are allowed to rely on the contracts defined on each method,
440 /// and implementors must ensure such contracts remain true.
441 #[stable(feature = "global_alloc", since = "1.28.0")]
442 pub unsafe trait GlobalAlloc {
443 /// Allocate memory as described by the given `layout`.
445 /// Returns a pointer to newly-allocated memory,
446 /// or null to indicate allocation failure.
450 /// This function is unsafe because undefined behavior can result
451 /// if the caller does not ensure that `layout` has non-zero size.
453 /// (Extension subtraits might provide more specific bounds on
454 /// behavior, e.g., guarantee a sentinel address or a null pointer
455 /// in response to a zero-size allocation request.)
457 /// The allocated block of memory may or may not be initialized.
461 /// Returning a null pointer indicates that either memory is exhausted
462 /// or `layout` does not meet this allocator's size or alignment constraints.
464 /// Implementations are encouraged to return null on memory
465 /// exhaustion rather than aborting, but this is not
466 /// a strict requirement. (Specifically: it is *legal* to
467 /// implement this trait atop an underlying native allocation
468 /// library that aborts on memory exhaustion.)
470 /// Clients wishing to abort computation in response to an
471 /// allocation error are encouraged to call the [`handle_alloc_error`] function,
472 /// rather than directly invoking `panic!` or similar.
474 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
475 #[stable(feature = "global_alloc", since = "1.28.0")]
476 unsafe fn alloc(&self, layout: Layout) -> *mut u8;
478 /// Deallocate the block of memory at the given `ptr` pointer with the given `layout`.
482 /// This function is unsafe because undefined behavior can result
483 /// if the caller does not ensure all of the following:
485 /// * `ptr` must denote a block of memory currently allocated via
488 /// * `layout` must be the same layout that was used
489 /// to allocate that block of memory,
490 #[stable(feature = "global_alloc", since = "1.28.0")]
491 unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout);
493 /// Behaves like `alloc`, but also ensures that the contents
494 /// are set to zero before being returned.
498 /// This function is unsafe for the same reasons that `alloc` is.
499 /// However the allocated block of memory is guaranteed to be initialized.
503 /// Returning a null pointer indicates that either memory is exhausted
504 /// or `layout` does not meet allocator's size or alignment constraints,
505 /// just as in `alloc`.
507 /// Clients wishing to abort computation in response to an
508 /// allocation error are encouraged to call the [`handle_alloc_error`] function,
509 /// rather than directly invoking `panic!` or similar.
511 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
512 #[stable(feature = "global_alloc", since = "1.28.0")]
513 unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
514 let size = layout.size();
515 let ptr = self.alloc(layout);
517 ptr::write_bytes(ptr, 0, size);
522 /// Shrink or grow a block of memory to the given `new_size`.
523 /// The block is described by the given `ptr` pointer and `layout`.
525 /// If this returns a non-null pointer, then ownership of the memory block
526 /// referenced by `ptr` has been transferred to this allocator.
527 /// The memory may or may not have been deallocated,
528 /// and should be considered unusable (unless of course it was
529 /// transferred back to the caller again via the return value of
530 /// this method). The new memory block is allocated with `layout`, but
531 /// with the `size` updated to `new_size`.
533 /// If this method returns null, then ownership of the memory
534 /// block has not been transferred to this allocator, and the
535 /// contents of the memory block are unaltered.
539 /// This function is unsafe because undefined behavior can result
540 /// if the caller does not ensure all of the following:
542 /// * `ptr` must be currently allocated via this allocator,
544 /// * `layout` must be the same layout that was used
545 /// to allocate that block of memory,
547 /// * `new_size` must be greater than zero.
549 /// * `new_size`, when rounded up to the nearest multiple of `layout.align()`,
550 /// must not overflow (i.e., the rounded value must be less than `usize::MAX`).
552 /// (Extension subtraits might provide more specific bounds on
553 /// behavior, e.g., guarantee a sentinel address or a null pointer
554 /// in response to a zero-size allocation request.)
558 /// Returns null if the new layout does not meet the size
559 /// and alignment constraints of the allocator, or if reallocation
562 /// Implementations are encouraged to return null on memory
563 /// exhaustion rather than panicking or aborting, but this is not
564 /// a strict requirement. (Specifically: it is *legal* to
565 /// implement this trait atop an underlying native allocation
566 /// library that aborts on memory exhaustion.)
568 /// Clients wishing to abort computation in response to a
569 /// reallocation error are encouraged to call the [`handle_alloc_error`] function,
570 /// rather than directly invoking `panic!` or similar.
572 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
573 #[stable(feature = "global_alloc", since = "1.28.0")]
574 unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
575 let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
576 let new_ptr = self.alloc(new_layout);
577 if !new_ptr.is_null() {
578 ptr::copy_nonoverlapping(ptr, new_ptr, cmp::min(layout.size(), new_size));
579 self.dealloc(ptr, layout);
585 /// An implementation of `AllocRef` can allocate, reallocate, and
586 /// deallocate arbitrary blocks of data described via `Layout`.
588 /// `AllocRef` is designed to be implemented on ZSTs, references, or
589 /// smart pointers because having an allocator like `MyAlloc([u8; N])`
590 /// cannot be moved, without updating the pointers to the allocated
593 /// Some of the methods require that a memory block be *currently
594 /// allocated* via an allocator. This means that:
596 /// * the starting address for that memory block was previously
597 /// returned by a previous call to an allocation method (`alloc`,
598 /// `alloc_zeroed`, `alloc_excess`) or reallocation method
599 /// (`realloc`, `realloc_excess`), and
601 /// * the memory block has not been subsequently deallocated, where
602 /// blocks are deallocated either by being passed to a deallocation
603 /// method (`dealloc`, `dealloc_one`, `dealloc_array`) or by being
604 /// passed to a reallocation method (see above) that returns `Ok`.
606 /// A note regarding zero-sized types and zero-sized layouts: many
607 /// methods in the `AllocRef` trait state that allocation requests
608 /// must be non-zero size, or else undefined behavior can result.
610 /// * If an `AllocRef` implementation chooses to return `Ok` in this
611 /// case (i.e., the pointer denotes a zero-sized inaccessible block)
612 /// then that returned pointer must be considered "currently
613 /// allocated". On such an allocator, *all* methods that take
614 /// currently-allocated pointers as inputs must accept these
615 /// zero-sized pointers, *without* causing undefined behavior.
617 /// * In other words, if a zero-sized pointer can flow out of an
618 /// allocator, then that allocator must likewise accept that pointer
619 /// flowing back into its deallocation and reallocation methods.
621 /// Some of the methods require that a layout *fit* a memory block.
622 /// What it means for a layout to "fit" a memory block means (or
623 /// equivalently, for a memory block to "fit" a layout) is that the
624 /// following two conditions must hold:
626 /// 1. The block's starting address must be aligned to `layout.align()`.
628 /// 2. The block's size must fall in the range `[use_min, use_max]`, where:
630 /// * `use_min` is `self.usable_size(layout).0`, and
632 /// * `use_max` is the capacity that was (or would have been)
633 /// returned when (if) the block was allocated via a call to
634 /// `alloc_excess` or `realloc_excess`.
638 /// * the size of the layout most recently used to allocate the block
639 /// is guaranteed to be in the range `[use_min, use_max]`, and
641 /// * a lower-bound on `use_max` can be safely approximated by a call to
644 /// * if a layout `k` fits a memory block (denoted by `ptr`)
645 /// currently allocated via an allocator `a`, then it is legal to
646 /// use that layout to deallocate it, i.e., `a.dealloc(ptr, k);`.
650 /// The `AllocRef` trait is an `unsafe` trait for a number of reasons, and
651 /// implementors must ensure that they adhere to these contracts:
653 /// * Pointers returned from allocation functions must point to valid memory and
654 /// retain their validity until at least one instance of `AllocRef` is dropped
657 /// * Cloning or moving the allocator must not invalidate pointers returned
658 /// from this allocator. Cloning must return a reference to the same allocator.
660 /// * `Layout` queries and calculations in general must be correct. Callers of
661 /// this trait are allowed to rely on the contracts defined on each method,
662 /// and implementors must ensure such contracts remain true.
664 /// Note that this list may get tweaked over time as clarifications are made in
666 #[unstable(feature = "allocator_api", issue = "32838")]
667 pub unsafe trait AllocRef {
668 // (Note: some existing allocators have unspecified but well-defined
669 // behavior in response to a zero size allocation request ;
670 // e.g., in C, `malloc` of 0 will either return a null pointer or a
671 // unique pointer, but will not have arbitrary undefined
673 // However in jemalloc for example,
674 // `mallocx(0)` is documented as undefined behavior.)
676 /// Returns a pointer meeting the size and alignment guarantees of
679 /// If this method returns an `Ok(addr)`, then the `addr` returned
680 /// will be non-null address pointing to a block of storage
681 /// suitable for holding an instance of `layout`.
683 /// The returned block of storage may or may not have its contents
684 /// initialized. (Extension subtraits might restrict this
685 /// behavior, e.g., to ensure initialization to particular sets of
690 /// This function is unsafe because undefined behavior can result
691 /// if the caller does not ensure that `layout` has non-zero size.
693 /// (Extension subtraits might provide more specific bounds on
694 /// behavior, e.g., guarantee a sentinel address or a null pointer
695 /// in response to a zero-size allocation request.)
699 /// Returning `Err` indicates that either memory is exhausted or
700 /// `layout` does not meet allocator's size or alignment
703 /// Implementations are encouraged to return `Err` on memory
704 /// exhaustion rather than panicking or aborting, but this is not
705 /// a strict requirement. (Specifically: it is *legal* to
706 /// implement this trait atop an underlying native allocation
707 /// library that aborts on memory exhaustion.)
709 /// Clients wishing to abort computation in response to an
710 /// allocation error are encouraged to call the [`handle_alloc_error`] function,
711 /// rather than directly invoking `panic!` or similar.
713 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
714 unsafe fn alloc(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr>;
716 /// Deallocate the memory referenced by `ptr`.
720 /// This function is unsafe because undefined behavior can result
721 /// if the caller does not ensure all of the following:
723 /// * `ptr` must denote a block of memory currently allocated via
726 /// * `layout` must *fit* that block of memory,
728 /// * In addition to fitting the block of memory `layout`, the
729 /// alignment of the `layout` must match the alignment used
730 /// to allocate that block of memory.
731 unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout);
733 // == ALLOCATOR-SPECIFIC QUANTITIES AND LIMITS ==
736 /// Returns bounds on the guaranteed usable size of a successful
737 /// allocation created with the specified `layout`.
739 /// In particular, if one has a memory block allocated via a given
740 /// allocator `a` and layout `k` where `a.usable_size(k)` returns
741 /// `(l, u)`, then one can pass that block to `a.dealloc()` with a
742 /// layout in the size range [l, u].
744 /// (All implementors of `usable_size` must ensure that
745 /// `l <= k.size() <= u`)
747 /// Both the lower- and upper-bounds (`l` and `u` respectively)
748 /// are provided, because an allocator based on size classes could
749 /// misbehave if one attempts to deallocate a block without
750 /// providing a correct value for its size (i.e., one within the
753 /// Clients who wish to make use of excess capacity are encouraged
754 /// to use the `alloc_excess` and `realloc_excess` instead, as
755 /// this method is constrained to report conservative values that
756 /// serve as valid bounds for *all possible* allocation method
759 /// However, for clients that do not wish to track the capacity
760 /// returned by `alloc_excess` locally, this method is likely to
761 /// produce useful results.
763 fn usable_size(&self, layout: &Layout) -> (usize, usize) {
764 (layout.size(), layout.size())
767 // == METHODS FOR MEMORY REUSE ==
768 // realloc. alloc_excess, realloc_excess
770 /// Returns a pointer suitable for holding data described by
771 /// a new layout with `layout`’s alignment and a size given
772 /// by `new_size`. To
773 /// accomplish this, this may extend or shrink the allocation
774 /// referenced by `ptr` to fit the new layout.
776 /// If this returns `Ok`, then ownership of the memory block
777 /// referenced by `ptr` has been transferred to this
778 /// allocator. The memory may or may not have been freed, and
779 /// should be considered unusable (unless of course it was
780 /// transferred back to the caller again via the return value of
783 /// If this method returns `Err`, then ownership of the memory
784 /// block has not been transferred to this allocator, and the
785 /// contents of the memory block are unaltered.
789 /// This function is unsafe because undefined behavior can result
790 /// if the caller does not ensure all of the following:
792 /// * `ptr` must be currently allocated via this allocator,
794 /// * `layout` must *fit* the `ptr` (see above). (The `new_size`
795 /// argument need not fit it.)
797 /// * `new_size` must be greater than zero.
799 /// * `new_size`, when rounded up to the nearest multiple of `layout.align()`,
800 /// must not overflow (i.e., the rounded value must be less than `usize::MAX`).
802 /// (Extension subtraits might provide more specific bounds on
803 /// behavior, e.g., guarantee a sentinel address or a null pointer
804 /// in response to a zero-size allocation request.)
808 /// Returns `Err` only if the new layout
809 /// does not meet the allocator's size
810 /// and alignment constraints of the allocator, or if reallocation
813 /// Implementations are encouraged to return `Err` on memory
814 /// exhaustion rather than panicking or aborting, but this is not
815 /// a strict requirement. (Specifically: it is *legal* to
816 /// implement this trait atop an underlying native allocation
817 /// library that aborts on memory exhaustion.)
819 /// Clients wishing to abort computation in response to a
820 /// reallocation error are encouraged to call the [`handle_alloc_error`] function,
821 /// rather than directly invoking `panic!` or similar.
823 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
829 ) -> Result<NonNull<u8>, AllocErr> {
830 let old_size = layout.size();
832 if new_size >= old_size {
833 if let Ok(()) = self.grow_in_place(ptr, layout, new_size) {
836 } else if new_size < old_size {
837 if let Ok(()) = self.shrink_in_place(ptr, layout, new_size) {
842 // otherwise, fall back on alloc + copy + dealloc.
843 let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
844 let result = self.alloc(new_layout);
845 if let Ok(new_ptr) = result {
846 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_ptr(), cmp::min(old_size, new_size));
847 self.dealloc(ptr, layout);
852 /// Behaves like `realloc`, but also ensures that the new contents
853 /// are set to zero before being returned.
857 /// This function is unsafe for the same reasons that `realloc` is.
861 /// Returns `Err` only if the new layout
862 /// does not meet the allocator's size
863 /// and alignment constraints of the allocator, or if reallocation
866 /// Implementations are encouraged to return `Err` on memory
867 /// exhaustion rather than panicking or aborting, but this is not
868 /// a strict requirement. (Specifically: it is *legal* to
869 /// implement this trait atop an underlying native allocation
870 /// library that aborts on memory exhaustion.)
872 /// Clients wishing to abort computation in response to a
873 /// reallocation error are encouraged to call the [`handle_alloc_error`] function,
874 /// rather than directly invoking `panic!` or similar.
876 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
877 unsafe fn realloc_zeroed(
882 ) -> Result<NonNull<u8>, AllocErr> {
883 let old_size = layout.size();
885 if new_size >= old_size {
886 if let Ok(()) = self.grow_in_place_zeroed(ptr, layout, new_size) {
889 } else if new_size < old_size {
890 if let Ok(()) = self.shrink_in_place(ptr, layout, new_size) {
895 // otherwise, fall back on alloc + copy + dealloc.
896 let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
897 let result = self.alloc_zeroed(new_layout);
898 if let Ok(new_ptr) = result {
899 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_ptr(), cmp::min(old_size, new_size));
900 self.dealloc(ptr, layout);
905 /// Behaves like `alloc`, but also ensures that the contents
906 /// are set to zero before being returned.
910 /// This function is unsafe for the same reasons that `alloc` is.
914 /// Returning `Err` indicates that either memory is exhausted or
915 /// `layout` does not meet allocator's size or alignment
916 /// constraints, just as in `alloc`.
918 /// Clients wishing to abort computation in response to an
919 /// allocation error are encouraged to call the [`handle_alloc_error`] function,
920 /// rather than directly invoking `panic!` or similar.
922 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
923 unsafe fn alloc_zeroed(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
924 let size = layout.size();
925 let p = self.alloc(layout);
927 ptr::write_bytes(p.as_ptr(), 0, size);
932 /// Behaves like `alloc`, but also returns the whole size of
933 /// the returned block. For some `layout` inputs, like arrays, this
934 /// may include extra storage usable for additional data.
938 /// This function is unsafe for the same reasons that `alloc` is.
942 /// Returning `Err` indicates that either memory is exhausted or
943 /// `layout` does not meet allocator's size or alignment
944 /// constraints, just as in `alloc`.
946 /// Clients wishing to abort computation in response to an
947 /// allocation error are encouraged to call the [`handle_alloc_error`] function,
948 /// rather than directly invoking `panic!` or similar.
950 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
951 unsafe fn alloc_excess(&mut self, layout: Layout) -> Result<Excess, AllocErr> {
952 let usable_size = self.usable_size(&layout);
953 self.alloc(layout).map(|p| Excess(p, usable_size.1))
956 /// Behaves like `alloc`, but also returns the whole size of
957 /// the returned block. For some `layout` inputs, like arrays, this
958 /// may include extra storage usable for additional data.
959 /// Also it ensures that the contents are set to zero before being returned.
963 /// This function is unsafe for the same reasons that `alloc` is.
967 /// Returning `Err` indicates that either memory is exhausted or
968 /// `layout` does not meet allocator's size or alignment
969 /// constraints, just as in `alloc`.
971 /// Clients wishing to abort computation in response to an
972 /// allocation error are encouraged to call the [`handle_alloc_error`] function,
973 /// rather than directly invoking `panic!` or similar.
975 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
976 unsafe fn alloc_excess_zeroed(&mut self, layout: Layout) -> Result<Excess, AllocErr> {
977 let usable_size = self.usable_size(&layout);
978 self.alloc_zeroed(layout).map(|p| Excess(p, usable_size.1))
981 /// Behaves like `realloc`, but also returns the whole size of
982 /// the returned block. For some `layout` inputs, like arrays, this
983 /// may include extra storage usable for additional data.
987 /// This function is unsafe for the same reasons that `realloc` is.
991 /// Returning `Err` indicates that either memory is exhausted or
992 /// `layout` does not meet allocator's size or alignment
993 /// constraints, just as in `realloc`.
995 /// Clients wishing to abort computation in response to a
996 /// reallocation error are encouraged to call the [`handle_alloc_error`] function,
997 /// rather than directly invoking `panic!` or similar.
999 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
1000 unsafe fn realloc_excess(
1005 ) -> Result<Excess, AllocErr> {
1006 let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
1007 let usable_size = self.usable_size(&new_layout);
1008 self.realloc(ptr, layout, new_size).map(|p| Excess(p, usable_size.1))
1011 /// Behaves like `realloc`, but also returns the whole size of
1012 /// the returned block. For some `layout` inputs, like arrays, this
1013 /// may include extra storage usable for additional data.
1014 /// Also it ensures that the contents are set to zero before being returned.
1018 /// This function is unsafe for the same reasons that `realloc` is.
1022 /// Returning `Err` indicates that either memory is exhausted or
1023 /// `layout` does not meet allocator's size or alignment
1024 /// constraints, just as in `realloc`.
1026 /// Clients wishing to abort computation in response to a
1027 /// reallocation error are encouraged to call the [`handle_alloc_error`] function,
1028 /// rather than directly invoking `panic!` or similar.
1030 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
1031 unsafe fn realloc_excess_zeroed(
1036 ) -> Result<Excess, AllocErr> {
1037 let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
1038 let usable_size = self.usable_size(&new_layout);
1039 self.realloc_zeroed(ptr, layout, new_size).map(|p| Excess(p, usable_size.1))
1042 /// Attempts to extend the allocation referenced by `ptr` to fit `new_size`.
1044 /// If this returns `Ok`, then the allocator has asserted that the
1045 /// memory block referenced by `ptr` now fits `new_size`, and thus can
1046 /// be used to carry data of a layout of that size and same alignment as
1047 /// `layout`. (The allocator is allowed to
1048 /// expend effort to accomplish this, such as extending the memory block to
1049 /// include successor blocks, or virtual memory tricks.)
1051 /// Regardless of what this method returns, ownership of the
1052 /// memory block referenced by `ptr` has not been transferred, and
1053 /// the contents of the memory block are unaltered.
1057 /// This function is unsafe because undefined behavior can result
1058 /// if the caller does not ensure all of the following:
1060 /// * `ptr` must be currently allocated via this allocator,
1062 /// * `layout` must *fit* the `ptr` (see above); note the
1063 /// `new_size` argument need not fit it,
1065 /// * `new_size` must not be less than `layout.size()`,
1069 /// Returns `Err(CannotReallocInPlace)` when the allocator is
1070 /// unable to assert that the memory block referenced by `ptr`
1071 /// could fit `layout`.
1073 /// Note that one cannot pass `CannotReallocInPlace` to the `handle_alloc_error`
1074 /// function; clients are expected either to be able to recover from
1075 /// `grow_in_place` failures without aborting, or to fall back on
1076 /// another reallocation method before resorting to an abort.
1077 unsafe fn grow_in_place(
1082 ) -> Result<(), CannotReallocInPlace> {
1083 let _ = ptr; // this default implementation doesn't care about the actual address.
1084 debug_assert!(new_size >= layout.size());
1085 let (_l, u) = self.usable_size(&layout);
1086 // _l <= layout.size() [guaranteed by usable_size()]
1087 // layout.size() <= new_layout.size() [required by this method]
1088 if new_size <= u { Ok(()) } else { Err(CannotReallocInPlace) }
1091 /// Behaves like `grow_in_place`, but also ensures that the new
1092 /// contents are set to zero before being returned.
1096 /// This function is unsafe for the same reasons that `grow_in_place` is.
1100 /// Returns `Err(CannotReallocInPlace)` when the allocator is
1101 /// unable to assert that the memory block referenced by `ptr`
1102 /// could fit `layout`.
1104 /// Note that one cannot pass `CannotReallocInPlace` to the `handle_alloc_error`
1105 /// function; clients are expected either to be able to recover from
1106 /// `grow_in_place` failures without aborting, or to fall back on
1107 /// another reallocation method before resorting to an abort.
1108 unsafe fn grow_in_place_zeroed(
1113 ) -> Result<(), CannotReallocInPlace> {
1114 self.grow_in_place(ptr, layout, new_size)?;
1115 ptr.as_ptr().add(layout.size()).write_bytes(0, new_size - layout.size());
1119 /// Attempts to shrink the allocation referenced by `ptr` to fit `new_size`.
1121 /// If this returns `Ok`, then the allocator has asserted that the
1122 /// memory block referenced by `ptr` now fits `new_size`, and
1123 /// thus can only be used to carry data of that smaller
1124 /// layout. (The allocator is allowed to take advantage of this,
1125 /// carving off portions of the block for reuse elsewhere.) The
1126 /// truncated contents of the block within the smaller layout are
1127 /// unaltered, and ownership of block has not been transferred.
1129 /// If this returns `Err`, then the memory block is considered to
1130 /// still represent the original (larger) `layout`. None of the
1131 /// block has been carved off for reuse elsewhere, ownership of
1132 /// the memory block has not been transferred, and the contents of
1133 /// the memory block are unaltered.
1137 /// This function is unsafe because undefined behavior can result
1138 /// if the caller does not ensure all of the following:
1140 /// * `ptr` must be currently allocated via this allocator,
1142 /// * `layout` must *fit* the `ptr` (see above); note the
1143 /// `new_size` argument need not fit it,
1145 /// * `new_size` must not be greater than `layout.size()`
1146 /// (and must be greater than zero),
1150 /// Returns `Err(CannotReallocInPlace)` when the allocator is
1151 /// unable to assert that the memory block referenced by `ptr`
1152 /// could fit `layout`.
1154 /// Note that one cannot pass `CannotReallocInPlace` to the `handle_alloc_error`
1155 /// function; clients are expected either to be able to recover from
1156 /// `shrink_in_place` failures without aborting, or to fall back
1157 /// on another reallocation method before resorting to an abort.
1158 unsafe fn shrink_in_place(
1163 ) -> Result<(), CannotReallocInPlace> {
1164 let _ = ptr; // this default implementation doesn't care about the actual address.
1165 debug_assert!(new_size <= layout.size());
1166 let (l, _u) = self.usable_size(&layout);
1167 // layout.size() <= _u [guaranteed by usable_size()]
1168 // new_layout.size() <= layout.size() [required by this method]
1169 if l <= new_size { Ok(()) } else { Err(CannotReallocInPlace) }