summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBotahamec <botahamec@outlook.com>2023-07-29 21:20:35 -0400
committerBotahamec <botahamec@outlook.com>2023-07-29 21:20:35 -0400
commit496f8b6261ca6815383794f5da5ce805dcda0f84 (patch)
treef6502293011ef089380ccc429f28e653945984d7
parentb51fc330303cca2183dde31f59934d9d038003fb (diff)
Add position to scanner
-rw-r--r--src/scanner.rs40
1 files 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: Read> {
- source: Source,
+pub struct Scanner {
+ source: Box<[char]>,
+ position: usize,
}
-impl<Source: Read> Scanner<Source> {
- pub fn new(source: Source) -> Self {
- Self { source }
+impl Scanner {
+ pub fn new(source: impl AsRef<str>) -> 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<String> {
+ // 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<String> {
+ self.goto(self.position + amount)
}
}