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