Crates.io | fallible_alloc |
lib.rs | fallible_alloc |
version | 0.2.0 |
source | src |
created_at | 2021-07-16 09:09:10.41696 |
updated_at | 2021-07-20 08:36:06.241882 |
description | Fallible rust stable std collections allocations |
homepage | |
repository | https://github.com/zkud/fallible-alloc |
max_upload_size | |
id | 423446 |
size | 58,698 |
At the moment we have an unstabilized allocations API in the std, so this is a temporary safe solution for a stable rust.
To create a vector you could use this code example:
use fallible_alloc::vec::alloc_with_size;
...
let vector_size: usize = 10;
let maybe_vector = alloc_with_size::<f64>(vector_size);
match maybe_vector {
Ok(vec) => println!("Created a vec with size 10"),
Err(error) => println!("Failed to create a vec, reason: {}", error)
}
As you could see, the maybe_vector has a Result<Vec<T>, AllocError> type
,
so now it's possible to handle a part of allocation errors.
Also it's possible to change the allocator used by crate with this code example:
use std::alloc::{GlobalAlloc, System, Layout};
struct MyAllocator;
unsafe impl GlobalAlloc for MyAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
System.alloc(layout)
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
System.dealloc(ptr, layout)
}
}
#[global_allocator]
static GLOBAL: MyAllocator = MyAllocator;