core/alloc/mod.rs
1//! Memory allocation APIs
2
3#![stable(feature = "alloc_module", since = "1.28.0")]
4
5mod global;
6mod layout;
7
8#[stable(feature = "global_alloc", since = "1.28.0")]
9pub use self::global::GlobalAlloc;
10#[stable(feature = "alloc_layout", since = "1.28.0")]
11pub use self::layout::Layout;
12#[stable(feature = "alloc_layout", since = "1.28.0")]
13#[deprecated(
14 since = "1.52.0",
15 note = "Name does not follow std convention, use LayoutError",
16 suggestion = "LayoutError"
17)]
18#[allow(deprecated, deprecated_in_future)]
19pub use self::layout::LayoutErr;
20#[stable(feature = "alloc_layout_error", since = "1.50.0")]
21pub use self::layout::LayoutError;
22use crate::error::Error;
23use crate::fmt;
24use crate::ptr::{self, NonNull};
25
26/// The `AllocError` error indicates an allocation failure
27/// that may be due to resource exhaustion or to
28/// something wrong when combining the given input arguments with this
29/// allocator.
30#[unstable(feature = "allocator_api", issue = "32838")]
31#[derive(Copy, Clone, PartialEq, Eq, Debug)]
32pub struct AllocError;
33
34#[unstable(
35 feature = "allocator_api",
36 reason = "the precise API and guarantees it provides may be tweaked.",
37 issue = "32838"
38)]
39impl Error for AllocError {}
40
41// (we need this for downstream impl of trait Error)
42#[unstable(feature = "allocator_api", issue = "32838")]
43impl fmt::Display for AllocError {
44 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45 f.write_str("memory allocation failed")
46 }
47}
48
49/// An implementation of `Allocator` can allocate, grow, shrink, and deallocate arbitrary blocks of
50/// data described via [`Layout`][].
51///
52/// `Allocator` is designed to be implemented on ZSTs, references, or smart pointers.
53/// An allocator for `MyAlloc([u8; N])` cannot be moved, without updating the pointers to the
54/// allocated memory.
55///
56/// In contrast to [`GlobalAlloc`][], `Allocator` allows zero-sized allocations. If an underlying
57/// allocator does not support this (like jemalloc) or responds by returning a null pointer
58/// (such as `libc::malloc`), this must be caught by the implementation.
59///
60/// ### Equivalent allocators
61///
62/// Multiple allocator values can sometimes be interchangeable with each other.
63/// When this is the case, we refer to those allocators as being *equivalent* to
64/// each other.
65///
66/// The following conditions are sufficient conditions for allocators to be equivalent.
67/// * An allocator is equivalent to itself. (Equivalence is reflexive.)
68/// * If an allocator is equivalent to a second allocator, then
69/// the second allocator is also equivalent to the first. (Equivalence is symmetric.)
70/// * If an allocator is equivalent to a second allocator, and
71/// the second allocator is equivalent to a third allocator, then
72/// the first allocator is also equivalent to the third allocator.
73/// (Equivalence is transitive.)
74/// * Moving, subtyping, unsize-coercing, or trait-upcasting an allocator does not change
75/// what the allocator is equivalent to.
76/// * Copying or cloning allocator results in an allocator that's
77/// equivalent to the initial allocator.
78///
79/// Additionally, implementors of `Allocator` may specify additional equivalences
80/// between allocators. It is the responsibility of such implementors to make sure
81/// that equivalent allocators have "compatible" `Allocator` implementations.
82/// In particular, the standard library specifies the following equivalences:
83/// * A reference to an allocator (either `&` or `&mut`) is equivalent to
84/// the allocator being referenced.
85/// * A `Box`, `Rc`, or `Arc` containing an allocator is equivalent to
86/// the allocator inside.
87/// * All `Global` allocator instances are equivalent with each other.
88/// * All `System` allocator instances are equivalent with each other.
89///
90/// Note: Currently, the interaction between cloning and unsize-coercing allocators
91/// is unsound, and there is ongoing discussion on how to revise the `Allocator` trait
92/// to fix this. See [#156920].
93///
94/// [#156920]: https://github.com/rust-lang/rust/issues/156920
95///
96/// ### Currently allocated memory
97///
98/// Some of the methods require that a memory block is *currently allocated* by some specific allocator.
99/// This means that:
100/// * the starting address for that memory block was previously returned by
101/// the [`allocate`], [`allocate_zeroed`], [`grow`], [`grow_zeroed`], or [`shrink`] methods,
102/// called on an allocator that's equivalent to this specific allocator; and
103/// * the memory block has not subsequently been [*invalidated*].
104///
105/// [*invalidated*]: #invalidating-memory-blocks
106///
107/// ### Invalidating memory blocks
108///
109/// A memory block that is currently allocated becomes *invalidated* when one
110/// of the following happens:
111/// * The memory block is deallocated. This occurs when the memory block
112/// is passed as an argument to a [`deallocate`] call, or when it is passed
113/// as an argument to a [`grow`], [`grow_zeroed`] or [`shrink`] call that returns `Ok`.
114/// * All (equivalent) allocators that this memory block is allocated with,
115/// each has one of the following happen to them:
116/// * The allocator's destructor runs.
117/// * The allocator is mutated through public API taking `&mut` access.
118/// * One of the borrow-checker lifetimes in the allocator's type expires.
119///
120/// Note that these conditions imply that a collection may ensure that
121/// any specific currently allocated memory block won't be invalidated, by:
122/// * not deallocating that memory block,
123/// * owning an allocator that memory block is allocated with, and
124/// * not publicly exposing `&mut` access to that allocator.
125///
126/// Also note that safe public API of an allocator with `&` access is not
127/// allowed to invalidate its memory blocks. Furthermore, unsafe public API
128/// of an allocator with `&` access must document that they invalidate
129/// memory blocks (e.g., by calling `deallocate`) if they do. Therefore,
130/// collections may safely expose `&` access to its allocator.
131///
132/// Also note that, even in cases where are other "alive" allocators known to be
133/// equivalent to a given collection's allocator, most collections still should
134/// not publicly expose `&mut` access to its allocator. The fact that there are
135/// other "alive" allocators would prevent this `&mut` access from invalidating
136/// the collection's memory block, but public `&mut` access is still likely to
137/// be unsound, since a user could replace the collection's allocator with
138/// a non-equivalent allocator, causing the collection to deallocate its memory
139/// with the wrong allocator.
140///
141/// [`allocate`]: Allocator::allocate
142/// [`allocate_zeroed`]: Allocator::allocate_zeroed
143/// [`grow`]: Allocator::grow
144/// [`grow_zeroed`]: Allocator::grow_zeroed
145/// [`shrink`]: Allocator::shrink
146/// [`deallocate`]: Allocator::deallocate
147///
148/// ### Memory fitting
149///
150/// Some of the methods require that a `layout` *fit* a memory block or vice versa. This means that the
151/// following conditions must hold:
152/// * the memory block must be *currently allocated* with alignment of [`layout.align()`], and
153/// * [`layout.size()`] must fall in the range `min ..= max`, where:
154/// - `min` is the size of the layout used to allocate the block, and
155/// - `max` is the actual size returned from [`allocate`], [`allocate_zeroed`],
156/// [`grow`], [`grow_zeroed`], or [`shrink`].
157///
158/// [`layout.align()`]: Layout::align
159/// [`layout.size()`]: Layout::size
160///
161/// # Safety
162///
163/// Implementors of `Allocator` must ensure that a memory block that
164/// is [*currently allocated*] by the allocator points to valid memory,
165/// until that memory block is [*invalidated*]. The implementor must also
166/// not violate this invariant of `Allocator` via allocator equivalences
167/// that are in the implementor's control (e.g., via a misbehaving
168/// `impl Clone for Box<MyAllocator>`).
169///
170/// Additionally, any memory block returned by the allocator must
171/// satisfy the allocation invariants described in `core::ptr`.
172/// In particular, if a block has base address `p` and size `n`,
173/// then `p as usize + n <= usize::MAX` must hold.
174///
175/// This ensures that pointer arithmetic within the allocation
176/// (for example, `ptr.add(len)`) cannot overflow the address space.
177///
178/// [*currently allocated*]: #currently-allocated-memory
179/// [*invalidated*]: #invalidating-memory-blocks
180#[unstable(feature = "allocator_api", issue = "32838")]
181#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
182pub const unsafe trait Allocator {
183 /// Attempts to allocate a block of memory.
184 ///
185 /// On success, returns a [`NonNull<[u8]>`][NonNull] meeting the size and alignment guarantees of `layout`.
186 ///
187 /// The returned block may have a larger size than specified by `layout.size()`, and may or may
188 /// not have its contents initialized.
189 ///
190 /// Note that the returned block of memory is considered [*currently allocated*]
191 /// with this allocator (and equivalent allocators).
192 /// Therefore, it is the responsibility of implementors of `Allocator` to make sure that
193 /// this block of memory points to valid memory until the block is [*invalidated*]
194 ///
195 /// [*currently allocated*]: #currently-allocated-memory
196 /// [*invalidated*]: #invalidating-memory-blocks
197 ///
198 /// # Errors
199 ///
200 /// Returning `Err` indicates that either memory is exhausted or `layout` does not meet
201 /// allocator's size or alignment constraints.
202 ///
203 /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
204 /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
205 /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
206 ///
207 /// Clients wishing to abort computation in response to an allocation error are encouraged to
208 /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
209 ///
210 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
211 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>;
212
213 /// Behaves like `allocate`, but also ensures that the returned memory is zero-initialized.
214 ///
215 /// # Errors
216 ///
217 /// Returning `Err` indicates that either memory is exhausted or `layout` does not meet
218 /// allocator's size or alignment constraints.
219 ///
220 /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
221 /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
222 /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
223 ///
224 /// Clients wishing to abort computation in response to an allocation error are encouraged to
225 /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
226 ///
227 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
228 fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
229 let ptr = self.allocate(layout)?;
230 // SAFETY: `alloc` returns a valid memory block
231 unsafe { ptr.as_non_null_ptr().as_ptr().write_bytes(0, ptr.len()) }
232 Ok(ptr)
233 }
234
235 /// Deallocates the memory referenced by `ptr`.
236 ///
237 /// # Safety
238 ///
239 /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator, and
240 /// * `layout` must [*fit*] that block of memory.
241 ///
242 /// [*currently allocated*]: #currently-allocated-memory
243 /// [*fit*]: #memory-fitting
244 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout);
245
246 /// Attempts to extend the memory block.
247 ///
248 /// Returns a new [`NonNull<[u8]>`][NonNull] containing a pointer and the actual size of the allocated
249 /// memory. The pointer is suitable for holding data described by `new_layout`. To accomplish
250 /// this, the allocator may extend the allocation referenced by `ptr` to fit the new layout.
251 ///
252 /// If this returns `Ok`, then the memory block referenced by `ptr` has been [*invalidated*].
253 /// The old `ptr` must not be used to access the memory, even if the allocation was grown in-place.
254 /// The newly returned pointer is the only valid pointer for accessing this memory now.
255 ///
256 /// If this method returns `Err`, then the memory block has not been *invalidated*,
257 /// and the contents of the memory block are unaltered.
258 ///
259 /// # Safety
260 ///
261 /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator.
262 /// * `old_layout` must [*fit*] that block of memory (The `new_layout` argument need not fit it.).
263 /// * `new_layout.size()` must be greater than or equal to `old_layout.size()`.
264 ///
265 /// Note that `new_layout.align()` need not be the same as `old_layout.align()`.
266 ///
267 /// [*currently allocated*]: #currently-allocated-memory
268 /// [*fit*]: #memory-fitting
269 /// [*invalidated*]: #invalidating-memory-blocks
270 ///
271 /// # Errors
272 ///
273 /// Returns `Err` if the new layout does not meet the allocator's size and alignment
274 /// constraints of the allocator, or if growing otherwise fails.
275 ///
276 /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
277 /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
278 /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
279 ///
280 /// Clients wishing to abort computation in response to an allocation error are encouraged to
281 /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
282 ///
283 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
284 unsafe fn grow(
285 &self,
286 ptr: NonNull<u8>,
287 old_layout: Layout,
288 new_layout: Layout,
289 ) -> Result<NonNull<[u8]>, AllocError> {
290 debug_assert!(
291 new_layout.size() >= old_layout.size(),
292 "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
293 );
294
295 let new_ptr = self.allocate(new_layout)?;
296
297 // SAFETY: because `new_layout.size()` must be greater than or equal to
298 // `old_layout.size()`, both the old and new memory allocation are valid for reads and
299 // writes for `old_layout.size()` bytes. Also, because the old allocation wasn't yet
300 // deallocated, it cannot overlap `new_ptr`. Thus, the call to `copy_nonoverlapping` is
301 // safe. The safety contract for `dealloc` must be upheld by the caller.
302 unsafe {
303 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_layout.size());
304 self.deallocate(ptr, old_layout);
305 }
306
307 Ok(new_ptr)
308 }
309
310 /// Behaves like `grow`, but also ensures that the new contents are set to zero before being
311 /// returned.
312 ///
313 /// The memory block will contain the following contents after a successful call to
314 /// `grow_zeroed`:
315 /// * Bytes `0..old_layout.size()` are preserved from the original allocation.
316 /// * Bytes `old_layout.size()..old_size` will either be preserved or zeroed, depending on
317 /// the allocator implementation. `old_size` refers to the size of the memory block prior
318 /// to the `grow_zeroed` call, which may be larger than the size that was originally
319 /// requested when it was allocated.
320 /// * Bytes `old_size..new_size` are zeroed. `new_size` refers to the size of the memory
321 /// block returned by the `grow_zeroed` call.
322 ///
323 /// # Safety
324 ///
325 /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator.
326 /// * `old_layout` must [*fit*] that block of memory (The `new_layout` argument need not fit it.).
327 /// * `new_layout.size()` must be greater than or equal to `old_layout.size()`.
328 ///
329 /// Note that `new_layout.align()` need not be the same as `old_layout.align()`.
330 ///
331 /// [*currently allocated*]: #currently-allocated-memory
332 /// [*fit*]: #memory-fitting
333 ///
334 /// # Errors
335 ///
336 /// Returns `Err` if the new layout does not meet the allocator's size and alignment
337 /// constraints of the allocator, or if growing otherwise fails.
338 ///
339 /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
340 /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
341 /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
342 ///
343 /// Clients wishing to abort computation in response to an allocation error are encouraged to
344 /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
345 ///
346 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
347 unsafe fn grow_zeroed(
348 &self,
349 ptr: NonNull<u8>,
350 old_layout: Layout,
351 new_layout: Layout,
352 ) -> Result<NonNull<[u8]>, AllocError> {
353 debug_assert!(
354 new_layout.size() >= old_layout.size(),
355 "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
356 );
357
358 let new_ptr = self.allocate_zeroed(new_layout)?;
359
360 // SAFETY: because `new_layout.size()` must be greater than or equal to
361 // `old_layout.size()`, both the old and new memory allocation are valid for reads and
362 // writes for `old_layout.size()` bytes. Also, because the old allocation wasn't yet
363 // deallocated, it cannot overlap `new_ptr`. Thus, the call to `copy_nonoverlapping` is
364 // safe. The safety contract for `dealloc` must be upheld by the caller.
365 unsafe {
366 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_layout.size());
367 self.deallocate(ptr, old_layout);
368 }
369
370 Ok(new_ptr)
371 }
372
373 /// Attempts to shrink the memory block.
374 ///
375 /// Returns a new [`NonNull<[u8]>`][NonNull] containing a pointer and the actual size of the allocated
376 /// memory. The pointer is suitable for holding data described by `new_layout`. To accomplish
377 /// this, the allocator may shrink the allocation referenced by `ptr` to fit the new layout.
378 ///
379 ///
380 /// If this returns `Ok`, then the memory block referenced by `ptr` has been [*invalidated*].
381 /// The old `ptr` must not be used to access the memory, even if the allocation was shrunk in-place.
382 /// The newly returned pointer is the only valid pointer for accessing this memory now.
383 ///
384 /// If this method returns `Err`, then the memory block has not been *invalidated*,
385 /// and the contents of the memory block are unaltered.
386 ///
387 /// # Safety
388 ///
389 /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator.
390 /// * `old_layout` must [*fit*] that block of memory (The `new_layout` argument need not fit it.).
391 /// * `new_layout.size()` must be smaller than or equal to `old_layout.size()`.
392 ///
393 /// Note that `new_layout.align()` need not be the same as `old_layout.align()`.
394 ///
395 /// [*currently allocated*]: #currently-allocated-memory
396 /// [*fit*]: #memory-fitting
397 /// [*invalidated*]: #invalidating-memory-blocks
398 ///
399 /// # Errors
400 ///
401 /// Returns `Err` if the new layout does not meet the allocator's size and alignment
402 /// constraints of the allocator, or if shrinking otherwise fails.
403 ///
404 /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
405 /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
406 /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
407 ///
408 /// Clients wishing to abort computation in response to an allocation error are encouraged to
409 /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
410 ///
411 /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
412 unsafe fn shrink(
413 &self,
414 ptr: NonNull<u8>,
415 old_layout: Layout,
416 new_layout: Layout,
417 ) -> Result<NonNull<[u8]>, AllocError> {
418 debug_assert!(
419 new_layout.size() <= old_layout.size(),
420 "`new_layout.size()` must be smaller than or equal to `old_layout.size()`"
421 );
422
423 let new_ptr = self.allocate(new_layout)?;
424
425 // SAFETY: because `new_layout.size()` must be lower than or equal to
426 // `old_layout.size()`, both the old and new memory allocation are valid for reads and
427 // writes for `new_layout.size()` bytes. Also, because the old allocation wasn't yet
428 // deallocated, it cannot overlap `new_ptr`. Thus, the call to `copy_nonoverlapping` is
429 // safe. The safety contract for `dealloc` must be upheld by the caller.
430 unsafe {
431 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), new_layout.size());
432 self.deallocate(ptr, old_layout);
433 }
434
435 Ok(new_ptr)
436 }
437
438 /// Creates a "by reference" adapter for this instance of `Allocator`.
439 ///
440 /// The returned adapter also implements `Allocator` and will simply borrow this.
441 #[inline(always)]
442 fn by_ref(&self) -> &Self
443 where
444 Self: Sized,
445 {
446 self
447 }
448}
449
450/// An [`Allocator`] that can be registered as the standard library’s default
451/// through the `#[global_allocator]` attribute.
452///
453/// Types implementing this trait can be used as the default allocator for
454/// memory allocations through `Box`, `Vec` and the collection types. For
455/// instance, the `System` allocator implements this trait, and thus can be
456/// explicitly set as the default like so:
457/// ```
458/// use std::alloc::System;
459///
460/// #[global_allocator]
461/// static ALLOCATOR: System = System;
462/// ```
463///
464/// The `Global` allocator forwards all memory allocation requests to the
465/// `static` annotated with `#[global_allocator]`. Hence, `Global` does not
466/// implement `GlobalAllocator` itself, as that would lead to infinite recursion.
467///
468/// # Note to implementors
469///
470/// This trait is used to prevent the infinite recursion that would occur if the
471/// default allocator were to attempt to allocate memory through `Global` (and
472/// thus from itself).
473///
474/// When to implement this trait:
475/// * for custom global allocators that only use system memory allocation
476/// services.
477/// * for allocators that wrap another allocator that implements `GlobalAllocator`.
478///
479/// When **not** to implement this trait:
480/// * for wrappers of arbitrary allocators (which might end up being `Global`,
481/// leading to infinite recursion).
482///
483/// # Safety
484///
485/// In addition to the safety requirements of `Allocator`, global allocators are
486/// subject to some additional constraints:
487///
488/// * It's undefined behavior if global allocators unwind. This restriction may
489/// be lifted in the future, but currently a panic from any of these
490/// functions may lead to memory unsafety.
491///
492/// * You must not rely on allocations actually happening, even if there are explicit
493/// heap allocations in the source. The optimizer may detect unused allocations that it can either
494/// eliminate entirely or move to the stack and thus never invoke the allocator. The
495/// optimizer may further assume that allocation is infallible, so code that used to fail due
496/// to allocator failures may now suddenly work because the optimizer worked around the
497/// need for an allocation. More concretely, the following code example is unsound, irrespective
498/// of whether your custom allocator allows counting how many allocations have happened.
499///
500/// ```rust,ignore (unsound and has placeholders)
501/// drop(Box::new(42));
502/// let number_of_heap_allocs = /* call private allocator API */;
503/// unsafe { std::hint::assert_unchecked(number_of_heap_allocs > 0); }
504/// ```
505///
506/// Note that the optimizations mentioned above are not the only
507/// optimization that can be applied. You may generally not rely on heap allocations
508/// happening if they can be removed without changing program behavior.
509/// Whether allocations happen or not is not part of the program behavior, even if it
510/// could be detected via an allocator that tracks allocations by printing or otherwise
511/// having side effects.
512///
513/// # Re-entrance
514///
515/// When implementing a global allocator, one has to be careful not to create an infinitely recursive
516/// implementation by accident, as many constructs in the Rust standard library may allocate in
517/// their implementation. For example, on some platforms, [`std::sync::Mutex`] may allocate, so using
518/// it is highly problematic in a global allocator.
519///
520/// For this reason, one should generally stick to library features available through
521/// [`core`], and avoid using [`std`] in a global allocator. A few features from [`std`] are
522/// guaranteed to not use `#[global_allocator]` to allocate:
523///
524/// - [`std::thread_local`],
525/// - [`std::thread::current`],
526/// - [`std::thread::park`] and [`std::thread::Thread`]'s [`unpark`] method and
527/// [`Clone`] implementation.
528///
529/// [`std`]: ../../std/index.html
530/// [`std::sync::Mutex`]: ../../std/sync/struct.Mutex.html
531/// [`std::thread_local`]: ../../std/macro.thread_local.html
532/// [`std::thread::current`]: ../../std/thread/fn.current.html
533/// [`std::thread::park`]: ../../std/thread/fn.park.html
534/// [`std::thread::Thread`]: ../../std/thread/struct.Thread.html
535/// [`unpark`]: ../../std/thread/struct.Thread.html#method.unpark
536#[unstable(feature = "allocator_api", issue = "32838")]
537#[expect(multiple_supertrait_upcastable)]
538pub unsafe trait GlobalAllocator: Allocator + Sync + 'static {}
539
540#[unstable(feature = "allocator_api", issue = "32838")]
541#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
542const unsafe impl<A> Allocator for &A
543where
544 A: [const] Allocator + ?Sized,
545{
546 #[inline]
547 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
548 (**self).allocate(layout)
549 }
550
551 #[inline]
552 fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
553 (**self).allocate_zeroed(layout)
554 }
555
556 #[inline]
557 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
558 // SAFETY: the safety contract must be upheld by the caller
559 unsafe { (**self).deallocate(ptr, layout) }
560 }
561
562 #[inline]
563 unsafe fn grow(
564 &self,
565 ptr: NonNull<u8>,
566 old_layout: Layout,
567 new_layout: Layout,
568 ) -> Result<NonNull<[u8]>, AllocError> {
569 // SAFETY: the safety contract must be upheld by the caller
570 unsafe { (**self).grow(ptr, old_layout, new_layout) }
571 }
572
573 #[inline]
574 unsafe fn grow_zeroed(
575 &self,
576 ptr: NonNull<u8>,
577 old_layout: Layout,
578 new_layout: Layout,
579 ) -> Result<NonNull<[u8]>, AllocError> {
580 // SAFETY: the safety contract must be upheld by the caller
581 unsafe { (**self).grow_zeroed(ptr, old_layout, new_layout) }
582 }
583
584 #[inline]
585 unsafe fn shrink(
586 &self,
587 ptr: NonNull<u8>,
588 old_layout: Layout,
589 new_layout: Layout,
590 ) -> Result<NonNull<[u8]>, AllocError> {
591 // SAFETY: the safety contract must be upheld by the caller
592 unsafe { (**self).shrink(ptr, old_layout, new_layout) }
593 }
594}
595
596#[unstable(feature = "allocator_api", issue = "32838")]
597unsafe impl<A> Allocator for &mut A
598where
599 A: Allocator + ?Sized,
600{
601 #[inline]
602 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
603 (**self).allocate(layout)
604 }
605
606 #[inline]
607 fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
608 (**self).allocate_zeroed(layout)
609 }
610
611 #[inline]
612 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
613 // SAFETY: the safety contract must be upheld by the caller
614 unsafe { (**self).deallocate(ptr, layout) }
615 }
616
617 #[inline]
618 unsafe fn grow(
619 &self,
620 ptr: NonNull<u8>,
621 old_layout: Layout,
622 new_layout: Layout,
623 ) -> Result<NonNull<[u8]>, AllocError> {
624 // SAFETY: the safety contract must be upheld by the caller
625 unsafe { (**self).grow(ptr, old_layout, new_layout) }
626 }
627
628 #[inline]
629 unsafe fn grow_zeroed(
630 &self,
631 ptr: NonNull<u8>,
632 old_layout: Layout,
633 new_layout: Layout,
634 ) -> Result<NonNull<[u8]>, AllocError> {
635 // SAFETY: the safety contract must be upheld by the caller
636 unsafe { (**self).grow_zeroed(ptr, old_layout, new_layout) }
637 }
638
639 #[inline]
640 unsafe fn shrink(
641 &self,
642 ptr: NonNull<u8>,
643 old_layout: Layout,
644 new_layout: Layout,
645 ) -> Result<NonNull<[u8]>, AllocError> {
646 // SAFETY: the safety contract must be upheld by the caller
647 unsafe { (**self).shrink(ptr, old_layout, new_layout) }
648 }
649}