]> git.lizzy.rs Git - rust.git/blob - src/liballoc/allocator.rs
Fix test
[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, NonNull};
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<sup>31</sup> (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     /// # Safety
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<sup>31</sup>, 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 = self.size.checked_add(self.padding_needed_for(self.align))?;
221         let alloc_size = padded_size.checked_mul(n)?;
222
223         // We can assume that `self.align` is a power-of-two that does
224         // not exceed 2<sup>31</sup>. Furthermore, `alloc_size` has already been
225         // rounded up to a multiple of `self.align`; therefore, the
226         // call to `Layout::from_size_align` below should never panic.
227         Some((Layout::from_size_align(alloc_size, self.align).unwrap(), padded_size))
228     }
229
230     /// Creates a layout describing the record for `self` followed by
231     /// `next`, including any necessary padding to ensure that `next`
232     /// will be properly aligned. Note that the result layout will
233     /// satisfy the alignment properties of both `self` and `next`.
234     ///
235     /// Returns `Some((k, offset))`, where `k` is layout of the concatenated
236     /// record and `offset` is the relative location, in bytes, of the
237     /// start of the `next` embedded within the concatenated record
238     /// (assuming that the record itself starts at offset 0).
239     ///
240     /// On arithmetic overflow, returns `None`.
241     pub fn extend(&self, next: Self) -> Option<(Self, usize)> {
242         let new_align = cmp::max(self.align, next.align);
243         let realigned = Layout::from_size_align(self.size, new_align)?;
244
245         let pad = realigned.padding_needed_for(next.align);
246
247         let offset = self.size.checked_add(pad)?;
248         let new_size = offset.checked_add(next.size)?;
249
250         let layout = Layout::from_size_align(new_size, new_align)?;
251         Some((layout, offset))
252     }
253
254     /// Creates a layout describing the record for `n` instances of
255     /// `self`, with no padding between each instance.
256     ///
257     /// Note that, unlike `repeat`, `repeat_packed` does not guarantee
258     /// that the repeated instances of `self` will be properly
259     /// aligned, even if a given instance of `self` is properly
260     /// aligned. In other words, if the layout returned by
261     /// `repeat_packed` is used to allocate an array, it is not
262     /// guaranteed that all elements in the array will be properly
263     /// aligned.
264     ///
265     /// On arithmetic overflow, returns `None`.
266     pub fn repeat_packed(&self, n: usize) -> Option<Self> {
267         let size = self.size().checked_mul(n)?;
268         Layout::from_size_align(size, self.align)
269     }
270
271     /// Creates a layout describing the record for `self` followed by
272     /// `next` with no additional padding between the two. Since no
273     /// padding is inserted, the alignment of `next` is irrelevant,
274     /// and is not incorporated *at all* into the resulting layout.
275     ///
276     /// Returns `(k, offset)`, where `k` is layout of the concatenated
277     /// record and `offset` is the relative location, in bytes, of the
278     /// start of the `next` embedded within the concatenated record
279     /// (assuming that the record itself starts at offset 0).
280     ///
281     /// (The `offset` is always the same as `self.size()`; we use this
282     ///  signature out of convenience in matching the signature of
283     ///  `extend`.)
284     ///
285     /// On arithmetic overflow, returns `None`.
286     pub fn extend_packed(&self, next: Self) -> Option<(Self, usize)> {
287         let new_size = self.size().checked_add(next.size())?;
288         let layout = Layout::from_size_align(new_size, self.align)?;
289         Some((layout, self.size()))
290     }
291
292     /// Creates a layout describing the record for a `[T; n]`.
293     ///
294     /// On arithmetic overflow, returns `None`.
295     pub fn array<T>(n: usize) -> Option<Self> {
296         Layout::new::<T>()
297             .repeat(n)
298             .map(|(k, offs)| {
299                 debug_assert!(offs == mem::size_of::<T>());
300                 k
301             })
302     }
303 }
304
305 /// The `AllocErr` error specifies whether an allocation failure is
306 /// specifically due to resource exhaustion or if it is due to
307 /// something wrong when combining the given input arguments with this
308 /// allocator.
309 #[derive(Clone, PartialEq, Eq, Debug)]
310 pub enum AllocErr {
311     /// Error due to hitting some resource limit or otherwise running
312     /// out of memory. This condition strongly implies that *some*
313     /// series of deallocations would allow a subsequent reissuing of
314     /// the original allocation request to succeed.
315     Exhausted { request: Layout },
316
317     /// Error due to allocator being fundamentally incapable of
318     /// satisfying the original request. This condition implies that
319     /// such an allocation request will never succeed on the given
320     /// allocator, regardless of environment, memory pressure, or
321     /// other contextual conditions.
322     ///
323     /// For example, an allocator that does not support requests for
324     /// large memory blocks might return this error variant.
325     Unsupported { details: &'static str },
326 }
327
328 impl AllocErr {
329     #[inline]
330     pub fn invalid_input(details: &'static str) -> Self {
331         AllocErr::Unsupported { details: details }
332     }
333     #[inline]
334     pub fn is_memory_exhausted(&self) -> bool {
335         if let AllocErr::Exhausted { .. } = *self { true } else { false }
336     }
337     #[inline]
338     pub fn is_request_unsupported(&self) -> bool {
339         if let AllocErr::Unsupported { .. } = *self { true } else { false }
340     }
341     #[inline]
342     pub fn description(&self) -> &str {
343         match *self {
344             AllocErr::Exhausted { .. } => "allocator memory exhausted",
345             AllocErr::Unsupported { .. } => "unsupported allocator request",
346         }
347     }
348 }
349
350 // (we need this for downstream impl of trait Error)
351 impl fmt::Display for AllocErr {
352     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
353         write!(f, "{}", self.description())
354     }
355 }
356
357 /// The `CannotReallocInPlace` error is used when `grow_in_place` or
358 /// `shrink_in_place` were unable to reuse the given memory block for
359 /// a requested layout.
360 #[derive(Clone, PartialEq, Eq, Debug)]
361 pub struct CannotReallocInPlace;
362
363 impl CannotReallocInPlace {
364     pub fn description(&self) -> &str {
365         "cannot reallocate allocator's memory in place"
366     }
367 }
368
369 // (we need this for downstream impl of trait Error)
370 impl fmt::Display for CannotReallocInPlace {
371     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
372         write!(f, "{}", self.description())
373     }
374 }
375
376 /// Augments `AllocErr` with a CapacityOverflow variant.
377 #[derive(Clone, PartialEq, Eq, Debug)]
378 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
379 pub enum CollectionAllocErr {
380     /// Error due to the computed capacity exceeding the collection's maximum
381     /// (usually `isize::MAX` bytes).
382     CapacityOverflow,
383     /// Error due to the allocator (see the `AllocErr` type's docs).
384     AllocErr(AllocErr),
385 }
386
387 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
388 impl From<AllocErr> for CollectionAllocErr {
389     fn from(err: AllocErr) -> Self {
390         CollectionAllocErr::AllocErr(err)
391     }
392 }
393
394 /// An implementation of `Alloc` can allocate, reallocate, and
395 /// deallocate arbitrary blocks of data described via `Layout`.
396 ///
397 /// Some of the methods require that a memory block be *currently
398 /// allocated* via an allocator. This means that:
399 ///
400 /// * the starting address for that memory block was previously
401 ///   returned by a previous call to an allocation method (`alloc`,
402 ///   `alloc_zeroed`, `alloc_excess`, `alloc_one`, `alloc_array`) or
403 ///   reallocation method (`realloc`, `realloc_excess`, or
404 ///   `realloc_array`), and
405 ///
406 /// * the memory block has not been subsequently deallocated, where
407 ///   blocks are deallocated either by being passed to a deallocation
408 ///   method (`dealloc`, `dealloc_one`, `dealloc_array`) or by being
409 ///   passed to a reallocation method (see above) that returns `Ok`.
410 ///
411 /// A note regarding zero-sized types and zero-sized layouts: many
412 /// methods in the `Alloc` trait state that allocation requests
413 /// must be non-zero size, or else undefined behavior can result.
414 ///
415 /// * However, some higher-level allocation methods (`alloc_one`,
416 ///   `alloc_array`) are well-defined on zero-sized types and can
417 ///   optionally support them: it is left up to the implementor
418 ///   whether to return `Err`, or to return `Ok` with some pointer.
419 ///
420 /// * If an `Alloc` implementation chooses to return `Ok` in this
421 ///   case (i.e. the pointer denotes a zero-sized inaccessible block)
422 ///   then that returned pointer must be considered "currently
423 ///   allocated". On such an allocator, *all* methods that take
424 ///   currently-allocated pointers as inputs must accept these
425 ///   zero-sized pointers, *without* causing undefined behavior.
426 ///
427 /// * In other words, if a zero-sized pointer can flow out of an
428 ///   allocator, then that allocator must likewise accept that pointer
429 ///   flowing back into its deallocation and reallocation methods.
430 ///
431 /// Some of the methods require that a layout *fit* a memory block.
432 /// What it means for a layout to "fit" a memory block means (or
433 /// equivalently, for a memory block to "fit" a layout) is that the
434 /// following two conditions must hold:
435 ///
436 /// 1. The block's starting address must be aligned to `layout.align()`.
437 ///
438 /// 2. The block's size must fall in the range `[use_min, use_max]`, where:
439 ///
440 ///    * `use_min` is `self.usable_size(layout).0`, and
441 ///
442 ///    * `use_max` is the capacity that was (or would have been)
443 ///      returned when (if) the block was allocated via a call to
444 ///      `alloc_excess` or `realloc_excess`.
445 ///
446 /// Note that:
447 ///
448 ///  * the size of the layout most recently used to allocate the block
449 ///    is guaranteed to be in the range `[use_min, use_max]`, and
450 ///
451 ///  * a lower-bound on `use_max` can be safely approximated by a call to
452 ///    `usable_size`.
453 ///
454 ///  * if a layout `k` fits a memory block (denoted by `ptr`)
455 ///    currently allocated via an allocator `a`, then it is legal to
456 ///    use that layout to deallocate it, i.e. `a.dealloc(ptr, k);`.
457 ///
458 /// # Unsafety
459 ///
460 /// The `Alloc` trait is an `unsafe` trait for a number of reasons, and
461 /// implementors must ensure that they adhere to these contracts:
462 ///
463 /// * Pointers returned from allocation functions must point to valid memory and
464 ///   retain their validity until at least the instance of `Alloc` is dropped
465 ///   itself.
466 ///
467 /// * It's undefined behavior if global allocators unwind.  This restriction may
468 ///   be lifted in the future, but currently a panic from any of these
469 ///   functions may lead to memory unsafety. Note that as of the time of this
470 ///   writing allocators *not* intending to be global allocators can still panic
471 ///   in their implementation without violating memory safety.
472 ///
473 /// * `Layout` queries and calculations in general must be correct. Callers of
474 ///   this trait are allowed to rely on the contracts defined on each method,
475 ///   and implementors must ensure such contracts remain true.
476 ///
477 /// Note that this list may get tweaked over time as clarifications are made in
478 /// the future. Additionally global allocators may gain unique requirements for
479 /// how to safely implement one in the future as well.
480 pub unsafe trait Alloc {
481
482     // (Note: existing allocators have unspecified but well-defined
483     // behavior in response to a zero size allocation request ;
484     // e.g. in C, `malloc` of 0 will either return a null pointer or a
485     // unique pointer, but will not have arbitrary undefined
486     // behavior. Rust should consider revising the alloc::heap crate
487     // to reflect this reality.)
488
489     /// Returns a pointer meeting the size and alignment guarantees of
490     /// `layout`.
491     ///
492     /// If this method returns an `Ok(addr)`, then the `addr` returned
493     /// will be non-null address pointing to a block of storage
494     /// suitable for holding an instance of `layout`.
495     ///
496     /// The returned block of storage may or may not have its contents
497     /// initialized. (Extension subtraits might restrict this
498     /// behavior, e.g. to ensure initialization to particular sets of
499     /// bit patterns.)
500     ///
501     /// # Safety
502     ///
503     /// This function is unsafe because undefined behavior can result
504     /// if the caller does not ensure that `layout` has non-zero size.
505     ///
506     /// (Extension subtraits might provide more specific bounds on
507     /// behavior, e.g. guarantee a sentinel address or a null pointer
508     /// in response to a zero-size allocation request.)
509     ///
510     /// # Errors
511     ///
512     /// Returning `Err` indicates that either memory is exhausted or
513     /// `layout` does not meet allocator's size or alignment
514     /// constraints.
515     ///
516     /// Implementations are encouraged to return `Err` on memory
517     /// exhaustion rather than panicking or aborting, but this is not
518     /// a strict requirement. (Specifically: it is *legal* to
519     /// implement this trait atop an underlying native allocation
520     /// library that aborts on memory exhaustion.)
521     ///
522     /// Clients wishing to abort computation in response to an
523     /// allocation error are encouraged to call the allocator's `oom`
524     /// method, rather than directly invoking `panic!` or similar.
525     unsafe fn alloc(&mut self, layout: Layout) -> Result<*mut u8, AllocErr>;
526
527     /// Deallocate the memory referenced by `ptr`.
528     ///
529     /// # Safety
530     ///
531     /// This function is unsafe because undefined behavior can result
532     /// if the caller does not ensure all of the following:
533     ///
534     /// * `ptr` must denote a block of memory currently allocated via
535     ///   this allocator,
536     ///
537     /// * `layout` must *fit* that block of memory,
538     ///
539     /// * In addition to fitting the block of memory `layout`, the
540     ///   alignment of the `layout` must match the alignment used
541     ///   to allocate that block of memory.
542     unsafe fn dealloc(&mut self, ptr: *mut u8, layout: Layout);
543
544     /// Allocator-specific method for signaling an out-of-memory
545     /// condition.
546     ///
547     /// `oom` aborts the thread or process, optionally performing
548     /// cleanup or logging diagnostic information before panicking or
549     /// aborting.
550     ///
551     /// `oom` is meant to be used by clients unable to cope with an
552     /// unsatisfied allocation request (signaled by an error such as
553     /// `AllocErr::Exhausted`), and wish to abandon computation rather
554     /// than attempt to recover locally. Such clients should pass the
555     /// signaling error value back into `oom`, where the allocator
556     /// may incorporate that error value into its diagnostic report
557     /// before aborting.
558     ///
559     /// Implementations of the `oom` method are discouraged from
560     /// infinitely regressing in nested calls to `oom`. In
561     /// practice this means implementors should eschew allocating,
562     /// especially from `self` (directly or indirectly).
563     ///
564     /// Implementations of the allocation and reallocation methods
565     /// (e.g. `alloc`, `alloc_one`, `realloc`) are discouraged from
566     /// panicking (or aborting) in the event of memory exhaustion;
567     /// instead they should return an appropriate error from the
568     /// invoked method, and let the client decide whether to invoke
569     /// this `oom` method in response.
570     fn oom(&mut self, _: AllocErr) -> ! {
571         unsafe { ::core::intrinsics::abort() }
572     }
573
574     // == ALLOCATOR-SPECIFIC QUANTITIES AND LIMITS ==
575     // usable_size
576
577     /// Returns bounds on the guaranteed usable size of a successful
578     /// allocation created with the specified `layout`.
579     ///
580     /// In particular, if one has a memory block allocated via a given
581     /// allocator `a` and layout `k` where `a.usable_size(k)` returns
582     /// `(l, u)`, then one can pass that block to `a.dealloc()` with a
583     /// layout in the size range [l, u].
584     ///
585     /// (All implementors of `usable_size` must ensure that
586     /// `l <= k.size() <= u`)
587     ///
588     /// Both the lower- and upper-bounds (`l` and `u` respectively)
589     /// are provided, because an allocator based on size classes could
590     /// misbehave if one attempts to deallocate a block without
591     /// providing a correct value for its size (i.e., one within the
592     /// range `[l, u]`).
593     ///
594     /// Clients who wish to make use of excess capacity are encouraged
595     /// to use the `alloc_excess` and `realloc_excess` instead, as
596     /// this method is constrained to report conservative values that
597     /// serve as valid bounds for *all possible* allocation method
598     /// calls.
599     ///
600     /// However, for clients that do not wish to track the capacity
601     /// returned by `alloc_excess` locally, this method is likely to
602     /// produce useful results.
603     #[inline]
604     fn usable_size(&self, layout: &Layout) -> (usize, usize) {
605         (layout.size(), layout.size())
606     }
607
608     // == METHODS FOR MEMORY REUSE ==
609     // realloc. alloc_excess, realloc_excess
610
611     /// Returns a pointer suitable for holding data described by
612     /// `new_layout`, meeting its size and alignment guarantees. To
613     /// accomplish this, this may extend or shrink the allocation
614     /// referenced by `ptr` to fit `new_layout`.
615     ///
616     /// If this returns `Ok`, then ownership of the memory block
617     /// referenced by `ptr` has been transferred to this
618     /// allocator. The memory may or may not have been freed, and
619     /// should be considered unusable (unless of course it was
620     /// transferred back to the caller again via the return value of
621     /// this method).
622     ///
623     /// If this method returns `Err`, then ownership of the memory
624     /// block has not been transferred to this allocator, and the
625     /// contents of the memory block are unaltered.
626     ///
627     /// For best results, `new_layout` should not impose a different
628     /// alignment constraint than `layout`. (In other words,
629     /// `new_layout.align()` should equal `layout.align()`.) However,
630     /// behavior is well-defined (though underspecified) when this
631     /// constraint is violated; further discussion below.
632     ///
633     /// # Safety
634     ///
635     /// This function is unsafe because undefined behavior can result
636     /// if the caller does not ensure all of the following:
637     ///
638     /// * `ptr` must be currently allocated via this allocator,
639     ///
640     /// * `layout` must *fit* the `ptr` (see above). (The `new_layout`
641     ///   argument need not fit it.)
642     ///
643     /// * `new_layout` must have size greater than zero.
644     ///
645     /// * the alignment of `new_layout` is non-zero.
646     ///
647     /// (Extension subtraits might provide more specific bounds on
648     /// behavior, e.g. guarantee a sentinel address or a null pointer
649     /// in response to a zero-size allocation request.)
650     ///
651     /// # Errors
652     ///
653     /// Returns `Err` only if `new_layout` does not match the
654     /// alignment of `layout`, or does not meet the allocator's size
655     /// and alignment constraints of the allocator, or if reallocation
656     /// otherwise fails.
657     ///
658     /// (Note the previous sentence did not say "if and only if" -- in
659     /// particular, an implementation of this method *can* return `Ok`
660     /// if `new_layout.align() != old_layout.align()`; or it can
661     /// return `Err` in that scenario, depending on whether this
662     /// allocator can dynamically adjust the alignment constraint for
663     /// the block.)
664     ///
665     /// Implementations are encouraged to return `Err` on memory
666     /// exhaustion rather than panicking or aborting, but this is not
667     /// a strict requirement. (Specifically: it is *legal* to
668     /// implement this trait atop an underlying native allocation
669     /// library that aborts on memory exhaustion.)
670     ///
671     /// Clients wishing to abort computation in response to an
672     /// reallocation error are encouraged to call the allocator's `oom`
673     /// method, rather than directly invoking `panic!` or similar.
674     unsafe fn realloc(&mut self,
675                       ptr: *mut u8,
676                       layout: Layout,
677                       new_layout: Layout) -> Result<*mut u8, AllocErr> {
678         let new_size = new_layout.size();
679         let old_size = layout.size();
680         let aligns_match = layout.align == new_layout.align;
681
682         if new_size >= old_size && aligns_match {
683             if let Ok(()) = self.grow_in_place(ptr, layout.clone(), new_layout.clone()) {
684                 return Ok(ptr);
685             }
686         } else if new_size < old_size && aligns_match {
687             if let Ok(()) = self.shrink_in_place(ptr, layout.clone(), new_layout.clone()) {
688                 return Ok(ptr);
689             }
690         }
691
692         // otherwise, fall back on alloc + copy + dealloc.
693         let result = self.alloc(new_layout);
694         if let Ok(new_ptr) = result {
695             ptr::copy_nonoverlapping(ptr as *const u8, new_ptr, cmp::min(old_size, new_size));
696             self.dealloc(ptr, layout);
697         }
698         result
699     }
700
701     /// Behaves like `alloc`, but also ensures that the contents
702     /// are set to zero before being returned.
703     ///
704     /// # Safety
705     ///
706     /// This function is unsafe for the same reasons that `alloc` is.
707     ///
708     /// # Errors
709     ///
710     /// Returning `Err` indicates that either memory is exhausted or
711     /// `layout` does not meet allocator's size or alignment
712     /// constraints, just as in `alloc`.
713     ///
714     /// Clients wishing to abort computation in response to an
715     /// allocation error are encouraged to call the allocator's `oom`
716     /// method, rather than directly invoking `panic!` or similar.
717     unsafe fn alloc_zeroed(&mut self, layout: Layout) -> Result<*mut u8, AllocErr> {
718         let size = layout.size();
719         let p = self.alloc(layout);
720         if let Ok(p) = p {
721             ptr::write_bytes(p, 0, size);
722         }
723         p
724     }
725
726     /// Behaves like `alloc`, but also returns the whole size of
727     /// the returned block. For some `layout` inputs, like arrays, this
728     /// may include extra storage usable for additional data.
729     ///
730     /// # Safety
731     ///
732     /// This function is unsafe for the same reasons that `alloc` is.
733     ///
734     /// # Errors
735     ///
736     /// Returning `Err` indicates that either memory is exhausted or
737     /// `layout` does not meet allocator's size or alignment
738     /// constraints, just as in `alloc`.
739     ///
740     /// Clients wishing to abort computation in response to an
741     /// allocation error are encouraged to call the allocator's `oom`
742     /// method, rather than directly invoking `panic!` or similar.
743     unsafe fn alloc_excess(&mut self, layout: Layout) -> Result<Excess, AllocErr> {
744         let usable_size = self.usable_size(&layout);
745         self.alloc(layout).map(|p| Excess(p, usable_size.1))
746     }
747
748     /// Behaves like `realloc`, but also returns the whole size of
749     /// the returned block. For some `layout` inputs, like arrays, this
750     /// may include extra storage usable for additional data.
751     ///
752     /// # Safety
753     ///
754     /// This function is unsafe for the same reasons that `realloc` is.
755     ///
756     /// # Errors
757     ///
758     /// Returning `Err` indicates that either memory is exhausted or
759     /// `layout` does not meet allocator's size or alignment
760     /// constraints, just as in `realloc`.
761     ///
762     /// Clients wishing to abort computation in response to an
763     /// reallocation error are encouraged to call the allocator's `oom`
764     /// method, rather than directly invoking `panic!` or similar.
765     unsafe fn realloc_excess(&mut self,
766                              ptr: *mut u8,
767                              layout: Layout,
768                              new_layout: Layout) -> Result<Excess, AllocErr> {
769         let usable_size = self.usable_size(&new_layout);
770         self.realloc(ptr, layout, new_layout)
771             .map(|p| Excess(p, usable_size.1))
772     }
773
774     /// Attempts to extend the allocation referenced by `ptr` to fit `new_layout`.
775     ///
776     /// If this returns `Ok`, then the allocator has asserted that the
777     /// memory block referenced by `ptr` now fits `new_layout`, and thus can
778     /// be used to carry data of that layout. (The allocator is allowed to
779     /// expend effort to accomplish this, such as extending the memory block to
780     /// include successor blocks, or virtual memory tricks.)
781     ///
782     /// Regardless of what this method returns, ownership of the
783     /// memory block referenced by `ptr` has not been transferred, and
784     /// the contents of the memory block are unaltered.
785     ///
786     /// # Safety
787     ///
788     /// This function is unsafe because undefined behavior can result
789     /// if the caller does not ensure all of the following:
790     ///
791     /// * `ptr` must be currently allocated via this allocator,
792     ///
793     /// * `layout` must *fit* the `ptr` (see above); note the
794     ///   `new_layout` argument need not fit it,
795     ///
796     /// * `new_layout.size()` must not be less than `layout.size()`,
797     ///
798     /// * `new_layout.align()` must equal `layout.align()`.
799     ///
800     /// # Errors
801     ///
802     /// Returns `Err(CannotReallocInPlace)` when the allocator is
803     /// unable to assert that the memory block referenced by `ptr`
804     /// could fit `layout`.
805     ///
806     /// Note that one cannot pass `CannotReallocInPlace` to the `oom`
807     /// method; clients are expected either to be able to recover from
808     /// `grow_in_place` failures without aborting, or to fall back on
809     /// another reallocation method before resorting to an abort.
810     unsafe fn grow_in_place(&mut self,
811                             ptr: *mut u8,
812                             layout: Layout,
813                             new_layout: Layout) -> Result<(), CannotReallocInPlace> {
814         let _ = ptr; // this default implementation doesn't care about the actual address.
815         debug_assert!(new_layout.size >= layout.size);
816         debug_assert!(new_layout.align == layout.align);
817         let (_l, u) = self.usable_size(&layout);
818         // _l <= layout.size()                       [guaranteed by usable_size()]
819         //       layout.size() <= new_layout.size()  [required by this method]
820         if new_layout.size <= u {
821             return Ok(());
822         } else {
823             return Err(CannotReallocInPlace);
824         }
825     }
826
827     /// Attempts to shrink the allocation referenced by `ptr` to fit `new_layout`.
828     ///
829     /// If this returns `Ok`, then the allocator has asserted that the
830     /// memory block referenced by `ptr` now fits `new_layout`, and
831     /// thus can only be used to carry data of that smaller
832     /// layout. (The allocator is allowed to take advantage of this,
833     /// carving off portions of the block for reuse elsewhere.) The
834     /// truncated contents of the block within the smaller layout are
835     /// unaltered, and ownership of block has not been transferred.
836     ///
837     /// If this returns `Err`, then the memory block is considered to
838     /// still represent the original (larger) `layout`. None of the
839     /// block has been carved off for reuse elsewhere, ownership of
840     /// the memory block has not been transferred, and the contents of
841     /// the memory block are unaltered.
842     ///
843     /// # Safety
844     ///
845     /// This function is unsafe because undefined behavior can result
846     /// if the caller does not ensure all of the following:
847     ///
848     /// * `ptr` must be currently allocated via this allocator,
849     ///
850     /// * `layout` must *fit* the `ptr` (see above); note the
851     ///   `new_layout` argument need not fit it,
852     ///
853     /// * `new_layout.size()` must not be greater than `layout.size()`
854     ///   (and must be greater than zero),
855     ///
856     /// * `new_layout.align()` must equal `layout.align()`.
857     ///
858     /// # Errors
859     ///
860     /// Returns `Err(CannotReallocInPlace)` when the allocator is
861     /// unable to assert that the memory block referenced by `ptr`
862     /// could fit `layout`.
863     ///
864     /// Note that one cannot pass `CannotReallocInPlace` to the `oom`
865     /// method; clients are expected either to be able to recover from
866     /// `shrink_in_place` failures without aborting, or to fall back
867     /// on another reallocation method before resorting to an abort.
868     unsafe fn shrink_in_place(&mut self,
869                               ptr: *mut u8,
870                               layout: Layout,
871                               new_layout: Layout) -> Result<(), CannotReallocInPlace> {
872         let _ = ptr; // this default implementation doesn't care about the actual address.
873         debug_assert!(new_layout.size <= layout.size);
874         debug_assert!(new_layout.align == layout.align);
875         let (l, _u) = self.usable_size(&layout);
876         //                      layout.size() <= _u  [guaranteed by usable_size()]
877         // new_layout.size() <= layout.size()        [required by this method]
878         if l <= new_layout.size {
879             return Ok(());
880         } else {
881             return Err(CannotReallocInPlace);
882         }
883     }
884
885
886     // == COMMON USAGE PATTERNS ==
887     // alloc_one, dealloc_one, alloc_array, realloc_array. dealloc_array
888
889     /// Allocates a block suitable for holding an instance of `T`.
890     ///
891     /// Captures a common usage pattern for allocators.
892     ///
893     /// The returned block is suitable for passing to the
894     /// `alloc`/`realloc` methods of this allocator.
895     ///
896     /// Note to implementors: If this returns `Ok(ptr)`, then `ptr`
897     /// must be considered "currently allocated" and must be
898     /// acceptable input to methods such as `realloc` or `dealloc`,
899     /// *even if* `T` is a zero-sized type. In other words, if your
900     /// `Alloc` implementation overrides this method in a manner
901     /// that can return a zero-sized `ptr`, then all reallocation and
902     /// deallocation methods need to be similarly overridden to accept
903     /// such values as input.
904     ///
905     /// # Errors
906     ///
907     /// Returning `Err` indicates that either memory is exhausted or
908     /// `T` does not meet allocator's size or alignment constraints.
909     ///
910     /// For zero-sized `T`, may return either of `Ok` or `Err`, but
911     /// will *not* yield undefined behavior.
912     ///
913     /// Clients wishing to abort computation in response to an
914     /// allocation error are encouraged to call the allocator's `oom`
915     /// method, rather than directly invoking `panic!` or similar.
916     fn alloc_one<T>(&mut self) -> Result<NonNull<T>, AllocErr>
917         where Self: Sized
918     {
919         let k = Layout::new::<T>();
920         if k.size() > 0 {
921             unsafe { self.alloc(k).map(|p| NonNull::new_unchecked(p as *mut T)) }
922         } else {
923             Err(AllocErr::invalid_input("zero-sized type invalid for alloc_one"))
924         }
925     }
926
927     /// Deallocates a block suitable for holding an instance of `T`.
928     ///
929     /// The given block must have been produced by this allocator,
930     /// and must be suitable for storing a `T` (in terms of alignment
931     /// as well as minimum and maximum size); otherwise yields
932     /// undefined behavior.
933     ///
934     /// Captures a common usage pattern for allocators.
935     ///
936     /// # Safety
937     ///
938     /// This function is unsafe because undefined behavior can result
939     /// if the caller does not ensure both:
940     ///
941     /// * `ptr` must denote a block of memory currently allocated via this allocator
942     ///
943     /// * the layout of `T` must *fit* that block of memory.
944     unsafe fn dealloc_one<T>(&mut self, ptr: NonNull<T>)
945         where Self: Sized
946     {
947         let raw_ptr = ptr.as_ptr() as *mut u8;
948         let k = Layout::new::<T>();
949         if k.size() > 0 {
950             self.dealloc(raw_ptr, k);
951         }
952     }
953
954     /// Allocates a block suitable for holding `n` instances of `T`.
955     ///
956     /// Captures a common usage pattern for allocators.
957     ///
958     /// The returned block is suitable for passing to the
959     /// `alloc`/`realloc` methods of this allocator.
960     ///
961     /// Note to implementors: If this returns `Ok(ptr)`, then `ptr`
962     /// must be considered "currently allocated" and must be
963     /// acceptable input to methods such as `realloc` or `dealloc`,
964     /// *even if* `T` is a zero-sized type. In other words, if your
965     /// `Alloc` implementation overrides this method in a manner
966     /// that can return a zero-sized `ptr`, then all reallocation and
967     /// deallocation methods need to be similarly overridden to accept
968     /// such values as input.
969     ///
970     /// # Errors
971     ///
972     /// Returning `Err` indicates that either memory is exhausted or
973     /// `[T; n]` does not meet allocator's size or alignment
974     /// constraints.
975     ///
976     /// For zero-sized `T` or `n == 0`, may return either of `Ok` or
977     /// `Err`, but will *not* yield undefined behavior.
978     ///
979     /// Always returns `Err` on arithmetic overflow.
980     ///
981     /// Clients wishing to abort computation in response to an
982     /// allocation error are encouraged to call the allocator's `oom`
983     /// method, rather than directly invoking `panic!` or similar.
984     fn alloc_array<T>(&mut self, n: usize) -> Result<NonNull<T>, AllocErr>
985         where Self: Sized
986     {
987         match Layout::array::<T>(n) {
988             Some(ref layout) if layout.size() > 0 => {
989                 unsafe {
990                     self.alloc(layout.clone())
991                         .map(|p| {
992                             NonNull::new_unchecked(p as *mut T)
993                         })
994                 }
995             }
996             _ => Err(AllocErr::invalid_input("invalid layout for alloc_array")),
997         }
998     }
999
1000     /// Reallocates a block previously suitable for holding `n_old`
1001     /// instances of `T`, returning a block suitable for holding
1002     /// `n_new` instances of `T`.
1003     ///
1004     /// Captures a common usage pattern for allocators.
1005     ///
1006     /// The returned block is suitable for passing to the
1007     /// `alloc`/`realloc` methods of this allocator.
1008     ///
1009     /// # Safety
1010     ///
1011     /// This function is unsafe because undefined behavior can result
1012     /// if the caller does not ensure all of the following:
1013     ///
1014     /// * `ptr` must be currently allocated via this allocator,
1015     ///
1016     /// * the layout of `[T; n_old]` must *fit* that block of memory.
1017     ///
1018     /// # Errors
1019     ///
1020     /// Returning `Err` indicates that either memory is exhausted or
1021     /// `[T; n_new]` does not meet allocator's size or alignment
1022     /// constraints.
1023     ///
1024     /// For zero-sized `T` or `n_new == 0`, may return either of `Ok` or
1025     /// `Err`, but will *not* yield undefined behavior.
1026     ///
1027     /// Always returns `Err` on arithmetic overflow.
1028     ///
1029     /// Clients wishing to abort computation in response to an
1030     /// reallocation error are encouraged to call the allocator's `oom`
1031     /// method, rather than directly invoking `panic!` or similar.
1032     unsafe fn realloc_array<T>(&mut self,
1033                                ptr: NonNull<T>,
1034                                n_old: usize,
1035                                n_new: usize) -> Result<NonNull<T>, AllocErr>
1036         where Self: Sized
1037     {
1038         match (Layout::array::<T>(n_old), Layout::array::<T>(n_new), ptr.as_ptr()) {
1039             (Some(ref k_old), Some(ref k_new), ptr) if k_old.size() > 0 && k_new.size() > 0 => {
1040                 self.realloc(ptr as *mut u8, k_old.clone(), k_new.clone())
1041                     .map(|p| NonNull::new_unchecked(p as *mut T))
1042             }
1043             _ => {
1044                 Err(AllocErr::invalid_input("invalid layout for realloc_array"))
1045             }
1046         }
1047     }
1048
1049     /// Deallocates a block suitable for holding `n` instances of `T`.
1050     ///
1051     /// Captures a common usage pattern for allocators.
1052     ///
1053     /// # Safety
1054     ///
1055     /// This function is unsafe because undefined behavior can result
1056     /// if the caller does not ensure both:
1057     ///
1058     /// * `ptr` must denote a block of memory currently allocated via this allocator
1059     ///
1060     /// * the layout of `[T; n]` must *fit* that block of memory.
1061     ///
1062     /// # Errors
1063     ///
1064     /// Returning `Err` indicates that either `[T; n]` or the given
1065     /// memory block does not meet allocator's size or alignment
1066     /// constraints.
1067     ///
1068     /// Always returns `Err` on arithmetic overflow.
1069     unsafe fn dealloc_array<T>(&mut self, ptr: NonNull<T>, n: usize) -> Result<(), AllocErr>
1070         where Self: Sized
1071     {
1072         let raw_ptr = ptr.as_ptr() as *mut u8;
1073         match Layout::array::<T>(n) {
1074             Some(ref k) if k.size() > 0 => {
1075                 Ok(self.dealloc(raw_ptr, k.clone()))
1076             }
1077             _ => {
1078                 Err(AllocErr::invalid_input("invalid layout for dealloc_array"))
1079             }
1080         }
1081     }
1082 }