1 //! Memory allocation APIs
3 #![stable(feature = "alloc_module", since = "1.28.0")]
9 use ptr::{self, NonNull};
10 use 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 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.
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 /// though the `#[global_allocator]` attributes.
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 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 allocated 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 allocated 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(
574 cmp::min(layout.size(), new_size),
576 self.dealloc(ptr, layout);
582 /// An implementation of `Alloc` can allocate, reallocate, and
583 /// deallocate arbitrary blocks of data described via `Layout`.
585 /// Some of the methods require that a memory block be *currently
586 /// allocated* via an allocator. This means that:
588 /// * the starting address for that memory block was previously
589 /// returned by a previous call to an allocation method (`alloc`,
590 /// `alloc_zeroed`, `alloc_excess`, `alloc_one`, `alloc_array`) or
591 /// reallocation method (`realloc`, `realloc_excess`, or
592 /// `realloc_array`), and
594 /// * the memory block has not been subsequently deallocated, where
595 /// blocks are deallocated either by being passed to a deallocation
596 /// method (`dealloc`, `dealloc_one`, `dealloc_array`) or by being
597 /// passed to a reallocation method (see above) that returns `Ok`.
599 /// A note regarding zero-sized types and zero-sized layouts: many
600 /// methods in the `Alloc` trait state that allocation requests
601 /// must be non-zero size, or else undefined behavior can result.
603 /// * However, some higher-level allocation methods (`alloc_one`,
604 /// `alloc_array`) are well-defined on zero-sized types and can
605 /// optionally support them: it is left up to the implementor
606 /// whether to return `Err`, or to return `Ok` with some pointer.
608 /// * If an `Alloc` implementation chooses to return `Ok` in this
609 /// case (i.e., the pointer denotes a zero-sized inaccessible block)
610 /// then that returned pointer must be considered "currently
611 /// allocated". On such an allocator, *all* methods that take
612 /// currently-allocated pointers as inputs must accept these
613 /// zero-sized pointers, *without* causing undefined behavior.
615 /// * In other words, if a zero-sized pointer can flow out of an
616 /// allocator, then that allocator must likewise accept that pointer
617 /// flowing back into its deallocation and reallocation methods.
619 /// Some of the methods require that a layout *fit* a memory block.
620 /// What it means for a layout to "fit" a memory block means (or
621 /// equivalently, for a memory block to "fit" a layout) is that the
622 /// following two conditions must hold:
624 /// 1. The block's starting address must be aligned to `layout.align()`.
626 /// 2. The block's size must fall in the range `[use_min, use_max]`, where:
628 /// * `use_min` is `self.usable_size(layout).0`, and
630 /// * `use_max` is the capacity that was (or would have been)
631 /// returned when (if) the block was allocated via a call to
632 /// `alloc_excess` or `realloc_excess`.
636 /// * the size of the layout most recently used to allocate the block
637 /// is guaranteed to be in the range `[use_min, use_max]`, and
639 /// * a lower-bound on `use_max` can be safely approximated by a call to
642 /// * if a layout `k` fits a memory block (denoted by `ptr`)
643 /// currently allocated via an allocator `a`, then it is legal to
644 /// use that layout to deallocate it, i.e., `a.dealloc(ptr, k);`.
648 /// The `Alloc` trait is an `unsafe` trait for a number of reasons, and
649 /// implementors must ensure that they adhere to these contracts:
651 /// * Pointers returned from allocation functions must point to valid memory and
652 /// retain their validity until at least the instance of `Alloc` is dropped
655 /// * `Layout` queries and calculations in general must be correct. Callers of
656 /// this trait are allowed to rely on the contracts defined on each method,
657 /// and implementors must ensure such contracts remain true.
659 /// Note that this list may get tweaked over time as clarifications are made in
661 #[unstable(feature = "allocator_api", issue = "32838")]
662 pub unsafe trait Alloc {
664 // (Note: some existing allocators have unspecified but well-defined
665 // behavior in response to a zero size allocation request ;
666 // e.g., in C, `malloc` of 0 will either return a null pointer or a
667 // unique pointer, but will not have arbitrary undefined
669 // However in jemalloc for example,
670 // `mallocx(0)` is documented as undefined behavior.)
672 /// Returns a pointer meeting the size and alignment guarantees of
675 /// If this method returns an `Ok(addr)`, then the `addr` returned
676 /// will be non-null address pointing to a block of storage
677 /// suitable for holding an instance of `layout`.
679 /// The returned block of storage may or may not have its contents
680 /// initialized. (Extension subtraits might restrict this
681 /// behavior, e.g., to ensure initialization to particular sets of
686 /// This function is unsafe because undefined behavior can result
687 /// if the caller does not ensure that `layout` has non-zero size.
689 /// (Extension subtraits might provide more specific bounds on
690 /// behavior, e.g., guarantee a sentinel address or a null pointer
691 /// in response to a zero-size allocation request.)
695 /// Returning `Err` indicates that either memory is exhausted or
696 /// `layout` does not meet allocator's size or alignment
699 /// Implementations are encouraged to return `Err` on memory
700 /// exhaustion rather than panicking or aborting, but this is not
701 /// a strict requirement. (Specifically: it is *legal* to
702 /// implement this trait atop an underlying native allocation
703 /// library that aborts on memory exhaustion.)
705 /// Clients wishing to abort computation in response to an
706 /// allocation error are encouraged to call the [`handle_alloc_error`] function,
707 /// rather than directly invoking `panic!` or similar.
709 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
710 unsafe fn alloc(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr>;
712 /// Deallocate the memory referenced by `ptr`.
716 /// This function is unsafe because undefined behavior can result
717 /// if the caller does not ensure all of the following:
719 /// * `ptr` must denote a block of memory currently allocated via
722 /// * `layout` must *fit* that block of memory,
724 /// * In addition to fitting the block of memory `layout`, the
725 /// alignment of the `layout` must match the alignment used
726 /// to allocate that block of memory.
727 unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout);
729 // == ALLOCATOR-SPECIFIC QUANTITIES AND LIMITS ==
732 /// Returns bounds on the guaranteed usable size of a successful
733 /// allocation created with the specified `layout`.
735 /// In particular, if one has a memory block allocated via a given
736 /// allocator `a` and layout `k` where `a.usable_size(k)` returns
737 /// `(l, u)`, then one can pass that block to `a.dealloc()` with a
738 /// layout in the size range [l, u].
740 /// (All implementors of `usable_size` must ensure that
741 /// `l <= k.size() <= u`)
743 /// Both the lower- and upper-bounds (`l` and `u` respectively)
744 /// are provided, because an allocator based on size classes could
745 /// misbehave if one attempts to deallocate a block without
746 /// providing a correct value for its size (i.e., one within the
749 /// Clients who wish to make use of excess capacity are encouraged
750 /// to use the `alloc_excess` and `realloc_excess` instead, as
751 /// this method is constrained to report conservative values that
752 /// serve as valid bounds for *all possible* allocation method
755 /// However, for clients that do not wish to track the capacity
756 /// returned by `alloc_excess` locally, this method is likely to
757 /// produce useful results.
759 fn usable_size(&self, layout: &Layout) -> (usize, usize) {
760 (layout.size(), layout.size())
763 // == METHODS FOR MEMORY REUSE ==
764 // realloc. alloc_excess, realloc_excess
766 /// Returns a pointer suitable for holding data described by
767 /// a new layout with `layout`’s alignment and a size given
768 /// by `new_size`. To
769 /// accomplish this, this may extend or shrink the allocation
770 /// referenced by `ptr` to fit the new layout.
772 /// If this returns `Ok`, then ownership of the memory block
773 /// referenced by `ptr` has been transferred to this
774 /// allocator. The memory may or may not have been freed, and
775 /// should be considered unusable (unless of course it was
776 /// transferred back to the caller again via the return value of
779 /// If this method returns `Err`, then ownership of the memory
780 /// block has not been transferred to this allocator, and the
781 /// contents of the memory block are unaltered.
785 /// This function is unsafe because undefined behavior can result
786 /// if the caller does not ensure all of the following:
788 /// * `ptr` must be currently allocated via this allocator,
790 /// * `layout` must *fit* the `ptr` (see above). (The `new_size`
791 /// argument need not fit it.)
793 /// * `new_size` must be greater than zero.
795 /// * `new_size`, when rounded up to the nearest multiple of `layout.align()`,
796 /// must not overflow (i.e., the rounded value must be less than `usize::MAX`).
798 /// (Extension subtraits might provide more specific bounds on
799 /// behavior, e.g., guarantee a sentinel address or a null pointer
800 /// in response to a zero-size allocation request.)
804 /// Returns `Err` only if the new layout
805 /// does not meet the allocator's size
806 /// and alignment constraints of the allocator, or if reallocation
809 /// Implementations are encouraged to return `Err` on memory
810 /// exhaustion rather than panicking or aborting, but this is not
811 /// a strict requirement. (Specifically: it is *legal* to
812 /// implement this trait atop an underlying native allocation
813 /// library that aborts on memory exhaustion.)
815 /// Clients wishing to abort computation in response to a
816 /// reallocation error are encouraged to call the [`handle_alloc_error`] function,
817 /// rather than directly invoking `panic!` or similar.
819 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
820 unsafe fn realloc(&mut self,
823 new_size: usize) -> Result<NonNull<u8>, AllocErr> {
824 let old_size = layout.size();
826 if new_size >= old_size {
827 if let Ok(()) = self.grow_in_place(ptr, layout.clone(), new_size) {
830 } else if new_size < old_size {
831 if let Ok(()) = self.shrink_in_place(ptr, layout.clone(), new_size) {
836 // otherwise, fall back on alloc + copy + dealloc.
837 let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
838 let result = self.alloc(new_layout);
839 if let Ok(new_ptr) = result {
840 ptr::copy_nonoverlapping(ptr.as_ptr(),
842 cmp::min(old_size, new_size));
843 self.dealloc(ptr, layout);
848 /// Behaves like `alloc`, but also ensures that the contents
849 /// are set to zero before being returned.
853 /// This function is unsafe for the same reasons that `alloc` is.
857 /// Returning `Err` indicates that either memory is exhausted or
858 /// `layout` does not meet allocator's size or alignment
859 /// constraints, just as in `alloc`.
861 /// Clients wishing to abort computation in response to an
862 /// allocation error are encouraged to call the [`handle_alloc_error`] function,
863 /// rather than directly invoking `panic!` or similar.
865 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
866 unsafe fn alloc_zeroed(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
867 let size = layout.size();
868 let p = self.alloc(layout);
870 ptr::write_bytes(p.as_ptr(), 0, size);
875 /// Behaves like `alloc`, but also returns the whole size of
876 /// the returned block. For some `layout` inputs, like arrays, this
877 /// may include extra storage usable for additional data.
881 /// This function is unsafe for the same reasons that `alloc` is.
885 /// Returning `Err` indicates that either memory is exhausted or
886 /// `layout` does not meet allocator's size or alignment
887 /// constraints, just as in `alloc`.
889 /// Clients wishing to abort computation in response to an
890 /// allocation error are encouraged to call the [`handle_alloc_error`] function,
891 /// rather than directly invoking `panic!` or similar.
893 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
894 unsafe fn alloc_excess(&mut self, layout: Layout) -> Result<Excess, AllocErr> {
895 let usable_size = self.usable_size(&layout);
896 self.alloc(layout).map(|p| Excess(p, usable_size.1))
899 /// Behaves like `realloc`, but also returns the whole size of
900 /// the returned block. For some `layout` inputs, like arrays, this
901 /// may include extra storage usable for additional data.
905 /// This function is unsafe for the same reasons that `realloc` is.
909 /// Returning `Err` indicates that either memory is exhausted or
910 /// `layout` does not meet allocator's size or alignment
911 /// constraints, just as in `realloc`.
913 /// Clients wishing to abort computation in response to a
914 /// reallocation error are encouraged to call the [`handle_alloc_error`] function,
915 /// rather than directly invoking `panic!` or similar.
917 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
918 unsafe fn realloc_excess(&mut self,
921 new_size: usize) -> Result<Excess, AllocErr> {
922 let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
923 let usable_size = self.usable_size(&new_layout);
924 self.realloc(ptr, layout, new_size)
925 .map(|p| Excess(p, usable_size.1))
928 /// Attempts to extend the allocation referenced by `ptr` to fit `new_size`.
930 /// If this returns `Ok`, then the allocator has asserted that the
931 /// memory block referenced by `ptr` now fits `new_size`, and thus can
932 /// be used to carry data of a layout of that size and same alignment as
933 /// `layout`. (The allocator is allowed to
934 /// expend effort to accomplish this, such as extending the memory block to
935 /// include successor blocks, or virtual memory tricks.)
937 /// Regardless of what this method returns, ownership of the
938 /// memory block referenced by `ptr` has not been transferred, and
939 /// the contents of the memory block are unaltered.
943 /// This function is unsafe because undefined behavior can result
944 /// if the caller does not ensure all of the following:
946 /// * `ptr` must be currently allocated via this allocator,
948 /// * `layout` must *fit* the `ptr` (see above); note the
949 /// `new_size` argument need not fit it,
951 /// * `new_size` must not be less than `layout.size()`,
955 /// Returns `Err(CannotReallocInPlace)` when the allocator is
956 /// unable to assert that the memory block referenced by `ptr`
957 /// could fit `layout`.
959 /// Note that one cannot pass `CannotReallocInPlace` to the `handle_alloc_error`
960 /// function; clients are expected either to be able to recover from
961 /// `grow_in_place` failures without aborting, or to fall back on
962 /// another reallocation method before resorting to an abort.
963 unsafe fn grow_in_place(&mut self,
966 new_size: usize) -> Result<(), CannotReallocInPlace> {
967 let _ = ptr; // this default implementation doesn't care about the actual address.
968 debug_assert!(new_size >= layout.size());
969 let (_l, u) = self.usable_size(&layout);
970 // _l <= layout.size() [guaranteed by usable_size()]
971 // layout.size() <= new_layout.size() [required by this method]
975 Err(CannotReallocInPlace)
979 /// Attempts to shrink the allocation referenced by `ptr` to fit `new_size`.
981 /// If this returns `Ok`, then the allocator has asserted that the
982 /// memory block referenced by `ptr` now fits `new_size`, and
983 /// thus can only be used to carry data of that smaller
984 /// layout. (The allocator is allowed to take advantage of this,
985 /// carving off portions of the block for reuse elsewhere.) The
986 /// truncated contents of the block within the smaller layout are
987 /// unaltered, and ownership of block has not been transferred.
989 /// If this returns `Err`, then the memory block is considered to
990 /// still represent the original (larger) `layout`. None of the
991 /// block has been carved off for reuse elsewhere, ownership of
992 /// the memory block has not been transferred, and the contents of
993 /// the memory block are unaltered.
997 /// This function is unsafe because undefined behavior can result
998 /// if the caller does not ensure all of the following:
1000 /// * `ptr` must be currently allocated via this allocator,
1002 /// * `layout` must *fit* the `ptr` (see above); note the
1003 /// `new_size` argument need not fit it,
1005 /// * `new_size` must not be greater than `layout.size()`
1006 /// (and must be greater than zero),
1010 /// Returns `Err(CannotReallocInPlace)` when the allocator is
1011 /// unable to assert that the memory block referenced by `ptr`
1012 /// could fit `layout`.
1014 /// Note that one cannot pass `CannotReallocInPlace` to the `handle_alloc_error`
1015 /// function; clients are expected either to be able to recover from
1016 /// `shrink_in_place` failures without aborting, or to fall back
1017 /// on another reallocation method before resorting to an abort.
1018 unsafe fn shrink_in_place(&mut self,
1021 new_size: usize) -> Result<(), CannotReallocInPlace> {
1022 let _ = ptr; // this default implementation doesn't care about the actual address.
1023 debug_assert!(new_size <= layout.size());
1024 let (l, _u) = self.usable_size(&layout);
1025 // layout.size() <= _u [guaranteed by usable_size()]
1026 // new_layout.size() <= layout.size() [required by this method]
1030 Err(CannotReallocInPlace)
1035 // == COMMON USAGE PATTERNS ==
1036 // alloc_one, dealloc_one, alloc_array, realloc_array. dealloc_array
1038 /// Allocates a block suitable for holding an instance of `T`.
1040 /// Captures a common usage pattern for allocators.
1042 /// The returned block is suitable for passing to the
1043 /// `alloc`/`realloc` methods of this allocator.
1045 /// Note to implementors: If this returns `Ok(ptr)`, then `ptr`
1046 /// must be considered "currently allocated" and must be
1047 /// acceptable input to methods such as `realloc` or `dealloc`,
1048 /// *even if* `T` is a zero-sized type. In other words, if your
1049 /// `Alloc` implementation overrides this method in a manner
1050 /// that can return a zero-sized `ptr`, then all reallocation and
1051 /// deallocation methods need to be similarly overridden to accept
1052 /// such values as input.
1056 /// Returning `Err` indicates that either memory is exhausted or
1057 /// `T` does not meet allocator's size or alignment constraints.
1059 /// For zero-sized `T`, may return either of `Ok` or `Err`, but
1060 /// will *not* yield undefined behavior.
1062 /// Clients wishing to abort computation in response to an
1063 /// allocation error are encouraged to call the [`handle_alloc_error`] function,
1064 /// rather than directly invoking `panic!` or similar.
1066 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
1067 fn alloc_one<T>(&mut self) -> Result<NonNull<T>, AllocErr>
1070 let k = Layout::new::<T>();
1072 unsafe { self.alloc(k).map(|p| p.cast()) }
1078 /// Deallocates a block suitable for holding an instance of `T`.
1080 /// The given block must have been produced by this allocator,
1081 /// and must be suitable for storing a `T` (in terms of alignment
1082 /// as well as minimum and maximum size); otherwise yields
1083 /// undefined behavior.
1085 /// Captures a common usage pattern for allocators.
1089 /// This function is unsafe because undefined behavior can result
1090 /// if the caller does not ensure both:
1092 /// * `ptr` must denote a block of memory currently allocated via this allocator
1094 /// * the layout of `T` must *fit* that block of memory.
1095 unsafe fn dealloc_one<T>(&mut self, ptr: NonNull<T>)
1098 let k = Layout::new::<T>();
1100 self.dealloc(ptr.cast(), k);
1104 /// Allocates a block suitable for holding `n` instances of `T`.
1106 /// Captures a common usage pattern for allocators.
1108 /// The returned block is suitable for passing to the
1109 /// `alloc`/`realloc` methods of this allocator.
1111 /// Note to implementors: If this returns `Ok(ptr)`, then `ptr`
1112 /// must be considered "currently allocated" and must be
1113 /// acceptable input to methods such as `realloc` or `dealloc`,
1114 /// *even if* `T` is a zero-sized type. In other words, if your
1115 /// `Alloc` implementation overrides this method in a manner
1116 /// that can return a zero-sized `ptr`, then all reallocation and
1117 /// deallocation methods need to be similarly overridden to accept
1118 /// such values as input.
1122 /// Returning `Err` indicates that either memory is exhausted or
1123 /// `[T; n]` does not meet allocator's size or alignment
1126 /// For zero-sized `T` or `n == 0`, may return either of `Ok` or
1127 /// `Err`, but will *not* yield undefined behavior.
1129 /// Always returns `Err` on arithmetic overflow.
1131 /// Clients wishing to abort computation in response to an
1132 /// allocation error are encouraged to call the [`handle_alloc_error`] function,
1133 /// rather than directly invoking `panic!` or similar.
1135 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
1136 fn alloc_array<T>(&mut self, n: usize) -> Result<NonNull<T>, AllocErr>
1139 match Layout::array::<T>(n) {
1140 Ok(ref layout) if layout.size() > 0 => {
1142 self.alloc(layout.clone()).map(|p| p.cast())
1149 /// Reallocates a block previously suitable for holding `n_old`
1150 /// instances of `T`, returning a block suitable for holding
1151 /// `n_new` instances of `T`.
1153 /// Captures a common usage pattern for allocators.
1155 /// The returned block is suitable for passing to the
1156 /// `alloc`/`realloc` methods of this allocator.
1160 /// This function is unsafe because undefined behavior can result
1161 /// if the caller does not ensure all of the following:
1163 /// * `ptr` must be currently allocated via this allocator,
1165 /// * the layout of `[T; n_old]` must *fit* that block of memory.
1169 /// Returning `Err` indicates that either memory is exhausted or
1170 /// `[T; n_new]` does not meet allocator's size or alignment
1173 /// For zero-sized `T` or `n_new == 0`, may return either of `Ok` or
1174 /// `Err`, but will *not* yield undefined behavior.
1176 /// Always returns `Err` on arithmetic overflow.
1178 /// Clients wishing to abort computation in response to a
1179 /// reallocation error are encouraged to call the [`handle_alloc_error`] function,
1180 /// rather than directly invoking `panic!` or similar.
1182 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
1183 unsafe fn realloc_array<T>(&mut self,
1186 n_new: usize) -> Result<NonNull<T>, AllocErr>
1189 match (Layout::array::<T>(n_old), Layout::array::<T>(n_new)) {
1190 (Ok(ref k_old), Ok(ref k_new)) if k_old.size() > 0 && k_new.size() > 0 => {
1191 debug_assert!(k_old.align() == k_new.align());
1192 self.realloc(ptr.cast(), k_old.clone(), k_new.size()).map(NonNull::cast)
1200 /// Deallocates a block suitable for holding `n` instances of `T`.
1202 /// Captures a common usage pattern for allocators.
1206 /// This function is unsafe because undefined behavior can result
1207 /// if the caller does not ensure both:
1209 /// * `ptr` must denote a block of memory currently allocated via this allocator
1211 /// * the layout of `[T; n]` must *fit* that block of memory.
1215 /// Returning `Err` indicates that either `[T; n]` or the given
1216 /// memory block does not meet allocator's size or alignment
1219 /// Always returns `Err` on arithmetic overflow.
1220 unsafe fn dealloc_array<T>(&mut self, ptr: NonNull<T>, n: usize) -> Result<(), AllocErr>
1223 match Layout::array::<T>(n) {
1224 Ok(ref k) if k.size() > 0 => {
1225 Ok(self.dealloc(ptr.cast(), k.clone()))