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