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
use crate::util::ShouldSkip;
use serde::de::DeserializeOwned;
use serde_json::{value::RawValue, Value};
#[derive(Clone, Default, Serialize, Deserialize)]
pub struct Source(Box<RawValue>);
impl std::fmt::Debug for Source {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl std::fmt::Display for Source {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl PartialEq for Source {
fn eq(&self, other: &Self) -> bool {
self.0.get() == other.0.get()
}
}
impl ShouldSkip for Source {
fn should_skip(&self) -> bool {
self.eq(&Source::default())
}
}
impl Source {
pub fn parse<T>(&self) -> Result<T, serde_json::Error>
where
T: DeserializeOwned,
{
serde_json::from_str(self.0.get())
}
pub fn from_string(value: String) -> Result<Self, serde_json::Error> {
RawValue::from_string(value).map(Self)
}
}
impl From<Value> for Source {
fn from(value: Value) -> Self {
Self(RawValue::from_string(format!("{value}")).expect("valid json"))
}
}
impl From<Box<RawValue>> for Source {
fn from(value: Box<RawValue>) -> Self {
Self(value)
}
}
impl<'a> From<&'a RawValue> for Source {
fn from(value: &'a RawValue) -> Self {
Self(value.to_owned())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn creates_from_json_value() {
let _ = Source::from(json!({"key": "value"}));
let _ = Source::from(json!({"key": ["value", 1, 1.2, true, null, {"key2": "value2"}]}));
let _ = Source::from(json!(["one", 2, 3.0, false, null, {}]));
}
}