diff options
| author | Botahamec <botahamec@outlook.com> | 2023-08-02 22:07:26 -0400 |
|---|---|---|
| committer | Botahamec <botahamec@outlook.com> | 2023-08-02 22:07:26 -0400 |
| commit | 144e080d03fb7bb2e2958dab90a10f36673f1491 (patch) | |
| tree | 307e3f2a26c7ce95237ed6c9b81dafbb018b414f | |
| parent | af48624ab95eea7eb78001b1550d0c0ea2e89068 (diff) | |
Fix find_substring function
| -rw-r--r-- | src/scanner.rs | 36 |
1 files changed, 31 insertions, 5 deletions
diff --git a/src/scanner.rs b/src/scanner.rs index 475098c..6c82041 100644 --- a/src/scanner.rs +++ b/src/scanner.rs @@ -198,11 +198,37 @@ impl Scanner { /// # Some(()) /// # } pub fn find_substring(&self, substring: impl AsRef<str>) -> Option<usize> { - self.source - .get(self.position..)? - .iter() - .collect::<String>() - .find(substring.as_ref()) + if substring.as_ref().is_empty() { + return Some(self.position); + } + + let chars: Vec<char> = substring.as_ref().chars().collect(); + let mut i = self.position; + let mut chars_i = 0; + let mut start = None; + + while i < self.len() { + if self.source[i] == chars[chars_i] { + if chars_i == 0 { + start = Some(i); + } + + chars_i += 1; + + if let Some(start) = start { + if chars_i == chars.len() { + return Some(start); + } + } + } else { + chars_i = 0; + start = None; + } + + i += 1; + } + + start } /// If `source[position..]` starts with the given string, then this returns |
