fizyk20 / generic-array

Generic array types in Rust
MIT License
405 stars 77 forks source link

Is there a way to get a `usize` from an `ArrayLength`? #127

Closed agostbiro closed 2 years ago

agostbiro commented 2 years ago

Hi,

First of all, thanks for the library! I'm wondering if there is a way to get a usize from an ArrayLength without constructing an array. Currently I'm doing this:

// FieldSize<Curve> implements ArrayLength<u8>
let arr: GenericArray<u8, elliptic_curve::FieldSize<Curve>> =
    Default::default();
let size = arr.len();

I've looked through the source but couldn't find a better way. I'm wondering if I'm missing something?

novacrazy commented 2 years ago

ArrayLength type values are required to also implement typenum::Unsigned as per the trait definition, and Unsigned can provide a variety of associated constants and methods to get it as a regular integer value.

use generic_array::{ArrayLength, typenum::Unsigned}; // typenum is re-exported in generic_array

let size = <FieldSize<Curve> as Unsigned>::USIZE; // or ::to_usize()
agostbiro commented 2 years ago

Great, that's exactly what I was looking for. Thanks a lot for the quick answer!