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