diff --git a/src/hex.rs b/src/hex.rs new file mode 100644 index 0000000..badcdd1 --- /dev/null +++ b/src/hex.rs @@ -0,0 +1,48 @@ +use std::iter; +use std::str::Chars; + +pub enum HexResult { + Byte(u8), + Invalid(char), +} + +pub struct HexDecoder<'a> { + input: Chars<'a>, +} + +impl<'a> HexDecoder<'a> { + fn new(input: &'a str) -> HexDecoder { + HexDecoder { input: input.chars() } + } +} + +impl<'a> iter::Iterator for HexDecoder<'a> { + type Item = HexResult; + + fn next(&mut self) -> Option { + if let Some(c) = self.input.next() { + if let Some(hex) = c.to_digit(16) { + Some(HexResult::Byte(hex as u8)) + } else { + Some(HexResult::Invalid(c)) + } + } else { + None + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn simple() { + let decoder = HexDecoder::new("123"); + let collected: Vec = decoder.map(|c| match c { + HexResult::Byte(c) => c, + _ => panic!(), + }).collect(); + assert_eq!(collected, vec![1, 2, 3]); + } +} diff --git a/src/lib.rs b/src/lib.rs index 07c2538..0b4ae41 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,2 +1,3 @@ pub mod b64; pub mod xor; +pub mod hex;