Add a HexDecoder that converts char iterator to a HexResult iterator
This commit is contained in:
parent
d7a94df135
commit
2621f30830
2 changed files with 49 additions and 0 deletions
48
src/hex.rs
Normal file
48
src/hex.rs
Normal file
|
@ -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<Self::Item> {
|
||||
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<u8> = decoder.map(|c| match c {
|
||||
HexResult::Byte(c) => c,
|
||||
_ => panic!(),
|
||||
}).collect();
|
||||
assert_eq!(collected, vec![1, 2, 3]);
|
||||
}
|
||||
}
|
|
@ -1,2 +1,3 @@
|
|||
pub mod b64;
|
||||
pub mod xor;
|
||||
pub mod hex;
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue