将值切片转换为字节切片

xrl*_*xrl 2 casting vector rust

我正在尝试一个 API,调用者提供一个Vec<Point>他们希望我填写的数据。他们可以通过创建向量来分配向量中的空间,with_capacity然后通过执行 来推出其大小push(Point{...})。然后,我将使用磁盘中的字节填充底层缓冲区,根据需要切换其字节序表示,然后将其作为Vec<Point>.

这是获取向量并用数据填充它的函数。问题在于,transmute 仅在类型大小相同时才起作用,aPoint为 12 字节,而 transmute 会丢弃其中的 11 个字节。

fn read_points(&self, offset: u64, points: &mut [point::Point]) {
    let mut file = self.handle.borrow_mut();
    file.seek(SeekFrom::Start(offset)).unwrap();

    // bleep bloorp. danger!
    let points_buf : &mut [u8] = unsafe { mem::transmute(points) };
    file.read(points_buf).unwrap();

    // should take the 12 bytes and do the endian swaps
    for mut chunk in points_buf.chunks_mut(point::POINT_SIZE) {
        let point = point::buf_to_point(chunk);
        let buf : &mut [u8] = &mut chunk;
        point::fill_buf(buf, point.timestamp, point.value);
    }
}
Run Code Online (Sandbox Code Playgroud)

这个 API 可以在 Rust 中完成吗?或者我应该转而进行更安全但更慢的复制操作?

Sim*_*pin 5

的内存表示形式&mut [T]是,(*mut T, usize)其中 usize 是切片中元素的数量T,而不是字节数。因此,转换 20 个点的切片会得到 20 个字节的切片。

您必须计算正确的字节数:

let n_bytes = points.len() * std::mem::size_of::<Point>();
let points_buf = std::slice::from_raw_parts_mut(points.as_mut_ptr(), n_bytes);
Run Code Online (Sandbox Code Playgroud)

(当然,接下来要解决所有其他的不安全问题。)