forked from amphitheatre-app/common
-
Notifications
You must be signed in to change notification settings - Fork 0
/
de.rs
93 lines (83 loc) · 2.65 KB
/
de.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// Copyright (c) The Amphitheatre Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use json_comments::StripComments;
use serde::de;
/// Deserialize an instance of type T from an I/O stream of JSON.
pub fn from_reader<R, T>(rdr: R) -> Result<T, serde_json::Error>
where
R: std::io::Read,
T: de::DeserializeOwned,
{
let stripped = StripComments::new(rdr);
serde_json::from_reader(stripped)
}
/// Deserialize an instance of type T from bytes of JSON text.
pub fn from_slice<T>(slice: &[u8]) -> Result<T, serde_json::Error>
where
T: de::DeserializeOwned,
{
let stripped = StripComments::new(slice);
serde_json::from_reader(stripped)
}
/// Deserialize an instance of type `T` from a string of JSON text.
pub fn from_str<T>(s: &str) -> Result<T, serde_json::Error>
where
T: de::DeserializeOwned,
{
let stripped = StripComments::new(s.as_bytes());
serde_json::from_reader(stripped)
}
/// Interpret a serde_json::Value as an instance of type T.
pub fn from_value<T>(value: serde_json::Value) -> Result<T, serde_json::Error>
where
T: de::DeserializeOwned,
{
serde_json::from_value(value)
}
#[cfg(test)]
mod test {
use serde_json::json;
#[test]
fn test_from_reader() {
let json = r#"{
"foo": "bar" // This is a comment.
}"#;
let result: serde_json::Value = super::from_reader(json.as_bytes()).unwrap();
assert_eq!(result["foo"], "bar");
}
#[test]
fn test_from_slice() {
let json = r#"{
// This is a comment.
"foo": "bar"
}"#;
let result: serde_json::Value = super::from_slice(json.as_bytes()).unwrap();
assert_eq!(result["foo"], "bar");
}
#[test]
fn test_from_str() {
let json = r#"{
// This is a comment.
"foo": "bar"
}"#;
let result: serde_json::Value = super::from_str(json).unwrap();
assert_eq!(result["foo"], "bar");
}
#[test]
fn test_from_value() {
let json = json!({"foo": "bar"});
let result: serde_json::Value = super::from_value(json).unwrap();
assert_eq!(result["foo"], "bar");
}
}