mod arc;
mod boxed;
mod try_clone;
mod try_collect;
mod try_new;
mod vec;
pub use boxed::{
BoxedSliceFromFallibleIterError, TooFewItemsOrOom, boxed_slice_write_iter,
new_boxed_slice_from_fallible_iter, new_boxed_slice_from_iter,
new_boxed_slice_from_iter_with_len, new_uninit_boxed_slice,
};
pub use try_clone::TryClone;
pub use try_collect::{TryCollect, TryExtend, TryFromIterator};
pub use try_new::{TryNew, try_new};
pub use vec::Vec;
use crate::error::OutOfMemory;
use core::{alloc::Layout, ptr::NonNull};
#[inline]
unsafe fn try_alloc(layout: Layout) -> Result<NonNull<u8>, OutOfMemory> {
debug_assert!(layout.size() > 0);
let ptr = unsafe { std_alloc::alloc::alloc(layout) };
if let Some(ptr) = NonNull::new(ptr) {
Ok(ptr)
} else {
Err(OutOfMemory::new(layout.size()))
}
}
#[inline]
unsafe fn try_realloc(
ptr: *mut u8,
layout: Layout,
new_size: usize,
) -> Result<NonNull<u8>, OutOfMemory> {
debug_assert!(layout.size() > 0);
debug_assert!(new_size > 0);
let ptr = unsafe { std_alloc::alloc::realloc(ptr, layout, new_size) };
if let Some(ptr) = NonNull::new(ptr) {
Ok(ptr)
} else {
Err(OutOfMemory::new(new_size))
}
}
pub trait PanicOnOom {
type Result;
fn panic_on_oom(self) -> Self::Result;
}
impl<T> PanicOnOom for Result<T, OutOfMemory> {
type Result = T;
#[track_caller]
fn panic_on_oom(self) -> Self::Result {
match self {
Ok(x) => x,
Err(oom) => panic!("unhandled out-of-memory error: {oom}"),
}
}
}