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",
21 use core::ptr::{self, Unique};
23 /// Represents the combination of a starting address and
24 /// a total capacity of the returned block.
26 pub struct Excess(pub *mut u8, pub usize);
28 fn size_align<T>() -> (usize, usize) {
29 (mem::size_of::<T>(), mem::align_of::<T>())
32 /// Layout of a block of memory.
34 /// An instance of `Layout` describes a particular layout of memory.
35 /// You build a `Layout` up as an input to give to an allocator.
37 /// All layouts have an associated non-negative size and a
38 /// power-of-two alignment.
40 /// (Note however that layouts are *not* required to have positive
41 /// size, even though many allocators require that all memory
42 /// requeusts have positive size. A caller to the `Alloc::alloc`
43 /// method must either ensure that conditions like this are met, or
44 /// use specific allocators with looser requirements.)
45 #[derive(Clone, Debug, PartialEq, Eq)]
47 // size of the requested block of memory, measured in bytes.
50 // alignment of the requested block of memory, measured in bytes.
51 // we ensure that this is always a power-of-two, because API's
52 // like `posix_memalign` require it and it is a reasonable
53 // constraint to impose on Layout constructors.
55 // (However, we do not analogously require `align >= sizeof(void*)`,
56 // even though that is *also* a requirement of `posix_memalign`.)
61 // FIXME: audit default implementations for overflow errors,
62 // (potentially switching to overflowing_add and
63 // overflowing_mul as necessary).
66 /// Constructs a `Layout` from a given `size` and `align`.
70 /// Panics if any of the following conditions are not met:
72 /// * `align` must be a power of two,
74 /// * `size`, when rounded up to the nearest multiple of `align`,
75 /// must not overflow (i.e. the rounded value must be less than
77 pub fn from_size_align(size: usize, align: usize) -> Layout {
78 assert!(align.is_power_of_two()); // (this implies align != 0.)
80 // Rounded up size is:
81 // size_rounded_up = (size + align - 1) & !(align - 1);
83 // We know from above that align != 0. If adding (align - 1)
84 // does not overflow, then rounding up will be fine.
86 // Conversely, &-masking with !(align - 1) will subtract off
87 // only low-order-bits. Thus if overflow occurs with the sum,
88 // the &-mask cannot subtract enough to undo that overflow.
90 // Above implies that checking for summation overflow is both
91 // necessary and sufficient.
92 assert!(size <= usize::MAX - (align - 1));
94 Layout { size: size, align: align }
97 /// The minimum size in bytes for a memory block of this layout.
98 pub fn size(&self) -> usize { self.size }
100 /// The minimum byte alignment for a memory block of this layout.
101 pub fn align(&self) -> usize { self.align }
103 /// Constructs a `Layout` suitable for holding a value of type `T`.
104 pub fn new<T>() -> Self {
105 let (size, align) = size_align::<T>();
106 Layout::from_size_align(size, align)
109 /// Produces layout describing a record that could be used to
110 /// allocate backing structure for `T` (which could be a trait
111 /// or other unsized type like a slice).
112 pub fn for_value<T: ?Sized>(t: &T) -> Self {
113 let (size, align) = (mem::size_of_val(t), mem::align_of_val(t));
114 Layout::from_size_align(size, align)
117 /// Creates a layout describing the record that can hold a value
118 /// of the same layout as `self`, but that also is aligned to
119 /// alignment `align` (measured in bytes).
121 /// If `self` already meets the prescribed alignment, then returns
124 /// Note that this method does not add any padding to the overall
125 /// size, regardless of whether the returned layout has a different
126 /// alignment. In other words, if `K` has size 16, `K.align_to(32)`
127 /// will *still* have size 16.
131 /// Panics if `align` is not a power of two.
132 pub fn align_to(&self, align: usize) -> Self {
133 assert!(align.is_power_of_two());
134 Layout::from_size_align(self.size, cmp::max(self.align, align))
137 /// Returns the amount of padding we must insert after `self`
138 /// to ensure that the following address will satisfy `align`
139 /// (measured in bytes).
141 /// E.g. if `self.size` is 9, then `self.padding_needed_for(4)`
142 /// returns 3, because that is the minimum number of bytes of
143 /// padding required to get a 4-aligned address (assuming that the
144 /// corresponding memory block starts at a 4-aligned address).
146 /// The return value of this function has no meaning if `align` is
147 /// not a power-of-two.
149 /// Note that the utility of the returned value requires `align`
150 /// to be less than or equal to the alignment of the starting
151 /// address for the whole allocated block of memory. One way to
152 /// satisfy this constraint is to ensure `align <= self.align`.
153 pub fn padding_needed_for(&self, align: usize) -> usize {
154 let len = self.size();
156 // Rounded up value is:
157 // len_rounded_up = (len + align - 1) & !(align - 1);
158 // and then we return the padding difference: `len_rounded_up - len`.
160 // We use modular arithmetic throughout:
162 // 1. align is guaranteed to be > 0, so align - 1 is always
165 // 2. `len + align - 1` can overflow by at most `align - 1`,
166 // so the &-mask wth `!(align - 1)` will ensure that in the
167 // case of overflow, `len_rounded_up` will itself be 0.
168 // Thus the returned padding, when added to `len`, yields 0,
169 // which trivially satisfies the alignment `align`.
171 // (Of course, attempts to allocate blocks of memory whose
172 // size and padding overflow in the above manner should cause
173 // the allocator to yield an error anyway.)
175 let len_rounded_up = len.wrapping_add(align).wrapping_sub(1) & !align.wrapping_sub(1);
176 return len_rounded_up.wrapping_sub(len);
179 /// Creates a layout describing the record for `n` instances of
180 /// `self`, with a suitable amount of padding between each to
181 /// ensure that each instance is given its requested size and
182 /// alignment. On success, returns `(k, offs)` where `k` is the
183 /// layout of the array and `offs` is the distance between the start
184 /// of each element in the array.
186 /// On arithmetic overflow, returns `None`.
187 pub fn repeat(&self, n: usize) -> Option<(Self, usize)> {
188 let padded_size = match self.size.checked_add(self.padding_needed_for(self.align)) {
190 Some(padded_size) => padded_size,
192 let alloc_size = match padded_size.checked_mul(n) {
194 Some(alloc_size) => alloc_size,
196 Some((Layout::from_size_align(alloc_size, self.align), padded_size))
199 /// Creates a layout describing the record for `self` followed by
200 /// `next`, including any necessary padding to ensure that `next`
201 /// will be properly aligned. Note that the result layout will
202 /// satisfy the alignment properties of both `self` and `next`.
204 /// Returns `Some((k, offset))`, where `k` is layout of the concatenated
205 /// record and `offset` is the relative location, in bytes, of the
206 /// start of the `next` embedded witnin the concatenated record
207 /// (assuming that the record itself starts at offset 0).
209 /// On arithmetic overflow, returns `None`.
210 pub fn extend(&self, next: Self) -> Option<(Self, usize)> {
211 let new_align = cmp::max(self.align, next.align);
212 let realigned = Layout::from_size_align(self.size, new_align);
213 let pad = realigned.padding_needed_for(next.align);
214 let offset = match self.size.checked_add(pad) {
216 Some(offset) => offset,
218 let new_size = match offset.checked_add(next.size) {
220 Some(new_size) => new_size,
222 Some((Layout::from_size_align(new_size, new_align), offset))
225 /// Creates a layout describing the record for `n` instances of
226 /// `self`, with no padding between each instance.
228 /// Note that, unlike `repeat`, `repeat_packed` does not guarantee
229 /// that the repeated instances of `self` will be properly
230 /// aligned, even if a given instance of `self` is properly
231 /// aligned. In other words, if the layout returned by
232 /// `repeat_packed` is used to allocate an array, it is not
233 /// guaranteed that all elements in the array will be properly
236 /// On arithmetic overflow, returns `None`.
237 pub fn repeat_packed(&self, n: usize) -> Option<Self> {
238 let size = match self.size().checked_mul(n) {
240 Some(scaled) => scaled,
242 Some(Layout::from_size_align(size, self.align))
245 /// Creates a layout describing the record for `self` followed by
246 /// `next` with no additional padding between the two. Since no
247 /// padding is inserted, the alignment of `next` is irrelevant,
248 /// and is not incoporated *at all* into the resulting layout.
250 /// Returns `(k, offset)`, where `k` is layout of the concatenated
251 /// record and `offset` is the relative location, in bytes, of the
252 /// start of the `next` embedded witnin the concatenated record
253 /// (assuming that the record itself starts at offset 0).
255 /// (The `offset` is always the same as `self.size()`; we use this
256 /// signature out of convenience in matching the signature of
259 /// On arithmetic overflow, returns `None`.
260 pub fn extend_packed(&self, next: Self) -> Option<(Self, usize)> {
261 let new_size = match self.size().checked_add(next.size()) {
263 Some(new_size) => new_size,
265 Some((Layout::from_size_align(new_size, self.align), self.size()))
268 /// Creates a layout describing the record for a `[T; n]`.
270 /// On arithmetic overflow, returns `None`.
271 pub fn array<T>(n: usize) -> Option<Self> {
275 debug_assert!(offs == mem::size_of::<T>());
281 /// The `AllocErr` error specifies whether an allocation failure is
282 /// specifically due to resource exhaustion or if it is due to
283 /// something wrong when combining the given input arguments with this
285 #[derive(Clone, PartialEq, Eq, Debug)]
287 /// Error due to hitting some resource limit or otherwise running
288 /// out of memory. This condition strongly implies that *some*
289 /// series of deallocations would allow a subsequent reissuing of
290 /// the original allocation request to succeed.
291 Exhausted { request: Layout },
293 /// Error due to allocator being fundamentally incapable of
294 /// satisfying the original request. This condition implies that
295 /// such an allocation request will never succeed on the given
296 /// allocator, regardless of environment, memory pressure, or
297 /// other contextual conditions.
299 /// For example, an allocator that does not support requests for
300 /// large memory blocks might return this error variant.
301 Unsupported { details: &'static str },
305 pub fn invalid_input(details: &'static str) -> Self {
306 AllocErr::Unsupported { details: details }
308 pub fn is_memory_exhausted(&self) -> bool {
309 if let AllocErr::Exhausted { .. } = *self { true } else { false }
311 pub fn is_request_unsupported(&self) -> bool {
312 if let AllocErr::Unsupported { .. } = *self { true } else { false }
316 /// The `CannotReallocInPlace` error is used when `grow_in_place` or
317 /// `shrink_in_place` were unable to reuse the given memory block for
318 /// a requested layout.
319 #[derive(Clone, PartialEq, Eq, Debug)]
320 pub struct CannotReallocInPlace;
322 /// An implementation of `Alloc` can allocate, reallocate, and
323 /// deallocate arbitrary blocks of data described via `Layout`.
325 /// Some of the methods require that a memory block be *currently
326 /// allocated* via an allocator. This means that:
328 /// * the starting address for that memory block was previously
329 /// returned by a previous call to an allocation method (`alloc`,
330 /// `alloc_zeroed`, `alloc_excess`, `alloc_one`, `alloc_array`) or
331 /// reallocation method (`realloc`, `realloc_excess`, or
332 /// `realloc_array`), and
334 /// * the memory block has not been subsequently deallocated, where
335 /// blocks are deallocated either by being passed to a deallocation
336 /// method (`dealloc`, `dealloc_one`, `dealloc_array`) or by being
337 /// passed to a reallocation method (see above) that returns `Ok`.
339 /// A note regarding zero-sized types and zero-sized layouts: many
340 /// methods in the `Alloc` trait state that allocation requests
341 /// must be non-zero size, or else undefined behavior can result.
343 /// * However, some higher-level allocation methods (`alloc_one`,
344 /// `alloc_array`) are well-defined on zero-sized types and can
345 /// optionally support them: it is left up to the implementor
346 /// whether to return `Err`, or to return `Ok` with some pointer.
348 /// * If an `Alloc` implementation chooses to return `Ok` in this
349 /// case (i.e. the pointer denotes a zero-sized inaccessible block)
350 /// then that returned pointer must be considered "currently
351 /// allocated". On such an allocator, *all* methods that take
352 /// currently-allocated pointers as inputs must accept these
353 /// zero-sized pointers, *without* causing undefined behavior.
355 /// * In other words, if a zero-sized pointer can flow out of an
356 /// allocator, then that allocator must likewise accept that pointer
357 /// flowing back into its deallocation and reallocation methods.
359 /// Some of the methods require that a layout *fit* a memory block.
360 /// What it means for a layout to "fit" a memory block means (or
361 /// equivalently, for a memory block to "fit" a layout) is that the
362 /// following two conditions must hold:
364 /// 1. The block's starting address must be aligned to `layout.align()`.
366 /// 2. The block's size must fall in the range `[use_min, use_max]`, where:
368 /// * `use_min` is `self.usable_size(layout).0`, and
370 /// * `use_max` is the capacity that was (or would have been)
371 /// returned when (if) the block was allocated via a call to
372 /// `alloc_excess` or `realloc_excess`.
376 /// * the size of the layout most recently used to allocate the block
377 /// is guaranteed to be in the range `[use_min, use_max]`, and
379 /// * a lower-bound on `use_max` can be safely approximated by a call to
382 /// * if a layout `k` fits a memory block (denoted by `ptr`)
383 /// currently allocated via an allocator `a`, then it is legal to
384 /// use that layout to deallocate it, i.e. `a.dealloc(ptr, k);`.
385 pub unsafe trait Alloc {
387 // (Note: existing allocators have unspecified but well-defined
388 // behavior in response to a zero size allocation request ;
389 // e.g. in C, `malloc` of 0 will either return a null pointer or a
390 // unique pointer, but will not have arbitrary undefined
391 // behavior. Rust should consider revising the alloc::heap crate
392 // to reflect this reality.)
394 /// Returns a pointer meeting the size and alignment guarantees of
397 /// If this method returns an `Ok(addr)`, then the `addr` returned
398 /// will be non-null address pointing to a block of storage
399 /// suitable for holding an instance of `layout`.
401 /// The returned block of storage may or may not have its contents
402 /// initialized. (Extension subtraits might restrict this
403 /// behavior, e.g. to ensure initialization to particular sets of
408 /// This function is unsafe because undefined behavior can result
409 /// if the caller does not ensure that `layout` has non-zero size.
411 /// (Extension subtraits might provide more specific bounds on
412 /// behavior, e.g. guarantee a sentinel address or a null pointer
413 /// in response to a zero-size allocation request.)
417 /// Returning `Err` indicates that either memory is exhausted or
418 /// `layout` does not meet allocator's size or alignment
421 /// Implementations are encouraged to return `Err` on memory
422 /// exhaustion rather than panicking or aborting, but this is not
423 /// a strict requirement. (Specifically: it is *legal* to
424 /// implement this trait atop an underlying native allocation
425 /// library that aborts on memory exhaustion.)
427 /// Clients wishing to abort computation in response to an
428 /// allocation error are encouraged to call the allocator's `oom`
429 /// method, rather than directly invoking `panic!` or similar.
430 unsafe fn alloc(&mut self, layout: Layout) -> Result<*mut u8, AllocErr>;
432 /// Deallocate the memory referenced by `ptr`.
436 /// This function is unsafe because undefined behavior can result
437 /// if the caller does not ensure all of the following:
439 /// * `ptr` must denote a block of memory currently allocated via
442 /// * `layout` must *fit* that block of memory,
444 /// * In addition to fitting the block of memory `layout`, the
445 /// alignment of the `layout` must match the alignment used
446 /// to allocate that block of memory.
447 unsafe fn dealloc(&mut self, ptr: *mut u8, layout: Layout);
449 /// Allocator-specific method for signalling an out-of-memory
452 /// `oom` aborts the thread or process, optionally performing
453 /// cleanup or logging diagnostic information before panicking or
456 /// `oom` is meant to be used by clients unable to cope with an
457 /// unsatisfied allocation request (signaled by an error such as
458 /// `AllocErr::Exhausted`), and wish to abandon computation rather
459 /// than attempt to recover locally. Such clients should pass the
460 /// signalling error value back into `oom`, where the allocator
461 /// may incorporate that error value into its diagnostic report
464 /// Implementations of the `oom` method are discouraged from
465 /// infinitely regressing in nested calls to `oom`. In
466 /// practice this means implementors should eschew allocating,
467 /// especially from `self` (directly or indirectly).
469 /// Implementions of the allocation and reallocation methods
470 /// (e.g. `alloc`, `alloc_one`, `realloc`) are discouraged from
471 /// panicking (or aborting) in the event of memory exhaustion;
472 /// instead they should return an appropriate error from the
473 /// invoked method, and let the client decide whether to invoke
474 /// this `oom` method in response.
475 fn oom(&mut self, _: AllocErr) -> ! {
476 unsafe { ::core::intrinsics::abort() }
479 // == ALLOCATOR-SPECIFIC QUANTITIES AND LIMITS ==
482 /// Returns bounds on the guaranteed usable size of a successful
483 /// allocation created with the specified `layout`.
485 /// In particular, if one has a memory block allocated via a given
486 /// allocator `a` and layout `k` where `a.usable_size(k)` returns
487 /// `(l, u)`, then one can pass that block to `a.dealloc()` with a
488 /// layout in the size range [l, u].
490 /// (All implementors of `usable_size` must ensure that
491 /// `l <= k.size() <= u`)
493 /// Both the lower- and upper-bounds (`l` and `u` respectively)
494 /// are provided, because an allocator based on size classes could
495 /// misbehave if one attempts to deallocate a block without
496 /// providing a correct value for its size (i.e., one within the
499 /// Clients who wish to make use of excess capacity are encouraged
500 /// to use the `alloc_excess` and `realloc_excess` instead, as
501 /// this method is constrained to report conservative values that
502 /// serve as valid bounds for *all possible* allocation method
505 /// However, for clients that do not wish to track the capacity
506 /// returned by `alloc_excess` locally, this method is likely to
507 /// produce useful results.
508 fn usable_size(&self, layout: &Layout) -> (usize, usize) {
509 (layout.size(), layout.size())
512 // == METHODS FOR MEMORY REUSE ==
513 // realloc. alloc_excess, realloc_excess
515 /// Returns a pointer suitable for holding data described by
516 /// `new_layout`, meeting its size and alignment guarantees. To
517 /// accomplish this, this may extend or shrink the allocation
518 /// referenced by `ptr` to fit `new_layout`.
520 /// If this returns `Ok`, then ownership of the memory block
521 /// referenced by `ptr` has been transferred to this
522 /// allocator. The memory may or may not have been freed, and
523 /// should be considered unusable (unless of course it was
524 /// transferred back to the caller again via the return value of
527 /// If this method returns `Err`, then ownership of the memory
528 /// block has not been transferred to this allocator, and the
529 /// contents of the memory block are unaltered.
531 /// For best results, `new_layout` should not impose a different
532 /// alignment constraint than `layout`. (In other words,
533 /// `new_layout.align()` should equal `layout.align()`.) However,
534 /// behavior is well-defined (though underspecified) when this
535 /// constraint is violated; further discussion below.
539 /// This function is unsafe because undefined behavior can result
540 /// if the caller does not ensure all of the following:
542 /// * `ptr` must be currently allocated via this allocator,
544 /// * `layout` must *fit* the `ptr` (see above). (The `new_layout`
545 /// argument need not fit it.)
547 /// * `new_layout` must have size greater than zero.
549 /// * the alignment of `new_layout` is non-zero.
551 /// (Extension subtraits might provide more specific bounds on
552 /// behavior, e.g. guarantee a sentinel address or a null pointer
553 /// in response to a zero-size allocation request.)
557 /// Returns `Err` only if `new_layout` does not match the
558 /// alignment of `layout`, or does not meet the allocator's size
559 /// and alignment constraints of the allocator, or if reallocation
562 /// (Note the previous sentence did not say "if and only if" -- in
563 /// particular, an implementation of this method *can* return `Ok`
564 /// if `new_layout.align() != old_layout.align()`; or it can
565 /// return `Err` in that scenario, depending on whether this
566 /// allocator can dynamically adjust the alignment constraint for
569 /// Implementations are encouraged to return `Err` on memory
570 /// exhaustion rather than panicking or aborting, but this is not
571 /// a strict requirement. (Specifically: it is *legal* to
572 /// implement this trait atop an underlying native allocation
573 /// library that aborts on memory exhaustion.)
575 /// Clients wishing to abort computation in response to an
576 /// reallocation error are encouraged to call the allocator's `oom`
577 /// method, rather than directly invoking `panic!` or similar.
578 unsafe fn realloc(&mut self,
581 new_layout: Layout) -> Result<*mut u8, AllocErr> {
582 let new_size = new_layout.size();
583 let old_size = layout.size();
584 let aligns_match = layout.align == new_layout.align;
586 if new_size >= old_size && aligns_match {
587 if let Ok(()) = self.grow_in_place(ptr, layout.clone(), new_layout.clone()) {
590 } else if new_size < old_size && aligns_match {
591 if let Ok(()) = self.shrink_in_place(ptr, layout.clone(), new_layout.clone()) {
596 // otherwise, fall back on alloc + copy + dealloc.
597 let result = self.alloc(new_layout);
598 if let Ok(new_ptr) = result {
599 ptr::copy_nonoverlapping(ptr as *const u8, new_ptr, cmp::min(old_size, new_size));
600 self.dealloc(ptr, layout);
605 /// Behaves like `alloc`, but also ensures that the contents
606 /// are set to zero before being returned.
610 /// This function is unsafe for the same reasons that `alloc` is.
614 /// Returning `Err` indicates that either memory is exhausted or
615 /// `layout` does not meet allocator's size or alignment
616 /// constraints, just as in `alloc`.
618 /// Clients wishing to abort computation in response to an
619 /// allocation error are encouraged to call the allocator's `oom`
620 /// method, rather than directly invoking `panic!` or similar.
621 unsafe fn alloc_zeroed(&mut self, layout: Layout) -> Result<*mut u8, AllocErr> {
622 let size = layout.size();
623 let p = self.alloc(layout);
625 ptr::write_bytes(p, 0, size);
630 /// Behaves like `alloc`, but also returns the whole size of
631 /// the returned block. For some `layout` inputs, like arrays, this
632 /// may include extra storage usable for additional data.
636 /// This function is unsafe for the same reasons that `alloc` is.
640 /// Returning `Err` indicates that either memory is exhausted or
641 /// `layout` does not meet allocator's size or alignment
642 /// constraints, just as in `alloc`.
644 /// Clients wishing to abort computation in response to an
645 /// allocation error are encouraged to call the allocator's `oom`
646 /// method, rather than directly invoking `panic!` or similar.
647 unsafe fn alloc_excess(&mut self, layout: Layout) -> Result<Excess, AllocErr> {
648 let usable_size = self.usable_size(&layout);
649 self.alloc(layout).map(|p| Excess(p, usable_size.1))
652 /// Behaves like `realloc`, but also returns the whole size of
653 /// the returned block. For some `layout` inputs, like arrays, this
654 /// may include extra storage usable for additional data.
658 /// This function is unsafe for the same reasons that `realloc` is.
662 /// Returning `Err` indicates that either memory is exhausted or
663 /// `layout` does not meet allocator's size or alignment
664 /// constraints, just as in `realloc`.
666 /// Clients wishing to abort computation in response to an
667 /// reallocation error are encouraged to call the allocator's `oom`
668 /// method, rather than directly invoking `panic!` or similar.
669 unsafe fn realloc_excess(&mut self,
672 new_layout: Layout) -> Result<Excess, AllocErr> {
673 let usable_size = self.usable_size(&new_layout);
674 self.realloc(ptr, layout, new_layout)
675 .map(|p| Excess(p, usable_size.1))
678 /// Attempts to extend the allocation referenced by `ptr` to fit `new_layout`.
680 /// If this returns `Ok`, then the allocator has asserted that the
681 /// memory block referenced by `ptr` now fits `new_layout`, and thus can
682 /// be used to carry data of that layout. (The allocator is allowed to
683 /// expend effort to accomplish this, such as extending the memory block to
684 /// include successor blocks, or virtual memory tricks.)
686 /// Regardless of what this method returns, ownership of the
687 /// memory block referenced by `ptr` has not been transferred, and
688 /// the contents of the memory block are unaltered.
692 /// This function is unsafe because undefined behavior can result
693 /// if the caller does not ensure all of the following:
695 /// * `ptr` must be currently allocated via this allocator,
697 /// * `layout` must *fit* the `ptr` (see above); note the
698 /// `new_layout` argument need not fit it,
700 /// * `new_layout.size()` must not be less than `layout.size()`,
702 /// * `new_layout.align()` must equal `layout.align()`.
706 /// Returns `Err(CannotReallocInPlace)` when the allocator is
707 /// unable to assert that the memory block referenced by `ptr`
708 /// could fit `layout`.
710 /// Note that one cannot pass `CannotReallocInPlace` to the `oom`
711 /// method; clients are expected either to be able to recover from
712 /// `grow_in_place` failures without aborting, or to fall back on
713 /// another reallocation method before resorting to an abort.
714 unsafe fn grow_in_place(&mut self,
717 new_layout: Layout) -> Result<(), CannotReallocInPlace> {
718 let _ = ptr; // this default implementation doesn't care about the actual address.
719 debug_assert!(new_layout.size >= layout.size);
720 debug_assert!(new_layout.align == layout.align);
721 let (_l, u) = self.usable_size(&layout);
722 // _l <= layout.size() [guaranteed by usable_size()]
723 // layout.size() <= new_layout.size() [required by this method]
724 if new_layout.size <= u {
727 return Err(CannotReallocInPlace);
731 /// Attempts to shrink the allocation referenced by `ptr` to fit `new_layout`.
733 /// If this returns `Ok`, then the allocator has asserted that the
734 /// memory block referenced by `ptr` now fits `new_layout`, and
735 /// thus can only be used to carry data of that smaller
736 /// layout. (The allocator is allowed to take advantage of this,
737 /// carving off portions of the block for reuse elsewhere.) The
738 /// truncated contents of the block within the smaller layout are
739 /// unaltered, and ownership of block has not been transferred.
741 /// If this returns `Err`, then the memory block is considered to
742 /// still represent the original (larger) `layout`. None of the
743 /// block has been carved off for reuse elsewhere, ownership of
744 /// the memory block has not been transferred, and the contents of
745 /// the memory block are unaltered.
749 /// This function is unsafe because undefined behavior can result
750 /// if the caller does not ensure all of the following:
752 /// * `ptr` must be currently allocated via this allocator,
754 /// * `layout` must *fit* the `ptr` (see above); note the
755 /// `new_layout` argument need not fit it,
757 /// * `new_layout.size()` must not be greater than `layout.size()`
758 /// (and must be greater than zero),
760 /// * `new_layout.align()` must equal `layout.align()`.
764 /// Returns `Err(CannotReallocInPlace)` when the allocator is
765 /// unable to assert that the memory block referenced by `ptr`
766 /// could fit `layout`.
768 /// Note that one cannot pass `CannotReallocInPlace` to the `oom`
769 /// method; clients are expected either to be able to recover from
770 /// `shrink_in_place` failures without aborting, or to fall back
771 /// on another reallocation method before resorting to an abort.
772 unsafe fn shrink_in_place(&mut self,
775 new_layout: Layout) -> Result<(), CannotReallocInPlace> {
776 let _ = ptr; // this default implementation doesn't care about the actual address.
777 debug_assert!(new_layout.size <= layout.size);
778 debug_assert!(new_layout.align == layout.align);
779 let (l, _u) = self.usable_size(&layout);
780 // layout.size() <= _u [guaranteed by usable_size()]
781 // new_layout.size() <= layout.size() [required by this method]
782 if l <= new_layout.size {
785 return Err(CannotReallocInPlace);
790 // == COMMON USAGE PATTERNS ==
791 // alloc_one, dealloc_one, alloc_array, realloc_array. dealloc_array
793 /// Allocates a block suitable for holding an instance of `T`.
795 /// Captures a common usage pattern for allocators.
797 /// The returned block is suitable for passing to the
798 /// `alloc`/`realloc` methods of this allocator.
800 /// Note to implementors: If this returns `Ok(ptr)`, then `ptr`
801 /// must be considered "currently allocated" and must be
802 /// acceptable input to methods such as `realloc` or `dealloc`,
803 /// *even if* `T` is a zero-sized type. In other words, if your
804 /// `Alloc` implementation overrides this method in a manner
805 /// that can return a zero-sized `ptr`, then all reallocation and
806 /// deallocation methods need to be similarly overridden to accept
807 /// such values as input.
811 /// Returning `Err` indicates that either memory is exhausted or
812 /// `T` does not meet allocator's size or alignment constraints.
814 /// For zero-sized `T`, may return either of `Ok` or `Err`, but
815 /// will *not* yield undefined behavior.
817 /// Clients wishing to abort computation in response to an
818 /// allocation error are encouraged to call the allocator's `oom`
819 /// method, rather than directly invoking `panic!` or similar.
820 fn alloc_one<T>(&mut self) -> Result<Unique<T>, AllocErr>
823 let k = Layout::new::<T>();
825 unsafe { self.alloc(k).map(|p|Unique::new(*p as *mut T)) }
827 Err(AllocErr::invalid_input("zero-sized type invalid for alloc_one"))
831 /// Deallocates a block suitable for holding an instance of `T`.
833 /// The given block must have been produced by this allocator,
834 /// and must be suitable for storing a `T` (in terms of alignment
835 /// as well as minimum and maximum size); otherwise yields
836 /// undefined behavior.
838 /// Captures a common usage pattern for allocators.
842 /// This function is unsafe because undefined behavior can result
843 /// if the caller does not ensure both:
845 /// * `ptr` must denote a block of memory currently allocated via this allocator
847 /// * the layout of `T` must *fit* that block of memory.
848 unsafe fn dealloc_one<T>(&mut self, ptr: Unique<T>)
851 let raw_ptr = ptr.as_ptr() as *mut u8;
852 let k = Layout::new::<T>();
854 self.dealloc(raw_ptr, k);
858 /// Allocates a block suitable for holding `n` instances of `T`.
860 /// Captures a common usage pattern for allocators.
862 /// The returned block is suitable for passing to the
863 /// `alloc`/`realloc` methods of this allocator.
865 /// Note to implementors: If this returns `Ok(ptr)`, then `ptr`
866 /// must be considered "currently allocated" and must be
867 /// acceptable input to methods such as `realloc` or `dealloc`,
868 /// *even if* `T` is a zero-sized type. In other words, if your
869 /// `Alloc` implementation overrides this method in a manner
870 /// that can return a zero-sized `ptr`, then all reallocation and
871 /// deallocation methods need to be similarly overridden to accept
872 /// such values as input.
876 /// Returning `Err` indicates that either memory is exhausted or
877 /// `[T; n]` does not meet allocator's size or alignment
880 /// For zero-sized `T` or `n == 0`, may return either of `Ok` or
881 /// `Err`, but will *not* yield undefined behavior.
883 /// Always returns `Err` on arithmetic overflow.
885 /// Clients wishing to abort computation in response to an
886 /// allocation error are encouraged to call the allocator's `oom`
887 /// method, rather than directly invoking `panic!` or similar.
888 fn alloc_array<T>(&mut self, n: usize) -> Result<Unique<T>, AllocErr>
891 match Layout::array::<T>(n) {
892 Some(ref layout) if layout.size() > 0 => {
894 self.alloc(layout.clone())
896 Unique::new(p as *mut T)
900 _ => Err(AllocErr::invalid_input("invalid layout for alloc_array")),
904 /// Reallocates a block previously suitable for holding `n_old`
905 /// instances of `T`, returning a block suitable for holding
906 /// `n_new` instances of `T`.
908 /// Captures a common usage pattern for allocators.
910 /// The returned block is suitable for passing to the
911 /// `alloc`/`realloc` methods of this allocator.
915 /// This function is unsafe because undefined behavior can result
916 /// if the caller does not ensure all of the following:
918 /// * `ptr` must be currently allocated via this allocator,
920 /// * the layout of `[T; n_old]` must *fit* that block of memory.
924 /// Returning `Err` indicates that either memory is exhausted or
925 /// `[T; n_new]` does not meet allocator's size or alignment
928 /// For zero-sized `T` or `n_new == 0`, may return either of `Ok` or
929 /// `Err`, but will *not* yield undefined behavior.
931 /// Always returns `Err` on arithmetic overflow.
933 /// Clients wishing to abort computation in response to an
934 /// reallocation error are encouraged to call the allocator's `oom`
935 /// method, rather than directly invoking `panic!` or similar.
936 unsafe fn realloc_array<T>(&mut self,
939 n_new: usize) -> Result<Unique<T>, AllocErr>
942 match (Layout::array::<T>(n_old), Layout::array::<T>(n_new), ptr.as_ptr()) {
943 (Some(ref k_old), Some(ref k_new), ptr) if k_old.size() > 0 && k_new.size() > 0 => {
944 self.realloc(ptr as *mut u8, k_old.clone(), k_new.clone())
945 .map(|p|Unique::new(p as *mut T))
948 Err(AllocErr::invalid_input("invalid layout for realloc_array"))
953 /// Deallocates a block suitable for holding `n` instances of `T`.
955 /// Captures a common usage pattern for allocators.
959 /// This function is unsafe because undefined behavior can result
960 /// if the caller does not ensure both:
962 /// * `ptr` must denote a block of memory currently allocated via this allocator
964 /// * the layout of `[T; n]` must *fit* that block of memory.
968 /// Returning `Err` indicates that either `[T; n]` or the given
969 /// memory block does not meet allocator's size or alignment
972 /// Always returns `Err` on arithmetic overflow.
973 unsafe fn dealloc_array<T>(&mut self, ptr: Unique<T>, n: usize) -> Result<(), AllocErr>
976 let raw_ptr = ptr.as_ptr() as *mut u8;
977 match Layout::array::<T>(n) {
978 Some(ref k) if k.size() > 0 => {
979 Ok(self.dealloc(raw_ptr, k.clone()))
982 Err(AllocErr::invalid_input("invalid layout for dealloc_array"))