1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![unstable(feature = "allocator_api",
12 reason = "the precise API and guarantees it provides may be tweaked \
13 slightly, especially to possibly take into account the \
14 types being stored to make room for a future \
15 tracing garbage collector",
22 use ptr::{self, NonNull};
23 use num::NonZeroUsize;
26 /// An opaque, unsized type. Used for pointers to allocated memory.
28 /// This type can only be used behind a pointer like `*mut Opaque` or `ptr::NonNull<Opaque>`.
29 /// Such pointers are similar to C’s `void*` type.
34 /// Similar to `std::ptr::null`, which requires `T: Sized`.
35 pub fn null() -> *const Self {
39 /// Similar to `std::ptr::null_mut`, which requires `T: Sized`.
40 pub fn null_mut() -> *mut Self {
45 /// Represents the combination of a starting address and
46 /// a total capacity of the returned block.
48 pub struct Excess(pub NonNull<Opaque>, pub usize);
50 fn size_align<T>() -> (usize, usize) {
51 (mem::size_of::<T>(), mem::align_of::<T>())
54 /// Layout of a block of memory.
56 /// An instance of `Layout` describes a particular layout of memory.
57 /// You build a `Layout` up as an input to give to an allocator.
59 /// All layouts have an associated non-negative size and a
60 /// power-of-two alignment.
62 /// (Note however that layouts are *not* required to have positive
63 /// size, even though many allocators require that all memory
64 /// requests have positive size. A caller to the `Alloc::alloc`
65 /// method must either ensure that conditions like this are met, or
66 /// use specific allocators with looser requirements.)
67 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
69 // size of the requested block of memory, measured in bytes.
72 // alignment of the requested block of memory, measured in bytes.
73 // we ensure that this is always a power-of-two, because API's
74 // like `posix_memalign` require it and it is a reasonable
75 // constraint to impose on Layout constructors.
77 // (However, we do not analogously require `align >= sizeof(void*)`,
78 // even though that is *also* a requirement of `posix_memalign`.)
83 /// Constructs a `Layout` from a given `size` and `align`,
84 /// or returns `LayoutErr` if either of the following conditions
87 /// * `align` must be a power of two,
89 /// * `size`, when rounded up to the nearest multiple of `align`,
90 /// must not overflow (i.e. the rounded value must be less than
93 pub fn from_size_align(size: usize, align: usize) -> Result<Self, LayoutErr> {
94 if !align.is_power_of_two() {
95 return Err(LayoutErr { private: () });
98 // (power-of-two implies align != 0.)
100 // Rounded up size is:
101 // size_rounded_up = (size + align - 1) & !(align - 1);
103 // We know from above that align != 0. If adding (align - 1)
104 // does not overflow, then rounding up will be fine.
106 // Conversely, &-masking with !(align - 1) will subtract off
107 // only low-order-bits. Thus if overflow occurs with the sum,
108 // the &-mask cannot subtract enough to undo that overflow.
110 // Above implies that checking for summation overflow is both
111 // necessary and sufficient.
112 if size > usize::MAX - (align - 1) {
113 return Err(LayoutErr { private: () });
117 Ok(Layout::from_size_align_unchecked(size, align))
121 /// Creates a layout, bypassing all checks.
125 /// This function is unsafe as it does not verify the preconditions from
126 /// [`Layout::from_size_align`](#method.from_size_align).
128 pub unsafe fn from_size_align_unchecked(size: usize, align: usize) -> Self {
129 Layout { size_: size, align_: NonZeroUsize::new_unchecked(align) }
132 /// The minimum size in bytes for a memory block of this layout.
134 pub fn size(&self) -> usize { self.size_ }
136 /// The minimum byte alignment for a memory block of this layout.
138 pub fn align(&self) -> usize { self.align_.get() }
140 /// Constructs a `Layout` suitable for holding a value of type `T`.
142 pub fn new<T>() -> Self {
143 let (size, align) = size_align::<T>();
144 // Note that the align is guaranteed by rustc to be a power of two and
145 // the size+align combo is guaranteed to fit in our address space. As a
146 // result use the unchecked constructor here to avoid inserting code
147 // that panics if it isn't optimized well enough.
148 debug_assert!(Layout::from_size_align(size, align).is_ok());
150 Layout::from_size_align_unchecked(size, align)
154 /// Produces layout describing a record that could be used to
155 /// allocate backing structure for `T` (which could be a trait
156 /// or other unsized type like a slice).
158 pub fn for_value<T: ?Sized>(t: &T) -> Self {
159 let (size, align) = (mem::size_of_val(t), mem::align_of_val(t));
160 // See rationale in `new` for why this us using an unsafe variant below
161 debug_assert!(Layout::from_size_align(size, align).is_ok());
163 Layout::from_size_align_unchecked(size, align)
167 /// Creates a layout describing the record that can hold a value
168 /// of the same layout as `self`, but that also is aligned to
169 /// alignment `align` (measured in bytes).
171 /// If `self` already meets the prescribed alignment, then returns
174 /// Note that this method does not add any padding to the overall
175 /// size, regardless of whether the returned layout has a different
176 /// alignment. In other words, if `K` has size 16, `K.align_to(32)`
177 /// will *still* have size 16.
181 /// Panics if the combination of `self.size()` and the given `align`
182 /// violates the conditions listed in
183 /// [`Layout::from_size_align`](#method.from_size_align).
185 pub fn align_to(&self, align: usize) -> Self {
186 Layout::from_size_align(self.size(), cmp::max(self.align(), align)).unwrap()
189 /// Returns the amount of padding we must insert after `self`
190 /// to ensure that the following address will satisfy `align`
191 /// (measured in bytes).
193 /// E.g. if `self.size()` is 9, then `self.padding_needed_for(4)`
194 /// returns 3, because that is the minimum number of bytes of
195 /// padding required to get a 4-aligned address (assuming that the
196 /// corresponding memory block starts at a 4-aligned address).
198 /// The return value of this function has no meaning if `align` is
199 /// not a power-of-two.
201 /// Note that the utility of the returned value requires `align`
202 /// to be less than or equal to the alignment of the starting
203 /// address for the whole allocated block of memory. One way to
204 /// satisfy this constraint is to ensure `align <= self.align()`.
206 pub fn padding_needed_for(&self, align: usize) -> usize {
207 let len = self.size();
209 // Rounded up value is:
210 // len_rounded_up = (len + align - 1) & !(align - 1);
211 // and then we return the padding difference: `len_rounded_up - len`.
213 // We use modular arithmetic throughout:
215 // 1. align is guaranteed to be > 0, so align - 1 is always
218 // 2. `len + align - 1` can overflow by at most `align - 1`,
219 // so the &-mask wth `!(align - 1)` will ensure that in the
220 // case of overflow, `len_rounded_up` will itself be 0.
221 // Thus the returned padding, when added to `len`, yields 0,
222 // which trivially satisfies the alignment `align`.
224 // (Of course, attempts to allocate blocks of memory whose
225 // size and padding overflow in the above manner should cause
226 // the allocator to yield an error anyway.)
228 let len_rounded_up = len.wrapping_add(align).wrapping_sub(1)
229 & !align.wrapping_sub(1);
230 return len_rounded_up.wrapping_sub(len);
233 /// Creates a layout describing the record for `n` instances of
234 /// `self`, with a suitable amount of padding between each to
235 /// ensure that each instance is given its requested size and
236 /// alignment. On success, returns `(k, offs)` where `k` is the
237 /// layout of the array and `offs` is the distance between the start
238 /// of each element in the array.
240 /// On arithmetic overflow, returns `LayoutErr`.
242 pub fn repeat(&self, n: usize) -> Result<(Self, usize), LayoutErr> {
243 let padded_size = self.size().checked_add(self.padding_needed_for(self.align()))
244 .ok_or(LayoutErr { private: () })?;
245 let alloc_size = padded_size.checked_mul(n)
246 .ok_or(LayoutErr { private: () })?;
249 // self.align is already known to be valid and alloc_size has been
251 Ok((Layout::from_size_align_unchecked(alloc_size, self.align()), padded_size))
255 /// Creates a layout describing the record for `self` followed by
256 /// `next`, including any necessary padding to ensure that `next`
257 /// will be properly aligned. Note that the result layout will
258 /// satisfy the alignment properties of both `self` and `next`.
260 /// Returns `Some((k, offset))`, where `k` is layout of the concatenated
261 /// record and `offset` is the relative location, in bytes, of the
262 /// start of the `next` embedded within the concatenated record
263 /// (assuming that the record itself starts at offset 0).
265 /// On arithmetic overflow, returns `LayoutErr`.
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`.
293 pub fn repeat_packed(&self, n: usize) -> Result<Self, LayoutErr> {
294 let size = self.size().checked_mul(n).ok_or(LayoutErr { private: () })?;
295 Layout::from_size_align(size, self.align())
298 /// Creates a layout describing the record for `self` followed by
299 /// `next` with no additional padding between the two. Since no
300 /// padding is inserted, the alignment of `next` is irrelevant,
301 /// and is not incorporated *at all* into the resulting layout.
303 /// Returns `(k, offset)`, where `k` is layout of the concatenated
304 /// record and `offset` is the relative location, in bytes, of the
305 /// start of the `next` embedded within the concatenated record
306 /// (assuming that the record itself starts at offset 0).
308 /// (The `offset` is always the same as `self.size()`; we use this
309 /// signature out of convenience in matching the signature of
312 /// On arithmetic overflow, returns `LayoutErr`.
314 pub fn extend_packed(&self, next: Self) -> Result<(Self, usize), LayoutErr> {
315 let new_size = self.size().checked_add(next.size())
316 .ok_or(LayoutErr { private: () })?;
317 let layout = Layout::from_size_align(new_size, self.align())?;
318 Ok((layout, self.size()))
321 /// Creates a layout describing the record for a `[T; n]`.
323 /// On arithmetic overflow, returns `LayoutErr`.
325 pub fn array<T>(n: usize) -> Result<Self, LayoutErr> {
329 debug_assert!(offs == mem::size_of::<T>());
335 /// The parameters given to `Layout::from_size_align` do not satisfy
336 /// its documented constraints.
337 #[derive(Clone, PartialEq, Eq, Debug)]
338 pub struct LayoutErr {
342 // (we need this for downstream impl of trait Error)
343 impl fmt::Display for LayoutErr {
344 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
345 f.write_str("invalid parameters to Layout::from_size_align")
349 /// The `AllocErr` error specifies whether an allocation failure is
350 /// specifically due to resource exhaustion or if it is due to
351 /// something wrong when combining the given input arguments with this
353 #[derive(Clone, PartialEq, Eq, Debug)]
356 // (we need this for downstream impl of trait Error)
357 impl fmt::Display for AllocErr {
358 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
359 f.write_str("memory allocation failed")
363 /// The `CannotReallocInPlace` error is used when `grow_in_place` or
364 /// `shrink_in_place` were unable to reuse the given memory block for
365 /// a requested layout.
366 #[derive(Clone, PartialEq, Eq, Debug)]
367 pub struct CannotReallocInPlace;
369 impl CannotReallocInPlace {
370 pub fn description(&self) -> &str {
371 "cannot reallocate allocator's memory in place"
375 // (we need this for downstream impl of trait Error)
376 impl fmt::Display for CannotReallocInPlace {
377 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
378 write!(f, "{}", self.description())
382 /// Augments `AllocErr` with a CapacityOverflow variant.
383 #[derive(Clone, PartialEq, Eq, Debug)]
384 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
385 pub enum CollectionAllocErr {
386 /// Error due to the computed capacity exceeding the collection's maximum
387 /// (usually `isize::MAX` bytes).
389 /// Error due to the allocator (see the `AllocErr` type's docs).
393 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
394 impl From<AllocErr> for CollectionAllocErr {
396 fn from(AllocErr: AllocErr) -> Self {
397 CollectionAllocErr::AllocErr
401 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
402 impl From<LayoutErr> for CollectionAllocErr {
404 fn from(_: LayoutErr) -> Self {
405 CollectionAllocErr::CapacityOverflow
409 /// A memory allocator that can be registered to be the one backing `std::alloc::Global`
410 /// though the `#[global_allocator]` attributes.
411 pub unsafe trait GlobalAlloc {
412 /// Allocate memory as described by the given `layout`.
414 /// Returns a pointer to newly-allocated memory,
415 /// or NULL to indicate allocation failure.
419 /// **FIXME:** what are the exact requirements?
420 unsafe fn alloc(&self, layout: Layout) -> *mut Opaque;
422 /// Deallocate the block of memory at the given `ptr` pointer with the given `layout`.
426 /// **FIXME:** what are the exact requirements?
427 /// In particular around layout *fit*. (See docs for the `Alloc` trait.)
428 unsafe fn dealloc(&self, ptr: *mut Opaque, layout: Layout);
430 unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut Opaque {
431 let size = layout.size();
432 let ptr = self.alloc(layout);
434 ptr::write_bytes(ptr as *mut u8, 0, size);
439 /// Shink or grow a block of memory to the given `new_size`.
440 /// The block is described by the given `ptr` pointer and `layout`.
442 /// Return a new pointer (which may or may not be the same as `ptr`),
443 /// or NULL to indicate reallocation failure.
445 /// If reallocation is successful, the old `ptr` pointer is considered
446 /// to have been deallocated.
450 /// `new_size`, when rounded up to the nearest multiple of `old_layout.align()`,
451 /// must not overflow (i.e. the rounded value must be less than `usize::MAX`).
453 /// **FIXME:** what are the exact requirements?
454 /// In particular around layout *fit*. (See docs for the `Alloc` trait.)
455 unsafe fn realloc(&self, ptr: *mut Opaque, layout: Layout, new_size: usize) -> *mut Opaque {
456 let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
457 let new_ptr = self.alloc(new_layout);
458 if !new_ptr.is_null() {
459 ptr::copy_nonoverlapping(
462 cmp::min(layout.size(), new_size),
464 self.dealloc(ptr, layout);
470 /// An implementation of `Alloc` can allocate, reallocate, and
471 /// deallocate arbitrary blocks of data described via `Layout`.
473 /// Some of the methods require that a memory block be *currently
474 /// allocated* via an allocator. This means that:
476 /// * the starting address for that memory block was previously
477 /// returned by a previous call to an allocation method (`alloc`,
478 /// `alloc_zeroed`, `alloc_excess`, `alloc_one`, `alloc_array`) or
479 /// reallocation method (`realloc`, `realloc_excess`, or
480 /// `realloc_array`), and
482 /// * the memory block has not been subsequently deallocated, where
483 /// blocks are deallocated either by being passed to a deallocation
484 /// method (`dealloc`, `dealloc_one`, `dealloc_array`) or by being
485 /// passed to a reallocation method (see above) that returns `Ok`.
487 /// A note regarding zero-sized types and zero-sized layouts: many
488 /// methods in the `Alloc` trait state that allocation requests
489 /// must be non-zero size, or else undefined behavior can result.
491 /// * However, some higher-level allocation methods (`alloc_one`,
492 /// `alloc_array`) are well-defined on zero-sized types and can
493 /// optionally support them: it is left up to the implementor
494 /// whether to return `Err`, or to return `Ok` with some pointer.
496 /// * If an `Alloc` implementation chooses to return `Ok` in this
497 /// case (i.e. the pointer denotes a zero-sized inaccessible block)
498 /// then that returned pointer must be considered "currently
499 /// allocated". On such an allocator, *all* methods that take
500 /// currently-allocated pointers as inputs must accept these
501 /// zero-sized pointers, *without* causing undefined behavior.
503 /// * In other words, if a zero-sized pointer can flow out of an
504 /// allocator, then that allocator must likewise accept that pointer
505 /// flowing back into its deallocation and reallocation methods.
507 /// Some of the methods require that a layout *fit* a memory block.
508 /// What it means for a layout to "fit" a memory block means (or
509 /// equivalently, for a memory block to "fit" a layout) is that the
510 /// following two conditions must hold:
512 /// 1. The block's starting address must be aligned to `layout.align()`.
514 /// 2. The block's size must fall in the range `[use_min, use_max]`, where:
516 /// * `use_min` is `self.usable_size(layout).0`, and
518 /// * `use_max` is the capacity that was (or would have been)
519 /// returned when (if) the block was allocated via a call to
520 /// `alloc_excess` or `realloc_excess`.
524 /// * the size of the layout most recently used to allocate the block
525 /// is guaranteed to be in the range `[use_min, use_max]`, and
527 /// * a lower-bound on `use_max` can be safely approximated by a call to
530 /// * if a layout `k` fits a memory block (denoted by `ptr`)
531 /// currently allocated via an allocator `a`, then it is legal to
532 /// use that layout to deallocate it, i.e. `a.dealloc(ptr, k);`.
536 /// The `Alloc` trait is an `unsafe` trait for a number of reasons, and
537 /// implementors must ensure that they adhere to these contracts:
539 /// * Pointers returned from allocation functions must point to valid memory and
540 /// retain their validity until at least the instance of `Alloc` is dropped
543 /// * It's undefined behavior if global allocators unwind. This restriction may
544 /// be lifted in the future, but currently a panic from any of these
545 /// functions may lead to memory unsafety. Note that as of the time of this
546 /// writing allocators *not* intending to be global allocators can still panic
547 /// in their implementation without violating memory safety.
549 /// * `Layout` queries and calculations in general must be correct. Callers of
550 /// this trait are allowed to rely on the contracts defined on each method,
551 /// and implementors must ensure such contracts remain true.
553 /// Note that this list may get tweaked over time as clarifications are made in
554 /// the future. Additionally global allocators may gain unique requirements for
555 /// how to safely implement one in the future as well.
556 pub unsafe trait Alloc {
558 // (Note: existing allocators have unspecified but well-defined
559 // behavior in response to a zero size allocation request ;
560 // e.g. in C, `malloc` of 0 will either return a null pointer or a
561 // unique pointer, but will not have arbitrary undefined
562 // behavior. Rust should consider revising the alloc::heap crate
563 // to reflect this reality.)
565 /// Returns a pointer meeting the size and alignment guarantees of
568 /// If this method returns an `Ok(addr)`, then the `addr` returned
569 /// will be non-null address pointing to a block of storage
570 /// suitable for holding an instance of `layout`.
572 /// The returned block of storage may or may not have its contents
573 /// initialized. (Extension subtraits might restrict this
574 /// behavior, e.g. to ensure initialization to particular sets of
579 /// This function is unsafe because undefined behavior can result
580 /// if the caller does not ensure that `layout` has non-zero size.
582 /// (Extension subtraits might provide more specific bounds on
583 /// behavior, e.g. guarantee a sentinel address or a null pointer
584 /// in response to a zero-size allocation request.)
588 /// Returning `Err` indicates that either memory is exhausted or
589 /// `layout` does not meet allocator's size or alignment
592 /// Implementations are encouraged to return `Err` on memory
593 /// exhaustion rather than panicking or aborting, but this is not
594 /// a strict requirement. (Specifically: it is *legal* to
595 /// implement this trait atop an underlying native allocation
596 /// library that aborts on memory exhaustion.)
598 /// Clients wishing to abort computation in response to an
599 /// allocation error are encouraged to call the allocator's `oom`
600 /// method, rather than directly invoking `panic!` or similar.
601 unsafe fn alloc(&mut self, layout: Layout) -> Result<NonNull<Opaque>, AllocErr>;
603 /// Deallocate the memory referenced by `ptr`.
607 /// This function is unsafe because undefined behavior can result
608 /// if the caller does not ensure all of the following:
610 /// * `ptr` must denote a block of memory currently allocated via
613 /// * `layout` must *fit* that block of memory,
615 /// * In addition to fitting the block of memory `layout`, the
616 /// alignment of the `layout` must match the alignment used
617 /// to allocate that block of memory.
618 unsafe fn dealloc(&mut self, ptr: NonNull<Opaque>, layout: Layout);
620 // == ALLOCATOR-SPECIFIC QUANTITIES AND LIMITS ==
623 /// Returns bounds on the guaranteed usable size of a successful
624 /// allocation created with the specified `layout`.
626 /// In particular, if one has a memory block allocated via a given
627 /// allocator `a` and layout `k` where `a.usable_size(k)` returns
628 /// `(l, u)`, then one can pass that block to `a.dealloc()` with a
629 /// layout in the size range [l, u].
631 /// (All implementors of `usable_size` must ensure that
632 /// `l <= k.size() <= u`)
634 /// Both the lower- and upper-bounds (`l` and `u` respectively)
635 /// are provided, because an allocator based on size classes could
636 /// misbehave if one attempts to deallocate a block without
637 /// providing a correct value for its size (i.e., one within the
640 /// Clients who wish to make use of excess capacity are encouraged
641 /// to use the `alloc_excess` and `realloc_excess` instead, as
642 /// this method is constrained to report conservative values that
643 /// serve as valid bounds for *all possible* allocation method
646 /// However, for clients that do not wish to track the capacity
647 /// returned by `alloc_excess` locally, this method is likely to
648 /// produce useful results.
650 fn usable_size(&self, layout: &Layout) -> (usize, usize) {
651 (layout.size(), layout.size())
654 // == METHODS FOR MEMORY REUSE ==
655 // realloc. alloc_excess, realloc_excess
657 /// Returns a pointer suitable for holding data described by
658 /// a new layout with `layout`’s alginment and a size given
659 /// by `new_size`. To
660 /// accomplish this, this may extend or shrink the allocation
661 /// referenced by `ptr` to fit the new layout.
663 /// If this returns `Ok`, then ownership of the memory block
664 /// referenced by `ptr` has been transferred to this
665 /// allocator. The memory may or may not have been freed, and
666 /// should be considered unusable (unless of course it was
667 /// transferred back to the caller again via the return value of
670 /// If this method returns `Err`, then ownership of the memory
671 /// block has not been transferred to this allocator, and the
672 /// contents of the memory block are unaltered.
676 /// This function is unsafe because undefined behavior can result
677 /// if the caller does not ensure all of the following:
679 /// * `ptr` must be currently allocated via this allocator,
681 /// * `layout` must *fit* the `ptr` (see above). (The `new_size`
682 /// argument need not fit it.)
684 /// * `new_size` must be greater than zero.
686 /// * `new_size`, when rounded up to the nearest multiple of `layout.align()`,
687 /// must not overflow (i.e. the rounded value must be less than `usize::MAX`).
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 /// Returns `Err` only if the new layout
696 /// does not meet the allocator's size
697 /// and alignment constraints of the allocator, or if reallocation
700 /// Implementations are encouraged to return `Err` on memory
701 /// exhaustion rather than panicking or aborting, but this is not
702 /// a strict requirement. (Specifically: it is *legal* to
703 /// implement this trait atop an underlying native allocation
704 /// library that aborts on memory exhaustion.)
706 /// Clients wishing to abort computation in response to an
707 /// reallocation error are encouraged to call the allocator's `oom`
708 /// method, rather than directly invoking `panic!` or similar.
709 unsafe fn realloc(&mut self,
710 ptr: NonNull<Opaque>,
712 new_size: usize) -> Result<NonNull<Opaque>, AllocErr> {
713 let old_size = layout.size();
715 if new_size >= old_size {
716 if let Ok(()) = self.grow_in_place(ptr, layout.clone(), new_size) {
719 } else if new_size < old_size {
720 if let Ok(()) = self.shrink_in_place(ptr, layout.clone(), new_size) {
725 // otherwise, fall back on alloc + copy + dealloc.
726 let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
727 let result = self.alloc(new_layout);
728 if let Ok(new_ptr) = result {
729 ptr::copy_nonoverlapping(ptr.as_ptr() as *const u8,
730 new_ptr.as_ptr() as *mut u8,
731 cmp::min(old_size, new_size));
732 self.dealloc(ptr, layout);
737 /// Behaves like `alloc`, but also ensures that the contents
738 /// are set to zero before being returned.
742 /// This function is unsafe for the same reasons that `alloc` is.
746 /// Returning `Err` indicates that either memory is exhausted or
747 /// `layout` does not meet allocator's size or alignment
748 /// constraints, just as in `alloc`.
750 /// Clients wishing to abort computation in response to an
751 /// allocation error are encouraged to call the allocator's `oom`
752 /// method, rather than directly invoking `panic!` or similar.
753 unsafe fn alloc_zeroed(&mut self, layout: Layout) -> Result<NonNull<Opaque>, AllocErr> {
754 let size = layout.size();
755 let p = self.alloc(layout);
757 ptr::write_bytes(p.as_ptr() as *mut u8, 0, size);
762 /// Behaves like `alloc`, but also returns the whole size of
763 /// the returned block. For some `layout` inputs, like arrays, this
764 /// may include extra storage usable for additional data.
768 /// This function is unsafe for the same reasons that `alloc` is.
772 /// Returning `Err` indicates that either memory is exhausted or
773 /// `layout` does not meet allocator's size or alignment
774 /// constraints, just as in `alloc`.
776 /// Clients wishing to abort computation in response to an
777 /// allocation error are encouraged to call the allocator's `oom`
778 /// method, rather than directly invoking `panic!` or similar.
779 unsafe fn alloc_excess(&mut self, layout: Layout) -> Result<Excess, AllocErr> {
780 let usable_size = self.usable_size(&layout);
781 self.alloc(layout).map(|p| Excess(p, usable_size.1))
784 /// Behaves like `realloc`, but also returns the whole size of
785 /// the returned block. For some `layout` inputs, like arrays, this
786 /// may include extra storage usable for additional data.
790 /// This function is unsafe for the same reasons that `realloc` is.
794 /// Returning `Err` indicates that either memory is exhausted or
795 /// `layout` does not meet allocator's size or alignment
796 /// constraints, just as in `realloc`.
798 /// Clients wishing to abort computation in response to an
799 /// reallocation error are encouraged to call the allocator's `oom`
800 /// method, rather than directly invoking `panic!` or similar.
801 unsafe fn realloc_excess(&mut self,
802 ptr: NonNull<Opaque>,
804 new_size: usize) -> Result<Excess, AllocErr> {
805 let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
806 let usable_size = self.usable_size(&new_layout);
807 self.realloc(ptr, layout, new_size)
808 .map(|p| Excess(p, usable_size.1))
811 /// Attempts to extend the allocation referenced by `ptr` to fit `new_size`.
813 /// If this returns `Ok`, then the allocator has asserted that the
814 /// memory block referenced by `ptr` now fits `new_size`, and thus can
815 /// be used to carry data of a layout of that size and same alignment as
816 /// `layout`. (The allocator is allowed to
817 /// expend effort to accomplish this, such as extending the memory block to
818 /// include successor blocks, or virtual memory tricks.)
820 /// Regardless of what this method returns, ownership of the
821 /// memory block referenced by `ptr` has not been transferred, and
822 /// the contents of the memory block are unaltered.
826 /// This function is unsafe because undefined behavior can result
827 /// if the caller does not ensure all of the following:
829 /// * `ptr` must be currently allocated via this allocator,
831 /// * `layout` must *fit* the `ptr` (see above); note the
832 /// `new_size` argument need not fit it,
834 /// * `new_size` must not be less than `layout.size()`,
838 /// Returns `Err(CannotReallocInPlace)` when the allocator is
839 /// unable to assert that the memory block referenced by `ptr`
840 /// could fit `layout`.
842 /// Note that one cannot pass `CannotReallocInPlace` to the `oom`
843 /// method; clients are expected either to be able to recover from
844 /// `grow_in_place` failures without aborting, or to fall back on
845 /// another reallocation method before resorting to an abort.
846 unsafe fn grow_in_place(&mut self,
847 ptr: NonNull<Opaque>,
849 new_size: usize) -> Result<(), CannotReallocInPlace> {
850 let _ = ptr; // this default implementation doesn't care about the actual address.
851 debug_assert!(new_size >= layout.size());
852 let (_l, u) = self.usable_size(&layout);
853 // _l <= layout.size() [guaranteed by usable_size()]
854 // layout.size() <= new_layout.size() [required by this method]
858 return Err(CannotReallocInPlace);
862 /// Attempts to shrink the allocation referenced by `ptr` to fit `new_size`.
864 /// If this returns `Ok`, then the allocator has asserted that the
865 /// memory block referenced by `ptr` now fits `new_size`, and
866 /// thus can only be used to carry data of that smaller
867 /// layout. (The allocator is allowed to take advantage of this,
868 /// carving off portions of the block for reuse elsewhere.) The
869 /// truncated contents of the block within the smaller layout are
870 /// unaltered, and ownership of block has not been transferred.
872 /// If this returns `Err`, then the memory block is considered to
873 /// still represent the original (larger) `layout`. None of the
874 /// block has been carved off for reuse elsewhere, ownership of
875 /// the memory block has not been transferred, and the contents of
876 /// the memory block are unaltered.
880 /// This function is unsafe because undefined behavior can result
881 /// if the caller does not ensure all of the following:
883 /// * `ptr` must be currently allocated via this allocator,
885 /// * `layout` must *fit* the `ptr` (see above); note the
886 /// `new_size` argument need not fit it,
888 /// * `new_size` must not be greater than `layout.size()`
889 /// (and must be greater than zero),
893 /// Returns `Err(CannotReallocInPlace)` when the allocator is
894 /// unable to assert that the memory block referenced by `ptr`
895 /// could fit `layout`.
897 /// Note that one cannot pass `CannotReallocInPlace` to the `oom`
898 /// method; clients are expected either to be able to recover from
899 /// `shrink_in_place` failures without aborting, or to fall back
900 /// on another reallocation method before resorting to an abort.
901 unsafe fn shrink_in_place(&mut self,
902 ptr: NonNull<Opaque>,
904 new_size: usize) -> Result<(), CannotReallocInPlace> {
905 let _ = ptr; // this default implementation doesn't care about the actual address.
906 debug_assert!(new_size <= layout.size());
907 let (l, _u) = self.usable_size(&layout);
908 // layout.size() <= _u [guaranteed by usable_size()]
909 // new_layout.size() <= layout.size() [required by this method]
913 return Err(CannotReallocInPlace);
918 // == COMMON USAGE PATTERNS ==
919 // alloc_one, dealloc_one, alloc_array, realloc_array. dealloc_array
921 /// Allocates a block suitable for holding an instance of `T`.
923 /// Captures a common usage pattern for allocators.
925 /// The returned block is suitable for passing to the
926 /// `alloc`/`realloc` methods of this allocator.
928 /// Note to implementors: If this returns `Ok(ptr)`, then `ptr`
929 /// must be considered "currently allocated" and must be
930 /// acceptable input to methods such as `realloc` or `dealloc`,
931 /// *even if* `T` is a zero-sized type. In other words, if your
932 /// `Alloc` implementation overrides this method in a manner
933 /// that can return a zero-sized `ptr`, then all reallocation and
934 /// deallocation methods need to be similarly overridden to accept
935 /// such values as input.
939 /// Returning `Err` indicates that either memory is exhausted or
940 /// `T` does not meet allocator's size or alignment constraints.
942 /// For zero-sized `T`, may return either of `Ok` or `Err`, but
943 /// will *not* yield undefined behavior.
945 /// Clients wishing to abort computation in response to an
946 /// allocation error are encouraged to call the allocator's `oom`
947 /// method, rather than directly invoking `panic!` or similar.
948 fn alloc_one<T>(&mut self) -> Result<NonNull<T>, AllocErr>
951 let k = Layout::new::<T>();
953 unsafe { self.alloc(k).map(|p| p.cast()) }
959 /// Deallocates a block suitable for holding an instance of `T`.
961 /// The given block must have been produced by this allocator,
962 /// and must be suitable for storing a `T` (in terms of alignment
963 /// as well as minimum and maximum size); otherwise yields
964 /// undefined behavior.
966 /// Captures a common usage pattern for allocators.
970 /// This function is unsafe because undefined behavior can result
971 /// if the caller does not ensure both:
973 /// * `ptr` must denote a block of memory currently allocated via this allocator
975 /// * the layout of `T` must *fit* that block of memory.
976 unsafe fn dealloc_one<T>(&mut self, ptr: NonNull<T>)
979 let k = Layout::new::<T>();
981 self.dealloc(ptr.as_opaque(), k);
985 /// Allocates a block suitable for holding `n` instances of `T`.
987 /// Captures a common usage pattern for allocators.
989 /// The returned block is suitable for passing to the
990 /// `alloc`/`realloc` methods of this allocator.
992 /// Note to implementors: If this returns `Ok(ptr)`, then `ptr`
993 /// must be considered "currently allocated" and must be
994 /// acceptable input to methods such as `realloc` or `dealloc`,
995 /// *even if* `T` is a zero-sized type. In other words, if your
996 /// `Alloc` implementation overrides this method in a manner
997 /// that can return a zero-sized `ptr`, then all reallocation and
998 /// deallocation methods need to be similarly overridden to accept
999 /// such values as input.
1003 /// Returning `Err` indicates that either memory is exhausted or
1004 /// `[T; n]` does not meet allocator's size or alignment
1007 /// For zero-sized `T` or `n == 0`, may return either of `Ok` or
1008 /// `Err`, but will *not* yield undefined behavior.
1010 /// Always returns `Err` on arithmetic overflow.
1012 /// Clients wishing to abort computation in response to an
1013 /// allocation error are encouraged to call the allocator's `oom`
1014 /// method, rather than directly invoking `panic!` or similar.
1015 fn alloc_array<T>(&mut self, n: usize) -> Result<NonNull<T>, AllocErr>
1018 match Layout::array::<T>(n) {
1019 Ok(ref layout) if layout.size() > 0 => {
1021 self.alloc(layout.clone()).map(|p| p.cast())
1028 /// Reallocates a block previously suitable for holding `n_old`
1029 /// instances of `T`, returning a block suitable for holding
1030 /// `n_new` instances of `T`.
1032 /// Captures a common usage pattern for allocators.
1034 /// The returned block is suitable for passing to the
1035 /// `alloc`/`realloc` methods of this allocator.
1039 /// This function is unsafe because undefined behavior can result
1040 /// if the caller does not ensure all of the following:
1042 /// * `ptr` must be currently allocated via this allocator,
1044 /// * the layout of `[T; n_old]` must *fit* that block of memory.
1048 /// Returning `Err` indicates that either memory is exhausted or
1049 /// `[T; n_new]` does not meet allocator's size or alignment
1052 /// For zero-sized `T` or `n_new == 0`, may return either of `Ok` or
1053 /// `Err`, but will *not* yield undefined behavior.
1055 /// Always returns `Err` on arithmetic overflow.
1057 /// Clients wishing to abort computation in response to an
1058 /// reallocation error are encouraged to call the allocator's `oom`
1059 /// method, rather than directly invoking `panic!` or similar.
1060 unsafe fn realloc_array<T>(&mut self,
1063 n_new: usize) -> Result<NonNull<T>, AllocErr>
1066 match (Layout::array::<T>(n_old), Layout::array::<T>(n_new)) {
1067 (Ok(ref k_old), Ok(ref k_new)) if k_old.size() > 0 && k_new.size() > 0 => {
1068 debug_assert!(k_old.align() == k_new.align());
1069 self.realloc(ptr.as_opaque(), k_old.clone(), k_new.size()).map(NonNull::cast)
1077 /// Deallocates a block suitable for holding `n` instances of `T`.
1079 /// Captures a common usage pattern for allocators.
1083 /// This function is unsafe because undefined behavior can result
1084 /// if the caller does not ensure both:
1086 /// * `ptr` must denote a block of memory currently allocated via this allocator
1088 /// * the layout of `[T; n]` must *fit* that block of memory.
1092 /// Returning `Err` indicates that either `[T; n]` or the given
1093 /// memory block does not meet allocator's size or alignment
1096 /// Always returns `Err` on arithmetic overflow.
1097 unsafe fn dealloc_array<T>(&mut self, ptr: NonNull<T>, n: usize) -> Result<(), AllocErr>
1100 match Layout::array::<T>(n) {
1101 Ok(ref k) if k.size() > 0 => {
1102 Ok(self.dealloc(ptr.as_opaque(), k.clone()))