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