1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use alloc::borrow::Cow;
use crate::{IsAsciiLowercased, IsLowercased};
/// To extend `str` and `Cow<str>` to have `to_lowercase_cow` and `to_ascii_lowercase_cow` methods.
pub trait ToLowercase<'a> {
/// Converts the string to its lowercase form (Unicode-aware), returning a `Cow<str>` to avoid allocation when possible.
fn to_lowercase_cow(self) -> Cow<'a, str>;
/// Converts the string to its ASCII lowercase form, returning a `Cow<str>` to avoid allocation when possible.
fn to_ascii_lowercase_cow(self) -> Cow<'a, str>;
}
impl<'a> ToLowercase<'a> for &'a str {
#[inline]
fn to_lowercase_cow(self) -> Cow<'a, str> {
if self.is_lowercased() {
Cow::Borrowed(self)
} else {
Cow::Owned(self.to_lowercase())
}
}
#[inline]
fn to_ascii_lowercase_cow(self) -> Cow<'a, str> {
if self.is_ascii_lowercased() {
Cow::Borrowed(self)
} else {
Cow::Owned(self.to_ascii_lowercase())
}
}
}
impl<'a> ToLowercase<'a> for Cow<'a, str> {
#[inline]
fn to_lowercase_cow(self) -> Cow<'a, str> {
match self {
Cow::Borrowed(s) => s.to_lowercase_cow(),
Cow::Owned(s) => {
match s.to_lowercase_cow() {
Cow::Borrowed(_) => {
// it changes nothing
// if there were any characters that needed to be lowercased, it had to be `Cow::Owned`
Cow::Owned(s)
},
Cow::Owned(s) => Cow::Owned(s),
}
},
}
}
#[inline]
fn to_ascii_lowercase_cow(self) -> Cow<'a, str> {
match self {
Cow::Borrowed(s) => s.to_ascii_lowercase_cow(),
Cow::Owned(s) => {
match s.to_ascii_lowercase_cow() {
Cow::Borrowed(_) => {
// it changes nothing
// if there were any characters that needed to be lowercased, it had to be `Cow::Owned`
Cow::Owned(s)
},
Cow::Owned(s) => Cow::Owned(s),
}
},
}
}
}