From e154391f3271868eecdd8860ff4949cca3b9d889 Mon Sep 17 00:00:00 2001 From: Mahmoud Al-Qudsi Date: Tue, 16 May 2023 13:17:34 -0500 Subject: [PATCH] Add WCharExt::find() method to perform substring search --- fish-rust/src/wchar_ext.rs | 52 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/fish-rust/src/wchar_ext.rs b/fish-rust/src/wchar_ext.rs index c6715f10a..bb568474a 100644 --- a/fish-rust/src/wchar_ext.rs +++ b/fish-rust/src/wchar_ext.rs @@ -226,6 +226,15 @@ pub trait WExt { } } + /// Returns the index of the first match against the provided substring or `None`. + fn find(&self, search: impl AsRef<[char]>) -> Option { + fn inner(lhs: &[char], rhs: &[char]) -> Option { + lhs.windows(rhs.len()).position(|window| window == rhs) + } + + inner(self.as_char_slice(), search.as_ref()) + } + /// \return the index of the first occurrence of the given char, or None. fn find_char(&self, c: char) -> Option { self.as_char_slice().iter().position(|&x| x == c) @@ -318,4 +327,47 @@ mod tests { &["Hello", "world", "Rust"] ); } + + #[test] + fn find_prefix() { + let needle = L!("hello"); + let haystack = L!("hello world"); + assert_eq!(haystack.find(needle), Some(0)); + } + + #[test] + fn find_one() { + let needle = L!("ello"); + let haystack = L!("hello world"); + assert_eq!(haystack.find(needle), Some(1)); + } + + #[test] + fn find_suffix() { + let needle = L!("world"); + let haystack = L!("hello world"); + assert_eq!(haystack.find(needle), Some(6)); + } + + #[test] + fn find_none() { + let needle = L!("worldz"); + let haystack = L!("hello world"); + assert_eq!(haystack.find(needle), None); + } + + #[test] + fn find_none_larger() { + // Notice that `haystack` and `needle` are reversed. + let haystack = L!("world"); + let needle = L!("hello world"); + assert_eq!(haystack.find(needle), None); + } + + #[test] + fn find_none_case_mismatch() { + let haystack = L!("wOrld"); + let needle = L!("hello world"); + assert_eq!(haystack.find(needle), None); + } }