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