In writing one’s own Base64 codec for the Cryptopals Crypto Challenge in Rust, one gets to a point where every chunk of four adjacent elements in an input vector has to be transformed into a chunk of three elements in an output vector.
That is, the string
SSdt
containing four ASCII bytes becomes the stringI'm
containing three ASCII bytes, andIGtp
becomeski
, and so on, so thatSSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t
is decoded toI'm killing your brain like a poisonous mushroom
.
I had a function to do this four-to-three downconversion but looping over the two arrays, lining up the indexes, the keeping track of magic threes and magic fours in my code gave me a headache as I worked through writing the following:
pub fn decode(s: &[u8]) -> Vec<u8> {
let mut out: Vec<u8> = vec![0; s.len() / 4 * 3];
for i in 0..ou