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