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