Crates.io | safe-allocator-api |
lib.rs | safe-allocator-api |
version | 0.3.0 |
source | src |
created_at | 2024-11-24 13:16:26.301543 |
updated_at | 2024-11-26 22:34:09.817483 |
description | A safe wrapper around the `allocator_api`'s Allocator trait. |
homepage | |
repository | https://github.com/Sewer56/safe-allocator-api |
max_upload_size | |
id | 1459252 |
size | 24,582 |
A safe wrapper around the allocator_api
's Allocator trait.
This crate provides a wrapper around the returned results, ensuring that any allocated memory is automatically dropped when its lifetime expires.
Send
and Sync
)
In my case I wrote this crate to have a 'safe' way to make aligned allocations 😉.
Add this to your Cargo.toml
:
[dependencies]
safe-allocator-api = "0.1.0"
use allocator_api2::alloc::*;
use safe_allocator_api::RawAlloc;
fn allocate_example() -> Result<(), AllocError> {
// Create a new allocation of 1024 bytes
let layout = Layout::array::<u8>(1024).unwrap();
let mut alloc = RawAlloc::new(layout)?;
// Write some data
unsafe {
core::ptr::write(alloc.as_mut_ptr(), 42u8);
}
// Memory is automatically deallocated when alloc goes out of scope
Ok(())
}
use allocator_api2::alloc::*;
use safe_allocator_api::RawAlloc;
fn zero_initialized_example() -> Result<(), AllocError> {
// Create a zero-initialized allocation
let layout = Layout::array::<u8>(1024).unwrap();
let alloc = RawAlloc::new_zeroed(layout)?;
// Verify memory is zeroed
unsafe {
let slice = core::slice::from_raw_parts(alloc.as_ptr(), 1024);
assert!(slice.iter().all(|&x| x == 0));
}
Ok(())
}
use allocator_api2::alloc::*;
use safe_allocator_api::RawAlloc;
fn grow_and_shrink_example() -> Result<(), AllocError> {
// Start with a small allocation
let layout = Layout::array::<u8>(100).unwrap();
let mut alloc = RawAlloc::new(layout)?;
// Grow the allocation
let new_layout = Layout::array::<u8>(200).unwrap();
alloc.grow(new_layout)?;
// Shrink it back down
let final_layout = Layout::array::<u8>(50).unwrap();
alloc.shrink(final_layout)?;
Ok(())
}
use allocator_api2::alloc::*;
use safe_allocator_api::RawAlloc;
fn custom_allocator_example() -> Result<(), AllocError> {
let layout = Layout::new::<u64>();
let alloc = RawAlloc::new_in(layout, Global)?;
Ok(())
}
Operations will return AllocError in the following cases:
i.e. This is a thin wrapper around the existing API, so we reuse error types from std.
std
[default]: Builds against std
nightly
: Enables the nightly allocator_api
featureFor information on how to work with this codebase, see README-DEV.MD.
Licensed under MIT.
Learn more about Reloaded's general choice of licensing for projects..