50 releases (5 stable)

1.2.0 Jan 12, 2025
1.1.1 Nov 25, 2024
1.1.0 Jul 5, 2024
1.0.0 Sep 13, 2023
0.0.3 Nov 1, 2015

#16 in Data structures

Download history 2668424/week @ 2024-10-09 2773169/week @ 2024-10-16 2275370/week @ 2024-10-23 2142721/week @ 2024-10-30 2135997/week @ 2024-11-06 2253896/week @ 2024-11-13 2221442/week @ 2024-11-20 1957027/week @ 2024-11-27 2415871/week @ 2024-12-04 2585398/week @ 2024-12-11 1814348/week @ 2024-12-18 1100427/week @ 2024-12-25 1690378/week @ 2025-01-01 2405711/week @ 2025-01-08 2346393/week @ 2025-01-15 2002808/week @ 2025-01-22

8,618,001 downloads per month
Used in 28,313 crates (433 directly)

MIT license

110KB
2K SLoC

Crates.io Build Status

generic-array

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

**Requires minimum Rust version of 1.83.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 = [
    "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

~120–405KB
~10K SLoC