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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
use crate::any::ser::AnySerializer;
use ordered_float::NotNan;
use serde::de::{DeserializeOwned, Unexpected};
use serde::Serialize;
use std::collections::BTreeMap;
use std::error;
use std::f64;
use std::fmt;
mod de;
mod ser;
#[derive(Debug)]
pub struct Error(String);
impl error::Error for Error {}
impl fmt::Display for Error {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.write_str(&self.0)
}
}
impl serde::de::Error for Error {
fn custom<T>(msg: T) -> Self
where
T: fmt::Display,
{
Error(msg.to_string())
}
}
impl serde::ser::Error for Error {
fn custom<T>(msg: T) -> Self
where
T: fmt::Display,
{
Error(msg.to_string())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
enum Inner {
Null,
Bool(bool),
Float(NotNan<f64>),
PositiveInt(u64),
NegativeInt(i64),
String(String),
Array(Vec<Any>),
Object(BTreeMap<String, Any>),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Any(Inner);
impl Any {
pub fn new<T>(value: T) -> Result<Any, Error>
where
T: Serialize,
{
value.serialize(AnySerializer)
}
pub fn deserialize_into<T>(self) -> Result<T, Error>
where
T: DeserializeOwned,
{
T::deserialize(self)
}
fn unexpected(&self) -> Unexpected<'_> {
match &self.0 {
Inner::Null => Unexpected::Unit,
Inner::Bool(v) => Unexpected::Bool(*v),
Inner::Float(v) => Unexpected::Float(**v),
Inner::PositiveInt(v) => Unexpected::Unsigned(*v),
Inner::NegativeInt(v) => Unexpected::Signed(*v),
Inner::String(v) => Unexpected::Str(v),
Inner::Array(_) => Unexpected::Seq,
Inner::Object(_) => Unexpected::Map,
}
}
}