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 /// requeusts 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 either of the following conditions
71 /// * `align` must be a power of two,
73 /// * `size`, when rounded up to the nearest multiple of `align`,
74 /// must not overflow (i.e. the rounded value must be less than
76 pub fn from_size_align(size: usize, align: usize) -> Option<Layout> {
77 if !align.is_power_of_two() {
81 // (power-of-two implies align != 0.)
83 // Rounded up size is:
84 // size_rounded_up = (size + align - 1) & !(align - 1);
86 // We know from above that align != 0. If adding (align - 1)
87 // does not overflow, then rounding up will be fine.
89 // Conversely, &-masking with !(align - 1) will subtract off
90 // only low-order-bits. Thus if overflow occurs with the sum,
91 // the &-mask cannot subtract enough to undo that overflow.
93 // Above implies that checking for summation overflow is both
94 // necessary and sufficient.
95 if size > usize::MAX - (align - 1) {
99 Some(Layout { size: size, align: align })
102 /// The minimum size in bytes for a memory block of this layout.
103 pub fn size(&self) -> usize { self.size }
105 /// The minimum byte alignment for a memory block of this layout.
106 pub fn align(&self) -> usize { self.align }
108 /// Constructs a `Layout` suitable for holding a value of type `T`.
109 pub fn new<T>() -> Self {
110 let (size, align) = size_align::<T>();
111 Layout::from_size_align(size, align).unwrap()
114 /// Produces layout describing a record that could be used to
115 /// allocate backing structure for `T` (which could be a trait
116 /// or other unsized type like a slice).
117 pub fn for_value<T: ?Sized>(t: &T) -> Self {
118 let (size, align) = (mem::size_of_val(t), mem::align_of_val(t));
119 Layout::from_size_align(size, align).unwrap()
122 /// Creates a layout describing the record that can hold a value
123 /// of the same layout as `self`, but that also is aligned to
124 /// alignment `align` (measured in bytes).
126 /// If `self` already meets the prescribed alignment, then returns
129 /// Note that this method does not add any padding to the overall
130 /// size, regardless of whether the returned layout has a different
131 /// alignment. In other words, if `K` has size 16, `K.align_to(32)`
132 /// will *still* have size 16.
136 /// Panics if the combination of `self.size` and the given `align`
137 /// violates the conditions listed in `from_size_align`.
138 pub fn align_to(&self, align: usize) -> Self {
139 Layout::from_size_align(self.size, cmp::max(self.align, align)).unwrap()
142 /// Returns the amount of padding we must insert after `self`
143 /// to ensure that the following address will satisfy `align`
144 /// (measured in bytes).
146 /// E.g. if `self.size` is 9, then `self.padding_needed_for(4)`
147 /// returns 3, because that is the minimum number of bytes of
148 /// padding required to get a 4-aligned address (assuming that the
149 /// corresponding memory block starts at a 4-aligned address).
151 /// The return value of this function has no meaning if `align` is
152 /// not a power-of-two.
154 /// Note that the utility of the returned value requires `align`
155 /// to be less than or equal to the alignment of the starting
156 /// address for the whole allocated block of memory. One way to
157 /// satisfy this constraint is to ensure `align <= self.align`.
158 pub fn padding_needed_for(&self, align: usize) -> usize {
159 let len = self.size();
161 // Rounded up value is:
162 // len_rounded_up = (len + align - 1) & !(align - 1);
163 // and then we return the padding difference: `len_rounded_up - len`.
165 // We use modular arithmetic throughout:
167 // 1. align is guaranteed to be > 0, so align - 1 is always
170 // 2. `len + align - 1` can overflow by at most `align - 1`,
171 // so the &-mask wth `!(align - 1)` will ensure that in the
172 // case of overflow, `len_rounded_up` will itself be 0.
173 // Thus the returned padding, when added to `len`, yields 0,
174 // which trivially satisfies the alignment `align`.
176 // (Of course, attempts to allocate blocks of memory whose
177 // size and padding overflow in the above manner should cause
178 // the allocator to yield an error anyway.)
180 let len_rounded_up = len.wrapping_add(align).wrapping_sub(1) & !align.wrapping_sub(1);
181 return len_rounded_up.wrapping_sub(len);
184 /// Creates a layout describing the record for `n` instances of
185 /// `self`, with a suitable amount of padding between each to
186 /// ensure that each instance is given its requested size and
187 /// alignment. On success, returns `(k, offs)` where `k` is the
188 /// layout of the array and `offs` is the distance between the start
189 /// of each element in the array.
191 /// On arithmetic overflow, returns `None`.
192 pub fn repeat(&self, n: usize) -> Option<(Self, usize)> {
193 let padded_size = match self.size.checked_add(self.padding_needed_for(self.align)) {
195 Some(padded_size) => padded_size,
197 let alloc_size = match padded_size.checked_mul(n) {
199 Some(alloc_size) => alloc_size,
202 // We can assume that `self.align` is a power-of-two.
203 // Furthermore, `alloc_size` has alreayd been rounded up
204 // to a multiple of `self.align`; therefore, the call
205 // to `Layout::from_size_align` below should never panic.
206 Some((Layout::from_size_align(alloc_size, self.align).unwrap(), padded_size))
209 /// Creates a layout describing the record for `self` followed by
210 /// `next`, including any necessary padding to ensure that `next`
211 /// will be properly aligned. Note that the result layout will
212 /// satisfy the alignment properties of both `self` and `next`.
214 /// Returns `Some((k, offset))`, where `k` is layout of the concatenated
215 /// record and `offset` is the relative location, in bytes, of the
216 /// start of the `next` embedded witnin the concatenated record
217 /// (assuming that the record itself starts at offset 0).
219 /// On arithmetic overflow, returns `None`.
220 pub fn extend(&self, next: Self) -> Option<(Self, usize)> {
221 let new_align = cmp::max(self.align, next.align);
222 let realigned = match Layout::from_size_align(self.size, new_align) {
227 let pad = realigned.padding_needed_for(next.align);
229 let offset = match self.size.checked_add(pad) {
231 Some(offset) => offset,
233 let new_size = match offset.checked_add(next.size) {
235 Some(new_size) => new_size,
238 let layout = match Layout::from_size_align(new_size, new_align) {
242 Some((layout, offset))
245 /// Creates a layout describing the record for `n` instances of
246 /// `self`, with no padding between each instance.
248 /// Note that, unlike `repeat`, `repeat_packed` does not guarantee
249 /// that the repeated instances of `self` will be properly
250 /// aligned, even if a given instance of `self` is properly
251 /// aligned. In other words, if the layout returned by
252 /// `repeat_packed` is used to allocate an array, it is not
253 /// guaranteed that all elements in the array will be properly
256 /// On arithmetic overflow, returns `None`.
257 pub fn repeat_packed(&self, n: usize) -> Option<Self> {
258 let size = match self.size().checked_mul(n) {
260 Some(scaled) => scaled,
263 Layout::from_size_align(size, self.align)
266 /// Creates a layout describing the record for `self` followed by
267 /// `next` with no additional padding between the two. Since no
268 /// padding is inserted, the alignment of `next` is irrelevant,
269 /// and is not incoporated *at all* into the resulting layout.
271 /// Returns `(k, offset)`, where `k` is layout of the concatenated
272 /// record and `offset` is the relative location, in bytes, of the
273 /// start of the `next` embedded witnin the concatenated record
274 /// (assuming that the record itself starts at offset 0).
276 /// (The `offset` is always the same as `self.size()`; we use this
277 /// signature out of convenience in matching the signature of
280 /// On arithmetic overflow, returns `None`.
281 pub fn extend_packed(&self, next: Self) -> Option<(Self, usize)> {
282 let new_size = match self.size().checked_add(next.size()) {
284 Some(new_size) => new_size,
286 let layout = match Layout::from_size_align(new_size, self.align) {
290 Some((layout, self.size()))
293 /// Creates a layout describing the record for a `[T; n]`.
295 /// On arithmetic overflow, returns `None`.
296 pub fn array<T>(n: usize) -> Option<Self> {
300 debug_assert!(offs == mem::size_of::<T>());
306 /// The `AllocErr` error specifies whether an allocation failure is
307 /// specifically due to resource exhaustion or if it is due to
308 /// something wrong when combining the given input arguments with this
310 #[derive(Clone, PartialEq, Eq, Debug)]
312 /// Error due to hitting some resource limit or otherwise running
313 /// out of memory. This condition strongly implies that *some*
314 /// series of deallocations would allow a subsequent reissuing of
315 /// the original allocation request to succeed.
316 Exhausted { request: Layout },
318 /// Error due to allocator being fundamentally incapable of
319 /// satisfying the original request. This condition implies that
320 /// such an allocation request will never succeed on the given
321 /// allocator, regardless of environment, memory pressure, or
322 /// other contextual conditions.
324 /// For example, an allocator that does not support requests for
325 /// large memory blocks might return this error variant.
326 Unsupported { details: &'static str },
330 pub fn invalid_input(details: &'static str) -> Self {
331 AllocErr::Unsupported { details: details }
333 pub fn is_memory_exhausted(&self) -> bool {
334 if let AllocErr::Exhausted { .. } = *self { true } else { false }
336 pub fn is_request_unsupported(&self) -> bool {
337 if let AllocErr::Unsupported { .. } = *self { true } else { false }
339 pub fn description(&self) -> &str {
341 AllocErr::Exhausted { .. } => "allocator memory exhausted",
342 AllocErr::Unsupported { .. } => "unsupported allocator request",
347 // (we need this for downstream impl of trait Error)
348 impl fmt::Display for AllocErr {
349 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
350 write!(f, "{}", self.description())
354 /// The `CannotReallocInPlace` error is used when `grow_in_place` or
355 /// `shrink_in_place` were unable to reuse the given memory block for
356 /// a requested layout.
357 #[derive(Clone, PartialEq, Eq, Debug)]
358 pub struct CannotReallocInPlace;
360 impl CannotReallocInPlace {
361 pub fn description(&self) -> &str {
362 "cannot reallocate allocator's memory in place"
366 // (we need this for downstream impl of trait Error)
367 impl fmt::Display for CannotReallocInPlace {
368 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
369 write!(f, "{}", self.description())
373 /// An implementation of `Alloc` can allocate, reallocate, and
374 /// deallocate arbitrary blocks of data described via `Layout`.
376 /// Some of the methods require that a memory block be *currently
377 /// allocated* via an allocator. This means that:
379 /// * the starting address for that memory block was previously
380 /// returned by a previous call to an allocation method (`alloc`,
381 /// `alloc_zeroed`, `alloc_excess`, `alloc_one`, `alloc_array`) or
382 /// reallocation method (`realloc`, `realloc_excess`, or
383 /// `realloc_array`), and
385 /// * the memory block has not been subsequently deallocated, where
386 /// blocks are deallocated either by being passed to a deallocation
387 /// method (`dealloc`, `dealloc_one`, `dealloc_array`) or by being
388 /// passed to a reallocation method (see above) that returns `Ok`.
390 /// A note regarding zero-sized types and zero-sized layouts: many
391 /// methods in the `Alloc` trait state that allocation requests
392 /// must be non-zero size, or else undefined behavior can result.
394 /// * However, some higher-level allocation methods (`alloc_one`,
395 /// `alloc_array`) are well-defined on zero-sized types and can
396 /// optionally support them: it is left up to the implementor
397 /// whether to return `Err`, or to return `Ok` with some pointer.
399 /// * If an `Alloc` implementation chooses to return `Ok` in this
400 /// case (i.e. the pointer denotes a zero-sized inaccessible block)
401 /// then that returned pointer must be considered "currently
402 /// allocated". On such an allocator, *all* methods that take
403 /// currently-allocated pointers as inputs must accept these
404 /// zero-sized pointers, *without* causing undefined behavior.
406 /// * In other words, if a zero-sized pointer can flow out of an
407 /// allocator, then that allocator must likewise accept that pointer
408 /// flowing back into its deallocation and reallocation methods.
410 /// Some of the methods require that a layout *fit* a memory block.
411 /// What it means for a layout to "fit" a memory block means (or
412 /// equivalently, for a memory block to "fit" a layout) is that the
413 /// following two conditions must hold:
415 /// 1. The block's starting address must be aligned to `layout.align()`.
417 /// 2. The block's size must fall in the range `[use_min, use_max]`, where:
419 /// * `use_min` is `self.usable_size(layout).0`, and
421 /// * `use_max` is the capacity that was (or would have been)
422 /// returned when (if) the block was allocated via a call to
423 /// `alloc_excess` or `realloc_excess`.
427 /// * the size of the layout most recently used to allocate the block
428 /// is guaranteed to be in the range `[use_min, use_max]`, and
430 /// * a lower-bound on `use_max` can be safely approximated by a call to
433 /// * if a layout `k` fits a memory block (denoted by `ptr`)
434 /// currently allocated via an allocator `a`, then it is legal to
435 /// use that layout to deallocate it, i.e. `a.dealloc(ptr, k);`.
436 pub unsafe trait Alloc {
438 // (Note: existing allocators have unspecified but well-defined
439 // behavior in response to a zero size allocation request ;
440 // e.g. in C, `malloc` of 0 will either return a null pointer or a
441 // unique pointer, but will not have arbitrary undefined
442 // behavior. Rust should consider revising the alloc::heap crate
443 // to reflect this reality.)
445 /// Returns a pointer meeting the size and alignment guarantees of
448 /// If this method returns an `Ok(addr)`, then the `addr` returned
449 /// will be non-null address pointing to a block of storage
450 /// suitable for holding an instance of `layout`.
452 /// The returned block of storage may or may not have its contents
453 /// initialized. (Extension subtraits might restrict this
454 /// behavior, e.g. to ensure initialization to particular sets of
459 /// This function is unsafe because undefined behavior can result
460 /// if the caller does not ensure that `layout` has non-zero size.
462 /// (Extension subtraits might provide more specific bounds on
463 /// behavior, e.g. guarantee a sentinel address or a null pointer
464 /// in response to a zero-size allocation request.)
468 /// Returning `Err` indicates that either memory is exhausted or
469 /// `layout` does not meet allocator's size or alignment
472 /// Implementations are encouraged to return `Err` on memory
473 /// exhaustion rather than panicking or aborting, but this is not
474 /// a strict requirement. (Specifically: it is *legal* to
475 /// implement this trait atop an underlying native allocation
476 /// library that aborts on memory exhaustion.)
478 /// Clients wishing to abort computation in response to an
479 /// allocation error are encouraged to call the allocator's `oom`
480 /// method, rather than directly invoking `panic!` or similar.
481 unsafe fn alloc(&mut self, layout: Layout) -> Result<*mut u8, AllocErr>;
483 /// Deallocate the memory referenced by `ptr`.
487 /// This function is unsafe because undefined behavior can result
488 /// if the caller does not ensure all of the following:
490 /// * `ptr` must denote a block of memory currently allocated via
493 /// * `layout` must *fit* that block of memory,
495 /// * In addition to fitting the block of memory `layout`, the
496 /// alignment of the `layout` must match the alignment used
497 /// to allocate that block of memory.
498 unsafe fn dealloc(&mut self, ptr: *mut u8, layout: Layout);
500 /// Allocator-specific method for signalling an out-of-memory
503 /// `oom` aborts the thread or process, optionally performing
504 /// cleanup or logging diagnostic information before panicking or
507 /// `oom` is meant to be used by clients unable to cope with an
508 /// unsatisfied allocation request (signaled by an error such as
509 /// `AllocErr::Exhausted`), and wish to abandon computation rather
510 /// than attempt to recover locally. Such clients should pass the
511 /// signalling error value back into `oom`, where the allocator
512 /// may incorporate that error value into its diagnostic report
515 /// Implementations of the `oom` method are discouraged from
516 /// infinitely regressing in nested calls to `oom`. In
517 /// practice this means implementors should eschew allocating,
518 /// especially from `self` (directly or indirectly).
520 /// Implementions of the allocation and reallocation methods
521 /// (e.g. `alloc`, `alloc_one`, `realloc`) are discouraged from
522 /// panicking (or aborting) in the event of memory exhaustion;
523 /// instead they should return an appropriate error from the
524 /// invoked method, and let the client decide whether to invoke
525 /// this `oom` method in response.
526 fn oom(&mut self, _: AllocErr) -> ! {
527 unsafe { ::core::intrinsics::abort() }
530 // == ALLOCATOR-SPECIFIC QUANTITIES AND LIMITS ==
533 /// Returns bounds on the guaranteed usable size of a successful
534 /// allocation created with the specified `layout`.
536 /// In particular, if one has a memory block allocated via a given
537 /// allocator `a` and layout `k` where `a.usable_size(k)` returns
538 /// `(l, u)`, then one can pass that block to `a.dealloc()` with a
539 /// layout in the size range [l, u].
541 /// (All implementors of `usable_size` must ensure that
542 /// `l <= k.size() <= u`)
544 /// Both the lower- and upper-bounds (`l` and `u` respectively)
545 /// are provided, because an allocator based on size classes could
546 /// misbehave if one attempts to deallocate a block without
547 /// providing a correct value for its size (i.e., one within the
550 /// Clients who wish to make use of excess capacity are encouraged
551 /// to use the `alloc_excess` and `realloc_excess` instead, as
552 /// this method is constrained to report conservative values that
553 /// serve as valid bounds for *all possible* allocation method
556 /// However, for clients that do not wish to track the capacity
557 /// returned by `alloc_excess` locally, this method is likely to
558 /// produce useful results.
559 fn usable_size(&self, layout: &Layout) -> (usize, usize) {
560 (layout.size(), layout.size())
563 // == METHODS FOR MEMORY REUSE ==
564 // realloc. alloc_excess, realloc_excess
566 /// Returns a pointer suitable for holding data described by
567 /// `new_layout`, meeting its size and alignment guarantees. To
568 /// accomplish this, this may extend or shrink the allocation
569 /// referenced by `ptr` to fit `new_layout`.
571 /// If this returns `Ok`, then ownership of the memory block
572 /// referenced by `ptr` has been transferred to this
573 /// allocator. The memory may or may not have been freed, and
574 /// should be considered unusable (unless of course it was
575 /// transferred back to the caller again via the return value of
578 /// If this method returns `Err`, then ownership of the memory
579 /// block has not been transferred to this allocator, and the
580 /// contents of the memory block are unaltered.
582 /// For best results, `new_layout` should not impose a different
583 /// alignment constraint than `layout`. (In other words,
584 /// `new_layout.align()` should equal `layout.align()`.) However,
585 /// behavior is well-defined (though underspecified) when this
586 /// constraint is violated; further discussion below.
590 /// This function is unsafe because undefined behavior can result
591 /// if the caller does not ensure all of the following:
593 /// * `ptr` must be currently allocated via this allocator,
595 /// * `layout` must *fit* the `ptr` (see above). (The `new_layout`
596 /// argument need not fit it.)
598 /// * `new_layout` must have size greater than zero.
600 /// * the alignment of `new_layout` is non-zero.
602 /// (Extension subtraits might provide more specific bounds on
603 /// behavior, e.g. guarantee a sentinel address or a null pointer
604 /// in response to a zero-size allocation request.)
608 /// Returns `Err` only if `new_layout` does not match the
609 /// alignment of `layout`, or does not meet the allocator's size
610 /// and alignment constraints of the allocator, or if reallocation
613 /// (Note the previous sentence did not say "if and only if" -- in
614 /// particular, an implementation of this method *can* return `Ok`
615 /// if `new_layout.align() != old_layout.align()`; or it can
616 /// return `Err` in that scenario, depending on whether this
617 /// allocator can dynamically adjust the alignment constraint for
620 /// Implementations are encouraged to return `Err` on memory
621 /// exhaustion rather than panicking or aborting, but this is not
622 /// a strict requirement. (Specifically: it is *legal* to
623 /// implement this trait atop an underlying native allocation
624 /// library that aborts on memory exhaustion.)
626 /// Clients wishing to abort computation in response to an
627 /// reallocation error are encouraged to call the allocator's `oom`
628 /// method, rather than directly invoking `panic!` or similar.
629 unsafe fn realloc(&mut self,
632 new_layout: Layout) -> Result<*mut u8, AllocErr> {
633 let new_size = new_layout.size();
634 let old_size = layout.size();
635 let aligns_match = layout.align == new_layout.align;
637 if new_size >= old_size && aligns_match {
638 if let Ok(()) = self.grow_in_place(ptr, layout.clone(), new_layout.clone()) {
641 } else if new_size < old_size && aligns_match {
642 if let Ok(()) = self.shrink_in_place(ptr, layout.clone(), new_layout.clone()) {
647 // otherwise, fall back on alloc + copy + dealloc.
648 let result = self.alloc(new_layout);
649 if let Ok(new_ptr) = result {
650 ptr::copy_nonoverlapping(ptr as *const u8, new_ptr, cmp::min(old_size, new_size));
651 self.dealloc(ptr, layout);
656 /// Behaves like `alloc`, but also ensures that the contents
657 /// are set to zero before being returned.
661 /// This function is unsafe for the same reasons that `alloc` is.
665 /// Returning `Err` indicates that either memory is exhausted or
666 /// `layout` does not meet allocator's size or alignment
667 /// constraints, just as in `alloc`.
669 /// Clients wishing to abort computation in response to an
670 /// allocation error are encouraged to call the allocator's `oom`
671 /// method, rather than directly invoking `panic!` or similar.
672 unsafe fn alloc_zeroed(&mut self, layout: Layout) -> Result<*mut u8, AllocErr> {
673 let size = layout.size();
674 let p = self.alloc(layout);
676 ptr::write_bytes(p, 0, size);
681 /// Behaves like `alloc`, but also returns the whole size of
682 /// the returned block. For some `layout` inputs, like arrays, this
683 /// may include extra storage usable for additional data.
687 /// This function is unsafe for the same reasons that `alloc` is.
691 /// Returning `Err` indicates that either memory is exhausted or
692 /// `layout` does not meet allocator's size or alignment
693 /// constraints, just as in `alloc`.
695 /// Clients wishing to abort computation in response to an
696 /// allocation error are encouraged to call the allocator's `oom`
697 /// method, rather than directly invoking `panic!` or similar.
698 unsafe fn alloc_excess(&mut self, layout: Layout) -> Result<Excess, AllocErr> {
699 let usable_size = self.usable_size(&layout);
700 self.alloc(layout).map(|p| Excess(p, usable_size.1))
703 /// Behaves like `realloc`, but also returns the whole size of
704 /// the returned block. For some `layout` inputs, like arrays, this
705 /// may include extra storage usable for additional data.
709 /// This function is unsafe for the same reasons that `realloc` is.
713 /// Returning `Err` indicates that either memory is exhausted or
714 /// `layout` does not meet allocator's size or alignment
715 /// constraints, just as in `realloc`.
717 /// Clients wishing to abort computation in response to an
718 /// reallocation error are encouraged to call the allocator's `oom`
719 /// method, rather than directly invoking `panic!` or similar.
720 unsafe fn realloc_excess(&mut self,
723 new_layout: Layout) -> Result<Excess, AllocErr> {
724 let usable_size = self.usable_size(&new_layout);
725 self.realloc(ptr, layout, new_layout)
726 .map(|p| Excess(p, usable_size.1))
729 /// Attempts to extend the allocation referenced by `ptr` to fit `new_layout`.
731 /// If this returns `Ok`, then the allocator has asserted that the
732 /// memory block referenced by `ptr` now fits `new_layout`, and thus can
733 /// be used to carry data of that layout. (The allocator is allowed to
734 /// expend effort to accomplish this, such as extending the memory block to
735 /// include successor blocks, or virtual memory tricks.)
737 /// Regardless of what this method returns, ownership of the
738 /// memory block referenced by `ptr` has not been transferred, and
739 /// the contents of the memory block are unaltered.
743 /// This function is unsafe because undefined behavior can result
744 /// if the caller does not ensure all of the following:
746 /// * `ptr` must be currently allocated via this allocator,
748 /// * `layout` must *fit* the `ptr` (see above); note the
749 /// `new_layout` argument need not fit it,
751 /// * `new_layout.size()` must not be less than `layout.size()`,
753 /// * `new_layout.align()` must equal `layout.align()`.
757 /// Returns `Err(CannotReallocInPlace)` when the allocator is
758 /// unable to assert that the memory block referenced by `ptr`
759 /// could fit `layout`.
761 /// Note that one cannot pass `CannotReallocInPlace` to the `oom`
762 /// method; clients are expected either to be able to recover from
763 /// `grow_in_place` failures without aborting, or to fall back on
764 /// another reallocation method before resorting to an abort.
765 unsafe fn grow_in_place(&mut self,
768 new_layout: Layout) -> Result<(), CannotReallocInPlace> {
769 let _ = ptr; // this default implementation doesn't care about the actual address.
770 debug_assert!(new_layout.size >= layout.size);
771 debug_assert!(new_layout.align == layout.align);
772 let (_l, u) = self.usable_size(&layout);
773 // _l <= layout.size() [guaranteed by usable_size()]
774 // layout.size() <= new_layout.size() [required by this method]
775 if new_layout.size <= u {
778 return Err(CannotReallocInPlace);
782 /// Attempts to shrink the allocation referenced by `ptr` to fit `new_layout`.
784 /// If this returns `Ok`, then the allocator has asserted that the
785 /// memory block referenced by `ptr` now fits `new_layout`, and
786 /// thus can only be used to carry data of that smaller
787 /// layout. (The allocator is allowed to take advantage of this,
788 /// carving off portions of the block for reuse elsewhere.) The
789 /// truncated contents of the block within the smaller layout are
790 /// unaltered, and ownership of block has not been transferred.
792 /// If this returns `Err`, then the memory block is considered to
793 /// still represent the original (larger) `layout`. None of the
794 /// block has been carved off for reuse elsewhere, ownership of
795 /// the memory block has not been transferred, and the contents of
796 /// the memory block are unaltered.
800 /// This function is unsafe because undefined behavior can result
801 /// if the caller does not ensure all of the following:
803 /// * `ptr` must be currently allocated via this allocator,
805 /// * `layout` must *fit* the `ptr` (see above); note the
806 /// `new_layout` argument need not fit it,
808 /// * `new_layout.size()` must not be greater than `layout.size()`
809 /// (and must be greater than zero),
811 /// * `new_layout.align()` must equal `layout.align()`.
815 /// Returns `Err(CannotReallocInPlace)` when the allocator is
816 /// unable to assert that the memory block referenced by `ptr`
817 /// could fit `layout`.
819 /// Note that one cannot pass `CannotReallocInPlace` to the `oom`
820 /// method; clients are expected either to be able to recover from
821 /// `shrink_in_place` failures without aborting, or to fall back
822 /// on another reallocation method before resorting to an abort.
823 unsafe fn shrink_in_place(&mut self,
826 new_layout: Layout) -> Result<(), CannotReallocInPlace> {
827 let _ = ptr; // this default implementation doesn't care about the actual address.
828 debug_assert!(new_layout.size <= layout.size);
829 debug_assert!(new_layout.align == layout.align);
830 let (l, _u) = self.usable_size(&layout);
831 // layout.size() <= _u [guaranteed by usable_size()]
832 // new_layout.size() <= layout.size() [required by this method]
833 if l <= new_layout.size {
836 return Err(CannotReallocInPlace);
841 // == COMMON USAGE PATTERNS ==
842 // alloc_one, dealloc_one, alloc_array, realloc_array. dealloc_array
844 /// Allocates a block suitable for holding an instance of `T`.
846 /// Captures a common usage pattern for allocators.
848 /// The returned block is suitable for passing to the
849 /// `alloc`/`realloc` methods of this allocator.
851 /// Note to implementors: If this returns `Ok(ptr)`, then `ptr`
852 /// must be considered "currently allocated" and must be
853 /// acceptable input to methods such as `realloc` or `dealloc`,
854 /// *even if* `T` is a zero-sized type. In other words, if your
855 /// `Alloc` implementation overrides this method in a manner
856 /// that can return a zero-sized `ptr`, then all reallocation and
857 /// deallocation methods need to be similarly overridden to accept
858 /// such values as input.
862 /// Returning `Err` indicates that either memory is exhausted or
863 /// `T` does not meet allocator's size or alignment constraints.
865 /// For zero-sized `T`, may return either of `Ok` or `Err`, but
866 /// will *not* yield undefined behavior.
868 /// Clients wishing to abort computation in response to an
869 /// allocation error are encouraged to call the allocator's `oom`
870 /// method, rather than directly invoking `panic!` or similar.
871 fn alloc_one<T>(&mut self) -> Result<Unique<T>, AllocErr>
874 let k = Layout::new::<T>();
876 unsafe { self.alloc(k).map(|p|Unique::new(*p as *mut T)) }
878 Err(AllocErr::invalid_input("zero-sized type invalid for alloc_one"))
882 /// Deallocates a block suitable for holding an instance of `T`.
884 /// The given block must have been produced by this allocator,
885 /// and must be suitable for storing a `T` (in terms of alignment
886 /// as well as minimum and maximum size); otherwise yields
887 /// undefined behavior.
889 /// Captures a common usage pattern for allocators.
893 /// This function is unsafe because undefined behavior can result
894 /// if the caller does not ensure both:
896 /// * `ptr` must denote a block of memory currently allocated via this allocator
898 /// * the layout of `T` must *fit* that block of memory.
899 unsafe fn dealloc_one<T>(&mut self, ptr: Unique<T>)
902 let raw_ptr = ptr.as_ptr() as *mut u8;
903 let k = Layout::new::<T>();
905 self.dealloc(raw_ptr, k);
909 /// Allocates a block suitable for holding `n` instances of `T`.
911 /// Captures a common usage pattern for allocators.
913 /// The returned block is suitable for passing to the
914 /// `alloc`/`realloc` methods of this allocator.
916 /// Note to implementors: If this returns `Ok(ptr)`, then `ptr`
917 /// must be considered "currently allocated" and must be
918 /// acceptable input to methods such as `realloc` or `dealloc`,
919 /// *even if* `T` is a zero-sized type. In other words, if your
920 /// `Alloc` implementation overrides this method in a manner
921 /// that can return a zero-sized `ptr`, then all reallocation and
922 /// deallocation methods need to be similarly overridden to accept
923 /// such values as input.
927 /// Returning `Err` indicates that either memory is exhausted or
928 /// `[T; n]` does not meet allocator's size or alignment
931 /// For zero-sized `T` or `n == 0`, may return either of `Ok` or
932 /// `Err`, but will *not* yield undefined behavior.
934 /// Always returns `Err` on arithmetic overflow.
936 /// Clients wishing to abort computation in response to an
937 /// allocation error are encouraged to call the allocator's `oom`
938 /// method, rather than directly invoking `panic!` or similar.
939 fn alloc_array<T>(&mut self, n: usize) -> Result<Unique<T>, AllocErr>
942 match Layout::array::<T>(n) {
943 Some(ref layout) if layout.size() > 0 => {
945 self.alloc(layout.clone())
947 Unique::new(p as *mut T)
951 _ => Err(AllocErr::invalid_input("invalid layout for alloc_array")),
955 /// Reallocates a block previously suitable for holding `n_old`
956 /// instances of `T`, returning a block suitable for holding
957 /// `n_new` instances of `T`.
959 /// Captures a common usage pattern for allocators.
961 /// The returned block is suitable for passing to the
962 /// `alloc`/`realloc` methods of this allocator.
966 /// This function is unsafe because undefined behavior can result
967 /// if the caller does not ensure all of the following:
969 /// * `ptr` must be currently allocated via this allocator,
971 /// * the layout of `[T; n_old]` must *fit* that block of memory.
975 /// Returning `Err` indicates that either memory is exhausted or
976 /// `[T; n_new]` does not meet allocator's size or alignment
979 /// For zero-sized `T` or `n_new == 0`, may return either of `Ok` or
980 /// `Err`, but will *not* yield undefined behavior.
982 /// Always returns `Err` on arithmetic overflow.
984 /// Clients wishing to abort computation in response to an
985 /// reallocation error are encouraged to call the allocator's `oom`
986 /// method, rather than directly invoking `panic!` or similar.
987 unsafe fn realloc_array<T>(&mut self,
990 n_new: usize) -> Result<Unique<T>, AllocErr>
993 match (Layout::array::<T>(n_old), Layout::array::<T>(n_new), ptr.as_ptr()) {
994 (Some(ref k_old), Some(ref k_new), ptr) if k_old.size() > 0 && k_new.size() > 0 => {
995 self.realloc(ptr as *mut u8, k_old.clone(), k_new.clone())
996 .map(|p|Unique::new(p as *mut T))
999 Err(AllocErr::invalid_input("invalid layout for realloc_array"))
1004 /// Deallocates a block suitable for holding `n` instances of `T`.
1006 /// Captures a common usage pattern for allocators.
1010 /// This function is unsafe because undefined behavior can result
1011 /// if the caller does not ensure both:
1013 /// * `ptr` must denote a block of memory currently allocated via this allocator
1015 /// * the layout of `[T; n]` must *fit* that block of memory.
1019 /// Returning `Err` indicates that either `[T; n]` or the given
1020 /// memory block does not meet allocator's size or alignment
1023 /// Always returns `Err` on arithmetic overflow.
1024 unsafe fn dealloc_array<T>(&mut self, ptr: Unique<T>, n: usize) -> Result<(), AllocErr>
1027 let raw_ptr = ptr.as_ptr() as *mut u8;
1028 match Layout::array::<T>(n) {
1029 Some(ref k) if k.size() > 0 => {
1030 Ok(self.dealloc(raw_ptr, k.clone()))
1033 Err(AllocErr::invalid_input("invalid layout for dealloc_array"))