Skip to main content

json_syntax/serde/
mod.rs

1use core::fmt;
2
3use crate::{JsonParse, JsonValue};
4use serde::{
5	Serialize,
6	de::{DeserializeOwned, Error},
7};
8
9mod de;
10mod ser;
11
12pub use de::*;
13pub use ser::*;
14
15const NUMBER_TOKEN: &str = "$serde_json::private::Number";
16
17#[repr(transparent)]
18pub struct JsonSerdeAdaptor<T: ?Sized>(pub T);
19
20impl<T: ?Sized> JsonSerdeAdaptor<T> {
21	pub fn new_ref(value: &T) -> &Self {
22		unsafe { std::mem::transmute(value) }
23	}
24}
25
26impl<T> JsonSerdeAdaptor<T> {
27	pub fn unwrap(self) -> T {
28		self.0
29	}
30}
31
32impl<E: fmt::Debug> fmt::Debug for JsonSerdeAdaptor<E> {
33	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34		fmt::Debug::fmt(&self.0, f)
35	}
36}
37
38impl<E: fmt::Display> fmt::Display for JsonSerdeAdaptor<E> {
39	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40		fmt::Display::fmt(&self.0, f)
41	}
42}
43
44impl<E: std::error::Error> std::error::Error for JsonSerdeAdaptor<E> {}
45
46/// Serializes the given `value` into a JSON [`JsonValue`].
47///
48/// # Example
49///
50/// ```
51/// use serde::Serialize;
52/// use json_syntax::{json, JsonValue};
53///
54/// #[derive(Serialize)]
55/// struct User {
56///     fingerprint: String,
57///     location: String,
58/// }
59///
60/// let u = User {
61///   fingerprint: "0xF9BA143B95FF6D82".to_owned(),
62///   location: "Menlo Park, CA".to_owned(),
63/// };
64///
65/// let expected: JsonValue = json!({
66///   "fingerprint": "0xF9BA143B95FF6D82",
67///   "location": "Menlo Park, CA",
68/// });
69///
70/// let v = json_syntax::to_value(u).unwrap();
71/// assert_eq!(v, expected);
72/// ```
73pub fn to_value<T>(value: T) -> Result<JsonValue, SerializeError>
74where
75	T: Serialize,
76{
77	value.serialize(Serializer)
78}
79
80/// Deserializes the JSON `value` into an instance of type `T`.
81///
82/// # Example
83///
84/// ```
85/// use serde::Deserialize;
86/// use json_syntax::{json, JsonValue};
87///
88/// #[derive(Deserialize, Debug)]
89/// struct User {
90///     fingerprint: String,
91///     location: String,
92/// }
93///
94/// let j: JsonValue = json!({
95///   "fingerprint": "0xF9BA143B95FF6D82",
96///   "location": "Menlo Park, CA"
97/// });
98///
99/// let u: User = json_syntax::from_value(j).unwrap();
100/// println!("{:#?}", u);
101/// ```
102pub fn from_value<T>(value: JsonValue) -> Result<T, DeserializeError>
103where
104	T: DeserializeOwned,
105{
106	T::deserialize(value)
107}
108
109pub fn from_str<T>(s: &str) -> Result<T, DeserializeError>
110where
111	T: DeserializeOwned,
112{
113	let (json, _) = JsonValue::parse_str(s).map_err(DeserializeError::custom)?;
114	from_value(json)
115}
116
117pub fn from_slice<T>(s: &[u8]) -> Result<T, DeserializeError>
118where
119	T: DeserializeOwned,
120{
121	let (json, _) = JsonValue::parse_slice(s).map_err(DeserializeError::custom)?;
122	from_value(json)
123}