| Crates.io | alloc-checked |
| lib.rs | alloc-checked |
| version | 0.1.2 |
| created_at | 2024-10-03 10:23:42.483242+00 |
| updated_at | 2024-10-10 15:52:09.064558+00 |
| description | Collections that don't panic on alloc failures |
| homepage | |
| repository | https://github.com/questdb/alloc-checked |
| max_upload_size | |
| id | 1395068 |
| size | 43,037 |
The alloc-checked crate provides wrapper types for common collections that require an explicit allocator and
return a Result instead of panicking on allocation failure.
The wrapper collection types provide two main benefits:
The crate requires a recent build of the Rust "nightly" compiler, as it uses the
allocator_api feature.
By default, the crate compiles against the Rust standard library.
The crate is also #![no_std] compatible via the no_std feature.
When compiled in no_std mode, it still relies on the alloc, core crates.
Add the dependency
cargo add alloc-checked # --features no_std
Chances are you might have been using Vec in a few places. Import the type you need
use alloc_checked::vec::Vec;
let vec = Vec::new_in(your_allocator);
vec.push(42)?; // -> Result<(), TryReserveError>
and fix any resulting compile errors.
Along the way, you probably want to implement the From trait for your error type to make it easier to bubble up
allocation errors.
use alloc::AllocError;
use alloc::collections::TryReserveError;
impl From<AllocError> for YourErrorType { /* ... */ }
impl From<TryReserveError> for YourErrorType { /* ... */ }
We (QuestDB) are adding to this crate on a per-need basis. There's currently decent support for the Vec type,
with more types to come. Contributions are quite welcome even if they extend beyond our needs.
The core design philosophy here is that it should never be possible to use this crate in a way that it silently allocates memory. Having a different type that can't be misused also allows for improved API ergonomics.
As a small example, std's Vec has both fn with_capacity_in(alloc: Allocator) -> Vec and
fn try_with_capacity_in(alloc: Allocator) -> Result<Vec, TryReserveError> variants.
The Vec implementation in alloc-checked has a single fn with_capacity_in(alloc: Allocator) -> Vec,
likewise many common methods that silently panic in the standard library, here return a Result instead with the idea
of an easier code migration.
Licensed under either of
at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.