Lex Multi-Char Tokens With Iterator::peekable
Scan a character stream using Iterator::peekable to group multi-digit integers, identifiers, and two-character operators like == and !=.
Code
#[derive(Debug, PartialEq)]
enum Tok {
Ident(String),
Number(u64),
Eq,
EqEq,
Neq,
Bang,
}
fn lex(input: &str) -> Vec<Tok> {
let mut chars = input.chars().peekable();
let mut out = Vec::new();
while let Some(c) = chars.next() {
if c.is_whitespace() {
continue;
}
if c.is_ascii_digit() {
let mut digits = String::from(c);
while let Some(&next) = chars.peek() {
if !next.is_ascii_digit() {
break;
}
digits.push(chars.next().unwrap());
}
out.push(Tok::Number(digits.parse().unwrap()));
} else if c.is_ascii_alphabetic() || c == '_' {
let mut ident = String::from(c);
while let Some(&next) = chars.peek() {
if !(next.is_ascii_alphanumeric() || next == '_') {
break;
}
ident.push(chars.next().unwrap());
}
out.push(Tok::Ident(ident));
} else if c == '=' && chars.peek() == Some(&'=') {
chars.next();
out.push(Tok::EqEq);
} else if c == '=' {
out.push(Tok::Eq);
} else if c == '!' && chars.peek() == Some(&'=') {
chars.next();
out.push(Tok::Neq);
} else if c == '!' {
out.push(Tok::Bang);
}
}
out
}
fn main() {
let tokens = lex("status == 200 retries != 0 flag = !ready");
println!("tokens ({}): {tokens:?}", tokens.len());
}Execution path — Lex Multi-Char Tokens With Iterator::peekable
Lex Multi-Char Tokens With Iterator::peekable is built around the functions lex and main.
Repetition is confined to while let Some(c) = chars.next() — the rest of the file is straight-line.
What to watch for
- Any import statements resolve cleanly to stock standard-library packages.
Using it
Signature: fn lex(input: &str) -> Vec<Tok>
The demo output is labeled (tokens (); each label names the call that printed it.
Launch the file; main takes over and steps through lex.
Key statements
while let Some(&next) = chars.peek() {
if !next.is_ascii_digit() {
break;
}
digits.push(chars.next().unwrap());
}
while let Some(&next) = chars.peek() {
if !(next.is_ascii_alphanumeric() || next == '_') {
break;
}
ident.push(chars.next().unwrap());
}
out.push(Tok::Number(digits.parse().unwrap()));
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.LLM Token & Cost EstimatorEstimate BPE-approximate LLM token counts across English, CJK text, and source code and compare request and batch costs across pricing tiers.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- What does Lex Multi-Char Tokens With Iterator::peekable print when run?
- Execute the whole file; each printed line is prefixed with a label like `tokens (`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.