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