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