Created
December 2, 2020 11:40
-
-
Save jdmichaud/5c2979eefec370292facdb11a178c9b6 to your computer and use it in GitHub Desktop.
Tokenize a text file through a Iterator
This file contains hidden or 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
| // rustc lexer.rs && curl -s https://norvig.com/big.txt | ./lexer | |
| use std::io::{Read, Result, stdin}; | |
| #[derive(Debug)] | |
| struct Token<'a> { | |
| s: &'a str, | |
| start_index: usize, | |
| } | |
| fn tokenize<'a>(code: &'a str) -> impl Iterator<Item=Token<'a>> { | |
| let mut next_token = 0; | |
| let code_length = code.len(); | |
| code.char_indices() | |
| .filter_map(move |(index, c)| | |
| if c.is_whitespace() { | |
| let start_index = next_token; | |
| next_token = index + 1; | |
| Some(Token { s: &code[start_index..index], start_index }) | |
| } else if index == code_length - 1 { | |
| Some(Token { s: &code[next_token..index + 1], start_index: next_token }) | |
| } else { | |
| None | |
| }) | |
| } | |
| fn main() -> Result<()> { | |
| let mut buffer = String::new(); | |
| stdin().read_to_string(&mut buffer)?; | |
| for token in tokenize(buffer.as_str()) { | |
| print!("{:?} ", token); | |
| } | |
| Ok(()) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment