str_utils/
starts_with_ignore_case.rs

1use crate::{ToLowercase, ToUppercase};
2
3/// To extend `str` to have a `starts_with_ignore_case` method.
4pub trait StartsWithIgnoreCase {
5    /// Returns `true` if the given string slice case-insensitively (using case-folding) matches a prefix of this string slice.
6    ///
7    /// NOTE: This method may allocate heap memory.
8    fn starts_with_ignore_case<S: AsRef<str>>(&self, b: S) -> bool;
9}
10
11impl StartsWithIgnoreCase for str {
12    #[inline]
13    fn starts_with_ignore_case<S: AsRef<str>>(&self, b: S) -> bool {
14        let a = self;
15        let b = b.as_ref();
16
17        if b.is_empty() {
18            return true;
19        }
20
21        {
22            let au = a.to_uppercase_cow();
23            let bu = b.to_uppercase_cow();
24
25            let au_length = au.len();
26            let bu_length = bu.len();
27
28            if au_length >= bu_length && unsafe { au.get_unchecked(..bu_length) == bu } {
29                return true;
30            }
31        }
32
33        let al = a.to_lowercase_cow();
34        let bl = b.to_lowercase_cow();
35
36        let al_length = al.len();
37        let bl_length = bl.len();
38
39        if al_length >= bl_length {
40            unsafe { al.get_unchecked(..bl_length) == bl }
41        } else {
42            false
43        }
44    }
45}