How to slice a large Vec as &[u8]?

后端 未结 2 798
悲哀的现实
悲哀的现实 2021-01-19 06:33

I don\'t know how to convert a Vec into a &[u8] slice.

fn main() {
    let v: Vec = vec![1; 100_000_000];         


        
2条回答
  •  一整个雨季
    2021-01-19 07:02

    You can use 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::(),
        )
    };
    

    Following the comments on this answer, you should wrap this code in a function and have the return value borrow the input, so that you use the borrow checker as far as possible:

    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::(),
            )
        }
    }
    

提交回复
热议问题