xref: /wasmtime-44.0.1/crates/core/src/alloc.rs (revision 9acefdfe)
1 //! Low-level allocation and OOM-handling utilities.
2 
3 mod arc;
4 mod boxed;
5 mod try_new;
6 
7 pub use boxed::{BoxedSliceFromIterError, new_boxed_slice_from_iter};
8 pub use try_new::{TryNew, try_new};
9 
10 use core::{alloc::Layout, ptr::NonNull};
11 use wasmtime_error::OutOfMemory;
12 
13 /// Try to allocate a block of memory that fits the given layout, or return an
14 /// `OutOfMemory` error.
15 ///
16 /// # Safety
17 ///
18 /// Same as `alloc::alloc::alloc`: layout must have non-zero size.
19 #[inline]
20 unsafe fn try_alloc(layout: Layout) -> Result<NonNull<u8>, OutOfMemory> {
21     // Safety: same as our safety conditions.
22     debug_assert!(layout.size() > 0);
23     let ptr = unsafe { std_alloc::alloc::alloc(layout) };
24 
25     if let Some(ptr) = NonNull::new(ptr) {
26         Ok(ptr)
27     } else {
28         Err(OutOfMemory::new(layout.size()))
29     }
30 }
31