I am doing the Matasano crypto challenge while trying to use Rust (in an idomatic way).
The second assignment is to xor two vectors. The code I have now is:
extern crate rustc_serialize;
use rustc_serialize::hex::{FromHex,ToHex};
pub fn fixed_xor(l: &str, r: &str) -> String {
let mut l = l.from_hex().unwrap();
let r = r.from_hex().unwrap();
for i in 0..l.len() {
l[i] ^= r[i];
}
return l.to_hex();
}
This works, but it doesn't feel idiomatic code because of the range in the for-loop.
Is it possible to zip l
and r
and get a mutable reference to the element from l
and a non-mutable reference to the element from r
?
(Note, I don't check the length of the vectors. I know this would blow up in real life, but I would like to focus now on the for loop)
You would use the
.zip()
iterator adaptor, for example like this:You could consider generalizing this XOR operation by either
BitXor
.IntoIterator
arguments instead of just slices.Note that
zip
will stop whenever the shorter of the two iterators does.