1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76

use std::io::{self, Read, ErrorKind};
#[derive(Debug)]
pub struct Transformer<S: Read> {
	index: usize,
	xor: Vec<u8>,
	source: S
}
impl<S: Read> Transformer<S> {
	pub fn new(xor: Vec<u8>, source: S) -> Self {
		Transformer { index: 0, xor, source }
	}
	fn next_xor_byte(&mut self) -> u8 {
		let xored = self.xor[self.index];
		self.index += 1;
		if self.index == self.xor.len() {
			self.index = 0;
		}
		xored
	}
}
impl<S: Read> Read for Transformer<S> {
	fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
		let res = self.source.read(buf)?;
		for i in 0..res {
			buf[i] ^= self.next_xor_byte();
		}
		Ok(res)
	}
}
impl<S: Read> IntoIterator for Transformer<S> {
	type IntoIter = XorIter<S>;
	type Item = io::Result<Vec<u8>>;
	fn into_iter(self) -> Self::IntoIter {
		XorIter {
			transformer: self,
		}
	}
}
#[derive(Debug)]
pub struct XorIter<S: Read> {
	transformer: Transformer<S>,
}
impl<S: Read> Iterator for XorIter<S> {
	type Item = io::Result<Vec<u8>>;
	fn next(&mut self) -> Option<Self::Item> {
		let mut buf = [0u8; 1024];
		loop {
			match self.transformer.read(&mut buf) {
				Ok(0) => return None,
				Ok(n) => return Some(Ok(buf[..n].to_vec())),
				Err(e) => match e.kind() {
					ErrorKind::Interrupted
					| ErrorKind::WouldBlock => continue,
					_ => return Some(Err(e)),
				}
			}
		}
	}
}

#[cfg(test)]
mod test {
	use super::*;
	use std::io::{Result, repeat};
	type R = Result<()>;
	#[test]
	fn test() -> R {
		let trans = Transformer::new([0, 1, 2, 3].to_vec(), repeat(127));
		for v in trans {
			assert!(v?.chunks(4).all(|chunk| chunk == &[127, 126, 125, 124]));
			break;
		}
		Ok(())
	}
}