the duck
the duck

Reputation: 445

How to use GenericArray?

In the Rust code below, I cannot convert my array of bytes into a GenericArray. The compiler tells me to give a type the "bytes" like generic_array::GenericArray<u8, N>, but I don't know what to use as "N".

I found out the N must be of type ArrayLength and I am stuck here because I don't see the link with a size to pass.

fn main() {

    use aes::block_cipher_trait::generic_array::GenericArray;

    let phrase = "Le Rust tu comprendras jeune padawan !";

    println!("my phrase {:?}", &phrase);

    let b = phrase.as_bytes();

    println!("my bytes {:?} len : {}", &b, b.len());

    let bytes = GenericArray::clone_from_slice(&b[0..16]);

    println!("my bytes {:?}", &bytes);
}

Upvotes: 9

Views: 9686

Answers (1)

SCappella
SCappella

Reputation: 10464

aes::cipher::generic_array is just a copy of the crate generic_array, so it's worth perusing the documentation there.

The second type parameter in GenericArray<T, N> represents in some sense the length of the GenericArray. generic_array uses the types from the crate typenum by default (though with some effort, you could provide your own types — you'd just need to implement the necessary traits for them).

Much like how aes provides generic_array as a public dependency, generic_array has a copy of typenum in its tree, so you can use its types like so:

fn main() {
    use aes::cipher::generic_array::{typenum::U16, GenericArray};

    let phrase = "Le Rust tu comprendras jeune padawan !";

    println!("my phrase {:?}", &phrase);

    let b = phrase.as_bytes();

    println!("my bytes {:?} len : {}", &b, b.len());

    let bytes: GenericArray<_, U16> = GenericArray::clone_from_slice(&b[0..16]);

    println!("my bytes {:?}", &bytes);
}

(playground. Note that I used generic_array directly. The playground doesn't have the aes crate.)

Here, we've used typenum::U16 since we want an array of length 16.

Upvotes: 12

Related Questions