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