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