rust 平面化数组的方块片段

mklgxw1f  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(133)

在Rust中,我能以某种方式将一个装箱的切片Box<[[T;SIZE]]>扁平化为Box<[T]>(如果需要,不安全的代码是可以的)吗?我拥有这个盒子,我想在不做不必要的复制的情况下就地完成它。
它比看起来要复杂得多。有必要修改PtrComponents::metadata(此堆变量保存数组的长度),如www.example.com中所示https://doc.rust-lang.org/src/core/slice/mod.rs.html#137
如果你不考虑这个

pub fn flatten_box<T,const DIM:usize>(v:Box<[[T;DIM]]>)->Box<[T]>{
    // SAFETY: raw pointer is created from Box and
    // *mut [[T; N]] has the same aligment as *mut [T]
    unsafe { Box::from_raw(Box::into_raw(v) as *mut [T]) }
}

# [cfg(test)]

mod tests {
    use super::*;

    #[test]
    fn test6() {
        let v:Box<[[u32;13]]> = unsafe{Box::<[[u32;13]]>::new_uninit_slice(7).assume_init()};
        let l = v.len();
        let v = flatten_box(v);
        assert_eq!(v.len(),l*13);
    }
}

您将得到错误

Left:  7
Right: 91
<Click to see difference>

thread 'transmute::tests::test6' panicked at 'assertion failed: `(left == right)`
  left: `7`,
 right: `91`', vf\src\transmute.rs:76:9
z18hc3ub

z18hc3ub1#

你可以试试这个:

fn transmute<T, const N: usize>(b: Box<[[T; N]]>) -> Box<[T]> {
    // SAFETY: raw pointer is created from Box and
    // *mut [[T; N]] has the same aligment as *mut [T]
    unsafe { Box::from_raw(Box::into_raw(b) as *mut [T]) }
}

编辑。这并不保留切片的长度。请参见下面@eggyal的注解以获得解决方案。

相关问题