项目作者: fizyk20

项目描述 :
Generic array types in Rust
高级语言: Rust
项目地址: git://github.com/fizyk20/generic-array.git
创建时间: 2015-09-24T18:52:33Z
项目社区:https://github.com/fizyk20/generic-array

开源协议:MIT License

下载


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:

  1. struct Foo<N> {
  2. data: [i32; N],
  3. }

Since 1.51, the below syntax is valid:

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

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:

  1. trait Bar {
  2. const LEN: usize;
  3. // Error: cannot perform const operation using `Self`
  4. fn bar(&self) -> Foo<{ Self::LEN }>;
  5. }

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

  1. struct Foo<N: ArrayLength> {
  2. data: GenericArray<i32, N>
  3. }
  4. trait Bar {
  5. type LEN: ArrayLength;
  6. fn bar(&self) -> Foo<Self::LEN>;
  7. }

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

  1. use generic_array::typenum::U5;
  2. struct Foo<T, N: ArrayLength> {
  3. data: GenericArray<T, N>
  4. }
  5. let foo = Foo::<i32, U5> { data: GenericArray::default() };

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

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

Feature flags

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