arrayinit/
lib.rs

1//! A no-dependencies, no-std, stupidly simple and tiny crate for creating const-size arrays dynamically.
2//!
3//! By default, when constructing an array `[T; N]`, Rust allows only for two ways to initialize the array.
4//! For example, it allows naming all elements in the array like: `[1, 2, 3, 4]`, or by giving a default value for all of the array entries `["Hello"; 5]`.
5//!
6//! There are a few shortcomings to this approach - especially for generically-sized arrays.
7//! In particular, Rust at the moment, is not verbose enough initializing an array with differing values in such a case.
8//!
9//! A major problem occurs when `T` is an owned type that doesn't implement `Copy` (for example, `String` type).
10//! Since `N`, the size of the array, is generically defined - we are forced to initialize the array with `[concrete_value; N]`, which wouldn't compile since `concrete_value` is of type `T` which isn't `Copy`.
11//! In order to properly initialize such an array, ugly tricks are required.
12//!
13//! This crate comes to solve this problem and allow for a more dynamic initialization very simply.
14//!
15//! # Example usage
16//! There are multiple ways to use the `arr!` macro defined in this crate. The most generic way is by supplying a `producer` method, and giving the size of the array.
17//! ```
18//! let array = arr![|idx| idx * 2; 4];
19//!
20//! assert_eq!(array, [0, 2, 4, 6]);
21//! ```
22//!
23//! Its also possible to omit the size of the array, and let the compiler figure it out on its own
24//! ```
25//! let array = arr![|idx| idx * 2];
26//!
27//! // We need to use the array somewhere to help the compiler understand whats its size should be
28//! assert_eq!(array, [0, 2, 5, 6, 8, 10]);
29//! ```
30//!
31//! Its also possible to initialize statically all elements:
32//! ```
33//! let array = arr![1, 2, 3]; // Equivalent to `[1, 2, 3]`
34//!
35//! assert_eq!(array, [1, 2, 3]);
36//! ```
37
38pub mod arrayinit;
39
40#[cfg(test)]
41mod tests {
42    use crate::arr;
43
44    #[test]
45    fn macro_static() {
46        let array = arr![0, 5, 2];
47        assert_eq!(array, [0, 5, 2]);
48    }
49
50    #[test]
51    fn macro_indexed() {
52        // Implicit array size, implied by `assert_eq` below.
53        // Will NOT compile otherwise.
54        let array = arr![|i| i * 2];
55        assert_eq!(array, [0, 2, 4, 6]);
56    }
57
58    #[test]
59    fn macro_sized() {
60        // Explicit array size.
61        let array = arr![|i| i * 2; 4];
62        assert_eq!(array, [0, 2, 4, 6]);
63    }
64}