如何将大型Vec <i32>切成&amp; [u8]?</i32>

时间:2015-03-13 16:12:34

标签: rust

我不知道如何将Vec<i32>转换为&[u8]切片。

fn main() {
    let v: Vec<i32> = vec![1; 100_000_000];
    let v_bytes: &[u8] = /* ... */;
}

我想在文件中写一个大的Vec<i32>,以便我以后可以阅读它。

2 个答案:

答案 0 :(得分:9)

您可以使用std::slice::from_raw_parts

let v_bytes: &[u8] = unsafe {
    std::slice::from_raw_parts(
        v.as_ptr() as *const u8,
        v.len() * std::mem::size_of::<i32>(),
    )
};

根据对此答案的评论,您应该将此代码包装在一个函数中并使返回值借用输入,以便您尽可能使用借用检查器:

fn as_u8_slice(v: &[i32]) -> &[u8] {
    unsafe {
        std::slice::from_raw_parts(
            v.as_ptr() as *const u8,
            v.len() * std::mem::size_of::<i32>(),
        )
    }
}

答案 1 :(得分:5)

我拿了@swizards answer然后用它跑了一下以获得硬币的另一面 - 读回矢量:

use std::fs::File;
use std::io::{Read, Write};
use std::{mem, slice};

fn as_u8_slice(v: &[i32]) -> &[u8] {
    let element_size = mem::size_of::<i32>();
    unsafe { slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * element_size) }
}

fn from_u8(v: Vec<u8>) -> Vec<i32> {
    let data = v.as_ptr();
    let len = v.len();
    let capacity = v.capacity();
    let element_size = mem::size_of::<i32>();

    // Make sure we have a proper amount of capacity (may be overkill)
    assert_eq!(capacity % element_size, 0);
    // Make sure we are going to read a full chunk of stuff
    assert_eq!(len % element_size, 0);

    unsafe {
        // Don't allow the current vector to be dropped
        // (which would invalidate the memory)
        mem::forget(v);

        Vec::from_raw_parts(
            data as *mut i32,
            len / element_size,
            capacity / element_size,
        )
    }
}

fn do_write(filename: &str, v: &[i32]) {
    let mut f = File::create(filename).unwrap();
    f.write_all(as_u8_slice(v)).unwrap();
}

fn do_read(filename: &str) -> Vec<i32> {
    let mut f = File::open(filename).unwrap();
    let mut bytes = Vec::new();

    f.read_to_end(&mut bytes).unwrap();

    from_u8(bytes)
}

fn main() {
    let v = vec![42; 10];
    do_write("vector.dump", &v);
    let v2 = do_read("vector.dump");

    assert_eq!(v, v2);
    println!("{:?}", v2)
}