str_utils/
to_uppercase.rs

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