str_utils/
to_lowercase.rs

1use alloc::{borrow::Cow, str};
2
3/// To extend types which implement `AsRef<str>` to have `is_lowercase`, `is_ascii_lowercase`, `to_lowercase_cow` and `to_ascii_lowercase_cow` methods.
4pub trait ToLowercase {
5    /// Returns `true` if all characters in the string are lowercase according to Unicode.
6    fn is_lowercase(&self) -> bool;
7
8    /// Returns `true` if all characters in the string are ASCII lowercase.
9    fn is_ascii_lowercase(&self) -> bool;
10
11    /// Converts the string to its lowercase form (Unicode-aware), returning a `Cow<str>` to avoid allocation when possible.
12    fn to_lowercase_cow(&self) -> Cow<'_, str>;
13
14    /// Converts the string to its ASCII lowercase form, returning a `Cow<str>` to avoid allocation when possible.
15    fn to_ascii_lowercase_cow(&self) -> Cow<'_, str>;
16}
17
18impl<T: AsRef<str>> ToLowercase for T {
19    #[inline]
20    fn is_lowercase(&self) -> bool {
21        self.as_ref().chars().all(|c| c.is_lowercase())
22    }
23
24    #[inline]
25    fn is_ascii_lowercase(&self) -> bool {
26        self.as_ref().chars().all(|c| c.is_ascii_lowercase())
27    }
28
29    #[inline]
30    fn to_lowercase_cow(&self) -> Cow<'_, str> {
31        if self.is_lowercase() {
32            Cow::from(self.as_ref())
33        } else {
34            Cow::from(self.as_ref().to_lowercase())
35        }
36    }
37
38    #[inline]
39    fn to_ascii_lowercase_cow(&self) -> Cow<'_, str> {
40        if self.is_ascii_lowercase() {
41            Cow::from(self.as_ref())
42        } else {
43            Cow::from(self.as_ref().to_ascii_lowercase())
44        }
45    }
46}