Expand description
Allocate fixed-size arrays directly on the heap.
§The Problem
In Rust, Box::new([T; N]) allocates on the stack first, then moves to the
heap. For large arrays, this can overflow the stack. Rust’s optimizer
should handle this in optimized builds, but not in debug.
§The Solution
This crate allocates [T; N] directly on the heap, skipping the intermediate stack allocation.
§Example
const SIZE: usize = 1_000_000_000;
// This would overflow the stack in debug mode:
// let arr = Box::new([0u8; SIZE]);
// This works everywhere:
let arr: Box<[u8; SIZE]> = heap_arr::new_copied(&0u8);
assert_eq!(arr[0], 0);§API
new_copied– Allocate and fill by copying a value (forT: Copy)new_cloned– Allocate and fill by cloning a value (forT: Clone)new_default– Allocate and fill withT::default()from_fn– Initialize via a closuretry_from_fn– Initialize with a fallible closureuninit– Allocate uninitialized memoryassume_init– Transmute uninitialized memory (unsafe)
All functions return Box<[T; N]> compatible with standard library code.
§Features
#![no_std]compatible (usesalloconly)- Panic-safe initialization with automatic cleanup on drop
- Zero unsafe surface area for
new_*functions
Functions§
- assume_
init ⚠ - A helper function to transmute
Box<[MaybeUninit<T>; N]>intoBox<[T; N]>. - from_fn
- Allocates
[T; N]directly on the heap and initializes its entries to values produced by callingfwith the index of the entry as argument while walking forward through the array. - new_
cloned - Allocates
[T; N]directly on the heap and initializes its entries toinitialby cloning it. ForTthat are notClone, seenew_copied. - new_
copied - Allocates
[T; N]directly on the heap and initializes its entries toinitialby copying it. ForTthat are notCopy, seenew_cloned. - new_
default - Allocates
[T; N]directly on the heap and initializes its entries toT::default(). - try_
from_ fn - Allocates
[T; N]directly on the heap and initializes its entries to values produced by callingfwith the index of the entry as argument while walking forward through the array. - uninit
- Allocates
[T; N]directly on the heap and leaves its entries uninitialized.