Skip to content

Instantly share code, notes, and snippets.

@tautologico
Created May 28, 2022 16:33
Show Gist options
  • Save tautologico/4f1e512dcd7e6c66c4794ae6caa38edc to your computer and use it in GitHub Desktop.
Save tautologico/4f1e512dcd7e6c66c4794ae6caa38edc to your computer and use it in GitHub Desktop.
Peekable Char Iterator
use std::iter::Peekable;
use std::str::Chars;
fn main() {
let s = "Aussonderungsaxiom".to_string();
let mut bf = Buffer::new(&s);
println!("First character should be A: {}", bf.peek().expect("q"));
println!("First char: {}", bf.next().expect("q"));
println!("Next char: {}", bf.next().expect("q"));
println!("Peeking the next char: {}", bf.peek().expect("q"));
println!("Now the next char: {}", bf.next().expect("q"));
}
struct Buffer<'a> {
pci: Peekable<Chars<'a>>,
}
impl<'a> Buffer<'a> {
fn new(src: &str) -> Buffer {
Buffer {
pci: src.chars().peekable(),
}
}
fn peek(&mut self) -> Option<&char> {
self.pci.peek()
}
fn next(&mut self) -> Option<char> {
self.pci.next()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment