Expand description
A library for initializing arrays itemwise.
Normally, when using fixed size arrays, you can only initialize them with a const value. Example:
// Literals work.
let arr = [0; 5];
// Const values work too.
const STRING: String = String::new();
let arr = [STRING; 5];
// Function calls don't work.
let arr = [computation(); 5];
there are a few different ways of initializing an array itemwise, including:
- Using an array of
Option
s, initializing them all toNone
and then initializing each one toSome(computation())
. - Using a
Vec
and incrementally pushing items to it. - Using an array of
MaybeUninit
s, gradually initializing them and then transmuting the array. This requires usage ofunsafe
code.
This crate uses the third method but hides it behind a safe interface, so that no unsafe code is needed on the User end. It provides three functions to initialize arrays itemwise:
init_array
to initialize a stack-based fixed-size array.init_boxed_array
to initialize a heap-allocated fixed-size array.init_boxed_slice
to initialize a heap-allocated dynamically-sized slice.
There is also a try_init_array
function which allows to initialize an array fallibly and return the error early.
If you have the nightly
feature enabled, you will have access to additional versions of the init_boxed_...
functions compliant with the new Allocator API.
If you turn off the alloc
feature, which is enabled by default, you can use this crate in a #[no_std]
context without an allocator.
The crate is fully #[no_std]
compatible.
In addition to the 3 functions mentioned above, there are also two extension traits provided, ArrayExt
and SliceExt
,
which provide the same functionality as the free functions.
All of these functions share the property that, if the initialization of any item panics (i.e. if the stack unwinds), all the already initialized items are dropped, minimizing the risk of a memory leak.
Traits§
- Array
Ext - Extension trait for constant sized arrays.
- Slice
Ext - Extension trait for dynamically sized slices.
Functions§
- init_
array - Initialize a fixed-sized stack-based array.
- init_
boxed_ array - Initialize a fixed-sized heap-allocated array.
- init_
boxed_ slice - Initialize a dynamically-sized heap-allocated slice.
- init_
slice - Initialize all the elements in the slice with the result of calling the function with the index in the slice.
- try_
init_ array - Does the same as
init_array
but supports early return for fallible initialization of fixed size arrays. - try_
init_ slice - Try to initialize all the elements in a slice, returning early if it fails.