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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
use crate::any::ser::AnySerializer;
use ordered_float::OrderedFloat;
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),
I8(i8),
I16(i16),
I32(i32),
I64(i64),
I128(i128),
U8(u8),
U16(u16),
U32(u32),
U64(u64),
U128(u128),
F32(OrderedFloat<f32>),
F64(OrderedFloat<f64>),
Char(char),
String(String),
Bytes(Vec<u8>),
Seq(Vec<Any>),
Map(BTreeMap<Any, 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::I8(v) => Unexpected::Signed(i64::from(*v)),
Inner::I16(v) => Unexpected::Signed(i64::from(*v)),
Inner::I32(v) => Unexpected::Signed(i64::from(*v)),
Inner::I64(v) => Unexpected::Signed(*v),
Inner::I128(v) => Unexpected::Signed(*v as i64),
Inner::U8(v) => Unexpected::Unsigned(u64::from(*v)),
Inner::U16(v) => Unexpected::Unsigned(u64::from(*v)),
Inner::U32(v) => Unexpected::Unsigned(u64::from(*v)),
Inner::U64(v) => Unexpected::Unsigned(*v),
Inner::U128(v) => Unexpected::Unsigned(*v as u64),
Inner::F32(v) => Unexpected::Float(v.0 as f64),
Inner::F64(v) => Unexpected::Float(v.0),
Inner::Char(v) => Unexpected::Char(*v),
Inner::String(v) => Unexpected::Str(v),
Inner::Bytes(v) => Unexpected::Bytes(v),
Inner::Seq(_) => Unexpected::Seq,
Inner::Map(_) => Unexpected::Map,
}
}
}