Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::str::Chars;
- fn main() {
- let input = "1+3*5_6";
- let tokens = Scanner::new(input);
- for token_result in tokens {
- println!("{:?}", token_result)
- }
- }
- #[derive(Debug)]
- enum Token {
- Plus,
- Minus,
- Times,
- Digit(u8),
- }
- struct Scanner<'source> {
- input: Chars<'source>,
- }
- #[derive(Debug)]
- struct ScanError(char);
- impl Scanner<'_> {
- fn new(input: &str) -> Scanner<'_> {
- Scanner { input: input.chars() }
- }
- }
- impl Iterator for Scanner<'_> {
- type Item = Result<Token, ScanError>;
- fn next(&mut self) -> Option<Self::Item> {
- use Token::*;
- let tok = match self.input.next()? {
- '+' => Plus,
- '-' => Minus,
- '*' => Times,
- c @ '0'..='9' => Digit(c as u8 - b'0'),
- unmatched => return Some(Err(ScanError(unmatched)))
- };
- Some(Ok(tok))
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement