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 core::ptr::{self, Unique};
24 /// Represents the combination of a starting address and
25 /// a total capacity of the returned block.
27 pub struct Excess(pub *mut u8, pub usize);
29 fn size_align<T>() -> (usize, usize) {
30 (mem::size_of::<T>(), mem::align_of::<T>())
33 /// Layout of a block of memory.
35 /// An instance of `Layout` describes a particular layout of memory.
36 /// You build a `Layout` up as an input to give to an allocator.
38 /// All layouts have an associated non-negative size and a
39 /// power-of-two alignment.
41 /// (Note however that layouts are *not* required to have positive
42 /// size, even though many allocators require that all memory
43 /// requests have positive size. A caller to the `Alloc::alloc`
44 /// method must either ensure that conditions like this are met, or
45 /// use specific allocators with looser requirements.)
46 #[derive(Clone, Debug, PartialEq, Eq)]
48 // size of the requested block of memory, measured in bytes.
51 // alignment of the requested block of memory, measured in bytes.
52 // we ensure that this is always a power-of-two, because API's
53 // like `posix_memalign` require it and it is a reasonable
54 // constraint to impose on Layout constructors.
56 // (However, we do not analogously require `align >= sizeof(void*)`,
57 // even though that is *also* a requirement of `posix_memalign`.)
62 // FIXME: audit default implementations for overflow errors,
63 // (potentially switching to overflowing_add and
64 // overflowing_mul as necessary).
67 /// Constructs a `Layout` from a given `size` and `align`,
68 /// or returns `None` if any of the following conditions
71 /// * `align` must be a power of two,
73 /// * `align` must not exceed 2^31 (i.e. `1 << 31`),
75 /// * `size`, when rounded up to the nearest multiple of `align`,
76 /// must not overflow (i.e. the rounded value must be less than
79 pub fn from_size_align(size: usize, align: usize) -> Option<Layout> {
80 if !align.is_power_of_two() {
84 if align > (1 << 31) {
88 // (power-of-two implies align != 0.)
90 // Rounded up size is:
91 // size_rounded_up = (size + align - 1) & !(align - 1);
93 // We know from above that align != 0. If adding (align - 1)
94 // does not overflow, then rounding up will be fine.
96 // Conversely, &-masking with !(align - 1) will subtract off
97 // only low-order-bits. Thus if overflow occurs with the sum,
98 // the &-mask cannot subtract enough to undo that overflow.
100 // Above implies that checking for summation overflow is both
101 // necessary and sufficient.
102 if size > usize::MAX - (align - 1) {
107 Some(Layout::from_size_align_unchecked(size, align))
111 /// Creates a layout, bypassing all checks.
115 /// This function is unsafe as it does not verify that `align` is
116 /// a power-of-two that is also less than or equal to 2^31, nor
117 /// that `size` aligned to `align` fits within the address space
118 /// (i.e. the `Layout::from_size_align` preconditions).
120 pub unsafe fn from_size_align_unchecked(size: usize, align: usize) -> Layout {
121 Layout { size: size, align: align }
124 /// The minimum size in bytes for a memory block of this layout.
126 pub fn size(&self) -> usize { self.size }
128 /// The minimum byte alignment for a memory block of this layout.
130 pub fn align(&self) -> usize { self.align }
132 /// Constructs a `Layout` suitable for holding a value of type `T`.
133 pub fn new<T>() -> Self {
134 let (size, align) = size_align::<T>();
135 Layout::from_size_align(size, align).unwrap()
138 /// Produces layout describing a record that could be used to
139 /// allocate backing structure for `T` (which could be a trait
140 /// or other unsized type like a slice).
141 pub fn for_value<T: ?Sized>(t: &T) -> Self {
142 let (size, align) = (mem::size_of_val(t), mem::align_of_val(t));
143 Layout::from_size_align(size, align).unwrap()
146 /// Creates a layout describing the record that can hold a value
147 /// of the same layout as `self`, but that also is aligned to
148 /// alignment `align` (measured in bytes).
150 /// If `self` already meets the prescribed alignment, then returns
153 /// Note that this method does not add any padding to the overall
154 /// size, regardless of whether the returned layout has a different
155 /// alignment. In other words, if `K` has size 16, `K.align_to(32)`
156 /// will *still* have size 16.
160 /// Panics if the combination of `self.size` and the given `align`
161 /// violates the conditions listed in `from_size_align`.
163 pub fn align_to(&self, align: usize) -> Self {
164 Layout::from_size_align(self.size, cmp::max(self.align, align)).unwrap()
167 /// Returns the amount of padding we must insert after `self`
168 /// to ensure that the following address will satisfy `align`
169 /// (measured in bytes).
171 /// E.g. if `self.size` is 9, then `self.padding_needed_for(4)`
172 /// returns 3, because that is the minimum number of bytes of
173 /// padding required to get a 4-aligned address (assuming that the
174 /// corresponding memory block starts at a 4-aligned address).
176 /// The return value of this function has no meaning if `align` is
177 /// not a power-of-two.
179 /// Note that the utility of the returned value requires `align`
180 /// to be less than or equal to the alignment of the starting
181 /// address for the whole allocated block of memory. One way to
182 /// satisfy this constraint is to ensure `align <= self.align`.
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) & !align.wrapping_sub(1);
207 return len_rounded_up.wrapping_sub(len);
210 /// Creates a layout describing the record for `n` instances of
211 /// `self`, with a suitable amount of padding between each to
212 /// ensure that each instance is given its requested size and
213 /// alignment. On success, returns `(k, offs)` where `k` is the
214 /// layout of the array and `offs` is the distance between the start
215 /// of each element in the array.
217 /// On arithmetic overflow, returns `None`.
219 pub fn repeat(&self, n: usize) -> Option<(Self, usize)> {
220 let padded_size = match self.size.checked_add(self.padding_needed_for(self.align)) {
222 Some(padded_size) => padded_size,
224 let alloc_size = match padded_size.checked_mul(n) {
226 Some(alloc_size) => alloc_size,
229 // We can assume that `self.align` is a power-of-two that does
230 // not exceed 2^31. Furthermore, `alloc_size` has already been
231 // rounded up to a multiple of `self.align`; therefore, the
232 // call to `Layout::from_size_align` below should never panic.
233 Some((Layout::from_size_align(alloc_size, self.align).unwrap(), padded_size))
236 /// Creates a layout describing the record for `self` followed by
237 /// `next`, including any necessary padding to ensure that `next`
238 /// will be properly aligned. Note that the result layout will
239 /// satisfy the alignment properties of both `self` and `next`.
241 /// Returns `Some((k, offset))`, where `k` is layout of the concatenated
242 /// record and `offset` is the relative location, in bytes, of the
243 /// start of the `next` embedded within the concatenated record
244 /// (assuming that the record itself starts at offset 0).
246 /// On arithmetic overflow, returns `None`.
247 pub fn extend(&self, next: Self) -> Option<(Self, usize)> {
248 let new_align = cmp::max(self.align, next.align);
249 let realigned = match Layout::from_size_align(self.size, new_align) {
254 let pad = realigned.padding_needed_for(next.align);
256 let offset = match self.size.checked_add(pad) {
258 Some(offset) => offset,
260 let new_size = match offset.checked_add(next.size) {
262 Some(new_size) => new_size,
265 let layout = match Layout::from_size_align(new_size, new_align) {
269 Some((layout, offset))
272 /// Creates a layout describing the record for `n` instances of
273 /// `self`, with no padding between each instance.
275 /// Note that, unlike `repeat`, `repeat_packed` does not guarantee
276 /// that the repeated instances of `self` will be properly
277 /// aligned, even if a given instance of `self` is properly
278 /// aligned. In other words, if the layout returned by
279 /// `repeat_packed` is used to allocate an array, it is not
280 /// guaranteed that all elements in the array will be properly
283 /// On arithmetic overflow, returns `None`.
284 pub fn repeat_packed(&self, n: usize) -> Option<Self> {
285 let size = match self.size().checked_mul(n) {
287 Some(scaled) => scaled,
290 Layout::from_size_align(size, self.align)
293 /// Creates a layout describing the record for `self` followed by
294 /// `next` with no additional padding between the two. Since no
295 /// padding is inserted, the alignment of `next` is irrelevant,
296 /// and is not incorporated *at all* into the resulting layout.
298 /// Returns `(k, offset)`, where `k` is layout of the concatenated
299 /// record and `offset` is the relative location, in bytes, of the
300 /// start of the `next` embedded within the concatenated record
301 /// (assuming that the record itself starts at offset 0).
303 /// (The `offset` is always the same as `self.size()`; we use this
304 /// signature out of convenience in matching the signature of
307 /// On arithmetic overflow, returns `None`.
308 pub fn extend_packed(&self, next: Self) -> Option<(Self, usize)> {
309 let new_size = match self.size().checked_add(next.size()) {
311 Some(new_size) => new_size,
313 let layout = match Layout::from_size_align(new_size, self.align) {
317 Some((layout, self.size()))
320 /// Creates a layout describing the record for a `[T; n]`.
322 /// On arithmetic overflow, returns `None`.
323 pub fn array<T>(n: usize) -> Option<Self> {
327 debug_assert!(offs == mem::size_of::<T>());
333 /// The `AllocErr` error specifies whether an allocation failure is
334 /// specifically due to resource exhaustion or if it is due to
335 /// something wrong when combining the given input arguments with this
337 #[derive(Clone, PartialEq, Eq, Debug)]
339 /// Error due to hitting some resource limit or otherwise running
340 /// out of memory. This condition strongly implies that *some*
341 /// series of deallocations would allow a subsequent reissuing of
342 /// the original allocation request to succeed.
343 Exhausted { request: Layout },
345 /// Error due to allocator being fundamentally incapable of
346 /// satisfying the original request. This condition implies that
347 /// such an allocation request will never succeed on the given
348 /// allocator, regardless of environment, memory pressure, or
349 /// other contextual conditions.
351 /// For example, an allocator that does not support requests for
352 /// large memory blocks might return this error variant.
353 Unsupported { details: &'static str },
358 pub fn invalid_input(details: &'static str) -> Self {
359 AllocErr::Unsupported { details: details }
362 pub fn is_memory_exhausted(&self) -> bool {
363 if let AllocErr::Exhausted { .. } = *self { true } else { false }
366 pub fn is_request_unsupported(&self) -> bool {
367 if let AllocErr::Unsupported { .. } = *self { true } else { false }
370 pub fn description(&self) -> &str {
372 AllocErr::Exhausted { .. } => "allocator memory exhausted",
373 AllocErr::Unsupported { .. } => "unsupported allocator request",
378 // (we need this for downstream impl of trait Error)
379 impl fmt::Display for AllocErr {
380 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
381 write!(f, "{}", self.description())
385 /// The `CannotReallocInPlace` error is used when `grow_in_place` or
386 /// `shrink_in_place` were unable to reuse the given memory block for
387 /// a requested layout.
388 #[derive(Clone, PartialEq, Eq, Debug)]
389 pub struct CannotReallocInPlace;
391 impl CannotReallocInPlace {
392 pub fn description(&self) -> &str {
393 "cannot reallocate allocator's memory in place"
397 // (we need this for downstream impl of trait Error)
398 impl fmt::Display for CannotReallocInPlace {
399 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
400 write!(f, "{}", self.description())
404 /// An implementation of `Alloc` can allocate, reallocate, and
405 /// deallocate arbitrary blocks of data described via `Layout`.
407 /// Some of the methods require that a memory block be *currently
408 /// allocated* via an allocator. This means that:
410 /// * the starting address for that memory block was previously
411 /// returned by a previous call to an allocation method (`alloc`,
412 /// `alloc_zeroed`, `alloc_excess`, `alloc_one`, `alloc_array`) or
413 /// reallocation method (`realloc`, `realloc_excess`, or
414 /// `realloc_array`), and
416 /// * the memory block has not been subsequently deallocated, where
417 /// blocks are deallocated either by being passed to a deallocation
418 /// method (`dealloc`, `dealloc_one`, `dealloc_array`) or by being
419 /// passed to a reallocation method (see above) that returns `Ok`.
421 /// A note regarding zero-sized types and zero-sized layouts: many
422 /// methods in the `Alloc` trait state that allocation requests
423 /// must be non-zero size, or else undefined behavior can result.
425 /// * However, some higher-level allocation methods (`alloc_one`,
426 /// `alloc_array`) are well-defined on zero-sized types and can
427 /// optionally support them: it is left up to the implementor
428 /// whether to return `Err`, or to return `Ok` with some pointer.
430 /// * If an `Alloc` implementation chooses to return `Ok` in this
431 /// case (i.e. the pointer denotes a zero-sized inaccessible block)
432 /// then that returned pointer must be considered "currently
433 /// allocated". On such an allocator, *all* methods that take
434 /// currently-allocated pointers as inputs must accept these
435 /// zero-sized pointers, *without* causing undefined behavior.
437 /// * In other words, if a zero-sized pointer can flow out of an
438 /// allocator, then that allocator must likewise accept that pointer
439 /// flowing back into its deallocation and reallocation methods.
441 /// Some of the methods require that a layout *fit* a memory block.
442 /// What it means for a layout to "fit" a memory block means (or
443 /// equivalently, for a memory block to "fit" a layout) is that the
444 /// following two conditions must hold:
446 /// 1. The block's starting address must be aligned to `layout.align()`.
448 /// 2. The block's size must fall in the range `[use_min, use_max]`, where:
450 /// * `use_min` is `self.usable_size(layout).0`, and
452 /// * `use_max` is the capacity that was (or would have been)
453 /// returned when (if) the block was allocated via a call to
454 /// `alloc_excess` or `realloc_excess`.
458 /// * the size of the layout most recently used to allocate the block
459 /// is guaranteed to be in the range `[use_min, use_max]`, and
461 /// * a lower-bound on `use_max` can be safely approximated by a call to
464 /// * if a layout `k` fits a memory block (denoted by `ptr`)
465 /// currently allocated via an allocator `a`, then it is legal to
466 /// use that layout to deallocate it, i.e. `a.dealloc(ptr, k);`.
467 pub unsafe trait Alloc {
469 // (Note: existing allocators have unspecified but well-defined
470 // behavior in response to a zero size allocation request ;
471 // e.g. in C, `malloc` of 0 will either return a null pointer or a
472 // unique pointer, but will not have arbitrary undefined
473 // behavior. Rust should consider revising the alloc::heap crate
474 // to reflect this reality.)
476 /// Returns a pointer meeting the size and alignment guarantees of
479 /// If this method returns an `Ok(addr)`, then the `addr` returned
480 /// will be non-null address pointing to a block of storage
481 /// suitable for holding an instance of `layout`.
483 /// The returned block of storage may or may not have its contents
484 /// initialized. (Extension subtraits might restrict this
485 /// behavior, e.g. to ensure initialization to particular sets of
490 /// This function is unsafe because undefined behavior can result
491 /// if the caller does not ensure that `layout` has non-zero size.
493 /// (Extension subtraits might provide more specific bounds on
494 /// behavior, e.g. guarantee a sentinel address or a null pointer
495 /// in response to a zero-size allocation request.)
499 /// Returning `Err` indicates that either memory is exhausted or
500 /// `layout` does not meet allocator's size or alignment
503 /// Implementations are encouraged to return `Err` on memory
504 /// exhaustion rather than panicking or aborting, but this is not
505 /// a strict requirement. (Specifically: it is *legal* to
506 /// implement this trait atop an underlying native allocation
507 /// library that aborts on memory exhaustion.)
509 /// Clients wishing to abort computation in response to an
510 /// allocation error are encouraged to call the allocator's `oom`
511 /// method, rather than directly invoking `panic!` or similar.
512 unsafe fn alloc(&mut self, layout: Layout) -> Result<*mut u8, AllocErr>;
514 /// Deallocate the memory referenced by `ptr`.
518 /// This function is unsafe because undefined behavior can result
519 /// if the caller does not ensure all of the following:
521 /// * `ptr` must denote a block of memory currently allocated via
524 /// * `layout` must *fit* that block of memory,
526 /// * In addition to fitting the block of memory `layout`, the
527 /// alignment of the `layout` must match the alignment used
528 /// to allocate that block of memory.
529 unsafe fn dealloc(&mut self, ptr: *mut u8, layout: Layout);
531 /// Allocator-specific method for signaling an out-of-memory
534 /// `oom` aborts the thread or process, optionally performing
535 /// cleanup or logging diagnostic information before panicking or
538 /// `oom` is meant to be used by clients unable to cope with an
539 /// unsatisfied allocation request (signaled by an error such as
540 /// `AllocErr::Exhausted`), and wish to abandon computation rather
541 /// than attempt to recover locally. Such clients should pass the
542 /// signaling error value back into `oom`, where the allocator
543 /// may incorporate that error value into its diagnostic report
546 /// Implementations of the `oom` method are discouraged from
547 /// infinitely regressing in nested calls to `oom`. In
548 /// practice this means implementors should eschew allocating,
549 /// especially from `self` (directly or indirectly).
551 /// Implementations of the allocation and reallocation methods
552 /// (e.g. `alloc`, `alloc_one`, `realloc`) are discouraged from
553 /// panicking (or aborting) in the event of memory exhaustion;
554 /// instead they should return an appropriate error from the
555 /// invoked method, and let the client decide whether to invoke
556 /// this `oom` method in response.
557 fn oom(&mut self, _: AllocErr) -> ! {
558 unsafe { ::core::intrinsics::abort() }
561 // == ALLOCATOR-SPECIFIC QUANTITIES AND LIMITS ==
564 /// Returns bounds on the guaranteed usable size of a successful
565 /// allocation created with the specified `layout`.
567 /// In particular, if one has a memory block allocated via a given
568 /// allocator `a` and layout `k` where `a.usable_size(k)` returns
569 /// `(l, u)`, then one can pass that block to `a.dealloc()` with a
570 /// layout in the size range [l, u].
572 /// (All implementors of `usable_size` must ensure that
573 /// `l <= k.size() <= u`)
575 /// Both the lower- and upper-bounds (`l` and `u` respectively)
576 /// are provided, because an allocator based on size classes could
577 /// misbehave if one attempts to deallocate a block without
578 /// providing a correct value for its size (i.e., one within the
581 /// Clients who wish to make use of excess capacity are encouraged
582 /// to use the `alloc_excess` and `realloc_excess` instead, as
583 /// this method is constrained to report conservative values that
584 /// serve as valid bounds for *all possible* allocation method
587 /// However, for clients that do not wish to track the capacity
588 /// returned by `alloc_excess` locally, this method is likely to
589 /// produce useful results.
591 fn usable_size(&self, layout: &Layout) -> (usize, usize) {
592 (layout.size(), layout.size())
595 // == METHODS FOR MEMORY REUSE ==
596 // realloc. alloc_excess, realloc_excess
598 /// Returns a pointer suitable for holding data described by
599 /// `new_layout`, meeting its size and alignment guarantees. To
600 /// accomplish this, this may extend or shrink the allocation
601 /// referenced by `ptr` to fit `new_layout`.
603 /// If this returns `Ok`, then ownership of the memory block
604 /// referenced by `ptr` has been transferred to this
605 /// allocator. The memory may or may not have been freed, and
606 /// should be considered unusable (unless of course it was
607 /// transferred back to the caller again via the return value of
610 /// If this method returns `Err`, then ownership of the memory
611 /// block has not been transferred to this allocator, and the
612 /// contents of the memory block are unaltered.
614 /// For best results, `new_layout` should not impose a different
615 /// alignment constraint than `layout`. (In other words,
616 /// `new_layout.align()` should equal `layout.align()`.) However,
617 /// behavior is well-defined (though underspecified) when this
618 /// constraint is violated; further discussion below.
622 /// This function is unsafe because undefined behavior can result
623 /// if the caller does not ensure all of the following:
625 /// * `ptr` must be currently allocated via this allocator,
627 /// * `layout` must *fit* the `ptr` (see above). (The `new_layout`
628 /// argument need not fit it.)
630 /// * `new_layout` must have size greater than zero.
632 /// * the alignment of `new_layout` is non-zero.
634 /// (Extension subtraits might provide more specific bounds on
635 /// behavior, e.g. guarantee a sentinel address or a null pointer
636 /// in response to a zero-size allocation request.)
640 /// Returns `Err` only if `new_layout` does not match the
641 /// alignment of `layout`, or does not meet the allocator's size
642 /// and alignment constraints of the allocator, or if reallocation
645 /// (Note the previous sentence did not say "if and only if" -- in
646 /// particular, an implementation of this method *can* return `Ok`
647 /// if `new_layout.align() != old_layout.align()`; or it can
648 /// return `Err` in that scenario, depending on whether this
649 /// allocator can dynamically adjust the alignment constraint for
652 /// Implementations are encouraged to return `Err` on memory
653 /// exhaustion rather than panicking or aborting, but this is not
654 /// a strict requirement. (Specifically: it is *legal* to
655 /// implement this trait atop an underlying native allocation
656 /// library that aborts on memory exhaustion.)
658 /// Clients wishing to abort computation in response to an
659 /// reallocation error are encouraged to call the allocator's `oom`
660 /// method, rather than directly invoking `panic!` or similar.
661 unsafe fn realloc(&mut self,
664 new_layout: Layout) -> Result<*mut u8, AllocErr> {
665 let new_size = new_layout.size();
666 let old_size = layout.size();
667 let aligns_match = layout.align == new_layout.align;
669 if new_size >= old_size && aligns_match {
670 if let Ok(()) = self.grow_in_place(ptr, layout.clone(), new_layout.clone()) {
673 } else if new_size < old_size && aligns_match {
674 if let Ok(()) = self.shrink_in_place(ptr, layout.clone(), new_layout.clone()) {
679 // otherwise, fall back on alloc + copy + dealloc.
680 let result = self.alloc(new_layout);
681 if let Ok(new_ptr) = result {
682 ptr::copy_nonoverlapping(ptr as *const u8, new_ptr, cmp::min(old_size, new_size));
683 self.dealloc(ptr, layout);
688 /// Behaves like `alloc`, but also ensures that the contents
689 /// are set to zero before being returned.
693 /// This function is unsafe for the same reasons that `alloc` is.
697 /// Returning `Err` indicates that either memory is exhausted or
698 /// `layout` does not meet allocator's size or alignment
699 /// constraints, just as in `alloc`.
701 /// Clients wishing to abort computation in response to an
702 /// allocation error are encouraged to call the allocator's `oom`
703 /// method, rather than directly invoking `panic!` or similar.
704 unsafe fn alloc_zeroed(&mut self, layout: Layout) -> Result<*mut u8, AllocErr> {
705 let size = layout.size();
706 let p = self.alloc(layout);
708 ptr::write_bytes(p, 0, size);
713 /// Behaves like `alloc`, but also returns the whole size of
714 /// the returned block. For some `layout` inputs, like arrays, this
715 /// may include extra storage usable for additional data.
719 /// This function is unsafe for the same reasons that `alloc` is.
723 /// Returning `Err` indicates that either memory is exhausted or
724 /// `layout` does not meet allocator's size or alignment
725 /// constraints, just as in `alloc`.
727 /// Clients wishing to abort computation in response to an
728 /// allocation error are encouraged to call the allocator's `oom`
729 /// method, rather than directly invoking `panic!` or similar.
730 unsafe fn alloc_excess(&mut self, layout: Layout) -> Result<Excess, AllocErr> {
731 let usable_size = self.usable_size(&layout);
732 self.alloc(layout).map(|p| Excess(p, usable_size.1))
735 /// Behaves like `realloc`, but also returns the whole size of
736 /// the returned block. For some `layout` inputs, like arrays, this
737 /// may include extra storage usable for additional data.
741 /// This function is unsafe for the same reasons that `realloc` is.
745 /// Returning `Err` indicates that either memory is exhausted or
746 /// `layout` does not meet allocator's size or alignment
747 /// constraints, just as in `realloc`.
749 /// Clients wishing to abort computation in response to an
750 /// reallocation error are encouraged to call the allocator's `oom`
751 /// method, rather than directly invoking `panic!` or similar.
752 unsafe fn realloc_excess(&mut self,
755 new_layout: Layout) -> Result<Excess, AllocErr> {
756 let usable_size = self.usable_size(&new_layout);
757 self.realloc(ptr, layout, new_layout)
758 .map(|p| Excess(p, usable_size.1))
761 /// Attempts to extend the allocation referenced by `ptr` to fit `new_layout`.
763 /// If this returns `Ok`, then the allocator has asserted that the
764 /// memory block referenced by `ptr` now fits `new_layout`, and thus can
765 /// be used to carry data of that layout. (The allocator is allowed to
766 /// expend effort to accomplish this, such as extending the memory block to
767 /// include successor blocks, or virtual memory tricks.)
769 /// Regardless of what this method returns, ownership of the
770 /// memory block referenced by `ptr` has not been transferred, and
771 /// the contents of the memory block are unaltered.
775 /// This function is unsafe because undefined behavior can result
776 /// if the caller does not ensure all of the following:
778 /// * `ptr` must be currently allocated via this allocator,
780 /// * `layout` must *fit* the `ptr` (see above); note the
781 /// `new_layout` argument need not fit it,
783 /// * `new_layout.size()` must not be less than `layout.size()`,
785 /// * `new_layout.align()` must equal `layout.align()`.
789 /// Returns `Err(CannotReallocInPlace)` when the allocator is
790 /// unable to assert that the memory block referenced by `ptr`
791 /// could fit `layout`.
793 /// Note that one cannot pass `CannotReallocInPlace` to the `oom`
794 /// method; clients are expected either to be able to recover from
795 /// `grow_in_place` failures without aborting, or to fall back on
796 /// another reallocation method before resorting to an abort.
797 unsafe fn grow_in_place(&mut self,
800 new_layout: Layout) -> Result<(), CannotReallocInPlace> {
801 let _ = ptr; // this default implementation doesn't care about the actual address.
802 debug_assert!(new_layout.size >= layout.size);
803 debug_assert!(new_layout.align == layout.align);
804 let (_l, u) = self.usable_size(&layout);
805 // _l <= layout.size() [guaranteed by usable_size()]
806 // layout.size() <= new_layout.size() [required by this method]
807 if new_layout.size <= u {
810 return Err(CannotReallocInPlace);
814 /// Attempts to shrink the allocation referenced by `ptr` to fit `new_layout`.
816 /// If this returns `Ok`, then the allocator has asserted that the
817 /// memory block referenced by `ptr` now fits `new_layout`, and
818 /// thus can only be used to carry data of that smaller
819 /// layout. (The allocator is allowed to take advantage of this,
820 /// carving off portions of the block for reuse elsewhere.) The
821 /// truncated contents of the block within the smaller layout are
822 /// unaltered, and ownership of block has not been transferred.
824 /// If this returns `Err`, then the memory block is considered to
825 /// still represent the original (larger) `layout`. None of the
826 /// block has been carved off for reuse elsewhere, ownership of
827 /// the memory block has not been transferred, and the contents of
828 /// the memory block are unaltered.
832 /// This function is unsafe because undefined behavior can result
833 /// if the caller does not ensure all of the following:
835 /// * `ptr` must be currently allocated via this allocator,
837 /// * `layout` must *fit* the `ptr` (see above); note the
838 /// `new_layout` argument need not fit it,
840 /// * `new_layout.size()` must not be greater than `layout.size()`
841 /// (and must be greater than zero),
843 /// * `new_layout.align()` must equal `layout.align()`.
847 /// Returns `Err(CannotReallocInPlace)` when the allocator is
848 /// unable to assert that the memory block referenced by `ptr`
849 /// could fit `layout`.
851 /// Note that one cannot pass `CannotReallocInPlace` to the `oom`
852 /// method; clients are expected either to be able to recover from
853 /// `shrink_in_place` failures without aborting, or to fall back
854 /// on another reallocation method before resorting to an abort.
855 unsafe fn shrink_in_place(&mut self,
858 new_layout: Layout) -> Result<(), CannotReallocInPlace> {
859 let _ = ptr; // this default implementation doesn't care about the actual address.
860 debug_assert!(new_layout.size <= layout.size);
861 debug_assert!(new_layout.align == layout.align);
862 let (l, _u) = self.usable_size(&layout);
863 // layout.size() <= _u [guaranteed by usable_size()]
864 // new_layout.size() <= layout.size() [required by this method]
865 if l <= new_layout.size {
868 return Err(CannotReallocInPlace);
873 // == COMMON USAGE PATTERNS ==
874 // alloc_one, dealloc_one, alloc_array, realloc_array. dealloc_array
876 /// Allocates a block suitable for holding an instance of `T`.
878 /// Captures a common usage pattern for allocators.
880 /// The returned block is suitable for passing to the
881 /// `alloc`/`realloc` methods of this allocator.
883 /// Note to implementors: If this returns `Ok(ptr)`, then `ptr`
884 /// must be considered "currently allocated" and must be
885 /// acceptable input to methods such as `realloc` or `dealloc`,
886 /// *even if* `T` is a zero-sized type. In other words, if your
887 /// `Alloc` implementation overrides this method in a manner
888 /// that can return a zero-sized `ptr`, then all reallocation and
889 /// deallocation methods need to be similarly overridden to accept
890 /// such values as input.
894 /// Returning `Err` indicates that either memory is exhausted or
895 /// `T` does not meet allocator's size or alignment constraints.
897 /// For zero-sized `T`, may return either of `Ok` or `Err`, but
898 /// will *not* yield undefined behavior.
900 /// Clients wishing to abort computation in response to an
901 /// allocation error are encouraged to call the allocator's `oom`
902 /// method, rather than directly invoking `panic!` or similar.
903 fn alloc_one<T>(&mut self) -> Result<Unique<T>, AllocErr>
906 let k = Layout::new::<T>();
908 unsafe { self.alloc(k).map(|p| Unique::new_unchecked(p as *mut T)) }
910 Err(AllocErr::invalid_input("zero-sized type invalid for alloc_one"))
914 /// Deallocates a block suitable for holding an instance of `T`.
916 /// The given block must have been produced by this allocator,
917 /// and must be suitable for storing a `T` (in terms of alignment
918 /// as well as minimum and maximum size); otherwise yields
919 /// undefined behavior.
921 /// Captures a common usage pattern for allocators.
925 /// This function is unsafe because undefined behavior can result
926 /// if the caller does not ensure both:
928 /// * `ptr` must denote a block of memory currently allocated via this allocator
930 /// * the layout of `T` must *fit* that block of memory.
931 unsafe fn dealloc_one<T>(&mut self, ptr: Unique<T>)
934 let raw_ptr = ptr.as_ptr() as *mut u8;
935 let k = Layout::new::<T>();
937 self.dealloc(raw_ptr, k);
941 /// Allocates a block suitable for holding `n` instances of `T`.
943 /// Captures a common usage pattern for allocators.
945 /// The returned block is suitable for passing to the
946 /// `alloc`/`realloc` methods of this allocator.
948 /// Note to implementors: If this returns `Ok(ptr)`, then `ptr`
949 /// must be considered "currently allocated" and must be
950 /// acceptable input to methods such as `realloc` or `dealloc`,
951 /// *even if* `T` is a zero-sized type. In other words, if your
952 /// `Alloc` implementation overrides this method in a manner
953 /// that can return a zero-sized `ptr`, then all reallocation and
954 /// deallocation methods need to be similarly overridden to accept
955 /// such values as input.
959 /// Returning `Err` indicates that either memory is exhausted or
960 /// `[T; n]` does not meet allocator's size or alignment
963 /// For zero-sized `T` or `n == 0`, may return either of `Ok` or
964 /// `Err`, but will *not* yield undefined behavior.
966 /// Always returns `Err` on arithmetic overflow.
968 /// Clients wishing to abort computation in response to an
969 /// allocation error are encouraged to call the allocator's `oom`
970 /// method, rather than directly invoking `panic!` or similar.
971 fn alloc_array<T>(&mut self, n: usize) -> Result<Unique<T>, AllocErr>
974 match Layout::array::<T>(n) {
975 Some(ref layout) if layout.size() > 0 => {
977 self.alloc(layout.clone())
979 Unique::new_unchecked(p as *mut T)
983 _ => Err(AllocErr::invalid_input("invalid layout for alloc_array")),
987 /// Reallocates a block previously suitable for holding `n_old`
988 /// instances of `T`, returning a block suitable for holding
989 /// `n_new` instances of `T`.
991 /// Captures a common usage pattern for allocators.
993 /// The returned block is suitable for passing to the
994 /// `alloc`/`realloc` methods of this allocator.
998 /// This function is unsafe because undefined behavior can result
999 /// if the caller does not ensure all of the following:
1001 /// * `ptr` must be currently allocated via this allocator,
1003 /// * the layout of `[T; n_old]` must *fit* that block of memory.
1007 /// Returning `Err` indicates that either memory is exhausted or
1008 /// `[T; n_new]` does not meet allocator's size or alignment
1011 /// For zero-sized `T` or `n_new == 0`, may return either of `Ok` or
1012 /// `Err`, but will *not* yield undefined behavior.
1014 /// Always returns `Err` on arithmetic overflow.
1016 /// Clients wishing to abort computation in response to an
1017 /// reallocation error are encouraged to call the allocator's `oom`
1018 /// method, rather than directly invoking `panic!` or similar.
1019 unsafe fn realloc_array<T>(&mut self,
1022 n_new: usize) -> Result<Unique<T>, AllocErr>
1025 match (Layout::array::<T>(n_old), Layout::array::<T>(n_new), ptr.as_ptr()) {
1026 (Some(ref k_old), Some(ref k_new), ptr) if k_old.size() > 0 && k_new.size() > 0 => {
1027 self.realloc(ptr as *mut u8, k_old.clone(), k_new.clone())
1028 .map(|p|Unique::new_unchecked(p as *mut T))
1031 Err(AllocErr::invalid_input("invalid layout for realloc_array"))
1036 /// Deallocates a block suitable for holding `n` instances of `T`.
1038 /// Captures a common usage pattern for allocators.
1042 /// This function is unsafe because undefined behavior can result
1043 /// if the caller does not ensure both:
1045 /// * `ptr` must denote a block of memory currently allocated via this allocator
1047 /// * the layout of `[T; n]` must *fit* that block of memory.
1051 /// Returning `Err` indicates that either `[T; n]` or the given
1052 /// memory block does not meet allocator's size or alignment
1055 /// Always returns `Err` on arithmetic overflow.
1056 unsafe fn dealloc_array<T>(&mut self, ptr: Unique<T>, n: usize) -> Result<(), AllocErr>
1059 let raw_ptr = ptr.as_ptr() as *mut u8;
1060 match Layout::array::<T>(n) {
1061 Some(ref k) if k.size() > 0 => {
1062 Ok(self.dealloc(raw_ptr, k.clone()))
1065 Err(AllocErr::invalid_input("invalid layout for dealloc_array"))