Transmute safety with arrays

I have a really weird array like this:

let data = [[[[0u8; 3]; 3]; 3]; 3];

and it's a pain to work with, given the amount of typing. And any way, I thought that it would be logical to have it in more than one configuration:

let data_seq = [0u8; 81];
let data_sqr = [[0u8; 9]; 9];

So I thought about it and, I decided that a transmute would remove the boilerplate code, and make my life easier. A transmute between any of these types should be okay, but I feel like as if that is abit too much data to be copying around, so I thought that it'd be more logical to transmute a reference:

struct Container {
    data: [u8; 81]
}
impl Container {
    pub fn as_seq(&self) -> &[u8; 81] {
        &self.data
    }
    pub fn as_sqr(&self) -> &[[u8; 9]; 9] {
        unsafe { std::mem::transmute(&self.data) }
    }
    pub fn as_col(&self) -> &[[[[u8; 3]; 3]; 3]; 3] {
        unsafe { std::mem::transmute(&self.data) }
    }
}

Obviously I'd have to make sure that the values are created in such a way that the mapping works but otherwise this should be just fine right?

I'd slightly prefer pointer casts, like &*(self.data.as_ptr() as *const _), but yes this should be fine.

3 Likes