1 //! Memory allocation APIs
3 #![stable(feature = "alloc_module", since = "1.28.0")]
9 use crate::ptr::{self, NonNull};
10 use crate::num::NonZeroUsize;
12 /// Represents the combination of a starting address and
13 /// a total capacity of the returned block.
14 #[unstable(feature = "allocator_api", issue = "32838")]
16 pub struct Excess(pub NonNull<u8>, pub usize);
18 fn size_align<T>() -> (usize, usize) {
19 (mem::size_of::<T>(), mem::align_of::<T>())
22 /// Layout of a block of memory.
24 /// An instance of `Layout` describes a particular layout of memory.
25 /// You build a `Layout` up as an input to give to an allocator.
27 /// All layouts have an associated non-negative size and a
28 /// power-of-two alignment.
30 /// (Note however that layouts are *not* required to have positive
31 /// size, even though many allocators require that all memory
32 /// requests have positive size. A caller to the `Alloc::alloc`
33 /// method must either ensure that conditions like this are met, or
34 /// use specific allocators with looser requirements.)
35 #[stable(feature = "alloc_layout", since = "1.28.0")]
36 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
37 #[lang = "alloc_layout"]
39 // size of the requested block of memory, measured in bytes.
42 // alignment of the requested block of memory, measured in bytes.
43 // we ensure that this is always a power-of-two, because API's
44 // like `posix_memalign` require it and it is a reasonable
45 // constraint to impose on Layout constructors.
47 // (However, we do not analogously require `align >= sizeof(void*)`,
48 // even though that is *also* a requirement of `posix_memalign`.)
53 /// Constructs a `Layout` from a given `size` and `align`,
54 /// or returns `LayoutErr` if either of the following conditions
57 /// * `align` must not be zero,
59 /// * `align` must be a power of two,
61 /// * `size`, when rounded up to the nearest multiple of `align`,
62 /// must not overflow (i.e., the rounded value must be less than
64 #[stable(feature = "alloc_layout", since = "1.28.0")]
66 pub fn from_size_align(size: usize, align: usize) -> Result<Self, LayoutErr> {
67 if !align.is_power_of_two() {
68 return Err(LayoutErr { private: () });
71 // (power-of-two implies align != 0.)
73 // Rounded up size is:
74 // size_rounded_up = (size + align - 1) & !(align - 1);
76 // We know from above that align != 0. If adding (align - 1)
77 // does not overflow, then rounding up will be fine.
79 // Conversely, &-masking with !(align - 1) will subtract off
80 // only low-order-bits. Thus if overflow occurs with the sum,
81 // the &-mask cannot subtract enough to undo that overflow.
83 // Above implies that checking for summation overflow is both
84 // necessary and sufficient.
85 if size > usize::MAX - (align - 1) {
86 return Err(LayoutErr { private: () });
90 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")]
102 pub const unsafe fn from_size_align_unchecked(size: usize, align: usize) -> Self {
103 Layout { size_: size, align_: NonZeroUsize::new_unchecked(align) }
106 /// The minimum size in bytes for a memory block of this layout.
107 #[stable(feature = "alloc_layout", since = "1.28.0")]
109 pub fn size(&self) -> usize { self.size_ }
111 /// The minimum byte alignment for a memory block of this layout.
112 #[stable(feature = "alloc_layout", since = "1.28.0")]
114 pub fn align(&self) -> usize { self.align_.get() }
116 /// Constructs a `Layout` suitable for holding a value of type `T`.
117 #[stable(feature = "alloc_layout", since = "1.28.0")]
119 pub fn new<T>() -> Self {
120 let (size, align) = size_align::<T>();
121 // Note that the align is guaranteed by rustc to be a power of two and
122 // the size+align combo is guaranteed to fit in our address space. As a
123 // result use the unchecked constructor here to avoid inserting code
124 // that panics if it isn't optimized well enough.
125 debug_assert!(Layout::from_size_align(size, align).is_ok());
127 Layout::from_size_align_unchecked(size, align)
131 /// Produces layout describing a record that could be used to
132 /// allocate backing structure for `T` (which could be a trait
133 /// or other unsized type like a slice).
134 #[stable(feature = "alloc_layout", since = "1.28.0")]
136 pub fn for_value<T: ?Sized>(t: &T) -> Self {
137 let (size, align) = (mem::size_of_val(t), mem::align_of_val(t));
138 // See rationale in `new` for why this us using an unsafe variant below
139 debug_assert!(Layout::from_size_align(size, align).is_ok());
141 Layout::from_size_align_unchecked(size, align)
145 /// Creates a layout describing the record that can hold a value
146 /// of the same layout as `self`, but that also is aligned to
147 /// alignment `align` (measured in bytes).
149 /// If `self` already meets the prescribed alignment, then returns
152 /// Note that this method does not add any padding to the overall
153 /// size, regardless of whether the returned layout has a different
154 /// alignment. In other words, if `K` has size 16, `K.align_to(32)`
155 /// will *still* have size 16.
157 /// Returns an error if the combination of `self.size()` and the given
158 /// `align` violates the conditions listed in
159 /// [`Layout::from_size_align`](#method.from_size_align).
160 #[unstable(feature = "alloc_layout_extra", issue = "55724")]
162 pub fn align_to(&self, align: usize) -> Result<Self, LayoutErr> {
163 Layout::from_size_align(self.size(), cmp::max(self.align(), align))
166 /// Returns the amount of padding we must insert after `self`
167 /// to ensure that the following address will satisfy `align`
168 /// (measured in bytes).
170 /// e.g., if `self.size()` is 9, then `self.padding_needed_for(4)`
171 /// returns 3, because that is the minimum number of bytes of
172 /// padding required to get a 4-aligned address (assuming that the
173 /// corresponding memory block starts at a 4-aligned address).
175 /// The return value of this function has no meaning if `align` is
176 /// not a power-of-two.
178 /// Note that the utility of the returned value requires `align`
179 /// to be less than or equal to the alignment of the starting
180 /// address for the whole allocated block of memory. One way to
181 /// satisfy this constraint is to ensure `align <= self.align()`.
182 #[unstable(feature = "alloc_layout_extra", issue = "55724")]
184 pub fn padding_needed_for(&self, align: usize) -> usize {
185 let len = self.size();
187 // Rounded up value is:
188 // len_rounded_up = (len + align - 1) & !(align - 1);
189 // and then we return the padding difference: `len_rounded_up - len`.
191 // We use modular arithmetic throughout:
193 // 1. align is guaranteed to be > 0, so align - 1 is always
196 // 2. `len + align - 1` can overflow by at most `align - 1`,
197 // so the &-mask wth `!(align - 1)` will ensure that in the
198 // case of overflow, `len_rounded_up` will itself be 0.
199 // Thus the returned padding, when added to `len`, yields 0,
200 // which trivially satisfies the alignment `align`.
202 // (Of course, attempts to allocate blocks of memory whose
203 // size and padding overflow in the above manner should cause
204 // the allocator to yield an error anyway.)
206 let len_rounded_up = len.wrapping_add(align).wrapping_sub(1)
207 & !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 /// Returns `Err` if the padded size would overflow.
216 /// This is equivalent to adding the result of `padding_needed_for`
217 /// to the layout's current size.
218 #[unstable(feature = "alloc_layout_extra", issue = "55724")]
220 pub fn pad_to_align(&self) -> Result<Layout, LayoutErr> {
221 let pad = self.padding_needed_for(self.align());
222 let new_size = self.size().checked_add(pad)
223 .ok_or(LayoutErr { private: () })?;
225 Layout::from_size_align(new_size, self.align())
228 /// Creates a layout describing the record for `n` instances of
229 /// `self`, with a suitable amount of padding between each to
230 /// ensure that each instance is given its requested size and
231 /// alignment. On success, returns `(k, offs)` where `k` is the
232 /// layout of the array and `offs` is the distance between the start
233 /// of each element in the array.
235 /// On arithmetic overflow, returns `LayoutErr`.
236 #[unstable(feature = "alloc_layout_extra", issue = "55724")]
238 pub fn repeat(&self, n: usize) -> Result<(Self, usize), LayoutErr> {
239 let padded_size = self.size().checked_add(self.padding_needed_for(self.align()))
240 .ok_or(LayoutErr { private: () })?;
241 let alloc_size = padded_size.checked_mul(n)
242 .ok_or(LayoutErr { private: () })?;
245 // self.align is already known to be valid and alloc_size has been
247 Ok((Layout::from_size_align_unchecked(alloc_size, self.align()), padded_size))
251 /// Creates a layout describing the record for `self` followed by
252 /// `next`, including any necessary padding to ensure that `next`
253 /// will be properly aligned. Note that the result layout will
254 /// satisfy the alignment properties of both `self` and `next`.
256 /// The resulting layout will be the same as that of a C struct containing
257 /// two fields with the layouts of `self` and `next`, in that order.
259 /// Returns `Some((k, offset))`, where `k` is layout of the concatenated
260 /// record and `offset` is the relative location, in bytes, of the
261 /// start of the `next` embedded within the concatenated record
262 /// (assuming that the record itself starts at offset 0).
264 /// On arithmetic overflow, returns `LayoutErr`.
265 #[unstable(feature = "alloc_layout_extra", issue = "55724")]
267 pub fn extend(&self, next: Self) -> Result<(Self, usize), LayoutErr> {
268 let new_align = cmp::max(self.align(), next.align());
269 let pad = self.padding_needed_for(next.align());
271 let offset = self.size().checked_add(pad)
272 .ok_or(LayoutErr { private: () })?;
273 let new_size = offset.checked_add(next.size())
274 .ok_or(LayoutErr { private: () })?;
276 let layout = Layout::from_size_align(new_size, new_align)?;
280 /// Creates a layout describing the record for `n` instances of
281 /// `self`, with no padding between each instance.
283 /// Note that, unlike `repeat`, `repeat_packed` does not guarantee
284 /// that the repeated instances of `self` will be properly
285 /// aligned, even if a given instance of `self` is properly
286 /// aligned. In other words, if the layout returned by
287 /// `repeat_packed` is used to allocate an array, it is not
288 /// guaranteed that all elements in the array will be properly
291 /// On arithmetic overflow, returns `LayoutErr`.
292 #[unstable(feature = "alloc_layout_extra", issue = "55724")]
294 pub fn repeat_packed(&self, n: usize) -> Result<Self, LayoutErr> {
295 let size = self.size().checked_mul(n).ok_or(LayoutErr { private: () })?;
296 Layout::from_size_align(size, self.align())
299 /// Creates a layout describing the record for `self` followed by
300 /// `next` with no additional padding between the two. Since no
301 /// padding is inserted, the alignment of `next` is irrelevant,
302 /// and is not incorporated *at all* into the resulting layout.
304 /// On arithmetic overflow, returns `LayoutErr`.
305 #[unstable(feature = "alloc_layout_extra", issue = "55724")]
307 pub fn extend_packed(&self, next: Self) -> Result<Self, LayoutErr> {
308 let new_size = self.size().checked_add(next.size())
309 .ok_or(LayoutErr { private: () })?;
310 let layout = Layout::from_size_align(new_size, self.align())?;
314 /// Creates a layout describing the record for a `[T; n]`.
316 /// On arithmetic overflow, returns `LayoutErr`.
317 #[unstable(feature = "alloc_layout_extra", issue = "55724")]
319 pub fn array<T>(n: usize) -> Result<Self, LayoutErr> {
323 debug_assert!(offs == mem::size_of::<T>());
329 /// The parameters given to `Layout::from_size_align`
330 /// or some other `Layout` constructor
331 /// do not satisfy its documented constraints.
332 #[stable(feature = "alloc_layout", since = "1.28.0")]
333 #[derive(Clone, PartialEq, Eq, Debug)]
334 pub struct LayoutErr {
338 // (we need this for downstream impl of trait Error)
339 #[stable(feature = "alloc_layout", since = "1.28.0")]
340 impl fmt::Display for LayoutErr {
341 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
342 f.write_str("invalid parameters to Layout::from_size_align")
346 /// The `AllocErr` error indicates an allocation failure
347 /// that may be due to resource exhaustion or to
348 /// something wrong when combining the given input arguments with this
350 #[unstable(feature = "allocator_api", issue = "32838")]
351 #[derive(Clone, PartialEq, Eq, Debug)]
354 // (we need this for downstream impl of trait Error)
355 #[unstable(feature = "allocator_api", issue = "32838")]
356 impl fmt::Display for AllocErr {
357 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
358 f.write_str("memory allocation failed")
362 /// The `CannotReallocInPlace` error is used when [`grow_in_place`] or
363 /// [`shrink_in_place`] were unable to reuse the given memory block for
364 /// a requested layout.
366 /// [`grow_in_place`]: ./trait.Alloc.html#method.grow_in_place
367 /// [`shrink_in_place`]: ./trait.Alloc.html#method.shrink_in_place
368 #[unstable(feature = "allocator_api", issue = "32838")]
369 #[derive(Clone, PartialEq, Eq, Debug)]
370 pub struct CannotReallocInPlace;
372 #[unstable(feature = "allocator_api", issue = "32838")]
373 impl CannotReallocInPlace {
374 pub fn description(&self) -> &str {
375 "cannot reallocate allocator's memory in place"
379 // (we need this for downstream impl of trait Error)
380 #[unstable(feature = "allocator_api", issue = "32838")]
381 impl fmt::Display for CannotReallocInPlace {
382 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
383 write!(f, "{}", self.description())
387 /// A memory allocator that can be registered as the standard library’s default
388 /// though the `#[global_allocator]` attributes.
390 /// Some of the methods require that a memory block be *currently
391 /// allocated* via an allocator. This means that:
393 /// * the starting address for that memory block was previously
394 /// returned by a previous call to an allocation method
395 /// such as `alloc`, and
397 /// * the memory block has not been subsequently deallocated, where
398 /// blocks are deallocated either by being passed to a deallocation
399 /// method such as `dealloc` or by being
400 /// passed to a reallocation method that returns a non-null pointer.
406 /// use std::alloc::{GlobalAlloc, Layout, alloc};
407 /// use std::ptr::null_mut;
409 /// struct MyAllocator;
411 /// unsafe impl GlobalAlloc for MyAllocator {
412 /// unsafe fn alloc(&self, _layout: Layout) -> *mut u8 { null_mut() }
413 /// unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) {}
416 /// #[global_allocator]
417 /// static A: MyAllocator = MyAllocator;
421 /// assert!(alloc(Layout::new::<u32>()).is_null())
428 /// The `GlobalAlloc` trait is an `unsafe` trait for a number of reasons, and
429 /// implementors must ensure that they adhere to these contracts:
431 /// * It's undefined behavior if global allocators unwind. This restriction may
432 /// be lifted in the future, but currently a panic from any of these
433 /// functions may lead to memory unsafety.
435 /// * `Layout` queries and calculations in general must be correct. Callers of
436 /// this trait are allowed to rely on the contracts defined on each method,
437 /// and implementors must ensure such contracts remain true.
438 #[stable(feature = "global_alloc", since = "1.28.0")]
439 pub unsafe trait GlobalAlloc {
440 /// Allocate memory as described by the given `layout`.
442 /// Returns a pointer to newly-allocated memory,
443 /// or null to indicate allocation failure.
447 /// This function is unsafe because undefined behavior can result
448 /// if the caller does not ensure that `layout` has non-zero size.
450 /// (Extension subtraits might provide more specific bounds on
451 /// behavior, e.g., guarantee a sentinel address or a null pointer
452 /// in response to a zero-size allocation request.)
454 /// The allocated block of memory may or may not be initialized.
458 /// Returning a null pointer indicates that either memory is exhausted
459 /// or `layout` does not meet allocator's size or alignment constraints.
461 /// Implementations are encouraged to return null on memory
462 /// exhaustion rather than aborting, but this is not
463 /// a strict requirement. (Specifically: it is *legal* to
464 /// implement this trait atop an underlying native allocation
465 /// library that aborts on memory exhaustion.)
467 /// Clients wishing to abort computation in response to an
468 /// allocation error are encouraged to call the [`handle_alloc_error`] function,
469 /// rather than directly invoking `panic!` or similar.
471 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
472 #[stable(feature = "global_alloc", since = "1.28.0")]
473 unsafe fn alloc(&self, layout: Layout) -> *mut u8;
475 /// Deallocate the block of memory at the given `ptr` pointer with the given `layout`.
479 /// This function is unsafe because undefined behavior can result
480 /// if the caller does not ensure all of the following:
482 /// * `ptr` must denote a block of memory currently allocated via
485 /// * `layout` must be the same layout that was used
486 /// to allocate that block of memory,
487 #[stable(feature = "global_alloc", since = "1.28.0")]
488 unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout);
490 /// Behaves like `alloc`, but also ensures that the contents
491 /// are set to zero before being returned.
495 /// This function is unsafe for the same reasons that `alloc` is.
496 /// However the allocated block of memory is guaranteed to be initialized.
500 /// Returning a null pointer indicates that either memory is exhausted
501 /// or `layout` does not meet allocator's size or alignment constraints,
502 /// just as in `alloc`.
504 /// Clients wishing to abort computation in response to an
505 /// allocation error are encouraged to call the [`handle_alloc_error`] function,
506 /// rather than directly invoking `panic!` or similar.
508 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
509 #[stable(feature = "global_alloc", since = "1.28.0")]
510 unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
511 let size = layout.size();
512 let ptr = self.alloc(layout);
514 ptr::write_bytes(ptr, 0, size);
519 /// Shrink or grow a block of memory to the given `new_size`.
520 /// The block is described by the given `ptr` pointer and `layout`.
522 /// If this returns a non-null pointer, then ownership of the memory block
523 /// referenced by `ptr` has been transferred to this allocator.
524 /// The memory may or may not have been deallocated,
525 /// and should be considered unusable (unless of course it was
526 /// transferred back to the caller again via the return value of
529 /// If this method returns null, then ownership of the memory
530 /// block has not been transferred to this allocator, and the
531 /// contents of the memory block are unaltered.
535 /// This function is unsafe because undefined behavior can result
536 /// if the caller does not ensure all of the following:
538 /// * `ptr` must be currently allocated via this allocator,
540 /// * `layout` must be the same layout that was used
541 /// to allocate that block of memory,
543 /// * `new_size` must be greater than zero.
545 /// * `new_size`, when rounded up to the nearest multiple of `layout.align()`,
546 /// must not overflow (i.e., the rounded value must be less than `usize::MAX`).
548 /// (Extension subtraits might provide more specific bounds on
549 /// behavior, e.g., guarantee a sentinel address or a null pointer
550 /// in response to a zero-size allocation request.)
554 /// Returns null if the new layout does not meet the size
555 /// and alignment constraints of the allocator, or if reallocation
558 /// Implementations are encouraged to return null on memory
559 /// exhaustion rather than panicking or aborting, but this is not
560 /// a strict requirement. (Specifically: it is *legal* to
561 /// implement this trait atop an underlying native allocation
562 /// library that aborts on memory exhaustion.)
564 /// Clients wishing to abort computation in response to a
565 /// reallocation error are encouraged to call the [`handle_alloc_error`] function,
566 /// rather than directly invoking `panic!` or similar.
568 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
569 #[stable(feature = "global_alloc", since = "1.28.0")]
570 unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
571 let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
572 let new_ptr = self.alloc(new_layout);
573 if !new_ptr.is_null() {
574 ptr::copy_nonoverlapping(
577 cmp::min(layout.size(), new_size),
579 self.dealloc(ptr, layout);
585 /// An implementation of `Alloc` can allocate, reallocate, and
586 /// deallocate arbitrary blocks of data described via `Layout`.
588 /// Some of the methods require that a memory block be *currently
589 /// allocated* via an allocator. This means that:
591 /// * the starting address for that memory block was previously
592 /// returned by a previous call to an allocation method (`alloc`,
593 /// `alloc_zeroed`, `alloc_excess`, `alloc_one`, `alloc_array`) or
594 /// reallocation method (`realloc`, `realloc_excess`, or
595 /// `realloc_array`), and
597 /// * the memory block has not been subsequently deallocated, where
598 /// blocks are deallocated either by being passed to a deallocation
599 /// method (`dealloc`, `dealloc_one`, `dealloc_array`) or by being
600 /// passed to a reallocation method (see above) that returns `Ok`.
602 /// A note regarding zero-sized types and zero-sized layouts: many
603 /// methods in the `Alloc` trait state that allocation requests
604 /// must be non-zero size, or else undefined behavior can result.
606 /// * However, some higher-level allocation methods (`alloc_one`,
607 /// `alloc_array`) are well-defined on zero-sized types and can
608 /// optionally support them: it is left up to the implementor
609 /// whether to return `Err`, or to return `Ok` with some pointer.
611 /// * If an `Alloc` implementation chooses to return `Ok` in this
612 /// case (i.e., the pointer denotes a zero-sized inaccessible block)
613 /// then that returned pointer must be considered "currently
614 /// allocated". On such an allocator, *all* methods that take
615 /// currently-allocated pointers as inputs must accept these
616 /// zero-sized pointers, *without* causing undefined behavior.
618 /// * In other words, if a zero-sized pointer can flow out of an
619 /// allocator, then that allocator must likewise accept that pointer
620 /// flowing back into its deallocation and reallocation methods.
622 /// Some of the methods require that a layout *fit* a memory block.
623 /// What it means for a layout to "fit" a memory block means (or
624 /// equivalently, for a memory block to "fit" a layout) is that the
625 /// following two conditions must hold:
627 /// 1. The block's starting address must be aligned to `layout.align()`.
629 /// 2. The block's size must fall in the range `[use_min, use_max]`, where:
631 /// * `use_min` is `self.usable_size(layout).0`, and
633 /// * `use_max` is the capacity that was (or would have been)
634 /// returned when (if) the block was allocated via a call to
635 /// `alloc_excess` or `realloc_excess`.
639 /// * the size of the layout most recently used to allocate the block
640 /// is guaranteed to be in the range `[use_min, use_max]`, and
642 /// * a lower-bound on `use_max` can be safely approximated by a call to
645 /// * if a layout `k` fits a memory block (denoted by `ptr`)
646 /// currently allocated via an allocator `a`, then it is legal to
647 /// use that layout to deallocate it, i.e., `a.dealloc(ptr, k);`.
651 /// The `Alloc` trait is an `unsafe` trait for a number of reasons, and
652 /// implementors must ensure that they adhere to these contracts:
654 /// * Pointers returned from allocation functions must point to valid memory and
655 /// retain their validity until at least the instance of `Alloc` is dropped
658 /// * `Layout` queries and calculations in general must be correct. Callers of
659 /// this trait are allowed to rely on the contracts defined on each method,
660 /// and implementors must ensure such contracts remain true.
662 /// Note that this list may get tweaked over time as clarifications are made in
664 #[unstable(feature = "allocator_api", issue = "32838")]
665 pub unsafe trait Alloc {
667 // (Note: some existing allocators have unspecified but well-defined
668 // behavior in response to a zero size allocation request ;
669 // e.g., in C, `malloc` of 0 will either return a null pointer or a
670 // unique pointer, but will not have arbitrary undefined
672 // However in jemalloc for example,
673 // `mallocx(0)` is documented as undefined behavior.)
675 /// Returns a pointer meeting the size and alignment guarantees of
678 /// If this method returns an `Ok(addr)`, then the `addr` returned
679 /// will be non-null address pointing to a block of storage
680 /// suitable for holding an instance of `layout`.
682 /// The returned block of storage may or may not have its contents
683 /// initialized. (Extension subtraits might restrict this
684 /// behavior, e.g., to ensure initialization to particular sets of
689 /// This function is unsafe because undefined behavior can result
690 /// if the caller does not ensure that `layout` has non-zero size.
692 /// (Extension subtraits might provide more specific bounds on
693 /// behavior, e.g., guarantee a sentinel address or a null pointer
694 /// in response to a zero-size allocation request.)
698 /// Returning `Err` indicates that either memory is exhausted or
699 /// `layout` does not meet allocator's size or alignment
702 /// Implementations are encouraged to return `Err` on memory
703 /// exhaustion rather than panicking or aborting, but this is not
704 /// a strict requirement. (Specifically: it is *legal* to
705 /// implement this trait atop an underlying native allocation
706 /// library that aborts on memory exhaustion.)
708 /// Clients wishing to abort computation in response to an
709 /// allocation error are encouraged to call the [`handle_alloc_error`] function,
710 /// rather than directly invoking `panic!` or similar.
712 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
713 unsafe fn alloc(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr>;
715 /// Deallocate the memory referenced by `ptr`.
719 /// This function is unsafe because undefined behavior can result
720 /// if the caller does not ensure all of the following:
722 /// * `ptr` must denote a block of memory currently allocated via
725 /// * `layout` must *fit* that block of memory,
727 /// * In addition to fitting the block of memory `layout`, the
728 /// alignment of the `layout` must match the alignment used
729 /// to allocate that block of memory.
730 unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout);
732 // == ALLOCATOR-SPECIFIC QUANTITIES AND LIMITS ==
735 /// Returns bounds on the guaranteed usable size of a successful
736 /// allocation created with the specified `layout`.
738 /// In particular, if one has a memory block allocated via a given
739 /// allocator `a` and layout `k` where `a.usable_size(k)` returns
740 /// `(l, u)`, then one can pass that block to `a.dealloc()` with a
741 /// layout in the size range [l, u].
743 /// (All implementors of `usable_size` must ensure that
744 /// `l <= k.size() <= u`)
746 /// Both the lower- and upper-bounds (`l` and `u` respectively)
747 /// are provided, because an allocator based on size classes could
748 /// misbehave if one attempts to deallocate a block without
749 /// providing a correct value for its size (i.e., one within the
752 /// Clients who wish to make use of excess capacity are encouraged
753 /// to use the `alloc_excess` and `realloc_excess` instead, as
754 /// this method is constrained to report conservative values that
755 /// serve as valid bounds for *all possible* allocation method
758 /// However, for clients that do not wish to track the capacity
759 /// returned by `alloc_excess` locally, this method is likely to
760 /// produce useful results.
762 fn usable_size(&self, layout: &Layout) -> (usize, usize) {
763 (layout.size(), layout.size())
766 // == METHODS FOR MEMORY REUSE ==
767 // realloc. alloc_excess, realloc_excess
769 /// Returns a pointer suitable for holding data described by
770 /// a new layout with `layout`’s alignment and a size given
771 /// by `new_size`. To
772 /// accomplish this, this may extend or shrink the allocation
773 /// referenced by `ptr` to fit the new layout.
775 /// If this returns `Ok`, then ownership of the memory block
776 /// referenced by `ptr` has been transferred to this
777 /// allocator. The memory may or may not have been freed, and
778 /// should be considered unusable (unless of course it was
779 /// transferred back to the caller again via the return value of
782 /// If this method returns `Err`, then ownership of the memory
783 /// block has not been transferred to this allocator, and the
784 /// contents of the memory block are unaltered.
788 /// This function is unsafe because undefined behavior can result
789 /// if the caller does not ensure all of the following:
791 /// * `ptr` must be currently allocated via this allocator,
793 /// * `layout` must *fit* the `ptr` (see above). (The `new_size`
794 /// argument need not fit it.)
796 /// * `new_size` must be greater than zero.
798 /// * `new_size`, when rounded up to the nearest multiple of `layout.align()`,
799 /// must not overflow (i.e., the rounded value must be less than `usize::MAX`).
801 /// (Extension subtraits might provide more specific bounds on
802 /// behavior, e.g., guarantee a sentinel address or a null pointer
803 /// in response to a zero-size allocation request.)
807 /// Returns `Err` only if the new layout
808 /// does not meet the allocator's size
809 /// and alignment constraints of the allocator, or if reallocation
812 /// Implementations are encouraged to return `Err` on memory
813 /// exhaustion rather than panicking or aborting, but this is not
814 /// a strict requirement. (Specifically: it is *legal* to
815 /// implement this trait atop an underlying native allocation
816 /// library that aborts on memory exhaustion.)
818 /// Clients wishing to abort computation in response to a
819 /// reallocation error are encouraged to call the [`handle_alloc_error`] function,
820 /// rather than directly invoking `panic!` or similar.
822 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
823 unsafe fn realloc(&mut self,
826 new_size: usize) -> Result<NonNull<u8>, AllocErr> {
827 let old_size = layout.size();
829 if new_size >= old_size {
830 if let Ok(()) = self.grow_in_place(ptr, layout, new_size) {
833 } else if new_size < old_size {
834 if let Ok(()) = self.shrink_in_place(ptr, layout, new_size) {
839 // otherwise, fall back on alloc + copy + dealloc.
840 let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
841 let result = self.alloc(new_layout);
842 if let Ok(new_ptr) = result {
843 ptr::copy_nonoverlapping(ptr.as_ptr(),
845 cmp::min(old_size, new_size));
846 self.dealloc(ptr, layout);
851 /// Behaves like `alloc`, but also ensures that the contents
852 /// are set to zero before being returned.
856 /// This function is unsafe for the same reasons that `alloc` is.
860 /// Returning `Err` indicates that either memory is exhausted or
861 /// `layout` does not meet allocator's size or alignment
862 /// constraints, just as in `alloc`.
864 /// Clients wishing to abort computation in response to an
865 /// allocation error are encouraged to call the [`handle_alloc_error`] function,
866 /// rather than directly invoking `panic!` or similar.
868 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
869 unsafe fn alloc_zeroed(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
870 let size = layout.size();
871 let p = self.alloc(layout);
873 ptr::write_bytes(p.as_ptr(), 0, size);
878 /// Behaves like `alloc`, but also returns the whole size of
879 /// the returned block. For some `layout` inputs, like arrays, this
880 /// may include extra storage usable for additional data.
884 /// This function is unsafe for the same reasons that `alloc` is.
888 /// Returning `Err` indicates that either memory is exhausted or
889 /// `layout` does not meet allocator's size or alignment
890 /// constraints, just as in `alloc`.
892 /// Clients wishing to abort computation in response to an
893 /// allocation error are encouraged to call the [`handle_alloc_error`] function,
894 /// rather than directly invoking `panic!` or similar.
896 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
897 unsafe fn alloc_excess(&mut self, layout: Layout) -> Result<Excess, AllocErr> {
898 let usable_size = self.usable_size(&layout);
899 self.alloc(layout).map(|p| Excess(p, usable_size.1))
902 /// Behaves like `realloc`, but also returns the whole size of
903 /// the returned block. For some `layout` inputs, like arrays, this
904 /// may include extra storage usable for additional data.
908 /// This function is unsafe for the same reasons that `realloc` is.
912 /// Returning `Err` indicates that either memory is exhausted or
913 /// `layout` does not meet allocator's size or alignment
914 /// constraints, just as in `realloc`.
916 /// Clients wishing to abort computation in response to a
917 /// reallocation error are encouraged to call the [`handle_alloc_error`] function,
918 /// rather than directly invoking `panic!` or similar.
920 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
921 unsafe fn realloc_excess(&mut self,
924 new_size: usize) -> Result<Excess, AllocErr> {
925 let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
926 let usable_size = self.usable_size(&new_layout);
927 self.realloc(ptr, layout, new_size)
928 .map(|p| Excess(p, usable_size.1))
931 /// Attempts to extend the allocation referenced by `ptr` to fit `new_size`.
933 /// If this returns `Ok`, then the allocator has asserted that the
934 /// memory block referenced by `ptr` now fits `new_size`, and thus can
935 /// be used to carry data of a layout of that size and same alignment as
936 /// `layout`. (The allocator is allowed to
937 /// expend effort to accomplish this, such as extending the memory block to
938 /// include successor blocks, or virtual memory tricks.)
940 /// Regardless of what this method returns, ownership of the
941 /// memory block referenced by `ptr` has not been transferred, and
942 /// the contents of the memory block are unaltered.
946 /// This function is unsafe because undefined behavior can result
947 /// if the caller does not ensure all of the following:
949 /// * `ptr` must be currently allocated via this allocator,
951 /// * `layout` must *fit* the `ptr` (see above); note the
952 /// `new_size` argument need not fit it,
954 /// * `new_size` must not be less than `layout.size()`,
958 /// Returns `Err(CannotReallocInPlace)` when the allocator is
959 /// unable to assert that the memory block referenced by `ptr`
960 /// could fit `layout`.
962 /// Note that one cannot pass `CannotReallocInPlace` to the `handle_alloc_error`
963 /// function; clients are expected either to be able to recover from
964 /// `grow_in_place` failures without aborting, or to fall back on
965 /// another reallocation method before resorting to an abort.
966 unsafe fn grow_in_place(&mut self,
969 new_size: usize) -> Result<(), CannotReallocInPlace> {
970 let _ = ptr; // this default implementation doesn't care about the actual address.
971 debug_assert!(new_size >= layout.size());
972 let (_l, u) = self.usable_size(&layout);
973 // _l <= layout.size() [guaranteed by usable_size()]
974 // layout.size() <= new_layout.size() [required by this method]
978 Err(CannotReallocInPlace)
982 /// Attempts to shrink the allocation referenced by `ptr` to fit `new_size`.
984 /// If this returns `Ok`, then the allocator has asserted that the
985 /// memory block referenced by `ptr` now fits `new_size`, and
986 /// thus can only be used to carry data of that smaller
987 /// layout. (The allocator is allowed to take advantage of this,
988 /// carving off portions of the block for reuse elsewhere.) The
989 /// truncated contents of the block within the smaller layout are
990 /// unaltered, and ownership of block has not been transferred.
992 /// If this returns `Err`, then the memory block is considered to
993 /// still represent the original (larger) `layout`. None of the
994 /// block has been carved off for reuse elsewhere, ownership of
995 /// the memory block has not been transferred, and the contents of
996 /// the memory block are unaltered.
1000 /// This function is unsafe because undefined behavior can result
1001 /// if the caller does not ensure all of the following:
1003 /// * `ptr` must be currently allocated via this allocator,
1005 /// * `layout` must *fit* the `ptr` (see above); note the
1006 /// `new_size` argument need not fit it,
1008 /// * `new_size` must not be greater than `layout.size()`
1009 /// (and must be greater than zero),
1013 /// Returns `Err(CannotReallocInPlace)` when the allocator is
1014 /// unable to assert that the memory block referenced by `ptr`
1015 /// could fit `layout`.
1017 /// Note that one cannot pass `CannotReallocInPlace` to the `handle_alloc_error`
1018 /// function; clients are expected either to be able to recover from
1019 /// `shrink_in_place` failures without aborting, or to fall back
1020 /// on another reallocation method before resorting to an abort.
1021 unsafe fn shrink_in_place(&mut self,
1024 new_size: usize) -> Result<(), CannotReallocInPlace> {
1025 let _ = ptr; // this default implementation doesn't care about the actual address.
1026 debug_assert!(new_size <= layout.size());
1027 let (l, _u) = self.usable_size(&layout);
1028 // layout.size() <= _u [guaranteed by usable_size()]
1029 // new_layout.size() <= layout.size() [required by this method]
1033 Err(CannotReallocInPlace)
1038 // == COMMON USAGE PATTERNS ==
1039 // alloc_one, dealloc_one, alloc_array, realloc_array. dealloc_array
1041 /// Allocates a block suitable for holding an instance of `T`.
1043 /// Captures a common usage pattern for allocators.
1045 /// The returned block is suitable for passing to the
1046 /// `alloc`/`realloc` methods of this allocator.
1048 /// Note to implementors: If this returns `Ok(ptr)`, then `ptr`
1049 /// must be considered "currently allocated" and must be
1050 /// acceptable input to methods such as `realloc` or `dealloc`,
1051 /// *even if* `T` is a zero-sized type. In other words, if your
1052 /// `Alloc` implementation overrides this method in a manner
1053 /// that can return a zero-sized `ptr`, then all reallocation and
1054 /// deallocation methods need to be similarly overridden to accept
1055 /// such values as input.
1059 /// Returning `Err` indicates that either memory is exhausted or
1060 /// `T` does not meet allocator's size or alignment constraints.
1062 /// For zero-sized `T`, may return either of `Ok` or `Err`, but
1063 /// will *not* yield undefined behavior.
1065 /// Clients wishing to abort computation in response to an
1066 /// allocation error are encouraged to call the [`handle_alloc_error`] function,
1067 /// rather than directly invoking `panic!` or similar.
1069 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
1070 fn alloc_one<T>(&mut self) -> Result<NonNull<T>, AllocErr>
1073 let k = Layout::new::<T>();
1075 unsafe { self.alloc(k).map(|p| p.cast()) }
1081 /// Deallocates a block suitable for holding an instance of `T`.
1083 /// The given block must have been produced by this allocator,
1084 /// and must be suitable for storing a `T` (in terms of alignment
1085 /// as well as minimum and maximum size); otherwise yields
1086 /// undefined behavior.
1088 /// Captures a common usage pattern for allocators.
1092 /// This function is unsafe because undefined behavior can result
1093 /// if the caller does not ensure both:
1095 /// * `ptr` must denote a block of memory currently allocated via this allocator
1097 /// * the layout of `T` must *fit* that block of memory.
1098 unsafe fn dealloc_one<T>(&mut self, ptr: NonNull<T>)
1101 let k = Layout::new::<T>();
1103 self.dealloc(ptr.cast(), k);
1107 /// Allocates a block suitable for holding `n` instances of `T`.
1109 /// Captures a common usage pattern for allocators.
1111 /// The returned block is suitable for passing to the
1112 /// `alloc`/`realloc` methods of this allocator.
1114 /// Note to implementors: If this returns `Ok(ptr)`, then `ptr`
1115 /// must be considered "currently allocated" and must be
1116 /// acceptable input to methods such as `realloc` or `dealloc`,
1117 /// *even if* `T` is a zero-sized type. In other words, if your
1118 /// `Alloc` implementation overrides this method in a manner
1119 /// that can return a zero-sized `ptr`, then all reallocation and
1120 /// deallocation methods need to be similarly overridden to accept
1121 /// such values as input.
1125 /// Returning `Err` indicates that either memory is exhausted or
1126 /// `[T; n]` does not meet allocator's size or alignment
1129 /// For zero-sized `T` or `n == 0`, may return either of `Ok` or
1130 /// `Err`, but will *not* yield undefined behavior.
1132 /// Always returns `Err` on arithmetic overflow.
1134 /// Clients wishing to abort computation in response to an
1135 /// allocation error are encouraged to call the [`handle_alloc_error`] function,
1136 /// rather than directly invoking `panic!` or similar.
1138 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
1139 fn alloc_array<T>(&mut self, n: usize) -> Result<NonNull<T>, AllocErr>
1142 match Layout::array::<T>(n) {
1143 Ok(ref layout) if layout.size() > 0 => {
1145 self.alloc(layout.clone()).map(|p| p.cast())
1152 /// Reallocates a block previously suitable for holding `n_old`
1153 /// instances of `T`, returning a block suitable for holding
1154 /// `n_new` instances of `T`.
1156 /// Captures a common usage pattern for allocators.
1158 /// The returned block is suitable for passing to the
1159 /// `alloc`/`realloc` methods of this allocator.
1163 /// This function is unsafe because undefined behavior can result
1164 /// if the caller does not ensure all of the following:
1166 /// * `ptr` must be currently allocated via this allocator,
1168 /// * the layout of `[T; n_old]` must *fit* that block of memory.
1172 /// Returning `Err` indicates that either memory is exhausted or
1173 /// `[T; n_new]` does not meet allocator's size or alignment
1176 /// For zero-sized `T` or `n_new == 0`, may return either of `Ok` or
1177 /// `Err`, but will *not* yield undefined behavior.
1179 /// Always returns `Err` on arithmetic overflow.
1181 /// Clients wishing to abort computation in response to a
1182 /// reallocation error are encouraged to call the [`handle_alloc_error`] function,
1183 /// rather than directly invoking `panic!` or similar.
1185 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
1186 unsafe fn realloc_array<T>(&mut self,
1189 n_new: usize) -> Result<NonNull<T>, AllocErr>
1192 match (Layout::array::<T>(n_old), Layout::array::<T>(n_new)) {
1193 (Ok(ref k_old), Ok(ref k_new)) if k_old.size() > 0 && k_new.size() > 0 => {
1194 debug_assert!(k_old.align() == k_new.align());
1195 self.realloc(ptr.cast(), k_old.clone(), k_new.size()).map(NonNull::cast)
1203 /// Deallocates a block suitable for holding `n` instances of `T`.
1205 /// Captures a common usage pattern for allocators.
1209 /// This function is unsafe because undefined behavior can result
1210 /// if the caller does not ensure both:
1212 /// * `ptr` must denote a block of memory currently allocated via this allocator
1214 /// * the layout of `[T; n]` must *fit* that block of memory.
1218 /// Returning `Err` indicates that either `[T; n]` or the given
1219 /// memory block does not meet allocator's size or alignment
1222 /// Always returns `Err` on arithmetic overflow.
1223 unsafe fn dealloc_array<T>(&mut self, ptr: NonNull<T>, n: usize) -> Result<(), AllocErr>
1226 match Layout::array::<T>(n) {
1227 Ok(ref k) if k.size() > 0 => {
1228 Ok(self.dealloc(ptr.cast(), k.clone()))