Skip to main content

core/alloc/
mod.rs

1//! Memory allocation APIs
2
3#![stable(feature = "alloc_module", since = "1.28.0")]
4
5#[cfg(not(feature = "ferrocene_subset"))]
6mod global;
7mod layout;
8
9#[stable(feature = "global_alloc", since = "1.28.0")]
10#[cfg(not(feature = "ferrocene_subset"))]
11pub use self::global::GlobalAlloc;
12#[stable(feature = "alloc_layout", since = "1.28.0")]
13pub use self::layout::Layout;
14#[stable(feature = "alloc_layout", since = "1.28.0")]
15#[deprecated(
16    since = "1.52.0",
17    note = "Name does not follow std convention, use LayoutError",
18    suggestion = "LayoutError"
19)]
20#[allow(deprecated, deprecated_in_future)]
21#[cfg(not(feature = "ferrocene_subset"))]
22pub use self::layout::LayoutErr;
23#[stable(feature = "alloc_layout_error", since = "1.50.0")]
24#[cfg(not(feature = "ferrocene_subset"))]
25pub use self::layout::LayoutError;
26#[cfg(not(feature = "ferrocene_subset"))]
27use crate::error::Error;
28#[cfg(not(feature = "ferrocene_subset"))]
29use crate::fmt;
30#[cfg(not(feature = "ferrocene_subset"))]
31use crate::ptr::{self, NonNull};
32
33/// The `AllocError` error indicates an allocation failure
34/// that may be due to resource exhaustion or to
35/// something wrong when combining the given input arguments with this
36/// allocator.
37#[unstable(feature = "allocator_api", issue = "32838")]
38#[derive(Copy, Clone, PartialEq, Eq, Debug)]
39#[cfg(not(feature = "ferrocene_subset"))]
40pub struct AllocError;
41
42#[unstable(
43    feature = "allocator_api",
44    reason = "the precise API and guarantees it provides may be tweaked.",
45    issue = "32838"
46)]
47#[cfg(not(feature = "ferrocene_subset"))]
48impl Error for AllocError {}
49
50// (we need this for downstream impl of trait Error)
51#[unstable(feature = "allocator_api", issue = "32838")]
52#[cfg(not(feature = "ferrocene_subset"))]
53impl fmt::Display for AllocError {
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        f.write_str("memory allocation failed")
56    }
57}
58
59/// An implementation of `Allocator` can allocate, grow, shrink, and deallocate arbitrary blocks of
60/// data described via [`Layout`][].
61///
62/// `Allocator` is designed to be implemented on ZSTs, references, or smart pointers.
63/// An allocator for `MyAlloc([u8; N])` cannot be moved, without updating the pointers to the
64/// allocated memory.
65///
66/// In contrast to [`GlobalAlloc`][], `Allocator` allows zero-sized allocations. If an underlying
67/// allocator does not support this (like jemalloc) or responds by returning a null pointer
68/// (such as `libc::malloc`), this must be caught by the implementation.
69///
70/// ### Currently allocated memory
71///
72/// Some of the methods require that a memory block is *currently allocated* by an allocator.
73/// This means that:
74///  * the starting address for that memory block was previously
75///    returned by [`allocate`], [`grow`], or [`shrink`], and
76///  * the memory block has not subsequently been deallocated.
77///
78/// A memory block is deallocated by a call to [`deallocate`],
79/// or by a call to [`grow`] or [`shrink`] that returns `Ok`.
80/// A call to `grow` or `shrink` that returns `Err`,
81/// does not deallocate the memory block passed to it.
82///
83/// [`allocate`]: Allocator::allocate
84/// [`grow`]: Allocator::grow
85/// [`shrink`]: Allocator::shrink
86/// [`deallocate`]: Allocator::deallocate
87///
88/// ### Memory fitting
89///
90/// Some of the methods require that a `layout` *fit* a memory block or vice versa. This means that the
91/// following conditions must hold:
92///  * the memory block must be *currently allocated* with alignment of [`layout.align()`], and
93///  * [`layout.size()`] must fall in the range `min ..= max`, where:
94///    - `min` is the size of the layout used to allocate the block, and
95///    - `max` is the actual size returned from [`allocate`], [`grow`], or [`shrink`].
96///
97/// [`layout.align()`]: Layout::align
98/// [`layout.size()`]: Layout::size
99///
100/// # Safety
101///
102/// Memory blocks that are [*currently allocated*] by an allocator,
103/// must point to valid memory, and retain their validity until either:
104///  - the memory block is deallocated, or
105///  - the allocator is dropped.
106///
107/// Copying, cloning, or moving the allocator must not invalidate memory blocks returned from it.
108/// A copied or cloned allocator must behave like the original allocator.
109///
110/// A memory block which is [*currently allocated*] may be passed to
111/// any method of the allocator that accepts such an argument.
112///
113/// [*currently allocated*]: #currently-allocated-memory
114#[unstable(feature = "allocator_api", issue = "32838")]
115#[cfg(not(feature = "ferrocene_subset"))]
116#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
117pub const unsafe trait Allocator {
118    /// Attempts to allocate a block of memory.
119    ///
120    /// On success, returns a [`NonNull<[u8]>`][NonNull] meeting the size and alignment guarantees of `layout`.
121    ///
122    /// The returned block may have a larger size than specified by `layout.size()`, and may or may
123    /// not have its contents initialized.
124    ///
125    /// The returned block of memory remains valid as long as it is [*currently allocated*] and the shorter of:
126    ///   - the borrow-checker lifetime of the allocator type itself.
127    ///   - as long as the allocator and all its clones have not been dropped.
128    ///
129    /// [*currently allocated*]: #currently-allocated-memory
130    ///
131    /// # Errors
132    ///
133    /// Returning `Err` indicates that either memory is exhausted or `layout` does not meet
134    /// allocator's size or alignment constraints.
135    ///
136    /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
137    /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
138    /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
139    ///
140    /// Clients wishing to abort computation in response to an allocation error are encouraged to
141    /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
142    ///
143    /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
144    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>;
145
146    /// Behaves like `allocate`, but also ensures that the returned memory is zero-initialized.
147    ///
148    /// # Errors
149    ///
150    /// Returning `Err` indicates that either memory is exhausted or `layout` does not meet
151    /// allocator's size or alignment constraints.
152    ///
153    /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
154    /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
155    /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
156    ///
157    /// Clients wishing to abort computation in response to an allocation error are encouraged to
158    /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
159    ///
160    /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
161    fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
162        let ptr = self.allocate(layout)?;
163        // SAFETY: `alloc` returns a valid memory block
164        unsafe { ptr.as_non_null_ptr().as_ptr().write_bytes(0, ptr.len()) }
165        Ok(ptr)
166    }
167
168    /// Deallocates the memory referenced by `ptr`.
169    ///
170    /// # Safety
171    ///
172    /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator, and
173    /// * `layout` must [*fit*] that block of memory.
174    ///
175    /// [*currently allocated*]: #currently-allocated-memory
176    /// [*fit*]: #memory-fitting
177    unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout);
178
179    /// Attempts to extend the memory block.
180    ///
181    /// Returns a new [`NonNull<[u8]>`][NonNull] containing a pointer and the actual size of the allocated
182    /// memory. The pointer is suitable for holding data described by `new_layout`. To accomplish
183    /// this, the allocator may extend the allocation referenced by `ptr` to fit the new layout.
184    ///
185    /// If this returns `Ok`, then ownership of the memory block referenced by `ptr` has been
186    /// transferred to this allocator. Any access to the old `ptr` is Undefined Behavior, even if the
187    /// allocation was grown in-place. The newly returned pointer is the only valid pointer
188    /// for accessing this memory now.
189    ///
190    /// If this method returns `Err`, then ownership of the memory block has not been transferred to
191    /// this allocator, and the contents of the memory block are unaltered.
192    ///
193    /// # Safety
194    ///
195    /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator.
196    /// * `old_layout` must [*fit*] that block of memory (The `new_layout` argument need not fit it.).
197    /// * `new_layout.size()` must be greater than or equal to `old_layout.size()`.
198    ///
199    /// Note that `new_layout.align()` need not be the same as `old_layout.align()`.
200    ///
201    /// [*currently allocated*]: #currently-allocated-memory
202    /// [*fit*]: #memory-fitting
203    ///
204    /// # Errors
205    ///
206    /// Returns `Err` if the new layout does not meet the allocator's size and alignment
207    /// constraints of the allocator, or if growing otherwise fails.
208    ///
209    /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
210    /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
211    /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
212    ///
213    /// Clients wishing to abort computation in response to an allocation error are encouraged to
214    /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
215    ///
216    /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
217    unsafe fn grow(
218        &self,
219        ptr: NonNull<u8>,
220        old_layout: Layout,
221        new_layout: Layout,
222    ) -> Result<NonNull<[u8]>, AllocError> {
223        debug_assert!(
224            new_layout.size() >= old_layout.size(),
225            "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
226        );
227
228        let new_ptr = self.allocate(new_layout)?;
229
230        // SAFETY: because `new_layout.size()` must be greater than or equal to
231        // `old_layout.size()`, both the old and new memory allocation are valid for reads and
232        // writes for `old_layout.size()` bytes. Also, because the old allocation wasn't yet
233        // deallocated, it cannot overlap `new_ptr`. Thus, the call to `copy_nonoverlapping` is
234        // safe. The safety contract for `dealloc` must be upheld by the caller.
235        unsafe {
236            ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_layout.size());
237            self.deallocate(ptr, old_layout);
238        }
239
240        Ok(new_ptr)
241    }
242
243    /// Behaves like `grow`, but also ensures that the new contents are set to zero before being
244    /// returned.
245    ///
246    /// The memory block will contain the following contents after a successful call to
247    /// `grow_zeroed`:
248    ///   * Bytes `0..old_layout.size()` are preserved from the original allocation.
249    ///   * Bytes `old_layout.size()..old_size` will either be preserved or zeroed, depending on
250    ///     the allocator implementation. `old_size` refers to the size of the memory block prior
251    ///     to the `grow_zeroed` call, which may be larger than the size that was originally
252    ///     requested when it was allocated.
253    ///   * Bytes `old_size..new_size` are zeroed. `new_size` refers to the size of the memory
254    ///     block returned by the `grow_zeroed` call.
255    ///
256    /// # Safety
257    ///
258    /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator.
259    /// * `old_layout` must [*fit*] that block of memory (The `new_layout` argument need not fit it.).
260    /// * `new_layout.size()` must be greater than or equal to `old_layout.size()`.
261    ///
262    /// Note that `new_layout.align()` need not be the same as `old_layout.align()`.
263    ///
264    /// [*currently allocated*]: #currently-allocated-memory
265    /// [*fit*]: #memory-fitting
266    ///
267    /// # Errors
268    ///
269    /// Returns `Err` if the new layout does not meet the allocator's size and alignment
270    /// constraints of the allocator, or if growing otherwise fails.
271    ///
272    /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
273    /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
274    /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
275    ///
276    /// Clients wishing to abort computation in response to an allocation error are encouraged to
277    /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
278    ///
279    /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
280    unsafe fn grow_zeroed(
281        &self,
282        ptr: NonNull<u8>,
283        old_layout: Layout,
284        new_layout: Layout,
285    ) -> Result<NonNull<[u8]>, AllocError> {
286        debug_assert!(
287            new_layout.size() >= old_layout.size(),
288            "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
289        );
290
291        let new_ptr = self.allocate_zeroed(new_layout)?;
292
293        // SAFETY: because `new_layout.size()` must be greater than or equal to
294        // `old_layout.size()`, both the old and new memory allocation are valid for reads and
295        // writes for `old_layout.size()` bytes. Also, because the old allocation wasn't yet
296        // deallocated, it cannot overlap `new_ptr`. Thus, the call to `copy_nonoverlapping` is
297        // safe. The safety contract for `dealloc` must be upheld by the caller.
298        unsafe {
299            ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_layout.size());
300            self.deallocate(ptr, old_layout);
301        }
302
303        Ok(new_ptr)
304    }
305
306    /// Attempts to shrink the memory block.
307    ///
308    /// Returns a new [`NonNull<[u8]>`][NonNull] containing a pointer and the actual size of the allocated
309    /// memory. The pointer is suitable for holding data described by `new_layout`. To accomplish
310    /// this, the allocator may shrink the allocation referenced by `ptr` to fit the new layout.
311    ///
312    /// If this returns `Ok`, then ownership of the memory block referenced by `ptr` has been
313    /// transferred to this allocator. Any access to the old `ptr` is Undefined Behavior, even if the
314    /// allocation was shrunk in-place. The newly returned pointer is the only valid pointer
315    /// for accessing this memory now.
316    ///
317    /// If this method returns `Err`, then ownership of the memory block has not been transferred to
318    /// this allocator, and the contents of the memory block are unaltered.
319    ///
320    /// # Safety
321    ///
322    /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator.
323    /// * `old_layout` must [*fit*] that block of memory (The `new_layout` argument need not fit it.).
324    /// * `new_layout.size()` must be smaller than or equal to `old_layout.size()`.
325    ///
326    /// Note that `new_layout.align()` need not be the same as `old_layout.align()`.
327    ///
328    /// [*currently allocated*]: #currently-allocated-memory
329    /// [*fit*]: #memory-fitting
330    ///
331    /// # Errors
332    ///
333    /// Returns `Err` if the new layout does not meet the allocator's size and alignment
334    /// constraints of the allocator, or if shrinking otherwise fails.
335    ///
336    /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
337    /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
338    /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
339    ///
340    /// Clients wishing to abort computation in response to an allocation error are encouraged to
341    /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
342    ///
343    /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
344    unsafe fn shrink(
345        &self,
346        ptr: NonNull<u8>,
347        old_layout: Layout,
348        new_layout: Layout,
349    ) -> Result<NonNull<[u8]>, AllocError> {
350        debug_assert!(
351            new_layout.size() <= old_layout.size(),
352            "`new_layout.size()` must be smaller than or equal to `old_layout.size()`"
353        );
354
355        let new_ptr = self.allocate(new_layout)?;
356
357        // SAFETY: because `new_layout.size()` must be lower than or equal to
358        // `old_layout.size()`, both the old and new memory allocation are valid for reads and
359        // writes for `new_layout.size()` bytes. Also, because the old allocation wasn't yet
360        // deallocated, it cannot overlap `new_ptr`. Thus, the call to `copy_nonoverlapping` is
361        // safe. The safety contract for `dealloc` must be upheld by the caller.
362        unsafe {
363            ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), new_layout.size());
364            self.deallocate(ptr, old_layout);
365        }
366
367        Ok(new_ptr)
368    }
369
370    /// Creates a "by reference" adapter for this instance of `Allocator`.
371    ///
372    /// The returned adapter also implements `Allocator` and will simply borrow this.
373    #[inline(always)]
374    fn by_ref(&self) -> &Self
375    where
376        Self: Sized,
377    {
378        self
379    }
380}
381
382#[unstable(feature = "allocator_api", issue = "32838")]
383#[cfg(not(feature = "ferrocene_subset"))]
384#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
385unsafe impl<A> const Allocator for &A
386where
387    A: [const] Allocator + ?Sized,
388{
389    #[inline]
390    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
391        (**self).allocate(layout)
392    }
393
394    #[inline]
395    fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
396        (**self).allocate_zeroed(layout)
397    }
398
399    #[inline]
400    unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
401        // SAFETY: the safety contract must be upheld by the caller
402        unsafe { (**self).deallocate(ptr, layout) }
403    }
404
405    #[inline]
406    unsafe fn grow(
407        &self,
408        ptr: NonNull<u8>,
409        old_layout: Layout,
410        new_layout: Layout,
411    ) -> Result<NonNull<[u8]>, AllocError> {
412        // SAFETY: the safety contract must be upheld by the caller
413        unsafe { (**self).grow(ptr, old_layout, new_layout) }
414    }
415
416    #[inline]
417    unsafe fn grow_zeroed(
418        &self,
419        ptr: NonNull<u8>,
420        old_layout: Layout,
421        new_layout: Layout,
422    ) -> Result<NonNull<[u8]>, AllocError> {
423        // SAFETY: the safety contract must be upheld by the caller
424        unsafe { (**self).grow_zeroed(ptr, old_layout, new_layout) }
425    }
426
427    #[inline]
428    unsafe fn shrink(
429        &self,
430        ptr: NonNull<u8>,
431        old_layout: Layout,
432        new_layout: Layout,
433    ) -> Result<NonNull<[u8]>, AllocError> {
434        // SAFETY: the safety contract must be upheld by the caller
435        unsafe { (**self).shrink(ptr, old_layout, new_layout) }
436    }
437}
438
439#[cfg(not(feature = "ferrocene_subset"))]
440#[unstable(feature = "allocator_api", issue = "32838")]
441unsafe impl<A> Allocator for &mut A
442where
443    A: Allocator + ?Sized,
444{
445    #[inline]
446    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
447        (**self).allocate(layout)
448    }
449
450    #[inline]
451    fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
452        (**self).allocate_zeroed(layout)
453    }
454
455    #[inline]
456    unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
457        // SAFETY: the safety contract must be upheld by the caller
458        unsafe { (**self).deallocate(ptr, layout) }
459    }
460
461    #[inline]
462    unsafe fn grow(
463        &self,
464        ptr: NonNull<u8>,
465        old_layout: Layout,
466        new_layout: Layout,
467    ) -> Result<NonNull<[u8]>, AllocError> {
468        // SAFETY: the safety contract must be upheld by the caller
469        unsafe { (**self).grow(ptr, old_layout, new_layout) }
470    }
471
472    #[inline]
473    unsafe fn grow_zeroed(
474        &self,
475        ptr: NonNull<u8>,
476        old_layout: Layout,
477        new_layout: Layout,
478    ) -> Result<NonNull<[u8]>, AllocError> {
479        // SAFETY: the safety contract must be upheld by the caller
480        unsafe { (**self).grow_zeroed(ptr, old_layout, new_layout) }
481    }
482
483    #[inline]
484    unsafe fn shrink(
485        &self,
486        ptr: NonNull<u8>,
487        old_layout: Layout,
488        new_layout: Layout,
489    ) -> Result<NonNull<[u8]>, AllocError> {
490        // SAFETY: the safety contract must be upheld by the caller
491        unsafe { (**self).shrink(ptr, old_layout, new_layout) }
492    }
493}