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