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 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 `Alloc::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")]
68 pub fn from_size_align(size: usize, align: usize) -> Result<Self, LayoutErr> {
69 if !align.is_power_of_two() {
70 return Err(LayoutErr { private: () });
73 // (power-of-two implies align != 0.)
75 // Rounded up size is:
76 // size_rounded_up = (size + align - 1) & !(align - 1);
78 // We know from above that align != 0. If adding (align - 1)
79 // does not overflow, then rounding up will be fine.
81 // Conversely, &-masking with !(align - 1) will subtract off
82 // only low-order-bits. Thus if overflow occurs with the sum,
83 // the &-mask cannot subtract enough to undo that overflow.
85 // Above implies that checking for summation overflow is both
86 // necessary and sufficient.
87 if size > usize::MAX - (align - 1) {
88 return Err(LayoutErr { private: () });
91 unsafe { Ok(Layout::from_size_align_unchecked(size, align)) }
94 /// Creates a layout, bypassing all checks.
98 /// This function is unsafe as it does not verify the preconditions from
99 /// [`Layout::from_size_align`](#method.from_size_align).
100 #[stable(feature = "alloc_layout", since = "1.28.0")]
101 #[rustc_const_stable(feature = "alloc_layout", since = "1.28.0")]
103 pub const unsafe fn from_size_align_unchecked(size: usize, align: usize) -> Self {
104 Layout { size_: size, align_: NonZeroUsize::new_unchecked(align) }
107 /// The minimum size in bytes for a memory block of this layout.
108 #[stable(feature = "alloc_layout", since = "1.28.0")]
110 pub fn size(&self) -> usize {
114 /// The minimum byte alignment for a memory block of this layout.
115 #[stable(feature = "alloc_layout", since = "1.28.0")]
117 pub fn align(&self) -> usize {
121 /// Constructs a `Layout` suitable for holding a value of type `T`.
122 #[stable(feature = "alloc_layout", since = "1.28.0")]
124 pub fn new<T>() -> Self {
125 let (size, align) = size_align::<T>();
126 // Note that the align is guaranteed by rustc to be a power of two and
127 // the size+align combo is guaranteed to fit in our address space. As a
128 // result use the unchecked constructor here to avoid inserting code
129 // that panics if it isn't optimized well enough.
130 debug_assert!(Layout::from_size_align(size, align).is_ok());
131 unsafe { Layout::from_size_align_unchecked(size, align) }
134 /// Produces layout describing a record that could be used to
135 /// allocate backing structure for `T` (which could be a trait
136 /// or other unsized type like a slice).
137 #[stable(feature = "alloc_layout", since = "1.28.0")]
139 pub fn for_value<T: ?Sized>(t: &T) -> Self {
140 let (size, align) = (mem::size_of_val(t), mem::align_of_val(t));
141 // See rationale in `new` for why this is using an unsafe variant below
142 debug_assert!(Layout::from_size_align(size, align).is_ok());
143 unsafe { Layout::from_size_align_unchecked(size, align) }
146 /// Creates a layout describing the record that can hold a value
147 /// of the same layout as `self`, but that also is aligned to
148 /// alignment `align` (measured in bytes).
150 /// If `self` already meets the prescribed alignment, then returns
153 /// Note that this method does not add any padding to the overall
154 /// size, regardless of whether the returned layout has a different
155 /// alignment. In other words, if `K` has size 16, `K.align_to(32)`
156 /// will *still* have size 16.
158 /// Returns an error if the combination of `self.size()` and the given
159 /// `align` violates the conditions listed in
160 /// [`Layout::from_size_align`](#method.from_size_align).
161 #[unstable(feature = "alloc_layout_extra", issue = "55724")]
163 pub fn align_to(&self, align: usize) -> Result<Self, LayoutErr> {
164 Layout::from_size_align(self.size(), cmp::max(self.align(), align))
167 /// Returns the amount of padding we must insert after `self`
168 /// to ensure that the following address will satisfy `align`
169 /// (measured in bytes).
171 /// e.g., if `self.size()` is 9, then `self.padding_needed_for(4)`
172 /// returns 3, because that is the minimum number of bytes of
173 /// padding required to get a 4-aligned address (assuming that the
174 /// corresponding memory block starts at a 4-aligned address).
176 /// The return value of this function has no meaning if `align` is
177 /// not a power-of-two.
179 /// Note that the utility of the returned value requires `align`
180 /// to be less than or equal to the alignment of the starting
181 /// address for the whole allocated block of memory. One way to
182 /// satisfy this constraint is to ensure `align <= self.align()`.
183 #[unstable(feature = "alloc_layout_extra", issue = "55724")]
185 pub fn padding_needed_for(&self, align: usize) -> usize {
186 let len = self.size();
188 // Rounded up value is:
189 // len_rounded_up = (len + align - 1) & !(align - 1);
190 // and then we return the padding difference: `len_rounded_up - len`.
192 // We use modular arithmetic throughout:
194 // 1. align is guaranteed to be > 0, so align - 1 is always
197 // 2. `len + align - 1` can overflow by at most `align - 1`,
198 // so the &-mask with `!(align - 1)` will ensure that in the
199 // case of overflow, `len_rounded_up` will itself be 0.
200 // Thus the returned padding, when added to `len`, yields 0,
201 // which trivially satisfies the alignment `align`.
203 // (Of course, attempts to allocate blocks of memory whose
204 // size and padding overflow in the above manner should cause
205 // the allocator to yield an error anyway.)
207 let len_rounded_up = len.wrapping_add(align).wrapping_sub(1) & !align.wrapping_sub(1);
208 len_rounded_up.wrapping_sub(len)
211 /// Creates a layout by rounding the size of this layout up to a multiple
212 /// of the layout's alignment.
214 /// This is equivalent to adding the result of `padding_needed_for`
215 /// to the layout's current size.
216 #[unstable(feature = "alloc_layout_extra", issue = "55724")]
218 pub fn pad_to_align(&self) -> Layout {
219 let pad = self.padding_needed_for(self.align());
220 // This cannot overflow. Quoting from the invariant of Layout:
221 // > `size`, when rounded up to the nearest multiple of `align`,
222 // > must not overflow (i.e., the rounded value must be less than
224 let new_size = self.size() + pad;
226 Layout::from_size_align(new_size, self.align()).unwrap()
229 /// Creates a layout describing the record for `n` instances of
230 /// `self`, with a suitable amount of padding between each to
231 /// ensure that each instance is given its requested size and
232 /// alignment. On success, returns `(k, offs)` where `k` is the
233 /// layout of the array and `offs` is the distance between the start
234 /// of each element in the array.
236 /// On arithmetic overflow, returns `LayoutErr`.
237 #[unstable(feature = "alloc_layout_extra", issue = "55724")]
239 pub fn repeat(&self, n: usize) -> Result<(Self, usize), LayoutErr> {
240 // This cannot overflow. Quoting from the invariant of Layout:
241 // > `size`, when rounded up to the nearest multiple of `align`,
242 // > must not overflow (i.e., the rounded value must be less than
244 let padded_size = self.size() + self.padding_needed_for(self.align());
245 let alloc_size = padded_size.checked_mul(n).ok_or(LayoutErr { private: () })?;
248 // self.align is already known to be valid and alloc_size has been
250 Ok((Layout::from_size_align_unchecked(alloc_size, self.align()), padded_size))
254 /// Creates a layout describing the record for `self` followed by
255 /// `next`, including any necessary padding to ensure that `next`
256 /// will be properly aligned. Note that the resulting layout will
257 /// satisfy the alignment properties of both `self` and `next`.
259 /// The resulting layout will be the same as that of a C struct containing
260 /// two fields with the layouts of `self` and `next`, in that order.
262 /// Returns `Some((k, offset))`, where `k` is layout of the concatenated
263 /// record and `offset` is the relative location, in bytes, of the
264 /// start of the `next` embedded within the concatenated record
265 /// (assuming that the record itself starts at offset 0).
267 /// On arithmetic overflow, returns `LayoutErr`.
268 #[unstable(feature = "alloc_layout_extra", issue = "55724")]
270 pub fn extend(&self, next: Self) -> Result<(Self, usize), LayoutErr> {
271 let new_align = cmp::max(self.align(), next.align());
272 let pad = self.padding_needed_for(next.align());
274 let offset = self.size().checked_add(pad).ok_or(LayoutErr { private: () })?;
275 let new_size = offset.checked_add(next.size()).ok_or(LayoutErr { private: () })?;
277 let layout = Layout::from_size_align(new_size, new_align)?;
281 /// Creates a layout describing the record for `n` instances of
282 /// `self`, with no padding between each instance.
284 /// Note that, unlike `repeat`, `repeat_packed` does not guarantee
285 /// that the repeated instances of `self` will be properly
286 /// aligned, even if a given instance of `self` is properly
287 /// aligned. In other words, if the layout returned by
288 /// `repeat_packed` is used to allocate an array, it is not
289 /// guaranteed that all elements in the array will be properly
292 /// On arithmetic overflow, returns `LayoutErr`.
293 #[unstable(feature = "alloc_layout_extra", issue = "55724")]
295 pub fn repeat_packed(&self, n: usize) -> Result<Self, LayoutErr> {
296 let size = self.size().checked_mul(n).ok_or(LayoutErr { private: () })?;
297 Layout::from_size_align(size, self.align())
300 /// Creates a layout describing the record for `self` followed by
301 /// `next` with no additional padding between the two. Since no
302 /// padding is inserted, the alignment of `next` is irrelevant,
303 /// and is not incorporated *at all* into the resulting layout.
305 /// On arithmetic overflow, returns `LayoutErr`.
306 #[unstable(feature = "alloc_layout_extra", issue = "55724")]
308 pub fn extend_packed(&self, next: Self) -> Result<Self, LayoutErr> {
309 let new_size = self.size().checked_add(next.size()).ok_or(LayoutErr { private: () })?;
310 Layout::from_size_align(new_size, self.align())
313 /// Creates a layout describing the record for a `[T; n]`.
315 /// On arithmetic overflow, returns `LayoutErr`.
316 #[unstable(feature = "alloc_layout_extra", issue = "55724")]
318 pub fn array<T>(n: usize) -> Result<Self, LayoutErr> {
319 Layout::new::<T>().repeat(n).map(|(k, offs)| {
320 debug_assert!(offs == mem::size_of::<T>());
326 /// The parameters given to `Layout::from_size_align`
327 /// or some other `Layout` constructor
328 /// do not satisfy its documented constraints.
329 #[stable(feature = "alloc_layout", since = "1.28.0")]
330 #[derive(Clone, PartialEq, Eq, Debug)]
331 pub struct LayoutErr {
335 // (we need this for downstream impl of trait Error)
336 #[stable(feature = "alloc_layout", since = "1.28.0")]
337 impl fmt::Display for LayoutErr {
338 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
339 f.write_str("invalid parameters to Layout::from_size_align")
343 /// The `AllocErr` error indicates an allocation failure
344 /// that may be due to resource exhaustion or to
345 /// something wrong when combining the given input arguments with this
347 #[unstable(feature = "allocator_api", issue = "32838")]
348 #[derive(Clone, PartialEq, Eq, Debug)]
351 // (we need this for downstream impl of trait Error)
352 #[unstable(feature = "allocator_api", issue = "32838")]
353 impl fmt::Display for AllocErr {
354 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
355 f.write_str("memory allocation failed")
359 /// The `CannotReallocInPlace` error is used when [`grow_in_place`] or
360 /// [`shrink_in_place`] were unable to reuse the given memory block for
361 /// a requested layout.
363 /// [`grow_in_place`]: ./trait.Alloc.html#method.grow_in_place
364 /// [`shrink_in_place`]: ./trait.Alloc.html#method.shrink_in_place
365 #[unstable(feature = "allocator_api", issue = "32838")]
366 #[derive(Clone, PartialEq, Eq, Debug)]
367 pub struct CannotReallocInPlace;
369 #[unstable(feature = "allocator_api", issue = "32838")]
370 impl CannotReallocInPlace {
371 pub fn description(&self) -> &str {
372 "cannot reallocate allocator's memory in place"
376 // (we need this for downstream impl of trait Error)
377 #[unstable(feature = "allocator_api", issue = "32838")]
378 impl fmt::Display for CannotReallocInPlace {
379 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
380 write!(f, "{}", self.description())
384 /// A memory allocator that can be registered as the standard library’s default
385 /// through the `#[global_allocator]` attribute.
387 /// Some of the methods require that a memory block be *currently
388 /// allocated* via an allocator. This means that:
390 /// * the starting address for that memory block was previously
391 /// returned by a previous call to an allocation method
392 /// such as `alloc`, and
394 /// * the memory block has not been subsequently deallocated, where
395 /// blocks are deallocated either by being passed to a deallocation
396 /// method such as `dealloc` or by being
397 /// passed to a reallocation method that returns a non-null pointer.
403 /// use std::alloc::{GlobalAlloc, Layout, alloc};
404 /// use std::ptr::null_mut;
406 /// struct MyAllocator;
408 /// unsafe impl GlobalAlloc for MyAllocator {
409 /// unsafe fn alloc(&self, _layout: Layout) -> *mut u8 { null_mut() }
410 /// unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) {}
413 /// #[global_allocator]
414 /// static A: MyAllocator = MyAllocator;
418 /// assert!(alloc(Layout::new::<u32>()).is_null())
425 /// The `GlobalAlloc` trait is an `unsafe` trait for a number of reasons, and
426 /// implementors must ensure that they adhere to these contracts:
428 /// * It's undefined behavior if global allocators unwind. This restriction may
429 /// be lifted in the future, but currently a panic from any of these
430 /// functions may lead to memory unsafety.
432 /// * `Layout` queries and calculations in general must be correct. Callers of
433 /// this trait are allowed to rely on the contracts defined on each method,
434 /// and implementors must ensure such contracts remain true.
435 #[stable(feature = "global_alloc", since = "1.28.0")]
436 pub unsafe trait GlobalAlloc {
437 /// Allocate memory as described by the given `layout`.
439 /// Returns a pointer to newly-allocated memory,
440 /// or null to indicate allocation failure.
444 /// This function is unsafe because undefined behavior can result
445 /// if the caller does not ensure that `layout` has non-zero size.
447 /// (Extension subtraits might provide more specific bounds on
448 /// behavior, e.g., guarantee a sentinel address or a null pointer
449 /// in response to a zero-size allocation request.)
451 /// The allocated block of memory may or may not be initialized.
455 /// Returning a null pointer indicates that either memory is exhausted
456 /// or `layout` does not meet this allocator's size or alignment constraints.
458 /// Implementations are encouraged to return null on memory
459 /// exhaustion rather than aborting, but this is not
460 /// a strict requirement. (Specifically: it is *legal* to
461 /// implement this trait atop an underlying native allocation
462 /// library that aborts on memory exhaustion.)
464 /// Clients wishing to abort computation in response to an
465 /// allocation error are encouraged to call the [`handle_alloc_error`] function,
466 /// rather than directly invoking `panic!` or similar.
468 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
469 #[stable(feature = "global_alloc", since = "1.28.0")]
470 unsafe fn alloc(&self, layout: Layout) -> *mut u8;
472 /// Deallocate the block of memory at the given `ptr` pointer with the given `layout`.
476 /// This function is unsafe because undefined behavior can result
477 /// if the caller does not ensure all of the following:
479 /// * `ptr` must denote a block of memory currently allocated via
482 /// * `layout` must be the same layout that was used
483 /// to allocate that block of memory,
484 #[stable(feature = "global_alloc", since = "1.28.0")]
485 unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout);
487 /// Behaves like `alloc`, but also ensures that the contents
488 /// are set to zero before being returned.
492 /// This function is unsafe for the same reasons that `alloc` is.
493 /// However the allocated block of memory is guaranteed to be initialized.
497 /// Returning a null pointer indicates that either memory is exhausted
498 /// or `layout` does not meet allocator's size or alignment constraints,
499 /// just as in `alloc`.
501 /// Clients wishing to abort computation in response to an
502 /// allocation error are encouraged to call the [`handle_alloc_error`] function,
503 /// rather than directly invoking `panic!` or similar.
505 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
506 #[stable(feature = "global_alloc", since = "1.28.0")]
507 unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
508 let size = layout.size();
509 let ptr = self.alloc(layout);
511 ptr::write_bytes(ptr, 0, size);
516 /// Shrink or grow a block of memory to the given `new_size`.
517 /// The block is described by the given `ptr` pointer and `layout`.
519 /// If this returns a non-null pointer, then ownership of the memory block
520 /// referenced by `ptr` has been transferred to this allocator.
521 /// The memory may or may not have been deallocated,
522 /// and should be considered unusable (unless of course it was
523 /// transferred back to the caller again via the return value of
526 /// If this method returns null, then ownership of the memory
527 /// block has not been transferred to this allocator, and the
528 /// contents of the memory block are unaltered.
532 /// This function is unsafe because undefined behavior can result
533 /// if the caller does not ensure all of the following:
535 /// * `ptr` must be currently allocated via this allocator,
537 /// * `layout` must be the same layout that was used
538 /// to allocate that block of memory,
540 /// * `new_size` must be greater than zero.
542 /// * `new_size`, when rounded up to the nearest multiple of `layout.align()`,
543 /// must not overflow (i.e., the rounded value must be less than `usize::MAX`).
545 /// (Extension subtraits might provide more specific bounds on
546 /// behavior, e.g., guarantee a sentinel address or a null pointer
547 /// in response to a zero-size allocation request.)
551 /// Returns null if the new layout does not meet the size
552 /// and alignment constraints of the allocator, or if reallocation
555 /// Implementations are encouraged to return null on memory
556 /// exhaustion rather than panicking or aborting, but this is not
557 /// a strict requirement. (Specifically: it is *legal* to
558 /// implement this trait atop an underlying native allocation
559 /// library that aborts on memory exhaustion.)
561 /// Clients wishing to abort computation in response to a
562 /// reallocation error are encouraged to call the [`handle_alloc_error`] function,
563 /// rather than directly invoking `panic!` or similar.
565 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
566 #[stable(feature = "global_alloc", since = "1.28.0")]
567 unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
568 let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
569 let new_ptr = self.alloc(new_layout);
570 if !new_ptr.is_null() {
571 ptr::copy_nonoverlapping(ptr, new_ptr, cmp::min(layout.size(), new_size));
572 self.dealloc(ptr, layout);
578 /// An implementation of `Alloc` can allocate, reallocate, and
579 /// deallocate arbitrary blocks of data described via `Layout`.
581 /// Some of the methods require that a memory block be *currently
582 /// allocated* via an allocator. This means that:
584 /// * the starting address for that memory block was previously
585 /// returned by a previous call to an allocation method (`alloc`,
586 /// `alloc_zeroed`, `alloc_excess`, `alloc_one`, `alloc_array`) or
587 /// reallocation method (`realloc`, `realloc_excess`, or
588 /// `realloc_array`), and
590 /// * the memory block has not been subsequently deallocated, where
591 /// blocks are deallocated either by being passed to a deallocation
592 /// method (`dealloc`, `dealloc_one`, `dealloc_array`) or by being
593 /// passed to a reallocation method (see above) that returns `Ok`.
595 /// A note regarding zero-sized types and zero-sized layouts: many
596 /// methods in the `Alloc` trait state that allocation requests
597 /// must be non-zero size, or else undefined behavior can result.
599 /// * However, some higher-level allocation methods (`alloc_one`,
600 /// `alloc_array`) are well-defined on zero-sized types and can
601 /// optionally support them: it is left up to the implementor
602 /// whether to return `Err`, or to return `Ok` with some pointer.
604 /// * If an `Alloc` implementation chooses to return `Ok` in this
605 /// case (i.e., the pointer denotes a zero-sized inaccessible block)
606 /// then that returned pointer must be considered "currently
607 /// allocated". On such an allocator, *all* methods that take
608 /// currently-allocated pointers as inputs must accept these
609 /// zero-sized pointers, *without* causing undefined behavior.
611 /// * In other words, if a zero-sized pointer can flow out of an
612 /// allocator, then that allocator must likewise accept that pointer
613 /// flowing back into its deallocation and reallocation methods.
615 /// Some of the methods require that a layout *fit* a memory block.
616 /// What it means for a layout to "fit" a memory block means (or
617 /// equivalently, for a memory block to "fit" a layout) is that the
618 /// following two conditions must hold:
620 /// 1. The block's starting address must be aligned to `layout.align()`.
622 /// 2. The block's size must fall in the range `[use_min, use_max]`, where:
624 /// * `use_min` is `self.usable_size(layout).0`, and
626 /// * `use_max` is the capacity that was (or would have been)
627 /// returned when (if) the block was allocated via a call to
628 /// `alloc_excess` or `realloc_excess`.
632 /// * the size of the layout most recently used to allocate the block
633 /// is guaranteed to be in the range `[use_min, use_max]`, and
635 /// * a lower-bound on `use_max` can be safely approximated by a call to
638 /// * if a layout `k` fits a memory block (denoted by `ptr`)
639 /// currently allocated via an allocator `a`, then it is legal to
640 /// use that layout to deallocate it, i.e., `a.dealloc(ptr, k);`.
644 /// The `Alloc` trait is an `unsafe` trait for a number of reasons, and
645 /// implementors must ensure that they adhere to these contracts:
647 /// * Pointers returned from allocation functions must point to valid memory and
648 /// retain their validity until at least the instance of `Alloc` is dropped
651 /// * `Layout` queries and calculations in general must be correct. Callers of
652 /// this trait are allowed to rely on the contracts defined on each method,
653 /// and implementors must ensure such contracts remain true.
655 /// Note that this list may get tweaked over time as clarifications are made in
657 #[unstable(feature = "allocator_api", issue = "32838")]
658 pub unsafe trait Alloc {
659 // (Note: some existing allocators have unspecified but well-defined
660 // behavior in response to a zero size allocation request ;
661 // e.g., in C, `malloc` of 0 will either return a null pointer or a
662 // unique pointer, but will not have arbitrary undefined
664 // However in jemalloc for example,
665 // `mallocx(0)` is documented as undefined behavior.)
667 /// Returns a pointer meeting the size and alignment guarantees of
670 /// If this method returns an `Ok(addr)`, then the `addr` returned
671 /// will be non-null address pointing to a block of storage
672 /// suitable for holding an instance of `layout`.
674 /// The returned block of storage may or may not have its contents
675 /// initialized. (Extension subtraits might restrict this
676 /// behavior, e.g., to ensure initialization to particular sets of
681 /// This function is unsafe because undefined behavior can result
682 /// if the caller does not ensure that `layout` has non-zero size.
684 /// (Extension subtraits might provide more specific bounds on
685 /// behavior, e.g., guarantee a sentinel address or a null pointer
686 /// in response to a zero-size allocation request.)
690 /// Returning `Err` indicates that either memory is exhausted or
691 /// `layout` does not meet allocator's size or alignment
694 /// Implementations are encouraged to return `Err` on memory
695 /// exhaustion rather than panicking or aborting, but this is not
696 /// a strict requirement. (Specifically: it is *legal* to
697 /// implement this trait atop an underlying native allocation
698 /// library that aborts on memory exhaustion.)
700 /// Clients wishing to abort computation in response to an
701 /// allocation error are encouraged to call the [`handle_alloc_error`] function,
702 /// rather than directly invoking `panic!` or similar.
704 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
705 unsafe fn alloc(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr>;
707 /// Deallocate the memory referenced by `ptr`.
711 /// This function is unsafe because undefined behavior can result
712 /// if the caller does not ensure all of the following:
714 /// * `ptr` must denote a block of memory currently allocated via
717 /// * `layout` must *fit* that block of memory,
719 /// * In addition to fitting the block of memory `layout`, the
720 /// alignment of the `layout` must match the alignment used
721 /// to allocate that block of memory.
722 unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout);
724 // == ALLOCATOR-SPECIFIC QUANTITIES AND LIMITS ==
727 /// Returns bounds on the guaranteed usable size of a successful
728 /// allocation created with the specified `layout`.
730 /// In particular, if one has a memory block allocated via a given
731 /// allocator `a` and layout `k` where `a.usable_size(k)` returns
732 /// `(l, u)`, then one can pass that block to `a.dealloc()` with a
733 /// layout in the size range [l, u].
735 /// (All implementors of `usable_size` must ensure that
736 /// `l <= k.size() <= u`)
738 /// Both the lower- and upper-bounds (`l` and `u` respectively)
739 /// are provided, because an allocator based on size classes could
740 /// misbehave if one attempts to deallocate a block without
741 /// providing a correct value for its size (i.e., one within the
744 /// Clients who wish to make use of excess capacity are encouraged
745 /// to use the `alloc_excess` and `realloc_excess` instead, as
746 /// this method is constrained to report conservative values that
747 /// serve as valid bounds for *all possible* allocation method
750 /// However, for clients that do not wish to track the capacity
751 /// returned by `alloc_excess` locally, this method is likely to
752 /// produce useful results.
754 fn usable_size(&self, layout: &Layout) -> (usize, usize) {
755 (layout.size(), layout.size())
758 // == METHODS FOR MEMORY REUSE ==
759 // realloc. alloc_excess, realloc_excess
761 /// Returns a pointer suitable for holding data described by
762 /// a new layout with `layout`’s alignment and a size given
763 /// by `new_size`. To
764 /// accomplish this, this may extend or shrink the allocation
765 /// referenced by `ptr` to fit the new layout.
767 /// If this returns `Ok`, then ownership of the memory block
768 /// referenced by `ptr` has been transferred to this
769 /// allocator. The memory may or may not have been freed, and
770 /// should be considered unusable (unless of course it was
771 /// transferred back to the caller again via the return value of
774 /// If this method returns `Err`, then ownership of the memory
775 /// block has not been transferred to this allocator, and the
776 /// contents of the memory block are unaltered.
780 /// This function is unsafe because undefined behavior can result
781 /// if the caller does not ensure all of the following:
783 /// * `ptr` must be currently allocated via this allocator,
785 /// * `layout` must *fit* the `ptr` (see above). (The `new_size`
786 /// argument need not fit it.)
788 /// * `new_size` must be greater than zero.
790 /// * `new_size`, when rounded up to the nearest multiple of `layout.align()`,
791 /// must not overflow (i.e., the rounded value must be less than `usize::MAX`).
793 /// (Extension subtraits might provide more specific bounds on
794 /// behavior, e.g., guarantee a sentinel address or a null pointer
795 /// in response to a zero-size allocation request.)
799 /// Returns `Err` only if the new layout
800 /// does not meet the allocator's size
801 /// and alignment constraints of the allocator, or if reallocation
804 /// Implementations are encouraged to return `Err` on memory
805 /// exhaustion rather than panicking or aborting, but this is not
806 /// a strict requirement. (Specifically: it is *legal* to
807 /// implement this trait atop an underlying native allocation
808 /// library that aborts on memory exhaustion.)
810 /// Clients wishing to abort computation in response to a
811 /// reallocation error are encouraged to call the [`handle_alloc_error`] function,
812 /// rather than directly invoking `panic!` or similar.
814 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
820 ) -> Result<NonNull<u8>, AllocErr> {
821 let old_size = layout.size();
823 if new_size >= old_size {
824 if let Ok(()) = self.grow_in_place(ptr, layout, new_size) {
827 } else if new_size < old_size {
828 if let Ok(()) = self.shrink_in_place(ptr, layout, new_size) {
833 // otherwise, fall back on alloc + copy + dealloc.
834 let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
835 let result = self.alloc(new_layout);
836 if let Ok(new_ptr) = result {
837 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_ptr(), cmp::min(old_size, new_size));
838 self.dealloc(ptr, layout);
843 /// Behaves like `alloc`, but also ensures that the contents
844 /// are set to zero before being returned.
848 /// This function is unsafe for the same reasons that `alloc` is.
852 /// Returning `Err` indicates that either memory is exhausted or
853 /// `layout` does not meet allocator's size or alignment
854 /// constraints, just as in `alloc`.
856 /// Clients wishing to abort computation in response to an
857 /// allocation error are encouraged to call the [`handle_alloc_error`] function,
858 /// rather than directly invoking `panic!` or similar.
860 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
861 unsafe fn alloc_zeroed(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
862 let size = layout.size();
863 let p = self.alloc(layout);
865 ptr::write_bytes(p.as_ptr(), 0, size);
870 /// Behaves like `alloc`, but also returns the whole size of
871 /// the returned block. For some `layout` inputs, like arrays, this
872 /// may include extra storage usable for additional data.
876 /// This function is unsafe for the same reasons that `alloc` is.
880 /// Returning `Err` indicates that either memory is exhausted or
881 /// `layout` does not meet allocator's size or alignment
882 /// constraints, just as in `alloc`.
884 /// Clients wishing to abort computation in response to an
885 /// allocation error are encouraged to call the [`handle_alloc_error`] function,
886 /// rather than directly invoking `panic!` or similar.
888 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
889 unsafe fn alloc_excess(&mut self, layout: Layout) -> Result<Excess, AllocErr> {
890 let usable_size = self.usable_size(&layout);
891 self.alloc(layout).map(|p| Excess(p, usable_size.1))
894 /// Behaves like `realloc`, but also returns the whole size of
895 /// the returned block. For some `layout` inputs, like arrays, this
896 /// may include extra storage usable for additional data.
900 /// This function is unsafe for the same reasons that `realloc` is.
904 /// Returning `Err` indicates that either memory is exhausted or
905 /// `layout` does not meet allocator's size or alignment
906 /// constraints, just as in `realloc`.
908 /// Clients wishing to abort computation in response to a
909 /// reallocation error are encouraged to call the [`handle_alloc_error`] function,
910 /// rather than directly invoking `panic!` or similar.
912 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
913 unsafe fn realloc_excess(
918 ) -> Result<Excess, AllocErr> {
919 let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
920 let usable_size = self.usable_size(&new_layout);
921 self.realloc(ptr, layout, new_size).map(|p| Excess(p, usable_size.1))
924 /// Attempts to extend the allocation referenced by `ptr` to fit `new_size`.
926 /// If this returns `Ok`, then the allocator has asserted that the
927 /// memory block referenced by `ptr` now fits `new_size`, and thus can
928 /// be used to carry data of a layout of that size and same alignment as
929 /// `layout`. (The allocator is allowed to
930 /// expend effort to accomplish this, such as extending the memory block to
931 /// include successor blocks, or virtual memory tricks.)
933 /// Regardless of what this method returns, ownership of the
934 /// memory block referenced by `ptr` has not been transferred, and
935 /// the contents of the memory block are unaltered.
939 /// This function is unsafe because undefined behavior can result
940 /// if the caller does not ensure all of the following:
942 /// * `ptr` must be currently allocated via this allocator,
944 /// * `layout` must *fit* the `ptr` (see above); note the
945 /// `new_size` argument need not fit it,
947 /// * `new_size` must not be less than `layout.size()`,
951 /// Returns `Err(CannotReallocInPlace)` when the allocator is
952 /// unable to assert that the memory block referenced by `ptr`
953 /// could fit `layout`.
955 /// Note that one cannot pass `CannotReallocInPlace` to the `handle_alloc_error`
956 /// function; clients are expected either to be able to recover from
957 /// `grow_in_place` failures without aborting, or to fall back on
958 /// another reallocation method before resorting to an abort.
959 unsafe fn grow_in_place(
964 ) -> Result<(), CannotReallocInPlace> {
965 let _ = ptr; // this default implementation doesn't care about the actual address.
966 debug_assert!(new_size >= layout.size());
967 let (_l, u) = self.usable_size(&layout);
968 // _l <= layout.size() [guaranteed by usable_size()]
969 // layout.size() <= new_layout.size() [required by this method]
970 if new_size <= u { Ok(()) } else { Err(CannotReallocInPlace) }
973 /// Attempts to shrink the allocation referenced by `ptr` to fit `new_size`.
975 /// If this returns `Ok`, then the allocator has asserted that the
976 /// memory block referenced by `ptr` now fits `new_size`, and
977 /// thus can only be used to carry data of that smaller
978 /// layout. (The allocator is allowed to take advantage of this,
979 /// carving off portions of the block for reuse elsewhere.) The
980 /// truncated contents of the block within the smaller layout are
981 /// unaltered, and ownership of block has not been transferred.
983 /// If this returns `Err`, then the memory block is considered to
984 /// still represent the original (larger) `layout`. None of the
985 /// block has been carved off for reuse elsewhere, ownership of
986 /// the memory block has not been transferred, and the contents of
987 /// the memory block are unaltered.
991 /// This function is unsafe because undefined behavior can result
992 /// if the caller does not ensure all of the following:
994 /// * `ptr` must be currently allocated via this allocator,
996 /// * `layout` must *fit* the `ptr` (see above); note the
997 /// `new_size` argument need not fit it,
999 /// * `new_size` must not be greater than `layout.size()`
1000 /// (and must be greater than zero),
1004 /// Returns `Err(CannotReallocInPlace)` when the allocator is
1005 /// unable to assert that the memory block referenced by `ptr`
1006 /// could fit `layout`.
1008 /// Note that one cannot pass `CannotReallocInPlace` to the `handle_alloc_error`
1009 /// function; clients are expected either to be able to recover from
1010 /// `shrink_in_place` failures without aborting, or to fall back
1011 /// on another reallocation method before resorting to an abort.
1012 unsafe fn shrink_in_place(
1017 ) -> Result<(), CannotReallocInPlace> {
1018 let _ = ptr; // this default implementation doesn't care about the actual address.
1019 debug_assert!(new_size <= layout.size());
1020 let (l, _u) = self.usable_size(&layout);
1021 // layout.size() <= _u [guaranteed by usable_size()]
1022 // new_layout.size() <= layout.size() [required by this method]
1023 if l <= new_size { Ok(()) } else { Err(CannotReallocInPlace) }
1026 // == COMMON USAGE PATTERNS ==
1027 // alloc_one, dealloc_one, alloc_array, realloc_array. dealloc_array
1029 /// Allocates a block suitable for holding an instance of `T`.
1031 /// Captures a common usage pattern for allocators.
1033 /// The returned block is suitable for passing to the
1034 /// `realloc`/`dealloc` methods of this allocator.
1036 /// Note to implementors: If this returns `Ok(ptr)`, then `ptr`
1037 /// must be considered "currently allocated" and must be
1038 /// acceptable input to methods such as `realloc` or `dealloc`,
1039 /// *even if* `T` is a zero-sized type. In other words, if your
1040 /// `Alloc` implementation overrides this method in a manner
1041 /// that can return a zero-sized `ptr`, then all reallocation and
1042 /// deallocation methods need to be similarly overridden to accept
1043 /// such values as input.
1047 /// Returning `Err` indicates that either memory is exhausted or
1048 /// `T` does not meet allocator's size or alignment constraints.
1050 /// For zero-sized `T`, may return either of `Ok` or `Err`, but
1051 /// will *not* yield undefined behavior.
1053 /// Clients wishing to abort computation in response to an
1054 /// allocation error are encouraged to call the [`handle_alloc_error`] function,
1055 /// rather than directly invoking `panic!` or similar.
1057 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
1058 fn alloc_one<T>(&mut self) -> Result<NonNull<T>, AllocErr>
1062 let k = Layout::new::<T>();
1063 if k.size() > 0 { unsafe { self.alloc(k).map(|p| p.cast()) } } else { Err(AllocErr) }
1066 /// Deallocates a block suitable for holding an instance of `T`.
1068 /// The given block must have been produced by this allocator,
1069 /// and must be suitable for storing a `T` (in terms of alignment
1070 /// as well as minimum and maximum size); otherwise yields
1071 /// undefined behavior.
1073 /// Captures a common usage pattern for allocators.
1077 /// This function is unsafe because undefined behavior can result
1078 /// if the caller does not ensure both:
1080 /// * `ptr` must denote a block of memory currently allocated via this allocator
1082 /// * the layout of `T` must *fit* that block of memory.
1083 unsafe fn dealloc_one<T>(&mut self, ptr: NonNull<T>)
1087 let k = Layout::new::<T>();
1089 self.dealloc(ptr.cast(), k);
1093 /// Allocates a block suitable for holding `n` instances of `T`.
1095 /// Captures a common usage pattern for allocators.
1097 /// The returned block is suitable for passing to the
1098 /// `realloc`/`dealloc` methods of this allocator.
1100 /// Note to implementors: If this returns `Ok(ptr)`, then `ptr`
1101 /// must be considered "currently allocated" and must be
1102 /// acceptable input to methods such as `realloc` or `dealloc`,
1103 /// *even if* `T` is a zero-sized type. In other words, if your
1104 /// `Alloc` implementation overrides this method in a manner
1105 /// that can return a zero-sized `ptr`, then all reallocation and
1106 /// deallocation methods need to be similarly overridden to accept
1107 /// such values as input.
1111 /// Returning `Err` indicates that either memory is exhausted or
1112 /// `[T; n]` does not meet allocator's size or alignment
1115 /// For zero-sized `T` or `n == 0`, may return either of `Ok` or
1116 /// `Err`, but will *not* yield undefined behavior.
1118 /// Always returns `Err` on arithmetic overflow.
1120 /// Clients wishing to abort computation in response to an
1121 /// allocation error are encouraged to call the [`handle_alloc_error`] function,
1122 /// rather than directly invoking `panic!` or similar.
1124 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
1125 fn alloc_array<T>(&mut self, n: usize) -> Result<NonNull<T>, AllocErr>
1129 match Layout::array::<T>(n) {
1130 Ok(layout) if layout.size() > 0 => unsafe { self.alloc(layout).map(|p| p.cast()) },
1135 /// Reallocates a block previously suitable for holding `n_old`
1136 /// instances of `T`, returning a block suitable for holding
1137 /// `n_new` instances of `T`.
1139 /// Captures a common usage pattern for allocators.
1141 /// The returned block is suitable for passing to the
1142 /// `realloc`/`dealloc` methods of this allocator.
1146 /// This function is unsafe because undefined behavior can result
1147 /// if the caller does not ensure all of the following:
1149 /// * `ptr` must be currently allocated via this allocator,
1151 /// * the layout of `[T; n_old]` must *fit* that block of memory.
1155 /// Returning `Err` indicates that either memory is exhausted or
1156 /// `[T; n_new]` does not meet allocator's size or alignment
1159 /// For zero-sized `T` or `n_new == 0`, may return either of `Ok` or
1160 /// `Err`, but will *not* yield undefined behavior.
1162 /// Always returns `Err` on arithmetic overflow.
1164 /// Clients wishing to abort computation in response to a
1165 /// reallocation error are encouraged to call the [`handle_alloc_error`] function,
1166 /// rather than directly invoking `panic!` or similar.
1168 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
1169 unsafe fn realloc_array<T>(
1174 ) -> Result<NonNull<T>, AllocErr>
1178 match (Layout::array::<T>(n_old), Layout::array::<T>(n_new)) {
1179 (Ok(k_old), Ok(k_new)) if k_old.size() > 0 && k_new.size() > 0 => {
1180 debug_assert!(k_old.align() == k_new.align());
1181 self.realloc(ptr.cast(), k_old, k_new.size()).map(NonNull::cast)
1187 /// Deallocates a block suitable for holding `n` instances of `T`.
1189 /// Captures a common usage pattern for allocators.
1193 /// This function is unsafe because undefined behavior can result
1194 /// if the caller does not ensure both:
1196 /// * `ptr` must denote a block of memory currently allocated via this allocator
1198 /// * the layout of `[T; n]` must *fit* that block of memory.
1202 /// Returning `Err` indicates that either `[T; n]` or the given
1203 /// memory block does not meet allocator's size or alignment
1206 /// Always returns `Err` on arithmetic overflow.
1207 unsafe fn dealloc_array<T>(&mut self, ptr: NonNull<T>, n: usize) -> Result<(), AllocErr>
1211 match Layout::array::<T>(n) {
1212 Ok(k) if k.size() > 0 => Ok(self.dealloc(ptr.cast(), k)),