]> git.lizzy.rs Git - rust.git/blob - src/liballoc/allocator.rs
fc6585a9f951d6d58c6bb29dbe27ee5eed5eb1b4
[rust.git] / src / liballoc / allocator.rs
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.
4 //
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.
10
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",
16             issue = "32838")]
17
18 use core::cmp;
19 use core::fmt;
20 use core::mem;
21 use core::usize;
22 use core::ptr::{self, Unique};
23
24 /// Represents the combination of a starting address and
25 /// a total capacity of the returned block.
26 #[derive(Debug)]
27 pub struct Excess(pub *mut u8, pub usize);
28
29 fn size_align<T>() -> (usize, usize) {
30     (mem::size_of::<T>(), mem::align_of::<T>())
31 }
32
33 /// Layout of a block of memory.
34 ///
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.
37 ///
38 /// All layouts have an associated non-negative size and a
39 /// power-of-two alignment.
40 ///
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)]
47 pub struct Layout {
48     // size of the requested block of memory, measured in bytes.
49     size: usize,
50
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.
55     //
56     // (However, we do not analogously require `align >= sizeof(void*)`,
57     //  even though that is *also* a requirement of `posix_memalign`.)
58     align: usize,
59 }
60
61
62 // FIXME: audit default implementations for overflow errors,
63 // (potentially switching to overflowing_add and
64 //  overflowing_mul as necessary).
65
66 impl Layout {
67     /// Constructs a `Layout` from a given `size` and `align`,
68     /// or returns `None` if any of the following conditions
69     /// are not met:
70     ///
71     /// * `align` must be a power of two,
72     ///
73     /// * `align` must not exceed 2^31 (i.e. `1 << 31`),
74     ///
75     /// * `size`, when rounded up to the nearest multiple of `align`,
76     ///    must not overflow (i.e. the rounded value must be less than
77     ///    `usize::MAX`).
78     #[inline]
79     pub fn from_size_align(size: usize, align: usize) -> Option<Layout> {
80         if !align.is_power_of_two() {
81             return None;
82         }
83
84         if align > (1 << 31) {
85             return None;
86         }
87
88         // (power-of-two implies align != 0.)
89
90         // Rounded up size is:
91         //   size_rounded_up = (size + align - 1) & !(align - 1);
92         //
93         // We know from above that align != 0. If adding (align - 1)
94         // does not overflow, then rounding up will be fine.
95         //
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.
99         //
100         // Above implies that checking for summation overflow is both
101         // necessary and sufficient.
102         if size > usize::MAX - (align - 1) {
103             return None;
104         }
105
106         unsafe {
107             Some(Layout::from_size_align_unchecked(size, align))
108         }
109     }
110
111     /// Creates a layout, bypassing all checks.
112     ///
113     /// # Unsafety
114     ///
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).
119     #[inline]
120     pub unsafe fn from_size_align_unchecked(size: usize, align: usize) -> Layout {
121         Layout { size: size, align: align }
122     }
123
124     /// The minimum size in bytes for a memory block of this layout.
125     #[inline]
126     pub fn size(&self) -> usize { self.size }
127
128     /// The minimum byte alignment for a memory block of this layout.
129     #[inline]
130     pub fn align(&self) -> usize { self.align }
131
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()
136     }
137
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()
144     }
145
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).
149     ///
150     /// If `self` already meets the prescribed alignment, then returns
151     /// `self`.
152     ///
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.
157     ///
158     /// # Panics
159     ///
160     /// Panics if the combination of `self.size` and the given `align`
161     /// violates the conditions listed in `from_size_align`.
162     #[inline]
163     pub fn align_to(&self, align: usize) -> Self {
164         Layout::from_size_align(self.size, cmp::max(self.align, align)).unwrap()
165     }
166
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).
170     ///
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).
175     ///
176     /// The return value of this function has no meaning if `align` is
177     /// not a power-of-two.
178     ///
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`.
183     #[inline]
184     pub fn padding_needed_for(&self, align: usize) -> usize {
185         let len = self.size();
186
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`.
190         //
191         // We use modular arithmetic throughout:
192         //
193         // 1. align is guaranteed to be > 0, so align - 1 is always
194         //    valid.
195         //
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`.
201         //
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.)
205
206         let len_rounded_up = len.wrapping_add(align).wrapping_sub(1) & !align.wrapping_sub(1);
207         return len_rounded_up.wrapping_sub(len);
208     }
209
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.
216     ///
217     /// On arithmetic overflow, returns `None`.
218     #[inline]
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)) {
221             None => return None,
222             Some(padded_size) => padded_size,
223         };
224         let alloc_size = match padded_size.checked_mul(n) {
225             None => return None,
226             Some(alloc_size) => alloc_size,
227         };
228
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))
234     }
235
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`.
240     ///
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).
245     ///
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) {
250             None => return None,
251             Some(l) => l,
252         };
253
254         let pad = realigned.padding_needed_for(next.align);
255
256         let offset = match self.size.checked_add(pad) {
257             None => return None,
258             Some(offset) => offset,
259         };
260         let new_size = match offset.checked_add(next.size) {
261             None => return None,
262             Some(new_size) => new_size,
263         };
264
265         let layout = match Layout::from_size_align(new_size, new_align) {
266             None => return None,
267             Some(l) => l,
268         };
269         Some((layout, offset))
270     }
271
272     /// Creates a layout describing the record for `n` instances of
273     /// `self`, with no padding between each instance.
274     ///
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
281     /// aligned.
282     ///
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) {
286             None => return None,
287             Some(scaled) => scaled,
288         };
289
290         Layout::from_size_align(size, self.align)
291     }
292
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.
297     ///
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).
302     ///
303     /// (The `offset` is always the same as `self.size()`; we use this
304     ///  signature out of convenience in matching the signature of
305     ///  `extend`.)
306     ///
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()) {
310             None => return None,
311             Some(new_size) => new_size,
312         };
313         let layout = match Layout::from_size_align(new_size, self.align) {
314             None => return None,
315             Some(l) => l,
316         };
317         Some((layout, self.size()))
318     }
319
320     /// Creates a layout describing the record for a `[T; n]`.
321     ///
322     /// On arithmetic overflow, returns `None`.
323     pub fn array<T>(n: usize) -> Option<Self> {
324         Layout::new::<T>()
325             .repeat(n)
326             .map(|(k, offs)| {
327                 debug_assert!(offs == mem::size_of::<T>());
328                 k
329             })
330     }
331 }
332
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
336 /// allocator.
337 #[derive(Clone, PartialEq, Eq, Debug)]
338 pub enum AllocErr {
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 },
344
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.
350     ///
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 },
354 }
355
356 impl AllocErr {
357     #[inline]
358     pub fn invalid_input(details: &'static str) -> Self {
359         AllocErr::Unsupported { details: details }
360     }
361     #[inline]
362     pub fn is_memory_exhausted(&self) -> bool {
363         if let AllocErr::Exhausted { .. } = *self { true } else { false }
364     }
365     #[inline]
366     pub fn is_request_unsupported(&self) -> bool {
367         if let AllocErr::Unsupported { .. } = *self { true } else { false }
368     }
369     #[inline]
370     pub fn description(&self) -> &str {
371         match *self {
372             AllocErr::Exhausted { .. } => "allocator memory exhausted",
373             AllocErr::Unsupported { .. } => "unsupported allocator request",
374         }
375     }
376 }
377
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())
382     }
383 }
384
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;
390
391 impl CannotReallocInPlace {
392     pub fn description(&self) -> &str {
393         "cannot reallocate allocator's memory in place"
394     }
395 }
396
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())
401     }
402 }
403
404 /// An implementation of `Alloc` can allocate, reallocate, and
405 /// deallocate arbitrary blocks of data described via `Layout`.
406 ///
407 /// Some of the methods require that a memory block be *currently
408 /// allocated* via an allocator. This means that:
409 ///
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
415 ///
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`.
420 ///
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.
424 ///
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.
429 ///
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.
436 ///
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.
440 ///
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:
445 ///
446 /// 1. The block's starting address must be aligned to `layout.align()`.
447 ///
448 /// 2. The block's size must fall in the range `[use_min, use_max]`, where:
449 ///
450 ///    * `use_min` is `self.usable_size(layout).0`, and
451 ///
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`.
455 ///
456 /// Note that:
457 ///
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
460 ///
461 ///  * a lower-bound on `use_max` can be safely approximated by a call to
462 ///    `usable_size`.
463 ///
464 ///  * if a layout `k` fits a memory block (denoted by `ptr`)
465 ///    currently allocated via an allocator `a`, then it is legal to
466 ///    use that layout to deallocate it, i.e. `a.dealloc(ptr, k);`.
467 pub unsafe trait Alloc {
468
469     // (Note: existing allocators have unspecified but well-defined
470     // behavior in response to a zero size allocation request ;
471     // e.g. in C, `malloc` of 0 will either return a null pointer or a
472     // unique pointer, but will not have arbitrary undefined
473     // behavior. Rust should consider revising the alloc::heap crate
474     // to reflect this reality.)
475
476     /// Returns a pointer meeting the size and alignment guarantees of
477     /// `layout`.
478     ///
479     /// If this method returns an `Ok(addr)`, then the `addr` returned
480     /// will be non-null address pointing to a block of storage
481     /// suitable for holding an instance of `layout`.
482     ///
483     /// The returned block of storage may or may not have its contents
484     /// initialized. (Extension subtraits might restrict this
485     /// behavior, e.g. to ensure initialization to particular sets of
486     /// bit patterns.)
487     ///
488     /// # Unsafety
489     ///
490     /// This function is unsafe because undefined behavior can result
491     /// if the caller does not ensure that `layout` has non-zero size.
492     ///
493     /// (Extension subtraits might provide more specific bounds on
494     /// behavior, e.g. guarantee a sentinel address or a null pointer
495     /// in response to a zero-size allocation request.)
496     ///
497     /// # Errors
498     ///
499     /// Returning `Err` indicates that either memory is exhausted or
500     /// `layout` does not meet allocator's size or alignment
501     /// constraints.
502     ///
503     /// Implementations are encouraged to return `Err` on memory
504     /// exhaustion rather than panicking or aborting, but this is not
505     /// a strict requirement. (Specifically: it is *legal* to
506     /// implement this trait atop an underlying native allocation
507     /// library that aborts on memory exhaustion.)
508     ///
509     /// Clients wishing to abort computation in response to an
510     /// allocation error are encouraged to call the allocator's `oom`
511     /// method, rather than directly invoking `panic!` or similar.
512     unsafe fn alloc(&mut self, layout: Layout) -> Result<*mut u8, AllocErr>;
513
514     /// Deallocate the memory referenced by `ptr`.
515     ///
516     /// # Unsafety
517     ///
518     /// This function is unsafe because undefined behavior can result
519     /// if the caller does not ensure all of the following:
520     ///
521     /// * `ptr` must denote a block of memory currently allocated via
522     ///   this allocator,
523     ///
524     /// * `layout` must *fit* that block of memory,
525     ///
526     /// * In addition to fitting the block of memory `layout`, the
527     ///   alignment of the `layout` must match the alignment used
528     ///   to allocate that block of memory.
529     unsafe fn dealloc(&mut self, ptr: *mut u8, layout: Layout);
530
531     /// Allocator-specific method for signaling an out-of-memory
532     /// condition.
533     ///
534     /// `oom` aborts the thread or process, optionally performing
535     /// cleanup or logging diagnostic information before panicking or
536     /// aborting.
537     ///
538     /// `oom` is meant to be used by clients unable to cope with an
539     /// unsatisfied allocation request (signaled by an error such as
540     /// `AllocErr::Exhausted`), and wish to abandon computation rather
541     /// than attempt to recover locally. Such clients should pass the
542     /// signaling error value back into `oom`, where the allocator
543     /// may incorporate that error value into its diagnostic report
544     /// before aborting.
545     ///
546     /// Implementations of the `oom` method are discouraged from
547     /// infinitely regressing in nested calls to `oom`. In
548     /// practice this means implementors should eschew allocating,
549     /// especially from `self` (directly or indirectly).
550     ///
551     /// Implementations of the allocation and reallocation methods
552     /// (e.g. `alloc`, `alloc_one`, `realloc`) are discouraged from
553     /// panicking (or aborting) in the event of memory exhaustion;
554     /// instead they should return an appropriate error from the
555     /// invoked method, and let the client decide whether to invoke
556     /// this `oom` method in response.
557     fn oom(&mut self, _: AllocErr) -> ! {
558         unsafe { ::core::intrinsics::abort() }
559     }
560
561     // == ALLOCATOR-SPECIFIC QUANTITIES AND LIMITS ==
562     // usable_size
563
564     /// Returns bounds on the guaranteed usable size of a successful
565     /// allocation created with the specified `layout`.
566     ///
567     /// In particular, if one has a memory block allocated via a given
568     /// allocator `a` and layout `k` where `a.usable_size(k)` returns
569     /// `(l, u)`, then one can pass that block to `a.dealloc()` with a
570     /// layout in the size range [l, u].
571     ///
572     /// (All implementors of `usable_size` must ensure that
573     /// `l <= k.size() <= u`)
574     ///
575     /// Both the lower- and upper-bounds (`l` and `u` respectively)
576     /// are provided, because an allocator based on size classes could
577     /// misbehave if one attempts to deallocate a block without
578     /// providing a correct value for its size (i.e., one within the
579     /// range `[l, u]`).
580     ///
581     /// Clients who wish to make use of excess capacity are encouraged
582     /// to use the `alloc_excess` and `realloc_excess` instead, as
583     /// this method is constrained to report conservative values that
584     /// serve as valid bounds for *all possible* allocation method
585     /// calls.
586     ///
587     /// However, for clients that do not wish to track the capacity
588     /// returned by `alloc_excess` locally, this method is likely to
589     /// produce useful results.
590     #[inline]
591     fn usable_size(&self, layout: &Layout) -> (usize, usize) {
592         (layout.size(), layout.size())
593     }
594
595     // == METHODS FOR MEMORY REUSE ==
596     // realloc. alloc_excess, realloc_excess
597
598     /// Returns a pointer suitable for holding data described by
599     /// `new_layout`, meeting its size and alignment guarantees. To
600     /// accomplish this, this may extend or shrink the allocation
601     /// referenced by `ptr` to fit `new_layout`.
602     ///
603     /// If this returns `Ok`, then ownership of the memory block
604     /// referenced by `ptr` has been transferred to this
605     /// allocator. The memory may or may not have been freed, and
606     /// should be considered unusable (unless of course it was
607     /// transferred back to the caller again via the return value of
608     /// this method).
609     ///
610     /// If this method returns `Err`, then ownership of the memory
611     /// block has not been transferred to this allocator, and the
612     /// contents of the memory block are unaltered.
613     ///
614     /// For best results, `new_layout` should not impose a different
615     /// alignment constraint than `layout`. (In other words,
616     /// `new_layout.align()` should equal `layout.align()`.) However,
617     /// behavior is well-defined (though underspecified) when this
618     /// constraint is violated; further discussion below.
619     ///
620     /// # Unsafety
621     ///
622     /// This function is unsafe because undefined behavior can result
623     /// if the caller does not ensure all of the following:
624     ///
625     /// * `ptr` must be currently allocated via this allocator,
626     ///
627     /// * `layout` must *fit* the `ptr` (see above). (The `new_layout`
628     ///   argument need not fit it.)
629     ///
630     /// * `new_layout` must have size greater than zero.
631     ///
632     /// * the alignment of `new_layout` is non-zero.
633     ///
634     /// (Extension subtraits might provide more specific bounds on
635     /// behavior, e.g. guarantee a sentinel address or a null pointer
636     /// in response to a zero-size allocation request.)
637     ///
638     /// # Errors
639     ///
640     /// Returns `Err` only if `new_layout` does not match the
641     /// alignment of `layout`, or does not meet the allocator's size
642     /// and alignment constraints of the allocator, or if reallocation
643     /// otherwise fails.
644     ///
645     /// (Note the previous sentence did not say "if and only if" -- in
646     /// particular, an implementation of this method *can* return `Ok`
647     /// if `new_layout.align() != old_layout.align()`; or it can
648     /// return `Err` in that scenario, depending on whether this
649     /// allocator can dynamically adjust the alignment constraint for
650     /// the block.)
651     ///
652     /// Implementations are encouraged to return `Err` on memory
653     /// exhaustion rather than panicking or aborting, but this is not
654     /// a strict requirement. (Specifically: it is *legal* to
655     /// implement this trait atop an underlying native allocation
656     /// library that aborts on memory exhaustion.)
657     ///
658     /// Clients wishing to abort computation in response to an
659     /// reallocation error are encouraged to call the allocator's `oom`
660     /// method, rather than directly invoking `panic!` or similar.
661     unsafe fn realloc(&mut self,
662                       ptr: *mut u8,
663                       layout: Layout,
664                       new_layout: Layout) -> Result<*mut u8, AllocErr> {
665         let new_size = new_layout.size();
666         let old_size = layout.size();
667         let aligns_match = layout.align == new_layout.align;
668
669         if new_size >= old_size && aligns_match {
670             if let Ok(()) = self.grow_in_place(ptr, layout.clone(), new_layout.clone()) {
671                 return Ok(ptr);
672             }
673         } else if new_size < old_size && aligns_match {
674             if let Ok(()) = self.shrink_in_place(ptr, layout.clone(), new_layout.clone()) {
675                 return Ok(ptr);
676             }
677         }
678
679         // otherwise, fall back on alloc + copy + dealloc.
680         let result = self.alloc(new_layout);
681         if let Ok(new_ptr) = result {
682             ptr::copy_nonoverlapping(ptr as *const u8, new_ptr, cmp::min(old_size, new_size));
683             self.dealloc(ptr, layout);
684         }
685         result
686     }
687
688     /// Behaves like `alloc`, but also ensures that the contents
689     /// are set to zero before being returned.
690     ///
691     /// # Unsafety
692     ///
693     /// This function is unsafe for the same reasons that `alloc` is.
694     ///
695     /// # Errors
696     ///
697     /// Returning `Err` indicates that either memory is exhausted or
698     /// `layout` does not meet allocator's size or alignment
699     /// constraints, just as in `alloc`.
700     ///
701     /// Clients wishing to abort computation in response to an
702     /// allocation error are encouraged to call the allocator's `oom`
703     /// method, rather than directly invoking `panic!` or similar.
704     unsafe fn alloc_zeroed(&mut self, layout: Layout) -> Result<*mut u8, AllocErr> {
705         let size = layout.size();
706         let p = self.alloc(layout);
707         if let Ok(p) = p {
708             ptr::write_bytes(p, 0, size);
709         }
710         p
711     }
712
713     /// Behaves like `alloc`, but also returns the whole size of
714     /// the returned block. For some `layout` inputs, like arrays, this
715     /// may include extra storage usable for additional data.
716     ///
717     /// # Unsafety
718     ///
719     /// This function is unsafe for the same reasons that `alloc` is.
720     ///
721     /// # Errors
722     ///
723     /// Returning `Err` indicates that either memory is exhausted or
724     /// `layout` does not meet allocator's size or alignment
725     /// constraints, just as in `alloc`.
726     ///
727     /// Clients wishing to abort computation in response to an
728     /// allocation error are encouraged to call the allocator's `oom`
729     /// method, rather than directly invoking `panic!` or similar.
730     unsafe fn alloc_excess(&mut self, layout: Layout) -> Result<Excess, AllocErr> {
731         let usable_size = self.usable_size(&layout);
732         self.alloc(layout).map(|p| Excess(p, usable_size.1))
733     }
734
735     /// Behaves like `realloc`, but also returns the whole size of
736     /// the returned block. For some `layout` inputs, like arrays, this
737     /// may include extra storage usable for additional data.
738     ///
739     /// # Unsafety
740     ///
741     /// This function is unsafe for the same reasons that `realloc` is.
742     ///
743     /// # Errors
744     ///
745     /// Returning `Err` indicates that either memory is exhausted or
746     /// `layout` does not meet allocator's size or alignment
747     /// constraints, just as in `realloc`.
748     ///
749     /// Clients wishing to abort computation in response to an
750     /// reallocation error are encouraged to call the allocator's `oom`
751     /// method, rather than directly invoking `panic!` or similar.
752     unsafe fn realloc_excess(&mut self,
753                              ptr: *mut u8,
754                              layout: Layout,
755                              new_layout: Layout) -> Result<Excess, AllocErr> {
756         let usable_size = self.usable_size(&new_layout);
757         self.realloc(ptr, layout, new_layout)
758             .map(|p| Excess(p, usable_size.1))
759     }
760
761     /// Attempts to extend the allocation referenced by `ptr` to fit `new_layout`.
762     ///
763     /// If this returns `Ok`, then the allocator has asserted that the
764     /// memory block referenced by `ptr` now fits `new_layout`, and thus can
765     /// be used to carry data of that layout. (The allocator is allowed to
766     /// expend effort to accomplish this, such as extending the memory block to
767     /// include successor blocks, or virtual memory tricks.)
768     ///
769     /// Regardless of what this method returns, ownership of the
770     /// memory block referenced by `ptr` has not been transferred, and
771     /// the contents of the memory block are unaltered.
772     ///
773     /// # Unsafety
774     ///
775     /// This function is unsafe because undefined behavior can result
776     /// if the caller does not ensure all of the following:
777     ///
778     /// * `ptr` must be currently allocated via this allocator,
779     ///
780     /// * `layout` must *fit* the `ptr` (see above); note the
781     ///   `new_layout` argument need not fit it,
782     ///
783     /// * `new_layout.size()` must not be less than `layout.size()`,
784     ///
785     /// * `new_layout.align()` must equal `layout.align()`.
786     ///
787     /// # Errors
788     ///
789     /// Returns `Err(CannotReallocInPlace)` when the allocator is
790     /// unable to assert that the memory block referenced by `ptr`
791     /// could fit `layout`.
792     ///
793     /// Note that one cannot pass `CannotReallocInPlace` to the `oom`
794     /// method; clients are expected either to be able to recover from
795     /// `grow_in_place` failures without aborting, or to fall back on
796     /// another reallocation method before resorting to an abort.
797     unsafe fn grow_in_place(&mut self,
798                             ptr: *mut u8,
799                             layout: Layout,
800                             new_layout: Layout) -> Result<(), CannotReallocInPlace> {
801         let _ = ptr; // this default implementation doesn't care about the actual address.
802         debug_assert!(new_layout.size >= layout.size);
803         debug_assert!(new_layout.align == layout.align);
804         let (_l, u) = self.usable_size(&layout);
805         // _l <= layout.size()                       [guaranteed by usable_size()]
806         //       layout.size() <= new_layout.size()  [required by this method]
807         if new_layout.size <= u {
808             return Ok(());
809         } else {
810             return Err(CannotReallocInPlace);
811         }
812     }
813
814     /// Attempts to shrink the allocation referenced by `ptr` to fit `new_layout`.
815     ///
816     /// If this returns `Ok`, then the allocator has asserted that the
817     /// memory block referenced by `ptr` now fits `new_layout`, and
818     /// thus can only be used to carry data of that smaller
819     /// layout. (The allocator is allowed to take advantage of this,
820     /// carving off portions of the block for reuse elsewhere.) The
821     /// truncated contents of the block within the smaller layout are
822     /// unaltered, and ownership of block has not been transferred.
823     ///
824     /// If this returns `Err`, then the memory block is considered to
825     /// still represent the original (larger) `layout`. None of the
826     /// block has been carved off for reuse elsewhere, ownership of
827     /// the memory block has not been transferred, and the contents of
828     /// the memory block are unaltered.
829     ///
830     /// # Unsafety
831     ///
832     /// This function is unsafe because undefined behavior can result
833     /// if the caller does not ensure all of the following:
834     ///
835     /// * `ptr` must be currently allocated via this allocator,
836     ///
837     /// * `layout` must *fit* the `ptr` (see above); note the
838     ///   `new_layout` argument need not fit it,
839     ///
840     /// * `new_layout.size()` must not be greater than `layout.size()`
841     ///   (and must be greater than zero),
842     ///
843     /// * `new_layout.align()` must equal `layout.align()`.
844     ///
845     /// # Errors
846     ///
847     /// Returns `Err(CannotReallocInPlace)` when the allocator is
848     /// unable to assert that the memory block referenced by `ptr`
849     /// could fit `layout`.
850     ///
851     /// Note that one cannot pass `CannotReallocInPlace` to the `oom`
852     /// method; clients are expected either to be able to recover from
853     /// `shrink_in_place` failures without aborting, or to fall back
854     /// on another reallocation method before resorting to an abort.
855     unsafe fn shrink_in_place(&mut self,
856                               ptr: *mut u8,
857                               layout: Layout,
858                               new_layout: Layout) -> Result<(), CannotReallocInPlace> {
859         let _ = ptr; // this default implementation doesn't care about the actual address.
860         debug_assert!(new_layout.size <= layout.size);
861         debug_assert!(new_layout.align == layout.align);
862         let (l, _u) = self.usable_size(&layout);
863         //                      layout.size() <= _u  [guaranteed by usable_size()]
864         // new_layout.size() <= layout.size()        [required by this method]
865         if l <= new_layout.size {
866             return Ok(());
867         } else {
868             return Err(CannotReallocInPlace);
869         }
870     }
871
872
873     // == COMMON USAGE PATTERNS ==
874     // alloc_one, dealloc_one, alloc_array, realloc_array. dealloc_array
875
876     /// Allocates a block suitable for holding an instance of `T`.
877     ///
878     /// Captures a common usage pattern for allocators.
879     ///
880     /// The returned block is suitable for passing to the
881     /// `alloc`/`realloc` methods of this allocator.
882     ///
883     /// Note to implementors: If this returns `Ok(ptr)`, then `ptr`
884     /// must be considered "currently allocated" and must be
885     /// acceptable input to methods such as `realloc` or `dealloc`,
886     /// *even if* `T` is a zero-sized type. In other words, if your
887     /// `Alloc` implementation overrides this method in a manner
888     /// that can return a zero-sized `ptr`, then all reallocation and
889     /// deallocation methods need to be similarly overridden to accept
890     /// such values as input.
891     ///
892     /// # Errors
893     ///
894     /// Returning `Err` indicates that either memory is exhausted or
895     /// `T` does not meet allocator's size or alignment constraints.
896     ///
897     /// For zero-sized `T`, may return either of `Ok` or `Err`, but
898     /// will *not* yield undefined behavior.
899     ///
900     /// Clients wishing to abort computation in response to an
901     /// allocation error are encouraged to call the allocator's `oom`
902     /// method, rather than directly invoking `panic!` or similar.
903     fn alloc_one<T>(&mut self) -> Result<Unique<T>, AllocErr>
904         where Self: Sized
905     {
906         let k = Layout::new::<T>();
907         if k.size() > 0 {
908             unsafe { self.alloc(k).map(|p| Unique::new_unchecked(p as *mut T)) }
909         } else {
910             Err(AllocErr::invalid_input("zero-sized type invalid for alloc_one"))
911         }
912     }
913
914     /// Deallocates a block suitable for holding an instance of `T`.
915     ///
916     /// The given block must have been produced by this allocator,
917     /// and must be suitable for storing a `T` (in terms of alignment
918     /// as well as minimum and maximum size); otherwise yields
919     /// undefined behavior.
920     ///
921     /// Captures a common usage pattern for allocators.
922     ///
923     /// # Unsafety
924     ///
925     /// This function is unsafe because undefined behavior can result
926     /// if the caller does not ensure both:
927     ///
928     /// * `ptr` must denote a block of memory currently allocated via this allocator
929     ///
930     /// * the layout of `T` must *fit* that block of memory.
931     unsafe fn dealloc_one<T>(&mut self, ptr: Unique<T>)
932         where Self: Sized
933     {
934         let raw_ptr = ptr.as_ptr() as *mut u8;
935         let k = Layout::new::<T>();
936         if k.size() > 0 {
937             self.dealloc(raw_ptr, k);
938         }
939     }
940
941     /// Allocates a block suitable for holding `n` instances of `T`.
942     ///
943     /// Captures a common usage pattern for allocators.
944     ///
945     /// The returned block is suitable for passing to the
946     /// `alloc`/`realloc` methods of this allocator.
947     ///
948     /// Note to implementors: If this returns `Ok(ptr)`, then `ptr`
949     /// must be considered "currently allocated" and must be
950     /// acceptable input to methods such as `realloc` or `dealloc`,
951     /// *even if* `T` is a zero-sized type. In other words, if your
952     /// `Alloc` implementation overrides this method in a manner
953     /// that can return a zero-sized `ptr`, then all reallocation and
954     /// deallocation methods need to be similarly overridden to accept
955     /// such values as input.
956     ///
957     /// # Errors
958     ///
959     /// Returning `Err` indicates that either memory is exhausted or
960     /// `[T; n]` does not meet allocator's size or alignment
961     /// constraints.
962     ///
963     /// For zero-sized `T` or `n == 0`, may return either of `Ok` or
964     /// `Err`, but will *not* yield undefined behavior.
965     ///
966     /// Always returns `Err` on arithmetic overflow.
967     ///
968     /// Clients wishing to abort computation in response to an
969     /// allocation error are encouraged to call the allocator's `oom`
970     /// method, rather than directly invoking `panic!` or similar.
971     fn alloc_array<T>(&mut self, n: usize) -> Result<Unique<T>, AllocErr>
972         where Self: Sized
973     {
974         match Layout::array::<T>(n) {
975             Some(ref layout) if layout.size() > 0 => {
976                 unsafe {
977                     self.alloc(layout.clone())
978                         .map(|p| {
979                             Unique::new_unchecked(p as *mut T)
980                         })
981                 }
982             }
983             _ => Err(AllocErr::invalid_input("invalid layout for alloc_array")),
984         }
985     }
986
987     /// Reallocates a block previously suitable for holding `n_old`
988     /// instances of `T`, returning a block suitable for holding
989     /// `n_new` instances of `T`.
990     ///
991     /// Captures a common usage pattern for allocators.
992     ///
993     /// The returned block is suitable for passing to the
994     /// `alloc`/`realloc` methods of this allocator.
995     ///
996     /// # Unsafety
997     ///
998     /// This function is unsafe because undefined behavior can result
999     /// if the caller does not ensure all of the following:
1000     ///
1001     /// * `ptr` must be currently allocated via this allocator,
1002     ///
1003     /// * the layout of `[T; n_old]` must *fit* that block of memory.
1004     ///
1005     /// # Errors
1006     ///
1007     /// Returning `Err` indicates that either memory is exhausted or
1008     /// `[T; n_new]` does not meet allocator's size or alignment
1009     /// constraints.
1010     ///
1011     /// For zero-sized `T` or `n_new == 0`, may return either of `Ok` or
1012     /// `Err`, but will *not* yield undefined behavior.
1013     ///
1014     /// Always returns `Err` on arithmetic overflow.
1015     ///
1016     /// Clients wishing to abort computation in response to an
1017     /// reallocation error are encouraged to call the allocator's `oom`
1018     /// method, rather than directly invoking `panic!` or similar.
1019     unsafe fn realloc_array<T>(&mut self,
1020                                ptr: Unique<T>,
1021                                n_old: usize,
1022                                n_new: usize) -> Result<Unique<T>, AllocErr>
1023         where Self: Sized
1024     {
1025         match (Layout::array::<T>(n_old), Layout::array::<T>(n_new), ptr.as_ptr()) {
1026             (Some(ref k_old), Some(ref k_new), ptr) if k_old.size() > 0 && k_new.size() > 0 => {
1027                 self.realloc(ptr as *mut u8, k_old.clone(), k_new.clone())
1028                     .map(|p|Unique::new_unchecked(p as *mut T))
1029             }
1030             _ => {
1031                 Err(AllocErr::invalid_input("invalid layout for realloc_array"))
1032             }
1033         }
1034     }
1035
1036     /// Deallocates a block suitable for holding `n` instances of `T`.
1037     ///
1038     /// Captures a common usage pattern for allocators.
1039     ///
1040     /// # Unsafety
1041     ///
1042     /// This function is unsafe because undefined behavior can result
1043     /// if the caller does not ensure both:
1044     ///
1045     /// * `ptr` must denote a block of memory currently allocated via this allocator
1046     ///
1047     /// * the layout of `[T; n]` must *fit* that block of memory.
1048     ///
1049     /// # Errors
1050     ///
1051     /// Returning `Err` indicates that either `[T; n]` or the given
1052     /// memory block does not meet allocator's size or alignment
1053     /// constraints.
1054     ///
1055     /// Always returns `Err` on arithmetic overflow.
1056     unsafe fn dealloc_array<T>(&mut self, ptr: Unique<T>, n: usize) -> Result<(), AllocErr>
1057         where Self: Sized
1058     {
1059         let raw_ptr = ptr.as_ptr() as *mut u8;
1060         match Layout::array::<T>(n) {
1061             Some(ref k) if k.size() > 0 => {
1062                 Ok(self.dealloc(raw_ptr, k.clone()))
1063             }
1064             _ => {
1065                 Err(AllocErr::invalid_input("invalid layout for dealloc_array"))
1066             }
1067         }
1068     }
1069 }