Grazosi
Grazosi

Reputation: 703

Best way to pad a vector with zero bytes?

I need to send some messages (as vectors), and they need to be sent as the same length. I want to pad the vectors with zeros if they are not the right length.

Let's say that we need all payloads to be of length 100. I thought I could use the extendfunction and do something like this:

let len = 100;
let mut msg = &[1,23,34].to_vec();
let  diff : usize = msg.len()-len;
let padding = [0;diff].to_vec();
msg.extend(padding);

This won't compile though, since the compiler complains that diff is not a constant. But also this seems rather verbose to do this simple thing that we are trying to.

Is there a nice and concise way to do this?

Upvotes: 14

Views: 4181

Answers (1)

Chayim Friedman
Chayim Friedman

Reputation: 71005

You can fix your code with std::iter::repeat():

let len = 100;
let mut msg = vec![1, 23, 34];
let diff = len - msg.len();
msg.extend(std::iter::repeat(0).take(diff));

But there is much better way - Vec::resize() is what you need:

let len = 100;
let mut msg = vec![1, 23, 34];
msg.resize(len, 0);

Upvotes: 22

Related Questions