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