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