46 releases (1 stable)

1.0.0 Sep 13, 2023
1.0.0-alpha.1 Mar 31, 2023
0.14.7 Mar 28, 2023
0.14.6 Aug 2, 2022
0.0.3 Nov 1, 2015

#22 in Data structures

Download history 1327653/week @ 2023-11-21 1532327/week @ 2023-11-28 1535310/week @ 2023-12-05 1560547/week @ 2023-12-12 1248684/week @ 2023-12-19 853069/week @ 2023-12-26 1403518/week @ 2024-01-02 1497197/week @ 2024-01-09 1611596/week @ 2024-01-16 1599960/week @ 2024-01-23 1668460/week @ 2024-01-30 1616170/week @ 2024-02-06 1579740/week @ 2024-02-13 1670134/week @ 2024-02-20 1736424/week @ 2024-02-27 1433082/week @ 2024-03-05

6,700,624 downloads per month
Used in 21,636 crates (374 directly)

MIT license

95KB
1.5K SLoC

Crates.io Build Status

generic-array

This crate implements a structure that can be used as a generic array type.

**Requires minumum Rust version of 1.65.0

Documentation on GH Pages may be required to view certain types on foreign crates.

Usage

Before Rust 1.51, arrays [T; N] were problematic in that they couldn't be generic with respect to the length N, so this wouldn't work:

struct Foo<N> {
    data: [i32; N],
}

Since 1.51, the below syntax is valid:

struct Foo<const N: usize> {
    data: [i32; N],
}

However, the const-generics we have as of writing this are still the minimum-viable product (min_const_generics), so many situations still result in errors, such as this example:

trait Bar {
    const LEN: usize;

    // Error: cannot perform const operation using `Self`
    fn bar(&self) -> Foo<{ Self::LEN }>;
}

generic-array defines a new trait ArrayLength and a struct GenericArray<T, N: ArrayLength>, which lets the above be implemented as:

struct Foo<N: ArrayLength> {
    data: GenericArray<i32, N>
}

trait Bar {
    type LEN: ArrayLength;
    fn bar(&self) -> Foo<Self::LEN>;
}

The ArrayLength trait is implemented for unsigned integer types from typenum crate. For example, GenericArray<T, U5> would work almost like [T; 5]:

use generic_array::typenum::U5;

struct Foo<T, N: ArrayLength> {
    data: GenericArray<T, N>
}

let foo = Foo::<i32, U5> { data: GenericArray::default() };

The arr! macro is provided to allow easier creation of literal arrays, as shown below:

let array = arr![1, 2, 3];
//  array: GenericArray<i32, typenum::U3>
assert_eq!(array[2], 3);

Feature flags

[dependencies.generic-array]
features = [
    "more_lengths",  # Expands From/Into implementation for more array lengths
    "serde",         # Serialize/Deserialize implementation
    "zeroize",       # Zeroize implementation for setting array elements to zero
    "const-default", # Compile-time const default value support via trait
    "alloc",         # Enables From/TryFrom implementations between GenericArray and Vec<T>/Box<[T]>
    "faster-hex"     # Enables internal use of the `faster-hex` crate for faster hex encoding via SIMD
]

Dependencies

~125–355KB