From 496f8b6261ca6815383794f5da5ce805dcda0f84 Mon Sep 17 00:00:00 2001 From: Botahamec Date: Sat, 29 Jul 2023 21:20:35 -0400 Subject: Add position to scanner --- src/scanner.rs | 40 +++++++++++++++++++++++++++++++++------- 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/src/scanner.rs b/src/scanner.rs index 83f68e3..e007f2f 100644 --- a/src/scanner.rs +++ b/src/scanner.rs @@ -1,11 +1,37 @@ -use std::io::Read; - -pub struct Scanner { - source: Source, +pub struct Scanner { + source: Box<[char]>, + position: usize, } -impl Scanner { - pub fn new(source: Source) -> Self { - Self { source } +impl Scanner { + pub fn new(source: impl AsRef) -> Self { + Self { + source: source.as_ref().chars().collect(), + position: 0, + } + } + + pub fn position(&self) -> usize { + self.position + } + + pub fn goto(&mut self, position: usize) -> Option { + // allow reverse ranges + let production = if self.position < position { + self.source.get(self.position..position)?.iter().collect() + } else { + self.source + .get(position..self.position)? + .iter() + .rev() + .collect() + }; + + self.position = position; + Some(production) + } + + pub fn advance(&mut self, amount: usize) -> Option { + self.goto(self.position + amount) } } -- cgit v1.2.3