Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to pad a vector with zero bytes?

Tags:

rust

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?

like image 437
Grazosi Avatar asked Dec 30 '25 05:12

Grazosi


1 Answers

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);
like image 140
Chayim Friedman Avatar answered Jan 01 '26 23:01

Chayim Friedman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!