7

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();
xrl
  • 2,155
  • 5
  • 26
  • 40

1 Answers1

9

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<_>>()
DK.
  • 55,277
  • 5
  • 189
  • 162
  • My concern is with reallocations. How can I find out if the `vec!` macro does a `with_capacity`? – xrl Jun 10 '15 at 17:32