Skip to content

Commit 71e502d

Browse files
committed
feat: FromStr implementation
1 parent dbacf5b commit 71e502d

File tree

2 files changed

+36
-18
lines changed

2 files changed

+36
-18
lines changed

src/error.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
use std::fmt::Display;
2+
3+
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
4+
pub struct EmptyString;
5+
6+
impl Display for EmptyString {
7+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8+
write!(f, "zero-value string")
9+
}
10+
}
11+
12+
impl std::error::Error for EmptyString {}

src/lib.rs

Lines changed: 24 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,10 @@ mod test_readme {
1111
}
1212

1313
use delegate::delegate;
14-
use std::fmt::Display;
15-
use std::ops::Deref;
14+
use error::EmptyString;
15+
use std::{fmt::Display, str::FromStr};
1616

17+
mod error;
1718
#[cfg(feature = "serde")]
1819
mod serde_support;
1920

@@ -129,13 +130,6 @@ impl AsRef<String> for NonEmptyString {
129130
}
130131
}
131132

132-
impl Deref for NonEmptyString {
133-
type Target = str;
134-
135-
fn deref(&self) -> &Self::Target {
136-
self.0.deref()
137-
}
138-
}
139133

140134
impl<'s> TryFrom<&'s str> for NonEmptyString {
141135
type Error = &'s str;
@@ -163,6 +157,18 @@ impl Display for NonEmptyString {
163157
}
164158
}
165159

160+
impl FromStr for NonEmptyString {
161+
type Err= EmptyString;
162+
163+
fn from_str(s: &str) -> Result<Self, Self::Err> {
164+
if s.is_empty(){
165+
return Err(EmptyString);
166+
}
167+
168+
Ok(Self(s.to_string()))
169+
}
170+
}
171+
166172
#[cfg(test)]
167173
mod tests {
168174
use super::*;
@@ -215,16 +221,16 @@ mod tests {
215221
assert_eq!(String::from("string"), str.to_string())
216222
}
217223

224+
#[test]
225+
fn from_str_works() {
226+
let empty_str = "";
227+
let valid_str = "string";
228+
229+
let _non_empty_string = NonEmptyString::from_str(empty_str)
230+
.expect_err("operation must be failed");
218231

219-
fn print_str(str: &str) {
220-
println!("{str}")
232+
let non_empty_string = NonEmptyString::from_str(valid_str).unwrap();
233+
assert_eq!(non_empty_string.as_str(), valid_str);
221234
}
222235

223-
#[test]
224-
fn deref_works() {
225-
let str = "My String";
226-
let non_empty_string = NonEmptyString::try_from(str).unwrap();
227-
print_str(&non_empty_string);
228-
assert_eq!(str, non_empty_string.deref());
229-
}
230236
}

0 commit comments

Comments
 (0)