Splitting array in const fn

I have a array of type [u8; 32] and I want to split it into [[u8; 16]; 2]]. What would be the most ergonomic way to do it? I'm just introducing a transmute for now.

const fn split(x: [u8; 32]) -> [[u8; 16]; 2] {
    unsafe { std::mem::transmute(x) }
}

I tried pattern matching but I can't get better than this

const fn split(x: [u8; 32]) -> [[u8; 16]; 2] {
    let [a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, b @ ..] = x;
    [[a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15], b]
}

1 Like

You can write a loop to do it:

const fn split(x: [u8; 32]) -> [[u8; 16]; 2] {
    let mut a = [0;16];
    let mut b = [0;16];

    let mut i = 0;
    while i < 16 {
        a[i] = x[i];
        b[i] = x[i+16];
        i += 1;
    }

    [a,b]
}

Or, on nightly:

#![feature(generic_const_exprs)]

const fn split<const N:usize, const M:usize>(x: [u8; N*M]) -> [[u8; N]; M] {
    let mut out = [[0;N];M];

    let mut i = 0;
    while i < N {
        let mut j=0;
        while j < M {
            out[j][i] = x[i+j*N];
            j += 1;
        }
        i += 1;
    }

    out
}
1 Like

Transmute is fine. There's also bytemuck crate that hides some of the unsafe.

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.