@@ -11,9 +11,10 @@ mod test_readme {
1111}
1212
1313use 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" ) ]
1819mod 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
140134impl < ' 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) ]
167173mod 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