Skip to main content

str_utils/
to_uppercase.rs

1use alloc::borrow::Cow;
2
3use crate::{IsAsciiUppercased, IsUppercased};
4
5/// To extend `str` and `Cow<str>` to have `to_uppercase_cow` and `to_ascii_uppercase_cow` methods.
6pub trait ToUppercase<'a> {
7    /// Converts the string to its uppercase form (Unicode-aware), returning a `Cow<str>` to avoid allocation when possible.
8    fn to_uppercase_cow(self) -> Cow<'a, str>;
9
10    /// Converts the string to its ASCII uppercase form, returning a `Cow<str>` to avoid allocation when possible.
11    fn to_ascii_uppercase_cow(self) -> Cow<'a, str>;
12}
13
14impl<'a> ToUppercase<'a> for &'a str {
15    #[inline]
16    fn to_uppercase_cow(self) -> Cow<'a, str> {
17        if self.is_uppercased() {
18            Cow::Borrowed(self)
19        } else {
20            Cow::Owned(self.to_uppercase())
21        }
22    }
23
24    #[inline]
25    fn to_ascii_uppercase_cow(self) -> Cow<'a, str> {
26        if self.is_ascii_uppercased() {
27            Cow::Borrowed(self)
28        } else {
29            Cow::Owned(self.to_ascii_uppercase())
30        }
31    }
32}
33
34impl<'a> ToUppercase<'a> for Cow<'a, str> {
35    #[inline]
36    fn to_uppercase_cow(self) -> Cow<'a, str> {
37        match self {
38            Cow::Borrowed(s) => s.to_uppercase_cow(),
39            Cow::Owned(s) => Cow::Owned(cow_into_owned!(s, s.as_str().to_uppercase_cow())),
40        }
41    }
42
43    #[inline]
44    fn to_ascii_uppercase_cow(self) -> Cow<'a, str> {
45        match self {
46            Cow::Borrowed(s) => s.to_ascii_uppercase_cow(),
47            Cow::Owned(s) => Cow::Owned(cow_into_owned!(s, s.as_str().to_ascii_uppercase_cow(),)),
48        }
49    }
50}