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
#[derive(Debug, Clone, PartialEq)]
pub struct Channel(String);
impl AsRef<str> for Channel {
fn as_ref(&self) -> &str {
&self.0
}
}
#[non_exhaustive]
#[derive(Debug, Copy, Clone)]
pub enum Error {
EmptyChannelName,
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::EmptyChannelName => f.write_str("empty channel name"),
}
}
}
impl std::error::Error for Error {}
pub trait IntoChannel {
fn into_channel(self) -> Result<Channel, Error>;
}
impl<T> IntoChannel for T
where
T: ToString,
{
fn into_channel(self) -> Result<Channel, Error> {
Channel::validate(self.to_string())
}
}
impl Channel {
pub(crate) fn validate(name: impl ToString) -> Result<Self, Error> {
let name = name.to_string();
if name.is_empty() {
return Err(Error::EmptyChannelName);
}
let name = name.to_lowercase();
let name = if !name.starts_with('#') {
["#", name.as_str()].concat()
} else {
name
};
Ok(Self(name))
}
}
impl std::fmt::Display for Channel {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl PartialEq<str> for Channel {
fn eq(&self, other: &str) -> bool {
self.0.eq(other)
}
}
impl PartialEq<&str> for Channel {
fn eq(&self, other: &&str) -> bool {
self.0.eq(other)
}
}
impl PartialEq<String> for Channel {
fn eq(&self, other: &String) -> bool {
self.0.eq(other)
}
}
impl std::ops::Deref for Channel {
type Target = String;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn good_channel() {
assert_eq!(Channel::validate("museun").unwrap().0, "#museun");
}
#[test]
fn equals() {
let s = "foobar";
let ch: Channel = s.into_channel().unwrap();
assert!(ch == "#foobar");
assert!(ch == "#foobar".to_string());
}
#[test]
fn bad_channel() {
let err = Channel::validate("").unwrap_err();
matches::assert_matches!(err, Error::EmptyChannelName);
}
#[test]
fn into_channel() {
let s = String::from("museun");
let channels: Vec<Channel> = vec![
s.as_str().into_channel().unwrap(),
s.clone().into_channel().unwrap(),
s.into_channel().unwrap(),
"museun".into_channel().unwrap(),
String::from("museun").into_channel().unwrap(),
std::sync::Arc::new(String::from("museun"))
.into_channel()
.unwrap(),
std::rc::Rc::new(String::from("museun"))
.into_channel()
.unwrap(),
String::from("museun")
.into_channel()
.unwrap()
.into_channel()
.unwrap(),
];
for name in channels {
assert_eq!(*name, "#museun");
}
}
}