What is an elegant way to deal with remainders when splitting a vector into chunks?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



What is an elegant way to deal with remainders when splitting a vector into chunks?



I have a buffer of 10 bytes:



I have a larger payload (in_data: Vec<u8>) that I need to split into chunks:


in_data: Vec<u8>


let mut buffer = vec![0u8; 10];

for chunk in in_data.chunks(7)
buffer[3..].copy_from_slice(chunk);
// Do something with each packet.. send to device, etc.



This is good if all chunks are size 7, but when there is a remainder, copy_from_slice fails because the chunk is smaller than the buffer slice.


copy_from_slice



I could add ifs, checks, etc. Ideally, I would like to fill any remaining space in the buffer with zeros but this is not critical.



What is an elegant Rust way of dealing with this?





I don't get your question :( There is split_at which you can use to split your buffer into two seperate slices. Is that, what you are looking for? Can you please else clarify your question (in regards in terms, because you use buffer not consistently)? :)
– hellow
Aug 7 at 8:27





1 Answer
1



I think this is the easiest, cleanest answer:


let mut buffer = vec![0u8; 10];

for chunk in in_data.chunks(7)
buffer[3..3 + chunk.len()].copy_from_slice(chunk);
// Do something with each packet.. send to device, etc.





Keep in mind that the rest will be garbage data.
– Stargateur
Aug 7 at 13:36





yes, I am aware. The header indicates the number of bytes... for the sake of improving the answer, maybe it makes sense to add a fill... but it seems that there is no slice.fill yet
– purpletentacle
Aug 7 at 14:39






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard