|
| 1 | +use mango::io::typ::Reader; |
| 2 | +use mango::io::typ::ReaderResult; |
| 3 | +use mango::io::util::REXCACHE; |
| 4 | + |
| 5 | +/// Implementation of [Reader] that reads from a pre-provided string. |
| 6 | +/// Mostly for testing purposes. |
| 7 | +#[derive(Debug)] |
| 8 | +pub struct StringReader { |
| 9 | + code: String, |
| 10 | + index: usize, |
| 11 | +} |
| 12 | + |
| 13 | +impl StringReader { |
| 14 | + pub fn new(code: String) -> Self { |
| 15 | + StringReader { code, index: 0 } |
| 16 | + } |
| 17 | +} |
| 18 | + |
| 19 | +impl Reader for StringReader { |
| 20 | + fn matches(&mut self, subpattern: &str) -> ReaderResult { |
| 21 | + // Check for subpattern |
| 22 | + REXCACHE.with(|rl| { |
| 23 | + let mut rexlib = rl.borrow_mut(); |
| 24 | + // Check for end of file |
| 25 | + // TODO: is there a better/faster way for this? maybe try this after a match and set a flag? |
| 26 | + let regex = rexlib.make_or_get(r"\s*$"); |
| 27 | + match regex.find(&self.code[self.index..]) { |
| 28 | + Some(mtch) => { |
| 29 | + if self.index + mtch.as_str().len() == self.code.len() { |
| 30 | + self.index += mtch.as_str().len(); |
| 31 | + return ReaderResult::EOF(); |
| 32 | + } |
| 33 | + } |
| 34 | + None => (), |
| 35 | + } |
| 36 | + // Check for subpattern |
| 37 | + let regex = rexlib.make_or_get(subpattern); |
| 38 | + return match regex.find(&self.code[self.index..]) { |
| 39 | + Some(mtch) => { |
| 40 | + self.index += mtch.as_str().len(); |
| 41 | + // Remove leading spaces |
| 42 | + let mut k = 0; |
| 43 | + for (i, byt) in mtch.as_str().chars().enumerate() { |
| 44 | + if byt != ' ' { |
| 45 | + break; |
| 46 | + } |
| 47 | + k = i + 1; |
| 48 | + } |
| 49 | + ReaderResult::Match((&mtch.as_str()[k..]).to_owned()) |
| 50 | + } |
| 51 | + None => ReaderResult::NoMatch(), |
| 52 | + }; |
| 53 | + }) |
| 54 | + } |
| 55 | + |
| 56 | + fn get_progress(&self) -> usize { |
| 57 | + self.index |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +// TODO: tests (spaces, end) |
0 commit comments