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::{IsAsciiUppercased, IsUppercased};
/// To extend `str` and `Cow<str>` to have `to_uppercase_cow` and `to_ascii_uppercase_cow` methods.
pub trait ToUppercase<'a> {
/// Converts the string to its uppercase form (Unicode-aware), returning a `Cow<str>` to avoid allocation when possible.
fn to_uppercase_cow(self) -> Cow<'a, str>;
/// Converts the string to its ASCII uppercase form, returning a `Cow<str>` to avoid allocation when possible.
fn to_ascii_uppercase_cow(self) -> Cow<'a, str>;
}
impl<'a> ToUppercase<'a> for &'a str {
#[inline]
fn to_uppercase_cow(self) -> Cow<'a, str> {
if self.is_uppercased() {
Cow::Borrowed(self)
} else {
Cow::Owned(self.to_uppercase())
}
}
#[inline]
fn to_ascii_uppercase_cow(self) -> Cow<'a, str> {
if self.is_ascii_uppercased() {
Cow::Borrowed(self)
} else {
Cow::Owned(self.to_ascii_uppercase())
}
}
}
impl<'a> ToUppercase<'a> for Cow<'a, str> {
#[inline]
fn to_uppercase_cow(self) -> Cow<'a, str> {
match self {
Cow::Borrowed(s) => s.to_uppercase_cow(),
Cow::Owned(s) => {
match s.to_uppercase_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_uppercase_cow(self) -> Cow<'a, str> {
match self {
Cow::Borrowed(s) => s.to_ascii_uppercase_cow(),
Cow::Owned(s) => {
match s.to_ascii_uppercase_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),
}
},
}
}
}