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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
use std::{
borrow::Cow,
cmp::Ordering,
convert::TryFrom,
fmt,
hash::{Hash, Hasher},
io::{self, Error, ErrorKind},
};
#[derive(Debug, Eq)]
pub struct CainStr<'a> {
src: Cow<'a, str>,
lowercase_src: String,
}
impl PartialEq for CainStr<'_> {
fn eq(&self, other: &Self) -> bool {
self.lowercase_src.eq(&other.lowercase_src)
}
}
impl Ord for CainStr<'_> {
fn cmp(&self, other: &Self) -> Ordering {
self.lowercase_src.cmp(&other.lowercase_src)
}
}
impl PartialOrd for CainStr<'_> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Hash for CainStr<'_> {
fn hash<H>(&self, h: &mut H) where H: Hasher {
self.lowercase_src.hash(h);
}
}
impl fmt::Display for CainStr<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
f.write_str(&self.src)
}
}
impl<'a> From<&'a str> for CainStr<'a> {
fn from(src: &'a str) -> Self {
Self {
src: src.into(),
lowercase_src: src.to_lowercase(),
}
}
}
impl<'a> From<&'a String> for CainStr<'a> {
fn from(src: &'a String) -> Self {
Self {
src: src.into(),
lowercase_src: src.to_lowercase(),
}
}
}
impl From<String> for CainStr<'_> {
fn from(src: String) -> Self {
let lowercase_src = src.to_lowercase();
Self {
src: src.into(),
lowercase_src,
}
}
}
impl<'a> TryFrom<CainStr<'a>> for &'a str {
type Error = Error;
fn try_from(cain_str: CainStr<'a>) -> io::Result<&'a str> {
match cain_str.src {
Cow::Borrowed(s) => Ok(s),
Cow::Owned(_) => Err(Error::new(ErrorKind::InvalidData, "CainStr is borrowed, not owned")),
}
}
}
impl<'a> TryFrom<CainStr<'a>> for String {
type Error = Error;
fn try_from(cain_str: CainStr<'a>) -> io::Result<String> {
match cain_str.src {
Cow::Owned(s) => Ok(s),
Cow::Borrowed(_) => Err(Error::new(ErrorKind::InvalidData, "CainStr is owned, not borrowed")),
}
}
}
impl AsRef<str> for CainStr<'_> {
fn as_ref(&self) -> &str {
&self.src
}
}
#[test]
fn test_cain_str() {
let s = "UPPER-CASE";
assert_eq!(s.to_lowercase(), CainStr::from(s).lowercase_src);
}