Concatenate two different size of array

Hello there !

I can not get my head around this simple action -_- ... And I would like your opinion and help on this issue.
I did not find any similar post, but I might be wrong.

The context:

I'm using the dryoc crate, and I'm trying to create specifics nonce (a static part, and a incremental part like so : saltpack_recipsbXXXXXXXX, with XXXXXXXX an 8-byte big-endian unsigned integer.
The nonce is basically a [u8, 24].

I tried this code snippet:
let nonce: [u8; 24] = [b"saltpack_recipsb", &index.to_be_bytes()].concat();
But as I understand from the compiler, each element need to be the same size.
expected an array with a fixed size of 16 elements, found one with 4 elements

I tried other flows but I just get lost in the rust conversion system each time. :sweat_smile:

Do you have an easy way to create this byte array ?

Thank's in advance !

You can convert the arrays into iterators and use the extend method from Iterator.

You can use copy_from_slice().

const PREFIX: &[u8] = b"saltpack_recipsb";
type Index = u64;
const NONCE_SIZE: usize = PREFIX.len() + std::mem::size_of::<Index>();

fn make_nonce(index: Index) -> [u8; NONCE_SIZE] {
    let mut nonce = [0u8; NONCE_SIZE];
    nonce[..PREFIX.len()].copy_from_slice(PREFIX);
    nonce[PREFIX.len()..].copy_from_slice(&index.to_be_bytes());

    nonce
}

I like this approach. I will try to remember to have a simpler approach for the next time.

Thank you all =)

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.