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);`.
470 /// The `Alloc` trait is an `unsafe` trait for a number of reasons, and
471 /// implementors must ensure that they adhere to these contracts:
473 /// * Pointers returned from allocation functions must point to valid memory and
474 /// retain their validity until at least the instance of `Alloc` is dropped
477 /// * It's undefined behavior if global allocators unwind. This restriction may
478 /// be lifted in the future, but currently a panic from any of these
479 /// functions may lead to memory unsafety. Note that as of the time of this
480 /// writing allocators *not* intending to be global allocators can still panic
481 /// in their implementation without violating memory safety.
483 /// * `Layout` queries and calculations in general must be correct. Callers of
484 /// this trait are allowed to rely on the contracts defined on each method,
485 /// and implementors must ensure such contracts remain true.
487 /// Note that this list may get tweaked over time as clarifications are made in
488 /// the future. Additionally global allocators may gain unique requirements for
489 /// how to safely implement one in the future as well.
490 pub unsafe trait Alloc {
492 // (Note: existing allocators have unspecified but well-defined
493 // behavior in response to a zero size allocation request ;
494 // e.g. in C, `malloc` of 0 will either return a null pointer or a
495 // unique pointer, but will not have arbitrary undefined
496 // behavior. Rust should consider revising the alloc::heap crate
497 // to reflect this reality.)
499 /// Returns a pointer meeting the size and alignment guarantees of
502 /// If this method returns an `Ok(addr)`, then the `addr` returned
503 /// will be non-null address pointing to a block of storage
504 /// suitable for holding an instance of `layout`.
506 /// The returned block of storage may or may not have its contents
507 /// initialized. (Extension subtraits might restrict this
508 /// behavior, e.g. to ensure initialization to particular sets of
513 /// This function is unsafe because undefined behavior can result
514 /// if the caller does not ensure that `layout` has non-zero size.
516 /// (Extension subtraits might provide more specific bounds on
517 /// behavior, e.g. guarantee a sentinel address or a null pointer
518 /// in response to a zero-size allocation request.)
522 /// Returning `Err` indicates that either memory is exhausted or
523 /// `layout` does not meet allocator's size or alignment
526 /// Implementations are encouraged to return `Err` on memory
527 /// exhaustion rather than panicking or aborting, but this is not
528 /// a strict requirement. (Specifically: it is *legal* to
529 /// implement this trait atop an underlying native allocation
530 /// library that aborts on memory exhaustion.)
532 /// Clients wishing to abort computation in response to an
533 /// allocation error are encouraged to call the allocator's `oom`
534 /// method, rather than directly invoking `panic!` or similar.
535 unsafe fn alloc(&mut self, layout: Layout) -> Result<*mut u8, AllocErr>;
537 /// Deallocate the memory referenced by `ptr`.
541 /// This function is unsafe because undefined behavior can result
542 /// if the caller does not ensure all of the following:
544 /// * `ptr` must denote a block of memory currently allocated via
547 /// * `layout` must *fit* that block of memory,
549 /// * In addition to fitting the block of memory `layout`, the
550 /// alignment of the `layout` must match the alignment used
551 /// to allocate that block of memory.
552 unsafe fn dealloc(&mut self, ptr: *mut u8, layout: Layout);
554 /// Allocator-specific method for signaling an out-of-memory
557 /// `oom` aborts the thread or process, optionally performing
558 /// cleanup or logging diagnostic information before panicking or
561 /// `oom` is meant to be used by clients unable to cope with an
562 /// unsatisfied allocation request (signaled by an error such as
563 /// `AllocErr::Exhausted`), and wish to abandon computation rather
564 /// than attempt to recover locally. Such clients should pass the
565 /// signaling error value back into `oom`, where the allocator
566 /// may incorporate that error value into its diagnostic report
569 /// Implementations of the `oom` method are discouraged from
570 /// infinitely regressing in nested calls to `oom`. In
571 /// practice this means implementors should eschew allocating,
572 /// especially from `self` (directly or indirectly).
574 /// Implementations of the allocation and reallocation methods
575 /// (e.g. `alloc`, `alloc_one`, `realloc`) are discouraged from
576 /// panicking (or aborting) in the event of memory exhaustion;
577 /// instead they should return an appropriate error from the
578 /// invoked method, and let the client decide whether to invoke
579 /// this `oom` method in response.
580 fn oom(&mut self, _: AllocErr) -> ! {
581 unsafe { ::core::intrinsics::abort() }
584 // == ALLOCATOR-SPECIFIC QUANTITIES AND LIMITS ==
587 /// Returns bounds on the guaranteed usable size of a successful
588 /// allocation created with the specified `layout`.
590 /// In particular, if one has a memory block allocated via a given
591 /// allocator `a` and layout `k` where `a.usable_size(k)` returns
592 /// `(l, u)`, then one can pass that block to `a.dealloc()` with a
593 /// layout in the size range [l, u].
595 /// (All implementors of `usable_size` must ensure that
596 /// `l <= k.size() <= u`)
598 /// Both the lower- and upper-bounds (`l` and `u` respectively)
599 /// are provided, because an allocator based on size classes could
600 /// misbehave if one attempts to deallocate a block without
601 /// providing a correct value for its size (i.e., one within the
604 /// Clients who wish to make use of excess capacity are encouraged
605 /// to use the `alloc_excess` and `realloc_excess` instead, as
606 /// this method is constrained to report conservative values that
607 /// serve as valid bounds for *all possible* allocation method
610 /// However, for clients that do not wish to track the capacity
611 /// returned by `alloc_excess` locally, this method is likely to
612 /// produce useful results.
614 fn usable_size(&self, layout: &Layout) -> (usize, usize) {
615 (layout.size(), layout.size())
618 // == METHODS FOR MEMORY REUSE ==
619 // realloc. alloc_excess, realloc_excess
621 /// Returns a pointer suitable for holding data described by
622 /// `new_layout`, meeting its size and alignment guarantees. To
623 /// accomplish this, this may extend or shrink the allocation
624 /// referenced by `ptr` to fit `new_layout`.
626 /// If this returns `Ok`, then ownership of the memory block
627 /// referenced by `ptr` has been transferred to this
628 /// allocator. The memory may or may not have been freed, and
629 /// should be considered unusable (unless of course it was
630 /// transferred back to the caller again via the return value of
633 /// If this method returns `Err`, then ownership of the memory
634 /// block has not been transferred to this allocator, and the
635 /// contents of the memory block are unaltered.
637 /// For best results, `new_layout` should not impose a different
638 /// alignment constraint than `layout`. (In other words,
639 /// `new_layout.align()` should equal `layout.align()`.) However,
640 /// behavior is well-defined (though underspecified) when this
641 /// constraint is violated; further discussion below.
645 /// This function is unsafe because undefined behavior can result
646 /// if the caller does not ensure all of the following:
648 /// * `ptr` must be currently allocated via this allocator,
650 /// * `layout` must *fit* the `ptr` (see above). (The `new_layout`
651 /// argument need not fit it.)
653 /// * `new_layout` must have size greater than zero.
655 /// * the alignment of `new_layout` is non-zero.
657 /// (Extension subtraits might provide more specific bounds on
658 /// behavior, e.g. guarantee a sentinel address or a null pointer
659 /// in response to a zero-size allocation request.)
663 /// Returns `Err` only if `new_layout` does not match the
664 /// alignment of `layout`, or does not meet the allocator's size
665 /// and alignment constraints of the allocator, or if reallocation
668 /// (Note the previous sentence did not say "if and only if" -- in
669 /// particular, an implementation of this method *can* return `Ok`
670 /// if `new_layout.align() != old_layout.align()`; or it can
671 /// return `Err` in that scenario, depending on whether this
672 /// allocator can dynamically adjust the alignment constraint for
675 /// Implementations are encouraged to return `Err` on memory
676 /// exhaustion rather than panicking or aborting, but this is not
677 /// a strict requirement. (Specifically: it is *legal* to
678 /// implement this trait atop an underlying native allocation
679 /// library that aborts on memory exhaustion.)
681 /// Clients wishing to abort computation in response to an
682 /// reallocation error are encouraged to call the allocator's `oom`
683 /// method, rather than directly invoking `panic!` or similar.
684 unsafe fn realloc(&mut self,
687 new_layout: Layout) -> Result<*mut u8, AllocErr> {
688 let new_size = new_layout.size();
689 let old_size = layout.size();
690 let aligns_match = layout.align == new_layout.align;
692 if new_size >= old_size && aligns_match {
693 if let Ok(()) = self.grow_in_place(ptr, layout.clone(), new_layout.clone()) {
696 } else if new_size < old_size && aligns_match {
697 if let Ok(()) = self.shrink_in_place(ptr, layout.clone(), new_layout.clone()) {
702 // otherwise, fall back on alloc + copy + dealloc.
703 let result = self.alloc(new_layout);
704 if let Ok(new_ptr) = result {
705 ptr::copy_nonoverlapping(ptr as *const u8, new_ptr, cmp::min(old_size, new_size));
706 self.dealloc(ptr, layout);
711 /// Behaves like `alloc`, but also ensures that the contents
712 /// are set to zero before being returned.
716 /// This function is unsafe for the same reasons that `alloc` is.
720 /// Returning `Err` indicates that either memory is exhausted or
721 /// `layout` does not meet allocator's size or alignment
722 /// constraints, just as in `alloc`.
724 /// Clients wishing to abort computation in response to an
725 /// allocation error are encouraged to call the allocator's `oom`
726 /// method, rather than directly invoking `panic!` or similar.
727 unsafe fn alloc_zeroed(&mut self, layout: Layout) -> Result<*mut u8, AllocErr> {
728 let size = layout.size();
729 let p = self.alloc(layout);
731 ptr::write_bytes(p, 0, size);
736 /// Behaves like `alloc`, but also returns the whole size of
737 /// the returned block. For some `layout` inputs, like arrays, this
738 /// may include extra storage usable for additional data.
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_excess(&mut self, layout: Layout) -> Result<Excess, AllocErr> {
754 let usable_size = self.usable_size(&layout);
755 self.alloc(layout).map(|p| Excess(p, usable_size.1))
758 /// Behaves like `realloc`, but also returns the whole size of
759 /// the returned block. For some `layout` inputs, like arrays, this
760 /// may include extra storage usable for additional data.
764 /// This function is unsafe for the same reasons that `realloc` is.
768 /// Returning `Err` indicates that either memory is exhausted or
769 /// `layout` does not meet allocator's size or alignment
770 /// constraints, just as in `realloc`.
772 /// Clients wishing to abort computation in response to an
773 /// reallocation error are encouraged to call the allocator's `oom`
774 /// method, rather than directly invoking `panic!` or similar.
775 unsafe fn realloc_excess(&mut self,
778 new_layout: Layout) -> Result<Excess, AllocErr> {
779 let usable_size = self.usable_size(&new_layout);
780 self.realloc(ptr, layout, new_layout)
781 .map(|p| Excess(p, usable_size.1))
784 /// Attempts to extend the allocation referenced by `ptr` to fit `new_layout`.
786 /// If this returns `Ok`, then the allocator has asserted that the
787 /// memory block referenced by `ptr` now fits `new_layout`, and thus can
788 /// be used to carry data of that layout. (The allocator is allowed to
789 /// expend effort to accomplish this, such as extending the memory block to
790 /// include successor blocks, or virtual memory tricks.)
792 /// Regardless of what this method returns, ownership of the
793 /// memory block referenced by `ptr` has not been transferred, and
794 /// the contents of the memory block are unaltered.
798 /// This function is unsafe because undefined behavior can result
799 /// if the caller does not ensure all of the following:
801 /// * `ptr` must be currently allocated via this allocator,
803 /// * `layout` must *fit* the `ptr` (see above); note the
804 /// `new_layout` argument need not fit it,
806 /// * `new_layout.size()` must not be less than `layout.size()`,
808 /// * `new_layout.align()` must equal `layout.align()`.
812 /// Returns `Err(CannotReallocInPlace)` when the allocator is
813 /// unable to assert that the memory block referenced by `ptr`
814 /// could fit `layout`.
816 /// Note that one cannot pass `CannotReallocInPlace` to the `oom`
817 /// method; clients are expected either to be able to recover from
818 /// `grow_in_place` failures without aborting, or to fall back on
819 /// another reallocation method before resorting to an abort.
820 unsafe fn grow_in_place(&mut self,
823 new_layout: Layout) -> Result<(), CannotReallocInPlace> {
824 let _ = ptr; // this default implementation doesn't care about the actual address.
825 debug_assert!(new_layout.size >= layout.size);
826 debug_assert!(new_layout.align == layout.align);
827 let (_l, u) = self.usable_size(&layout);
828 // _l <= layout.size() [guaranteed by usable_size()]
829 // layout.size() <= new_layout.size() [required by this method]
830 if new_layout.size <= u {
833 return Err(CannotReallocInPlace);
837 /// Attempts to shrink the allocation referenced by `ptr` to fit `new_layout`.
839 /// If this returns `Ok`, then the allocator has asserted that the
840 /// memory block referenced by `ptr` now fits `new_layout`, and
841 /// thus can only be used to carry data of that smaller
842 /// layout. (The allocator is allowed to take advantage of this,
843 /// carving off portions of the block for reuse elsewhere.) The
844 /// truncated contents of the block within the smaller layout are
845 /// unaltered, and ownership of block has not been transferred.
847 /// If this returns `Err`, then the memory block is considered to
848 /// still represent the original (larger) `layout`. None of the
849 /// block has been carved off for reuse elsewhere, ownership of
850 /// the memory block has not been transferred, and the contents of
851 /// the memory block are unaltered.
855 /// This function is unsafe because undefined behavior can result
856 /// if the caller does not ensure all of the following:
858 /// * `ptr` must be currently allocated via this allocator,
860 /// * `layout` must *fit* the `ptr` (see above); note the
861 /// `new_layout` argument need not fit it,
863 /// * `new_layout.size()` must not be greater than `layout.size()`
864 /// (and must be greater than zero),
866 /// * `new_layout.align()` must equal `layout.align()`.
870 /// Returns `Err(CannotReallocInPlace)` when the allocator is
871 /// unable to assert that the memory block referenced by `ptr`
872 /// could fit `layout`.
874 /// Note that one cannot pass `CannotReallocInPlace` to the `oom`
875 /// method; clients are expected either to be able to recover from
876 /// `shrink_in_place` failures without aborting, or to fall back
877 /// on another reallocation method before resorting to an abort.
878 unsafe fn shrink_in_place(&mut self,
881 new_layout: Layout) -> Result<(), CannotReallocInPlace> {
882 let _ = ptr; // this default implementation doesn't care about the actual address.
883 debug_assert!(new_layout.size <= layout.size);
884 debug_assert!(new_layout.align == layout.align);
885 let (l, _u) = self.usable_size(&layout);
886 // layout.size() <= _u [guaranteed by usable_size()]
887 // new_layout.size() <= layout.size() [required by this method]
888 if l <= new_layout.size {
891 return Err(CannotReallocInPlace);
896 // == COMMON USAGE PATTERNS ==
897 // alloc_one, dealloc_one, alloc_array, realloc_array. dealloc_array
899 /// Allocates a block suitable for holding an instance of `T`.
901 /// Captures a common usage pattern for allocators.
903 /// The returned block is suitable for passing to the
904 /// `alloc`/`realloc` methods of this allocator.
906 /// Note to implementors: If this returns `Ok(ptr)`, then `ptr`
907 /// must be considered "currently allocated" and must be
908 /// acceptable input to methods such as `realloc` or `dealloc`,
909 /// *even if* `T` is a zero-sized type. In other words, if your
910 /// `Alloc` implementation overrides this method in a manner
911 /// that can return a zero-sized `ptr`, then all reallocation and
912 /// deallocation methods need to be similarly overridden to accept
913 /// such values as input.
917 /// Returning `Err` indicates that either memory is exhausted or
918 /// `T` does not meet allocator's size or alignment constraints.
920 /// For zero-sized `T`, may return either of `Ok` or `Err`, but
921 /// will *not* yield undefined behavior.
923 /// Clients wishing to abort computation in response to an
924 /// allocation error are encouraged to call the allocator's `oom`
925 /// method, rather than directly invoking `panic!` or similar.
926 fn alloc_one<T>(&mut self) -> Result<Unique<T>, AllocErr>
929 let k = Layout::new::<T>();
931 unsafe { self.alloc(k).map(|p| Unique::new_unchecked(p as *mut T)) }
933 Err(AllocErr::invalid_input("zero-sized type invalid for alloc_one"))
937 /// Deallocates a block suitable for holding an instance of `T`.
939 /// The given block must have been produced by this allocator,
940 /// and must be suitable for storing a `T` (in terms of alignment
941 /// as well as minimum and maximum size); otherwise yields
942 /// undefined behavior.
944 /// Captures a common usage pattern for allocators.
948 /// This function is unsafe because undefined behavior can result
949 /// if the caller does not ensure both:
951 /// * `ptr` must denote a block of memory currently allocated via this allocator
953 /// * the layout of `T` must *fit* that block of memory.
954 unsafe fn dealloc_one<T>(&mut self, ptr: Unique<T>)
957 let raw_ptr = ptr.as_ptr() as *mut u8;
958 let k = Layout::new::<T>();
960 self.dealloc(raw_ptr, k);
964 /// Allocates a block suitable for holding `n` instances of `T`.
966 /// Captures a common usage pattern for allocators.
968 /// The returned block is suitable for passing to the
969 /// `alloc`/`realloc` methods of this allocator.
971 /// Note to implementors: If this returns `Ok(ptr)`, then `ptr`
972 /// must be considered "currently allocated" and must be
973 /// acceptable input to methods such as `realloc` or `dealloc`,
974 /// *even if* `T` is a zero-sized type. In other words, if your
975 /// `Alloc` implementation overrides this method in a manner
976 /// that can return a zero-sized `ptr`, then all reallocation and
977 /// deallocation methods need to be similarly overridden to accept
978 /// such values as input.
982 /// Returning `Err` indicates that either memory is exhausted or
983 /// `[T; n]` does not meet allocator's size or alignment
986 /// For zero-sized `T` or `n == 0`, may return either of `Ok` or
987 /// `Err`, but will *not* yield undefined behavior.
989 /// Always returns `Err` on arithmetic overflow.
991 /// Clients wishing to abort computation in response to an
992 /// allocation error are encouraged to call the allocator's `oom`
993 /// method, rather than directly invoking `panic!` or similar.
994 fn alloc_array<T>(&mut self, n: usize) -> Result<Unique<T>, AllocErr>
997 match Layout::array::<T>(n) {
998 Some(ref layout) if layout.size() > 0 => {
1000 self.alloc(layout.clone())
1002 Unique::new_unchecked(p as *mut T)
1006 _ => Err(AllocErr::invalid_input("invalid layout for alloc_array")),
1010 /// Reallocates a block previously suitable for holding `n_old`
1011 /// instances of `T`, returning a block suitable for holding
1012 /// `n_new` instances of `T`.
1014 /// Captures a common usage pattern for allocators.
1016 /// The returned block is suitable for passing to the
1017 /// `alloc`/`realloc` methods of this allocator.
1021 /// This function is unsafe because undefined behavior can result
1022 /// if the caller does not ensure all of the following:
1024 /// * `ptr` must be currently allocated via this allocator,
1026 /// * the layout of `[T; n_old]` must *fit* that block of memory.
1030 /// Returning `Err` indicates that either memory is exhausted or
1031 /// `[T; n_new]` does not meet allocator's size or alignment
1034 /// For zero-sized `T` or `n_new == 0`, may return either of `Ok` or
1035 /// `Err`, but will *not* yield undefined behavior.
1037 /// Always returns `Err` on arithmetic overflow.
1039 /// Clients wishing to abort computation in response to an
1040 /// reallocation error are encouraged to call the allocator's `oom`
1041 /// method, rather than directly invoking `panic!` or similar.
1042 unsafe fn realloc_array<T>(&mut self,
1045 n_new: usize) -> Result<Unique<T>, AllocErr>
1048 match (Layout::array::<T>(n_old), Layout::array::<T>(n_new), ptr.as_ptr()) {
1049 (Some(ref k_old), Some(ref k_new), ptr) if k_old.size() > 0 && k_new.size() > 0 => {
1050 self.realloc(ptr as *mut u8, k_old.clone(), k_new.clone())
1051 .map(|p|Unique::new_unchecked(p as *mut T))
1054 Err(AllocErr::invalid_input("invalid layout for realloc_array"))
1059 /// Deallocates a block suitable for holding `n` instances of `T`.
1061 /// Captures a common usage pattern for allocators.
1065 /// This function is unsafe because undefined behavior can result
1066 /// if the caller does not ensure both:
1068 /// * `ptr` must denote a block of memory currently allocated via this allocator
1070 /// * the layout of `[T; n]` must *fit* that block of memory.
1074 /// Returning `Err` indicates that either `[T; n]` or the given
1075 /// memory block does not meet allocator's size or alignment
1078 /// Always returns `Err` on arithmetic overflow.
1079 unsafe fn dealloc_array<T>(&mut self, ptr: Unique<T>, n: usize) -> Result<(), AllocErr>
1082 let raw_ptr = ptr.as_ptr() as *mut u8;
1083 match Layout::array::<T>(n) {
1084 Some(ref k) if k.size() > 0 => {
1085 Ok(self.dealloc(raw_ptr, k.clone()))
1088 Err(AllocErr::invalid_input("invalid layout for dealloc_array"))