-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathde.rs
More file actions
323 lines (285 loc) · 10.5 KB
/
de.rs
File metadata and controls
323 lines (285 loc) · 10.5 KB
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
use serde::{
de::{
self, DeserializeSeed, EnumAccess, IntoDeserializer, MapAccess, SeqAccess, VariantAccess,
Visitor,
},
forward_to_deserialize_any,
};
use super::{
BsonError,
error::ErrorKind,
parser::{ElementType, Parser},
};
pub struct Deserializer<'de> {
parser: Parser<'de>,
position: DeserializerPosition,
}
#[derive(Clone, Debug)]
enum DeserializerPosition {
/// The deserializer is outside of the initial document header.
OutsideOfDocument,
/// The deserializer expects the beginning of a key-value pair, or the end of the current
/// document.
BeforeTypeOrAtEndOfDocument,
/// The deserializer has read past the type of a key-value pair, but did not scan the name yet.
BeforeName { pending_type: ElementType },
/// Read type and name of a key-value pair, position is before the value now.
BeforeValue { pending_type: ElementType },
}
impl<'de> Deserializer<'de> {
/// When used as a name hint to [de::Deserialize.deserialize_enum], the BSON deserializer will
/// report documents a byte array view instead of parsing them.
///
/// This is used as an internal optimization when we want to keep a reference to a BSON sub-
/// document without actually inspecting the structure of that document.
pub const SPECIAL_CASE_EMBEDDED_DOCUMENT: &'static str = "\0SpecialCaseEmbedDoc";
fn outside_of_document(parser: Parser<'de>) -> Self {
Self {
parser,
position: DeserializerPosition::OutsideOfDocument,
}
}
pub fn from_bytes(bytes: &'de [u8]) -> Self {
let parser = Parser::new(bytes);
Self::outside_of_document(parser)
}
fn prepare_to_read(&mut self, allow_key: bool) -> Result<KeyOrValue<'de>, BsonError> {
match self.position.clone() {
DeserializerPosition::OutsideOfDocument => {
// The next value we're reading is a document
self.position = DeserializerPosition::BeforeValue {
pending_type: ElementType::Document,
};
Ok(KeyOrValue::PendingValue(ElementType::Document))
}
DeserializerPosition::BeforeValue { pending_type } => {
Ok(KeyOrValue::PendingValue(pending_type))
}
DeserializerPosition::BeforeTypeOrAtEndOfDocument { .. } => {
Err(self.parser.error(ErrorKind::InvalidStateExpectedType))
}
DeserializerPosition::BeforeName { pending_type } => {
if !allow_key {
return Err(self.parser.error(ErrorKind::InvalidStateExpectedName));
}
self.position = DeserializerPosition::BeforeValue {
pending_type: pending_type,
};
Ok(KeyOrValue::Key(self.parser.read_cstr()?))
}
}
}
fn prepare_to_read_value(&mut self) -> Result<ElementType, BsonError> {
let result = self.prepare_to_read(false)?;
match result {
KeyOrValue::Key(_) => unreachable!(),
KeyOrValue::PendingValue(element_type) => Ok(element_type),
}
}
fn object_reader(&mut self) -> Result<Deserializer<'de>, BsonError> {
let parser = self.parser.document_scope()?;
let deserializer = Deserializer {
parser,
position: DeserializerPosition::BeforeTypeOrAtEndOfDocument,
};
Ok(deserializer)
}
fn advance_to_next_name(&mut self) -> Result<Option<()>, BsonError> {
if self.parser.end_document()? {
return Ok(None);
}
self.position = DeserializerPosition::BeforeName {
pending_type: self.parser.read_element_type()?,
};
Ok(Some(()))
}
}
impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
type Error = BsonError;
fn is_human_readable(&self) -> bool {
false
}
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
let element_type = match self.prepare_to_read(true)? {
KeyOrValue::Key(name) => return visitor.visit_borrowed_str(name),
KeyOrValue::PendingValue(element_type) => element_type,
};
match element_type {
ElementType::Double => visitor.visit_f64(self.parser.read_double()?),
ElementType::String => visitor.visit_borrowed_str(self.parser.read_string()?),
ElementType::Document => {
let mut object = self.object_reader()?;
visitor.visit_map(&mut object)
}
ElementType::Array => {
let mut object = self.object_reader()?;
visitor.visit_seq(&mut object)
}
ElementType::Binary => {
let (_, bytes) = self.parser.read_binary()?;
visitor.visit_borrowed_bytes(bytes)
}
ElementType::ObjectId => visitor.visit_borrowed_bytes(self.parser.read_object_id()?),
ElementType::Boolean => visitor.visit_bool(self.parser.read_bool()?),
ElementType::DatetimeUtc | ElementType::Timestamp => {
visitor.visit_u64(self.parser.read_uint64()?)
}
ElementType::Null | ElementType::Undefined => visitor.visit_unit(),
ElementType::Int32 => visitor.visit_i32(self.parser.read_int32()?),
ElementType::Int64 => visitor.visit_i64(self.parser.read_int64()?),
}
}
fn deserialize_enum<V>(
self,
name: &'static str,
_variants: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
let kind = self.prepare_to_read_value()?;
// With this special name, the visitor indicates that it doesn't actually want to read an
// enum, it wants to read values regularly. Except that a document appearing at this
// position should not be parsed, it should be forwarded as an embedded byte array.
if name == Deserializer::SPECIAL_CASE_EMBEDDED_DOCUMENT {
return if matches!(kind, ElementType::Document) {
let object = self.parser.skip_document()?;
visitor.visit_borrowed_bytes(object)
} else {
self.deserialize_any(visitor)
};
}
match kind {
ElementType::String => {
visitor.visit_enum(self.parser.read_string()?.into_deserializer())
}
ElementType::Document => {
let mut object = self.object_reader()?;
visitor.visit_enum(&mut object)
}
_ => Err(self.parser.error(ErrorKind::ExpectedEnum { actual: kind })),
}
}
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
let kind = self.prepare_to_read_value()?;
match kind {
ElementType::Null => visitor.visit_none(),
_ => visitor.visit_some(self),
}
}
fn deserialize_newtype_struct<V>(
self,
_name: &'static str,
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
self.prepare_to_read_value()?;
visitor.visit_newtype_struct(self)
}
forward_to_deserialize_any! {
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
bytes byte_buf unit unit_struct seq tuple
tuple_struct map struct ignored_any identifier
}
}
impl<'de> MapAccess<'de> for Deserializer<'de> {
type Error = BsonError;
fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
where
K: DeserializeSeed<'de>,
{
if let None = self.advance_to_next_name()? {
return Ok(None);
}
Ok(Some(seed.deserialize(self)?))
}
fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
where
V: DeserializeSeed<'de>,
{
seed.deserialize(self)
}
}
impl<'de> SeqAccess<'de> for Deserializer<'de> {
type Error = BsonError;
fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
where
T: DeserializeSeed<'de>,
{
// Array elements are encoded as an object like `{"0": value, "1": another}`
if let None = self.advance_to_next_name()? {
return Ok(None);
}
// Skip name
assert!(matches!(
self.position,
DeserializerPosition::BeforeName { .. }
));
self.prepare_to_read(true)?;
// And deserialize value!
Ok(Some(seed.deserialize(self)?))
}
}
impl<'a, 'de> EnumAccess<'de> for &'a mut Deserializer<'de> {
type Error = BsonError;
type Variant = Self;
fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
where
V: DeserializeSeed<'de>,
{
if let None = self.advance_to_next_name()? {
return Err(self
.parser
.error(ErrorKind::UnexpectedEndOfDocumentForEnumVariant));
}
let value = seed.deserialize(&mut *self)?;
Ok((value, self))
}
}
impl<'a, 'de> VariantAccess<'de> for &'a mut Deserializer<'de> {
type Error = BsonError;
fn unit_variant(self) -> Result<(), Self::Error> {
// Unit variants are encoded as simple string values, which are handled directly in
// Deserializer::deserialize_enum.
Err(self.parser.error(ErrorKind::ExpectedString))
}
fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
where
T: DeserializeSeed<'de>,
{
// Newtype variants are represented as `{ NAME: VALUE }`, so we just have to deserialize the
// value here.
seed.deserialize(self)
}
fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
// Tuple variants are represented as `{ NAME: VALUES[] }`, so we deserialize the array here.
de::Deserializer::deserialize_seq(self, visitor)
}
fn struct_variant<V>(
self,
_fields: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
// Struct variants are represented as `{ NAME: { ... } }`, so we deserialize the struct.
de::Deserializer::deserialize_map(self, visitor)
}
}
enum KeyOrValue<'de> {
Key(&'de str),
PendingValue(ElementType),
}