@@ -11,9 +11,10 @@ mod test_readme {
11
11
}
12
12
13
13
use delegate:: delegate;
14
- use std :: fmt :: Display ;
15
- use std:: ops :: Deref ;
14
+ use error :: EmptyString ;
15
+ use std:: { fmt :: Display , str :: FromStr } ;
16
16
17
+ mod error;
17
18
#[ cfg( feature = "serde" ) ]
18
19
mod serde_support;
19
20
@@ -129,13 +130,6 @@ impl AsRef<String> for NonEmptyString {
129
130
}
130
131
}
131
132
132
- impl Deref for NonEmptyString {
133
- type Target = str ;
134
-
135
- fn deref ( & self ) -> & Self :: Target {
136
- self . 0 . deref ( )
137
- }
138
- }
139
133
140
134
impl < ' s > TryFrom < & ' s str > for NonEmptyString {
141
135
type Error = & ' s str ;
@@ -163,6 +157,18 @@ impl Display for NonEmptyString {
163
157
}
164
158
}
165
159
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
+
166
172
#[ cfg( test) ]
167
173
mod tests {
168
174
use super :: * ;
@@ -215,16 +221,16 @@ mod tests {
215
221
assert_eq ! ( String :: from( "string" ) , str . to_string( ) )
216
222
}
217
223
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" ) ;
218
231
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 ) ;
221
234
}
222
235
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
- }
230
236
}
0 commit comments