1
- #[ derive( serde:: Serialize , serde:: Deserialize , Clone ) ]
1
+ /// RawValue is like serde_json::value::RawValue, but removes newlines to ensure
2
+ /// values can safely be used in newline-delimited contexts.
3
+ #[ derive( serde:: Serialize , Clone ) ]
2
4
pub struct RawValue ( Box < serde_json:: value:: RawValue > ) ;
3
5
4
6
impl RawValue {
5
7
pub fn is_null ( & self ) -> bool {
6
8
return self . get ( ) == "null" ;
7
9
}
8
10
pub fn from_str ( s : & str ) -> serde_json:: Result < Self > {
9
- serde_json :: value :: RawValue :: from_string ( s. to_owned ( ) ) . map ( Into :: into )
11
+ Self :: from_string ( s. to_owned ( ) )
10
12
}
11
- pub fn from_string ( s : String ) -> serde_json:: Result < Self > {
12
- serde_json:: value:: RawValue :: from_string ( s) . map ( Into :: into)
13
+ pub fn from_string ( mut s : String ) -> serde_json:: Result < Self > {
14
+ s. retain ( |c| c != '\n' ) ; // Strip newlines.
15
+ let value = serde_json:: value:: RawValue :: from_string ( s) ?;
16
+ Ok ( Self ( value) )
13
17
}
14
18
pub fn from_value ( value : & serde_json:: Value ) -> Self {
15
19
Self :: from_string ( value. to_string ( ) ) . unwrap ( )
@@ -19,6 +23,16 @@ impl RawValue {
19
23
}
20
24
}
21
25
26
+ impl < ' de > serde:: Deserialize < ' de > for RawValue {
27
+ fn deserialize < D > ( deserializer : D ) -> Result < Self , D :: Error >
28
+ where
29
+ D : serde:: Deserializer < ' de > ,
30
+ {
31
+ let inner = Box :: < serde_json:: value:: RawValue > :: deserialize ( deserializer) ?;
32
+ Ok ( inner. into ( ) )
33
+ }
34
+ }
35
+
22
36
impl Default for RawValue {
23
37
fn default ( ) -> Self {
24
38
Self ( serde_json:: value:: RawValue :: from_string ( "null" . to_string ( ) ) . unwrap ( ) )
@@ -27,7 +41,12 @@ impl Default for RawValue {
27
41
28
42
impl From < Box < serde_json:: value:: RawValue > > for RawValue {
29
43
fn from ( value : Box < serde_json:: value:: RawValue > ) -> Self {
30
- Self ( value)
44
+ if value. get ( ) . contains ( '\n' ) {
45
+ let s: Box < str > = value. into ( ) ;
46
+ Self :: from_string ( s. into ( ) ) . unwrap ( )
47
+ } else {
48
+ Self ( value)
49
+ }
31
50
}
32
51
}
33
52
@@ -73,3 +92,21 @@ impl schemars::JsonSchema for RawValue {
73
92
serde_json:: Value :: json_schema ( gen)
74
93
}
75
94
}
95
+
96
+ #[ cfg( test) ]
97
+ mod test {
98
+
99
+ #[ test]
100
+ fn test_newlines_are_removed ( ) {
101
+ let fixture = serde_json:: to_string_pretty ( & serde_json:: json!( {
102
+ "one" : 2 ,
103
+ "three" : [ 4 , 5 ]
104
+ } ) )
105
+ . unwrap ( ) ;
106
+
107
+ let v = serde_json:: value:: RawValue :: from_string ( fixture) . unwrap ( ) ;
108
+ assert ! ( v. get( ) . contains( '\n' ) ) ;
109
+ let v = super :: RawValue :: from ( v) ;
110
+ assert ! ( !v. get( ) . contains( '\n' ) ) ;
111
+ }
112
+ }
0 commit comments