Write an int to either half of [u8; 32]

I'm setting up a crate-level seed for the ChaCha20 PRNG. I've got a working solution, but it feels a bit odd to have to iterate over index values to get it to work:

fn seed2(state: i128) {
    let mut seed = SEED.lock();
    let state = state.to_ne_bytes();
    for i in 16..32 {
        seed[i] = state[i-16];
    };
}

Is there a more idiomatic way to accomplish this? I guess I'm mostly just looking to improve my understanding of working with arrays/slices and bytes in general / more directly. Also, it is still doing panic/bounds checks, not that it matters (as long as I get the indices right). But it would be interesting to figure out how to use evaluated const parameters to actually get direct access to either [u8; 16] half for direct writes. I apparently really like compile-time guarantees, even when they aren't necessary.

Here's my current solution: playground

SEED.lock()[16..32]
    .copy_from_slice(&state.to_ne_bytes())
2 Likes

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.