Skip to main content

str_utils/
to_lowercase.rs

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