Last active
March 25, 2021 23:59
-
-
Save gnp/46c1f1372b051bc6a332be2e368a8da5 to your computer and use it in GitHub Desktop.
Custom bytes iterator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn compute_bytes_iter<I>(bytes_iter: I) -> Option<u16> | |
where | |
I: IntoIterator<Item=u8> | |
{ | |
for c in bytes_iter.into_iter() { | |
print!("{}", c as char); | |
} | |
println!(); | |
Some(0u16) | |
} | |
fn compute_bytes(bytes: &[u8]) -> Option<u16> { | |
compute_bytes_iter(bytes.iter().map(|x| *x)) | |
} | |
fn compute(string: &str) -> Option<u16> { | |
compute_bytes(string.as_bytes()) | |
} | |
struct DigitIterator<'a> { | |
bytes: &'a [u8], | |
scratch: Option<u8> | |
} | |
impl <'a> DigitIterator<'a> { | |
fn new(bytes: &'a [u8]) -> DigitIterator<'a> { | |
DigitIterator { | |
bytes, | |
scratch: None, | |
} | |
} | |
} | |
impl <'a> Iterator for DigitIterator<'a> { | |
type Item = u8; | |
fn next(&mut self) -> Option<u8> { | |
match self.scratch { | |
Some(d) => { | |
self.scratch = None; | |
Some(d) | |
} | |
None => { | |
let (d, rest) = self.bytes.split_first()?; | |
self.bytes = rest; | |
let d = match d { | |
v @ b'0'..=b'9' => v - b'0', | |
v @ b'A'..=b'Z' => v - b'A' + 10u8, | |
_ => panic!("DigitIterator should only be called on pure ASCII uppercase alphanumeric strings") | |
}; | |
if d < 10 { | |
Some(d + b'0') | |
} else { | |
self.scratch = Some((d % 10) + b'0'); | |
let d = (d / 10) + b'0'; | |
Some(d) | |
} | |
} | |
} | |
} | |
} | |
fn main() -> () { | |
let string = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; | |
let string_result = compute(string); | |
let it = DigitIterator::new(string.as_bytes()); | |
let it_result = compute_bytes_iter(it); | |
println!("string: {:?}; iterator: {:?}", string_result, it_result); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment