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
46pub fn to_value<T>(value: T) -> Result<JsonValue, SerializeError>
74where
75 T: Serialize,
76{
77 value.serialize(Serializer)
78}
79
80pub 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}