Creating byte buffers in rust

12.8k views Asked by At

What is the most efficient way to get access to &mut [u8]? Right now I'm borrowing from a Vec but it would be easier to just allocate the buffer more directly.

The best I can do right now is to preallocate a vector then push out its length but there is no way this is idiomatic.

    let mut points_buf : Vec<u8> = Vec::with_capacity(points.len() * point::POINT_SIZE);
    for _ in (0..points_buf.capacity()) {
        points_buf.push(0);
    }
    file.read(&mut points_buf[..]).unwrap();
1

There are 1 answers

1
DK. On BEST ANSWER

You could just create the vec with a given size directly:

vec![0; num_points]

Or use iterators:

repeat(0).take(num_points).collect::<Vec<_>>()