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