3
3
#![ deny( missing_docs, missing_debug_implementations) ]
4
4
5
5
use std:: path:: Path ;
6
+ use std:: str:: FromStr ;
6
7
7
8
use serde:: de;
8
9
@@ -21,6 +22,19 @@ pub enum Format {
21
22
Yaml ,
22
23
}
23
24
25
+ impl FromStr for Format {
26
+ type Err = String ;
27
+
28
+ fn from_str ( s : & str ) -> Result < Self , Self :: Err > {
29
+ match s. to_lowercase ( ) . as_str ( ) {
30
+ "toml" => Ok ( Format :: Toml ) ,
31
+ "yaml" => Ok ( Format :: Yaml ) ,
32
+ "json" => Ok ( Format :: Json ) ,
33
+ _ => Err ( format ! ( "Invalid format: {}" , s) ) ,
34
+ }
35
+ }
36
+ }
37
+
24
38
impl Format {
25
39
/// Obtain the format from the file path using extension as a hint.
26
40
pub fn from_path < T : AsRef < Path > > ( path : T ) -> Result < Self , T > {
@@ -34,8 +48,6 @@ impl Format {
34
48
}
35
49
36
50
/// Parse the string represented in the specified format.
37
- /// If the format is unknown - fallback to the default format and attempt
38
- /// parsing using that.
39
51
pub fn deserialize < T > ( content : & str , format : Format ) -> Result < T , Vec < String > >
40
52
where
41
53
T : de:: DeserializeOwned ,
47
59
}
48
60
}
49
61
62
+ /// Serialize the specified `value` into a string.
63
+ pub fn serialize < T > ( value : & T , format : Format ) -> Result < String , String >
64
+ where
65
+ T : serde:: ser:: Serialize ,
66
+ {
67
+ match format {
68
+ Format :: Toml => toml:: to_string ( value) . map_err ( |e| e. to_string ( ) ) ,
69
+ Format :: Yaml => serde_yaml:: to_string ( value) . map_err ( |e| e. to_string ( ) ) ,
70
+ Format :: Json => serde_json:: to_string_pretty ( value) . map_err ( |e| e. to_string ( ) ) ,
71
+ }
72
+ }
73
+
50
74
#[ cfg( test) ]
51
75
mod tests {
52
76
use super :: * ;
77
+ use proptest:: prelude:: * ;
78
+
79
+ impl Arbitrary for Format {
80
+ type Parameters = ( ) ;
81
+ fn arbitrary_with ( _args : Self :: Parameters ) -> Self :: Strategy {
82
+ prop_oneof ! [ Just ( Format :: Toml ) , Just ( Format :: Json ) , Just ( Format :: Yaml ) , ] . boxed ( )
83
+ }
84
+
85
+ type Strategy = BoxedStrategy < Self > ;
86
+ }
53
87
54
88
/// This test ensures the logic to guess file format from the file path
55
89
/// works correctly.
0 commit comments