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