Skip to content

Commit 8663379

Browse files
authored
Merge pull request #8 from jonhteper/master
Implement Display trait & unify TryFrom implementations
2 parents 11e1e3c + e811f88 commit 8663379

File tree

1 file changed

+25
-12
lines changed

1 file changed

+25
-12
lines changed

src/lib.rs

Lines changed: 25 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ mod test_readme {
1010
mod something {}
1111
}
1212

13+
use std::fmt::Display;
1314
use delegate::delegate;
1415

1516
#[cfg(feature = "serde")]
@@ -115,51 +116,56 @@ impl NonEmptyString {
115116
}
116117
}
117118

118-
impl std::convert::AsRef<str> for NonEmptyString {
119+
impl AsRef<str> for NonEmptyString {
119120
fn as_ref(&self) -> &str {
120121
&self.0
121122
}
122123
}
123124

124-
impl std::convert::AsRef<String> for NonEmptyString {
125+
impl AsRef<String> for NonEmptyString {
125126
fn as_ref(&self) -> &String {
126127
&self.0
127128
}
128129
}
129130

130-
impl<'s> std::convert::TryFrom<&'s str> for NonEmptyString {
131-
type Error = ();
131+
impl<'s> TryFrom<&'s str> for NonEmptyString {
132+
type Error = &'s str;
132133

133134
fn try_from(value: &'s str) -> Result<Self, Self::Error> {
134135
if value.is_empty() {
135-
Err(())
136-
} else {
137-
Ok(NonEmptyString::new(value.to_owned()).expect("Value is not empty"))
136+
return Err(value);
138137
}
138+
139+
Ok(NonEmptyString(value.to_owned()))
139140
}
140141
}
141142

142-
impl std::convert::TryFrom<String> for NonEmptyString {
143+
impl TryFrom<String> for NonEmptyString {
143144
type Error = String;
144145

145146
fn try_from(value: String) -> Result<Self, Self::Error> {
146147
NonEmptyString::new(value)
147148
}
148149
}
149150

151+
impl Display for NonEmptyString {
152+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
153+
Display::fmt(&self.0, f)
154+
}
155+
}
156+
150157
#[cfg(test)]
151158
mod tests {
152159
use super::*;
153-
use assert_matches::assert_matches;
154160

155161
#[test]
156-
fn empty_string_returns_none() {
162+
fn empty_string_returns_err() {
157163
assert_eq!(NonEmptyString::new("".to_owned()), Err("".to_owned()));
158164
}
159165

160166
#[test]
161-
fn non_empty_string_returns_some() {
162-
assert_matches!(NonEmptyString::new("string".to_owned()), Ok(_));
167+
fn non_empty_string_returns_ok() {
168+
assert!(NonEmptyString::new("string".to_owned()).is_ok())
163169
}
164170

165171
#[test]
@@ -192,4 +198,11 @@ mod tests {
192198
// `len` is a `String` method.
193199
assert!(nes.len() > 0);
194200
}
201+
202+
#[test]
203+
fn format_test() {
204+
let str = NonEmptyString::new("string".to_owned()).unwrap();
205+
println!("{}", &str);
206+
assert_eq!(String::from("string"), str.to_string())
207+
}
195208
}

0 commit comments

Comments
 (0)