'Removing padding at end of rust vector?

I have gotten this neat way of padding vector messages, such that I can know that they will be the same length

let len = 20;
let mut msg = vec![1, 23, 34];
msg.resize(len, 0);
println!("msg {:?}", msg);

Nice, this pads a lot of zeros to any message, running this code will give me:

msg [1, 23, 34, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

But let's say I send this message over some connection, and the other party receives it at their end. How do I take a vector like this, and strip off all the 0's in the end?

Notice that the length of the original message may be of variable length, but always less than 20

Another thing that could work for me, is to have all the padding at the beginning of the vector, doing something like this:

let len = 20;
let msg = vec![1, 23, 34];
let mut  payload = vec![0;len-msg.len()];
payload.extend(&msg);
println!("msg {:?}", payload);

And then just removing, all the preleading zero's.



Solution 1:[1]

As stated in the comments above, probably changing your protocol to include the length of the message is cleaner.

But here would be the solution to remove padding in front of the message (if the message doesn't start with zeros):

let msg: Vec<_> = payload.into_iter().skip_while(|x| *x == 0).collect();

Note that this allocates a new Vec for your msg, probably you could use the iterator directly.

Playground

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Akida