Advertisement
Guest User

Untitled

a guest
Jul 24th, 2019
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.89 KB | None | 0 0
  1. use std::str::Chars;
  2.  
  3. fn main() {
  4. let input = "1+3*5_6";
  5.  
  6. let tokens = Scanner::new(input);
  7.  
  8. for token_result in tokens {
  9. println!("{:?}", token_result)
  10. }
  11. }
  12.  
  13. #[derive(Debug)]
  14. enum Token {
  15. Plus,
  16. Minus,
  17. Times,
  18. Digit(u8),
  19. }
  20.  
  21. struct Scanner<'source> {
  22. input: Chars<'source>,
  23. }
  24.  
  25. #[derive(Debug)]
  26. struct ScanError(char);
  27.  
  28. impl Scanner<'_> {
  29. fn new(input: &str) -> Scanner<'_> {
  30. Scanner { input: input.chars() }
  31. }
  32. }
  33.  
  34. impl Iterator for Scanner<'_> {
  35. type Item = Result<Token, ScanError>;
  36.  
  37. fn next(&mut self) -> Option<Self::Item> {
  38. use Token::*;
  39.  
  40. let tok = match self.input.next()? {
  41. '+' => Plus,
  42. '-' => Minus,
  43. '*' => Times,
  44. c @ '0'..='9' => Digit(c as u8 - b'0'),
  45. unmatched => return Some(Err(ScanError(unmatched)))
  46. };
  47. Some(Ok(tok))
  48. }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement