1 | //! Definition of a TOML [value][Value] |
2 | |
3 | use std::collections::{BTreeMap, HashMap}; |
4 | use std::fmt; |
5 | use std::hash::Hash; |
6 | use std::mem::discriminant; |
7 | use std::ops; |
8 | use std::vec; |
9 | |
10 | use serde::de; |
11 | use serde::de::IntoDeserializer; |
12 | use serde::ser; |
13 | |
14 | use toml_datetime::__unstable as datetime; |
15 | pub use toml_datetime::{Date, Datetime, DatetimeParseError, Offset, Time}; |
16 | |
17 | /// Type representing a TOML array, payload of the `Value::Array` variant |
18 | pub type Array = Vec<Value>; |
19 | |
20 | #[doc (no_inline)] |
21 | pub use crate::Table; |
22 | |
23 | /// Representation of a TOML value. |
24 | #[derive (PartialEq, Clone, Debug)] |
25 | pub enum Value { |
26 | /// Represents a TOML string |
27 | String(String), |
28 | /// Represents a TOML integer |
29 | Integer(i64), |
30 | /// Represents a TOML float |
31 | Float(f64), |
32 | /// Represents a TOML boolean |
33 | Boolean(bool), |
34 | /// Represents a TOML datetime |
35 | Datetime(Datetime), |
36 | /// Represents a TOML array |
37 | Array(Array), |
38 | /// Represents a TOML table |
39 | Table(Table), |
40 | } |
41 | |
42 | impl Value { |
43 | /// Convert a `T` into `toml::Value` which is an enum that can represent |
44 | /// any valid TOML data. |
45 | /// |
46 | /// This conversion can fail if `T`'s implementation of `Serialize` decides to |
47 | /// fail, or if `T` contains a map with non-string keys. |
48 | pub fn try_from<T>(value: T) -> Result<Value, crate::ser::Error> |
49 | where |
50 | T: ser::Serialize, |
51 | { |
52 | value.serialize(ValueSerializer) |
53 | } |
54 | |
55 | /// Interpret a `toml::Value` as an instance of type `T`. |
56 | /// |
57 | /// This conversion can fail if the structure of the `Value` does not match the |
58 | /// structure expected by `T`, for example if `T` is a struct type but the |
59 | /// `Value` contains something other than a TOML table. It can also fail if the |
60 | /// structure is correct but `T`'s implementation of `Deserialize` decides that |
61 | /// something is wrong with the data, for example required struct fields are |
62 | /// missing from the TOML map or some number is too big to fit in the expected |
63 | /// primitive type. |
64 | pub fn try_into<'de, T>(self) -> Result<T, crate::de::Error> |
65 | where |
66 | T: de::Deserialize<'de>, |
67 | { |
68 | de::Deserialize::deserialize(self) |
69 | } |
70 | |
71 | /// Index into a TOML array or map. A string index can be used to access a |
72 | /// value in a map, and a usize index can be used to access an element of an |
73 | /// array. |
74 | /// |
75 | /// Returns `None` if the type of `self` does not match the type of the |
76 | /// index, for example if the index is a string and `self` is an array or a |
77 | /// number. Also returns `None` if the given key does not exist in the map |
78 | /// or the given index is not within the bounds of the array. |
79 | pub fn get<I: Index>(&self, index: I) -> Option<&Value> { |
80 | index.index(self) |
81 | } |
82 | |
83 | /// Mutably index into a TOML array or map. A string index can be used to |
84 | /// access a value in a map, and a usize index can be used to access an |
85 | /// element of an array. |
86 | /// |
87 | /// Returns `None` if the type of `self` does not match the type of the |
88 | /// index, for example if the index is a string and `self` is an array or a |
89 | /// number. Also returns `None` if the given key does not exist in the map |
90 | /// or the given index is not within the bounds of the array. |
91 | pub fn get_mut<I: Index>(&mut self, index: I) -> Option<&mut Value> { |
92 | index.index_mut(self) |
93 | } |
94 | |
95 | /// Extracts the integer value if it is an integer. |
96 | pub fn as_integer(&self) -> Option<i64> { |
97 | match *self { |
98 | Value::Integer(i) => Some(i), |
99 | _ => None, |
100 | } |
101 | } |
102 | |
103 | /// Tests whether this value is an integer. |
104 | pub fn is_integer(&self) -> bool { |
105 | self.as_integer().is_some() |
106 | } |
107 | |
108 | /// Extracts the float value if it is a float. |
109 | pub fn as_float(&self) -> Option<f64> { |
110 | match *self { |
111 | Value::Float(f) => Some(f), |
112 | _ => None, |
113 | } |
114 | } |
115 | |
116 | /// Tests whether this value is a float. |
117 | pub fn is_float(&self) -> bool { |
118 | self.as_float().is_some() |
119 | } |
120 | |
121 | /// Extracts the boolean value if it is a boolean. |
122 | pub fn as_bool(&self) -> Option<bool> { |
123 | match *self { |
124 | Value::Boolean(b) => Some(b), |
125 | _ => None, |
126 | } |
127 | } |
128 | |
129 | /// Tests whether this value is a boolean. |
130 | pub fn is_bool(&self) -> bool { |
131 | self.as_bool().is_some() |
132 | } |
133 | |
134 | /// Extracts the string of this value if it is a string. |
135 | pub fn as_str(&self) -> Option<&str> { |
136 | match *self { |
137 | Value::String(ref s) => Some(&**s), |
138 | _ => None, |
139 | } |
140 | } |
141 | |
142 | /// Tests if this value is a string. |
143 | pub fn is_str(&self) -> bool { |
144 | self.as_str().is_some() |
145 | } |
146 | |
147 | /// Extracts the datetime value if it is a datetime. |
148 | /// |
149 | /// Note that a parsed TOML value will only contain ISO 8601 dates. An |
150 | /// example date is: |
151 | /// |
152 | /// ```notrust |
153 | /// 1979-05-27T07:32:00Z |
154 | /// ``` |
155 | pub fn as_datetime(&self) -> Option<&Datetime> { |
156 | match *self { |
157 | Value::Datetime(ref s) => Some(s), |
158 | _ => None, |
159 | } |
160 | } |
161 | |
162 | /// Tests whether this value is a datetime. |
163 | pub fn is_datetime(&self) -> bool { |
164 | self.as_datetime().is_some() |
165 | } |
166 | |
167 | /// Extracts the array value if it is an array. |
168 | pub fn as_array(&self) -> Option<&Vec<Value>> { |
169 | match *self { |
170 | Value::Array(ref s) => Some(s), |
171 | _ => None, |
172 | } |
173 | } |
174 | |
175 | /// Extracts the array value if it is an array. |
176 | pub fn as_array_mut(&mut self) -> Option<&mut Vec<Value>> { |
177 | match *self { |
178 | Value::Array(ref mut s) => Some(s), |
179 | _ => None, |
180 | } |
181 | } |
182 | |
183 | /// Tests whether this value is an array. |
184 | pub fn is_array(&self) -> bool { |
185 | self.as_array().is_some() |
186 | } |
187 | |
188 | /// Extracts the table value if it is a table. |
189 | pub fn as_table(&self) -> Option<&Table> { |
190 | match *self { |
191 | Value::Table(ref s) => Some(s), |
192 | _ => None, |
193 | } |
194 | } |
195 | |
196 | /// Extracts the table value if it is a table. |
197 | pub fn as_table_mut(&mut self) -> Option<&mut Table> { |
198 | match *self { |
199 | Value::Table(ref mut s) => Some(s), |
200 | _ => None, |
201 | } |
202 | } |
203 | |
204 | /// Tests whether this value is a table. |
205 | pub fn is_table(&self) -> bool { |
206 | self.as_table().is_some() |
207 | } |
208 | |
209 | /// Tests whether this and another value have the same type. |
210 | pub fn same_type(&self, other: &Value) -> bool { |
211 | discriminant(self) == discriminant(other) |
212 | } |
213 | |
214 | /// Returns a human-readable representation of the type of this value. |
215 | pub fn type_str(&self) -> &'static str { |
216 | match *self { |
217 | Value::String(..) => "string" , |
218 | Value::Integer(..) => "integer" , |
219 | Value::Float(..) => "float" , |
220 | Value::Boolean(..) => "boolean" , |
221 | Value::Datetime(..) => "datetime" , |
222 | Value::Array(..) => "array" , |
223 | Value::Table(..) => "table" , |
224 | } |
225 | } |
226 | } |
227 | |
228 | impl<I> ops::Index<I> for Value |
229 | where |
230 | I: Index, |
231 | { |
232 | type Output = Value; |
233 | |
234 | fn index(&self, index: I) -> &Value { |
235 | self.get(index).expect(msg:"index not found" ) |
236 | } |
237 | } |
238 | |
239 | impl<I> ops::IndexMut<I> for Value |
240 | where |
241 | I: Index, |
242 | { |
243 | fn index_mut(&mut self, index: I) -> &mut Value { |
244 | self.get_mut(index).expect(msg:"index not found" ) |
245 | } |
246 | } |
247 | |
248 | impl<'a> From<&'a str> for Value { |
249 | #[inline ] |
250 | fn from(val: &'a str) -> Value { |
251 | Value::String(val.to_string()) |
252 | } |
253 | } |
254 | |
255 | impl<V: Into<Value>> From<Vec<V>> for Value { |
256 | fn from(val: Vec<V>) -> Value { |
257 | Value::Array(val.into_iter().map(|v: V| v.into()).collect()) |
258 | } |
259 | } |
260 | |
261 | impl<S: Into<String>, V: Into<Value>> From<BTreeMap<S, V>> for Value { |
262 | fn from(val: BTreeMap<S, V>) -> Value { |
263 | let table: Map = val.into_iter().map(|(s: S, v: V)| (s.into(), v.into())).collect(); |
264 | |
265 | Value::Table(table) |
266 | } |
267 | } |
268 | |
269 | impl<S: Into<String> + Hash + Eq, V: Into<Value>> From<HashMap<S, V>> for Value { |
270 | fn from(val: HashMap<S, V>) -> Value { |
271 | let table: Map = val.into_iter().map(|(s: S, v: V)| (s.into(), v.into())).collect(); |
272 | |
273 | Value::Table(table) |
274 | } |
275 | } |
276 | |
277 | macro_rules! impl_into_value { |
278 | ($variant:ident : $T:ty) => { |
279 | impl From<$T> for Value { |
280 | #[inline] |
281 | fn from(val: $T) -> Value { |
282 | Value::$variant(val.into()) |
283 | } |
284 | } |
285 | }; |
286 | } |
287 | |
288 | impl_into_value!(String: String); |
289 | impl_into_value!(Integer: i64); |
290 | impl_into_value!(Integer: i32); |
291 | impl_into_value!(Integer: i8); |
292 | impl_into_value!(Integer: u8); |
293 | impl_into_value!(Integer: u32); |
294 | impl_into_value!(Float: f64); |
295 | impl_into_value!(Float: f32); |
296 | impl_into_value!(Boolean: bool); |
297 | impl_into_value!(Datetime: Datetime); |
298 | impl_into_value!(Table: Table); |
299 | |
300 | /// Types that can be used to index a `toml::Value` |
301 | /// |
302 | /// Currently this is implemented for `usize` to index arrays and `str` to index |
303 | /// tables. |
304 | /// |
305 | /// This trait is sealed and not intended for implementation outside of the |
306 | /// `toml` crate. |
307 | pub trait Index: Sealed { |
308 | #[doc (hidden)] |
309 | fn index<'a>(&self, val: &'a Value) -> Option<&'a Value>; |
310 | #[doc (hidden)] |
311 | fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value>; |
312 | } |
313 | |
314 | /// An implementation detail that should not be implemented, this will change in |
315 | /// the future and break code otherwise. |
316 | #[doc (hidden)] |
317 | pub trait Sealed {} |
318 | impl Sealed for usize {} |
319 | impl Sealed for str {} |
320 | impl Sealed for String {} |
321 | impl<'a, T: Sealed + ?Sized> Sealed for &'a T {} |
322 | |
323 | impl Index for usize { |
324 | fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> { |
325 | match *val { |
326 | Value::Array(ref a: &Vec) => a.get(*self), |
327 | _ => None, |
328 | } |
329 | } |
330 | |
331 | fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> { |
332 | match *val { |
333 | Value::Array(ref mut a: &mut Vec) => a.get_mut(*self), |
334 | _ => None, |
335 | } |
336 | } |
337 | } |
338 | |
339 | impl Index for str { |
340 | fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> { |
341 | match *val { |
342 | Value::Table(ref a: &Map) => a.get(self), |
343 | _ => None, |
344 | } |
345 | } |
346 | |
347 | fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> { |
348 | match *val { |
349 | Value::Table(ref mut a: &mut Map) => a.get_mut(self), |
350 | _ => None, |
351 | } |
352 | } |
353 | } |
354 | |
355 | impl Index for String { |
356 | fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> { |
357 | self[..].index(val) |
358 | } |
359 | |
360 | fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> { |
361 | self[..].index_mut(val) |
362 | } |
363 | } |
364 | |
365 | impl<'s, T: ?Sized> Index for &'s T |
366 | where |
367 | T: Index, |
368 | { |
369 | fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> { |
370 | (**self).index(val) |
371 | } |
372 | |
373 | fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> { |
374 | (**self).index_mut(val) |
375 | } |
376 | } |
377 | |
378 | #[cfg (feature = "display" )] |
379 | impl fmt::Display for Value { |
380 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
381 | use serde::Serialize as _; |
382 | |
383 | let mut output: String = String::new(); |
384 | let serializer: ValueSerializer<'_> = crate::ser::ValueSerializer::new(&mut output); |
385 | self.serialize(serializer).unwrap(); |
386 | output.fmt(f) |
387 | } |
388 | } |
389 | |
390 | #[cfg (feature = "parse" )] |
391 | impl std::str::FromStr for Value { |
392 | type Err = crate::de::Error; |
393 | fn from_str(s: &str) -> Result<Value, Self::Err> { |
394 | crate::from_str(s) |
395 | } |
396 | } |
397 | |
398 | impl ser::Serialize for Value { |
399 | fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> |
400 | where |
401 | S: ser::Serializer, |
402 | { |
403 | use serde::ser::SerializeMap; |
404 | |
405 | match *self { |
406 | Value::String(ref s) => serializer.serialize_str(s), |
407 | Value::Integer(i) => serializer.serialize_i64(i), |
408 | Value::Float(f) => serializer.serialize_f64(f), |
409 | Value::Boolean(b) => serializer.serialize_bool(b), |
410 | Value::Datetime(ref s) => s.serialize(serializer), |
411 | Value::Array(ref a) => a.serialize(serializer), |
412 | Value::Table(ref t) => { |
413 | let mut map = serializer.serialize_map(Some(t.len()))?; |
414 | // Be sure to visit non-tables first (and also non |
415 | // array-of-tables) as all keys must be emitted first. |
416 | for (k, v) in t { |
417 | if !v.is_table() && !v.is_array() |
418 | || (v |
419 | .as_array() |
420 | .map(|a| !a.iter().any(|v| v.is_table())) |
421 | .unwrap_or(false)) |
422 | { |
423 | map.serialize_entry(k, v)?; |
424 | } |
425 | } |
426 | for (k, v) in t { |
427 | if v.as_array() |
428 | .map(|a| a.iter().any(|v| v.is_table())) |
429 | .unwrap_or(false) |
430 | { |
431 | map.serialize_entry(k, v)?; |
432 | } |
433 | } |
434 | for (k, v) in t { |
435 | if v.is_table() { |
436 | map.serialize_entry(k, v)?; |
437 | } |
438 | } |
439 | map.end() |
440 | } |
441 | } |
442 | } |
443 | } |
444 | |
445 | impl<'de> de::Deserialize<'de> for Value { |
446 | fn deserialize<D>(deserializer: D) -> Result<Value, D::Error> |
447 | where |
448 | D: de::Deserializer<'de>, |
449 | { |
450 | struct ValueVisitor; |
451 | |
452 | impl<'de> de::Visitor<'de> for ValueVisitor { |
453 | type Value = Value; |
454 | |
455 | fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { |
456 | formatter.write_str("any valid TOML value" ) |
457 | } |
458 | |
459 | fn visit_bool<E>(self, value: bool) -> Result<Value, E> { |
460 | Ok(Value::Boolean(value)) |
461 | } |
462 | |
463 | fn visit_i64<E>(self, value: i64) -> Result<Value, E> { |
464 | Ok(Value::Integer(value)) |
465 | } |
466 | |
467 | fn visit_u64<E: de::Error>(self, value: u64) -> Result<Value, E> { |
468 | if value <= i64::max_value() as u64 { |
469 | Ok(Value::Integer(value as i64)) |
470 | } else { |
471 | Err(de::Error::custom("u64 value was too large" )) |
472 | } |
473 | } |
474 | |
475 | fn visit_u32<E>(self, value: u32) -> Result<Value, E> { |
476 | Ok(Value::Integer(value.into())) |
477 | } |
478 | |
479 | fn visit_i32<E>(self, value: i32) -> Result<Value, E> { |
480 | Ok(Value::Integer(value.into())) |
481 | } |
482 | |
483 | fn visit_f64<E>(self, value: f64) -> Result<Value, E> { |
484 | Ok(Value::Float(value)) |
485 | } |
486 | |
487 | fn visit_str<E>(self, value: &str) -> Result<Value, E> { |
488 | Ok(Value::String(value.into())) |
489 | } |
490 | |
491 | fn visit_string<E>(self, value: String) -> Result<Value, E> { |
492 | Ok(Value::String(value)) |
493 | } |
494 | |
495 | fn visit_some<D>(self, deserializer: D) -> Result<Value, D::Error> |
496 | where |
497 | D: de::Deserializer<'de>, |
498 | { |
499 | de::Deserialize::deserialize(deserializer) |
500 | } |
501 | |
502 | fn visit_seq<V>(self, mut visitor: V) -> Result<Value, V::Error> |
503 | where |
504 | V: de::SeqAccess<'de>, |
505 | { |
506 | let mut vec = Vec::new(); |
507 | while let Some(elem) = visitor.next_element()? { |
508 | vec.push(elem); |
509 | } |
510 | Ok(Value::Array(vec)) |
511 | } |
512 | |
513 | fn visit_map<V>(self, mut visitor: V) -> Result<Value, V::Error> |
514 | where |
515 | V: de::MapAccess<'de>, |
516 | { |
517 | let mut key = String::new(); |
518 | let datetime = visitor.next_key_seed(DatetimeOrTable { key: &mut key })?; |
519 | match datetime { |
520 | Some(true) => { |
521 | let date: datetime::DatetimeFromString = visitor.next_value()?; |
522 | return Ok(Value::Datetime(date.value)); |
523 | } |
524 | None => return Ok(Value::Table(Table::new())), |
525 | Some(false) => {} |
526 | } |
527 | let mut map = Table::new(); |
528 | map.insert(key, visitor.next_value()?); |
529 | while let Some(key) = visitor.next_key::<String>()? { |
530 | if let crate::map::Entry::Vacant(vacant) = map.entry(&key) { |
531 | vacant.insert(visitor.next_value()?); |
532 | } else { |
533 | let msg = format!("duplicate key: ` {}`" , key); |
534 | return Err(de::Error::custom(msg)); |
535 | } |
536 | } |
537 | Ok(Value::Table(map)) |
538 | } |
539 | } |
540 | |
541 | deserializer.deserialize_any(ValueVisitor) |
542 | } |
543 | } |
544 | |
545 | // This is wrapped by `Table` and any trait methods implemented here need to be wrapped there. |
546 | impl<'de> de::Deserializer<'de> for Value { |
547 | type Error = crate::de::Error; |
548 | |
549 | fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, crate::de::Error> |
550 | where |
551 | V: de::Visitor<'de>, |
552 | { |
553 | match self { |
554 | Value::Boolean(v) => visitor.visit_bool(v), |
555 | Value::Integer(n) => visitor.visit_i64(n), |
556 | Value::Float(n) => visitor.visit_f64(n), |
557 | Value::String(v) => visitor.visit_string(v), |
558 | Value::Datetime(v) => visitor.visit_string(v.to_string()), |
559 | Value::Array(v) => { |
560 | let len = v.len(); |
561 | let mut deserializer = SeqDeserializer::new(v); |
562 | let seq = visitor.visit_seq(&mut deserializer)?; |
563 | let remaining = deserializer.iter.len(); |
564 | if remaining == 0 { |
565 | Ok(seq) |
566 | } else { |
567 | Err(de::Error::invalid_length(len, &"fewer elements in array" )) |
568 | } |
569 | } |
570 | Value::Table(v) => { |
571 | let len = v.len(); |
572 | let mut deserializer = MapDeserializer::new(v); |
573 | let map = visitor.visit_map(&mut deserializer)?; |
574 | let remaining = deserializer.iter.len(); |
575 | if remaining == 0 { |
576 | Ok(map) |
577 | } else { |
578 | Err(de::Error::invalid_length(len, &"fewer elements in map" )) |
579 | } |
580 | } |
581 | } |
582 | } |
583 | |
584 | #[inline ] |
585 | fn deserialize_enum<V>( |
586 | self, |
587 | _name: &'static str, |
588 | _variants: &'static [&'static str], |
589 | visitor: V, |
590 | ) -> Result<V::Value, crate::de::Error> |
591 | where |
592 | V: de::Visitor<'de>, |
593 | { |
594 | match self { |
595 | Value::String(variant) => visitor.visit_enum(variant.into_deserializer()), |
596 | Value::Table(variant) => { |
597 | use de::Error; |
598 | if variant.is_empty() { |
599 | Err(crate::de::Error::custom( |
600 | "wanted exactly 1 element, found 0 elements" , |
601 | )) |
602 | } else if variant.len() != 1 { |
603 | Err(crate::de::Error::custom( |
604 | "wanted exactly 1 element, more than 1 element" , |
605 | )) |
606 | } else { |
607 | let deserializer = MapDeserializer::new(variant); |
608 | visitor.visit_enum(deserializer) |
609 | } |
610 | } |
611 | _ => Err(de::Error::invalid_type( |
612 | de::Unexpected::UnitVariant, |
613 | &"string only" , |
614 | )), |
615 | } |
616 | } |
617 | |
618 | // `None` is interpreted as a missing field so be sure to implement `Some` |
619 | // as a present field. |
620 | fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, crate::de::Error> |
621 | where |
622 | V: de::Visitor<'de>, |
623 | { |
624 | visitor.visit_some(self) |
625 | } |
626 | |
627 | fn deserialize_newtype_struct<V>( |
628 | self, |
629 | _name: &'static str, |
630 | visitor: V, |
631 | ) -> Result<V::Value, crate::de::Error> |
632 | where |
633 | V: de::Visitor<'de>, |
634 | { |
635 | visitor.visit_newtype_struct(self) |
636 | } |
637 | |
638 | serde::forward_to_deserialize_any! { |
639 | bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq |
640 | bytes byte_buf map unit_struct tuple_struct struct |
641 | tuple ignored_any identifier |
642 | } |
643 | } |
644 | |
645 | struct SeqDeserializer { |
646 | iter: vec::IntoIter<Value>, |
647 | } |
648 | |
649 | impl SeqDeserializer { |
650 | fn new(vec: Vec<Value>) -> Self { |
651 | SeqDeserializer { |
652 | iter: vec.into_iter(), |
653 | } |
654 | } |
655 | } |
656 | |
657 | impl<'de> de::SeqAccess<'de> for SeqDeserializer { |
658 | type Error = crate::de::Error; |
659 | |
660 | fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, crate::de::Error> |
661 | where |
662 | T: de::DeserializeSeed<'de>, |
663 | { |
664 | match self.iter.next() { |
665 | Some(value: Value) => seed.deserialize(value).map(op:Some), |
666 | None => Ok(None), |
667 | } |
668 | } |
669 | |
670 | fn size_hint(&self) -> Option<usize> { |
671 | match self.iter.size_hint() { |
672 | (lower: usize, Some(upper: usize)) if lower == upper => Some(upper), |
673 | _ => None, |
674 | } |
675 | } |
676 | } |
677 | |
678 | struct MapDeserializer { |
679 | iter: <Table as IntoIterator>::IntoIter, |
680 | value: Option<(String, Value)>, |
681 | } |
682 | |
683 | impl MapDeserializer { |
684 | fn new(map: Table) -> Self { |
685 | MapDeserializer { |
686 | iter: map.into_iter(), |
687 | value: None, |
688 | } |
689 | } |
690 | } |
691 | |
692 | impl<'de> de::MapAccess<'de> for MapDeserializer { |
693 | type Error = crate::de::Error; |
694 | |
695 | fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, crate::de::Error> |
696 | where |
697 | T: de::DeserializeSeed<'de>, |
698 | { |
699 | match self.iter.next() { |
700 | Some((key, value)) => { |
701 | self.value = Some((key.clone(), value)); |
702 | seed.deserialize(Value::String(key)).map(Some) |
703 | } |
704 | None => Ok(None), |
705 | } |
706 | } |
707 | |
708 | fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, crate::de::Error> |
709 | where |
710 | T: de::DeserializeSeed<'de>, |
711 | { |
712 | let (key, res) = match self.value.take() { |
713 | Some((key, value)) => (key, seed.deserialize(value)), |
714 | None => return Err(de::Error::custom("value is missing" )), |
715 | }; |
716 | res.map_err(|mut error| { |
717 | error.add_key(key); |
718 | error |
719 | }) |
720 | } |
721 | |
722 | fn size_hint(&self) -> Option<usize> { |
723 | match self.iter.size_hint() { |
724 | (lower, Some(upper)) if lower == upper => Some(upper), |
725 | _ => None, |
726 | } |
727 | } |
728 | } |
729 | |
730 | impl<'de> de::EnumAccess<'de> for MapDeserializer { |
731 | type Error = crate::de::Error; |
732 | type Variant = MapEnumDeserializer; |
733 | |
734 | fn variant_seed<V>(mut self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> |
735 | where |
736 | V: serde::de::DeserializeSeed<'de>, |
737 | { |
738 | use de::Error; |
739 | let (key, value) = match self.iter.next() { |
740 | Some(pair) => pair, |
741 | None => { |
742 | return Err(Error::custom( |
743 | "expected table with exactly 1 entry, found empty table" , |
744 | )); |
745 | } |
746 | }; |
747 | |
748 | let val = seed.deserialize(key.into_deserializer())?; |
749 | |
750 | let variant = MapEnumDeserializer::new(value); |
751 | |
752 | Ok((val, variant)) |
753 | } |
754 | } |
755 | |
756 | /// Deserializes table values into enum variants. |
757 | pub(crate) struct MapEnumDeserializer { |
758 | value: Value, |
759 | } |
760 | |
761 | impl MapEnumDeserializer { |
762 | pub(crate) fn new(value: Value) -> Self { |
763 | MapEnumDeserializer { value } |
764 | } |
765 | } |
766 | |
767 | impl<'de> serde::de::VariantAccess<'de> for MapEnumDeserializer { |
768 | type Error = crate::de::Error; |
769 | |
770 | fn unit_variant(self) -> Result<(), Self::Error> { |
771 | use de::Error; |
772 | match self.value { |
773 | Value::Array(values) => { |
774 | if values.is_empty() { |
775 | Ok(()) |
776 | } else { |
777 | Err(Error::custom("expected empty array" )) |
778 | } |
779 | } |
780 | Value::Table(values) => { |
781 | if values.is_empty() { |
782 | Ok(()) |
783 | } else { |
784 | Err(Error::custom("expected empty table" )) |
785 | } |
786 | } |
787 | e => Err(Error::custom(format!( |
788 | "expected table, found {}" , |
789 | e.type_str() |
790 | ))), |
791 | } |
792 | } |
793 | |
794 | fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error> |
795 | where |
796 | T: serde::de::DeserializeSeed<'de>, |
797 | { |
798 | seed.deserialize(self.value.into_deserializer()) |
799 | } |
800 | |
801 | fn tuple_variant<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error> |
802 | where |
803 | V: serde::de::Visitor<'de>, |
804 | { |
805 | use de::Error; |
806 | match self.value { |
807 | Value::Array(values) => { |
808 | if values.len() == len { |
809 | serde::de::Deserializer::deserialize_seq(values.into_deserializer(), visitor) |
810 | } else { |
811 | Err(Error::custom(format!("expected tuple with length {}" , len))) |
812 | } |
813 | } |
814 | Value::Table(values) => { |
815 | let tuple_values: Result<Vec<_>, _> = values |
816 | .into_iter() |
817 | .enumerate() |
818 | .map(|(index, (key, value))| match key.parse::<usize>() { |
819 | Ok(key_index) if key_index == index => Ok(value), |
820 | Ok(_) | Err(_) => Err(Error::custom(format!( |
821 | "expected table key ` {}`, but was ` {}`" , |
822 | index, key |
823 | ))), |
824 | }) |
825 | .collect(); |
826 | let tuple_values = tuple_values?; |
827 | |
828 | if tuple_values.len() == len { |
829 | serde::de::Deserializer::deserialize_seq( |
830 | tuple_values.into_deserializer(), |
831 | visitor, |
832 | ) |
833 | } else { |
834 | Err(Error::custom(format!("expected tuple with length {}" , len))) |
835 | } |
836 | } |
837 | e => Err(Error::custom(format!( |
838 | "expected table, found {}" , |
839 | e.type_str() |
840 | ))), |
841 | } |
842 | } |
843 | |
844 | fn struct_variant<V>( |
845 | self, |
846 | fields: &'static [&'static str], |
847 | visitor: V, |
848 | ) -> Result<V::Value, Self::Error> |
849 | where |
850 | V: serde::de::Visitor<'de>, |
851 | { |
852 | serde::de::Deserializer::deserialize_struct( |
853 | self.value.into_deserializer(), |
854 | "" , // TODO: this should be the variant name |
855 | fields, |
856 | visitor, |
857 | ) |
858 | } |
859 | } |
860 | |
861 | impl<'de> de::IntoDeserializer<'de, crate::de::Error> for Value { |
862 | type Deserializer = Self; |
863 | |
864 | fn into_deserializer(self) -> Self { |
865 | self |
866 | } |
867 | } |
868 | |
869 | struct ValueSerializer; |
870 | |
871 | impl ser::Serializer for ValueSerializer { |
872 | type Ok = Value; |
873 | type Error = crate::ser::Error; |
874 | |
875 | type SerializeSeq = ValueSerializeVec; |
876 | type SerializeTuple = ValueSerializeVec; |
877 | type SerializeTupleStruct = ValueSerializeVec; |
878 | type SerializeTupleVariant = ValueSerializeTupleVariant; |
879 | type SerializeMap = ValueSerializeMap; |
880 | type SerializeStruct = ValueSerializeMap; |
881 | type SerializeStructVariant = ValueSerializeStructVariant; |
882 | |
883 | fn serialize_bool(self, value: bool) -> Result<Value, crate::ser::Error> { |
884 | Ok(Value::Boolean(value)) |
885 | } |
886 | |
887 | fn serialize_i8(self, value: i8) -> Result<Value, crate::ser::Error> { |
888 | self.serialize_i64(value.into()) |
889 | } |
890 | |
891 | fn serialize_i16(self, value: i16) -> Result<Value, crate::ser::Error> { |
892 | self.serialize_i64(value.into()) |
893 | } |
894 | |
895 | fn serialize_i32(self, value: i32) -> Result<Value, crate::ser::Error> { |
896 | self.serialize_i64(value.into()) |
897 | } |
898 | |
899 | fn serialize_i64(self, value: i64) -> Result<Value, crate::ser::Error> { |
900 | Ok(Value::Integer(value)) |
901 | } |
902 | |
903 | fn serialize_u8(self, value: u8) -> Result<Value, crate::ser::Error> { |
904 | self.serialize_i64(value.into()) |
905 | } |
906 | |
907 | fn serialize_u16(self, value: u16) -> Result<Value, crate::ser::Error> { |
908 | self.serialize_i64(value.into()) |
909 | } |
910 | |
911 | fn serialize_u32(self, value: u32) -> Result<Value, crate::ser::Error> { |
912 | self.serialize_i64(value.into()) |
913 | } |
914 | |
915 | fn serialize_u64(self, value: u64) -> Result<Value, crate::ser::Error> { |
916 | if value <= i64::max_value() as u64 { |
917 | self.serialize_i64(value as i64) |
918 | } else { |
919 | Err(ser::Error::custom("u64 value was too large" )) |
920 | } |
921 | } |
922 | |
923 | fn serialize_f32(self, value: f32) -> Result<Value, crate::ser::Error> { |
924 | self.serialize_f64(value as f64) |
925 | } |
926 | |
927 | fn serialize_f64(self, mut value: f64) -> Result<Value, crate::ser::Error> { |
928 | // Discard sign of NaN. See ValueSerializer::serialize_f64. |
929 | if value.is_nan() { |
930 | value = value.copysign(1.0); |
931 | } |
932 | Ok(Value::Float(value)) |
933 | } |
934 | |
935 | fn serialize_char(self, value: char) -> Result<Value, crate::ser::Error> { |
936 | let mut s = String::new(); |
937 | s.push(value); |
938 | self.serialize_str(&s) |
939 | } |
940 | |
941 | fn serialize_str(self, value: &str) -> Result<Value, crate::ser::Error> { |
942 | Ok(Value::String(value.to_owned())) |
943 | } |
944 | |
945 | fn serialize_bytes(self, value: &[u8]) -> Result<Value, crate::ser::Error> { |
946 | let vec = value.iter().map(|&b| Value::Integer(b.into())).collect(); |
947 | Ok(Value::Array(vec)) |
948 | } |
949 | |
950 | fn serialize_unit(self) -> Result<Value, crate::ser::Error> { |
951 | Err(crate::ser::Error::unsupported_type(Some("unit" ))) |
952 | } |
953 | |
954 | fn serialize_unit_struct(self, name: &'static str) -> Result<Value, crate::ser::Error> { |
955 | Err(crate::ser::Error::unsupported_type(Some(name))) |
956 | } |
957 | |
958 | fn serialize_unit_variant( |
959 | self, |
960 | _name: &'static str, |
961 | _variant_index: u32, |
962 | _variant: &'static str, |
963 | ) -> Result<Value, crate::ser::Error> { |
964 | self.serialize_str(_variant) |
965 | } |
966 | |
967 | fn serialize_newtype_struct<T: ?Sized>( |
968 | self, |
969 | _name: &'static str, |
970 | value: &T, |
971 | ) -> Result<Value, crate::ser::Error> |
972 | where |
973 | T: ser::Serialize, |
974 | { |
975 | value.serialize(self) |
976 | } |
977 | |
978 | fn serialize_newtype_variant<T: ?Sized>( |
979 | self, |
980 | _name: &'static str, |
981 | _variant_index: u32, |
982 | variant: &'static str, |
983 | value: &T, |
984 | ) -> Result<Value, crate::ser::Error> |
985 | where |
986 | T: ser::Serialize, |
987 | { |
988 | let value = value.serialize(ValueSerializer)?; |
989 | let mut table = Table::new(); |
990 | table.insert(variant.to_owned(), value); |
991 | Ok(table.into()) |
992 | } |
993 | |
994 | fn serialize_none(self) -> Result<Value, crate::ser::Error> { |
995 | Err(crate::ser::Error::unsupported_none()) |
996 | } |
997 | |
998 | fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Value, crate::ser::Error> |
999 | where |
1000 | T: ser::Serialize, |
1001 | { |
1002 | value.serialize(self) |
1003 | } |
1004 | |
1005 | fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, crate::ser::Error> { |
1006 | Ok(ValueSerializeVec { |
1007 | vec: Vec::with_capacity(len.unwrap_or(0)), |
1008 | }) |
1009 | } |
1010 | |
1011 | fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, crate::ser::Error> { |
1012 | self.serialize_seq(Some(len)) |
1013 | } |
1014 | |
1015 | fn serialize_tuple_struct( |
1016 | self, |
1017 | _name: &'static str, |
1018 | len: usize, |
1019 | ) -> Result<Self::SerializeTupleStruct, crate::ser::Error> { |
1020 | self.serialize_seq(Some(len)) |
1021 | } |
1022 | |
1023 | fn serialize_tuple_variant( |
1024 | self, |
1025 | _name: &'static str, |
1026 | _variant_index: u32, |
1027 | variant: &'static str, |
1028 | len: usize, |
1029 | ) -> Result<Self::SerializeTupleVariant, crate::ser::Error> { |
1030 | Ok(ValueSerializeTupleVariant::tuple(variant, len)) |
1031 | } |
1032 | |
1033 | fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, crate::ser::Error> { |
1034 | Ok(ValueSerializeMap { |
1035 | ser: SerializeMap { |
1036 | map: Table::new(), |
1037 | next_key: None, |
1038 | }, |
1039 | }) |
1040 | } |
1041 | |
1042 | fn serialize_struct( |
1043 | self, |
1044 | _name: &'static str, |
1045 | len: usize, |
1046 | ) -> Result<Self::SerializeStruct, crate::ser::Error> { |
1047 | self.serialize_map(Some(len)) |
1048 | } |
1049 | |
1050 | fn serialize_struct_variant( |
1051 | self, |
1052 | _name: &'static str, |
1053 | _variant_index: u32, |
1054 | variant: &'static str, |
1055 | len: usize, |
1056 | ) -> Result<Self::SerializeStructVariant, crate::ser::Error> { |
1057 | Ok(ValueSerializeStructVariant::struct_(variant, len)) |
1058 | } |
1059 | } |
1060 | |
1061 | pub(crate) struct TableSerializer; |
1062 | |
1063 | impl ser::Serializer for TableSerializer { |
1064 | type Ok = Table; |
1065 | type Error = crate::ser::Error; |
1066 | |
1067 | type SerializeSeq = ser::Impossible<Table, crate::ser::Error>; |
1068 | type SerializeTuple = ser::Impossible<Table, crate::ser::Error>; |
1069 | type SerializeTupleStruct = ser::Impossible<Table, crate::ser::Error>; |
1070 | type SerializeTupleVariant = ser::Impossible<Table, crate::ser::Error>; |
1071 | type SerializeMap = SerializeMap; |
1072 | type SerializeStruct = SerializeMap; |
1073 | type SerializeStructVariant = ser::Impossible<Table, crate::ser::Error>; |
1074 | |
1075 | fn serialize_bool(self, _value: bool) -> Result<Table, crate::ser::Error> { |
1076 | Err(crate::ser::Error::unsupported_type(None)) |
1077 | } |
1078 | |
1079 | fn serialize_i8(self, _value: i8) -> Result<Table, crate::ser::Error> { |
1080 | Err(crate::ser::Error::unsupported_type(None)) |
1081 | } |
1082 | |
1083 | fn serialize_i16(self, _value: i16) -> Result<Table, crate::ser::Error> { |
1084 | Err(crate::ser::Error::unsupported_type(None)) |
1085 | } |
1086 | |
1087 | fn serialize_i32(self, _value: i32) -> Result<Table, crate::ser::Error> { |
1088 | Err(crate::ser::Error::unsupported_type(None)) |
1089 | } |
1090 | |
1091 | fn serialize_i64(self, _value: i64) -> Result<Table, crate::ser::Error> { |
1092 | Err(crate::ser::Error::unsupported_type(None)) |
1093 | } |
1094 | |
1095 | fn serialize_u8(self, _value: u8) -> Result<Table, crate::ser::Error> { |
1096 | Err(crate::ser::Error::unsupported_type(None)) |
1097 | } |
1098 | |
1099 | fn serialize_u16(self, _value: u16) -> Result<Table, crate::ser::Error> { |
1100 | Err(crate::ser::Error::unsupported_type(None)) |
1101 | } |
1102 | |
1103 | fn serialize_u32(self, _value: u32) -> Result<Table, crate::ser::Error> { |
1104 | Err(crate::ser::Error::unsupported_type(None)) |
1105 | } |
1106 | |
1107 | fn serialize_u64(self, _value: u64) -> Result<Table, crate::ser::Error> { |
1108 | Err(crate::ser::Error::unsupported_type(None)) |
1109 | } |
1110 | |
1111 | fn serialize_f32(self, _value: f32) -> Result<Table, crate::ser::Error> { |
1112 | Err(crate::ser::Error::unsupported_type(None)) |
1113 | } |
1114 | |
1115 | fn serialize_f64(self, _value: f64) -> Result<Table, crate::ser::Error> { |
1116 | Err(crate::ser::Error::unsupported_type(None)) |
1117 | } |
1118 | |
1119 | fn serialize_char(self, _value: char) -> Result<Table, crate::ser::Error> { |
1120 | Err(crate::ser::Error::unsupported_type(None)) |
1121 | } |
1122 | |
1123 | fn serialize_str(self, _value: &str) -> Result<Table, crate::ser::Error> { |
1124 | Err(crate::ser::Error::unsupported_type(None)) |
1125 | } |
1126 | |
1127 | fn serialize_bytes(self, _value: &[u8]) -> Result<Table, crate::ser::Error> { |
1128 | Err(crate::ser::Error::unsupported_type(None)) |
1129 | } |
1130 | |
1131 | fn serialize_unit(self) -> Result<Table, crate::ser::Error> { |
1132 | Err(crate::ser::Error::unsupported_type(None)) |
1133 | } |
1134 | |
1135 | fn serialize_unit_struct(self, _name: &'static str) -> Result<Table, crate::ser::Error> { |
1136 | Err(crate::ser::Error::unsupported_type(None)) |
1137 | } |
1138 | |
1139 | fn serialize_unit_variant( |
1140 | self, |
1141 | name: &'static str, |
1142 | _variant_index: u32, |
1143 | _variant: &'static str, |
1144 | ) -> Result<Table, crate::ser::Error> { |
1145 | Err(crate::ser::Error::unsupported_type(Some(name))) |
1146 | } |
1147 | |
1148 | fn serialize_newtype_struct<T: ?Sized>( |
1149 | self, |
1150 | _name: &'static str, |
1151 | value: &T, |
1152 | ) -> Result<Table, crate::ser::Error> |
1153 | where |
1154 | T: ser::Serialize, |
1155 | { |
1156 | value.serialize(self) |
1157 | } |
1158 | |
1159 | fn serialize_newtype_variant<T: ?Sized>( |
1160 | self, |
1161 | _name: &'static str, |
1162 | _variant_index: u32, |
1163 | variant: &'static str, |
1164 | value: &T, |
1165 | ) -> Result<Table, crate::ser::Error> |
1166 | where |
1167 | T: ser::Serialize, |
1168 | { |
1169 | let value = value.serialize(ValueSerializer)?; |
1170 | let mut table = Table::new(); |
1171 | table.insert(variant.to_owned(), value); |
1172 | Ok(table) |
1173 | } |
1174 | |
1175 | fn serialize_none(self) -> Result<Table, crate::ser::Error> { |
1176 | Err(crate::ser::Error::unsupported_none()) |
1177 | } |
1178 | |
1179 | fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Table, crate::ser::Error> |
1180 | where |
1181 | T: ser::Serialize, |
1182 | { |
1183 | value.serialize(self) |
1184 | } |
1185 | |
1186 | fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, crate::ser::Error> { |
1187 | Err(crate::ser::Error::unsupported_type(None)) |
1188 | } |
1189 | |
1190 | fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, crate::ser::Error> { |
1191 | Err(crate::ser::Error::unsupported_type(None)) |
1192 | } |
1193 | |
1194 | fn serialize_tuple_struct( |
1195 | self, |
1196 | name: &'static str, |
1197 | _len: usize, |
1198 | ) -> Result<Self::SerializeTupleStruct, crate::ser::Error> { |
1199 | Err(crate::ser::Error::unsupported_type(Some(name))) |
1200 | } |
1201 | |
1202 | fn serialize_tuple_variant( |
1203 | self, |
1204 | name: &'static str, |
1205 | _variant_index: u32, |
1206 | _variant: &'static str, |
1207 | _len: usize, |
1208 | ) -> Result<Self::SerializeTupleVariant, crate::ser::Error> { |
1209 | Err(crate::ser::Error::unsupported_type(Some(name))) |
1210 | } |
1211 | |
1212 | fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, crate::ser::Error> { |
1213 | Ok(SerializeMap { |
1214 | map: Table::new(), |
1215 | next_key: None, |
1216 | }) |
1217 | } |
1218 | |
1219 | fn serialize_struct( |
1220 | self, |
1221 | _name: &'static str, |
1222 | len: usize, |
1223 | ) -> Result<Self::SerializeStruct, crate::ser::Error> { |
1224 | self.serialize_map(Some(len)) |
1225 | } |
1226 | |
1227 | fn serialize_struct_variant( |
1228 | self, |
1229 | name: &'static str, |
1230 | _variant_index: u32, |
1231 | _variant: &'static str, |
1232 | _len: usize, |
1233 | ) -> Result<Self::SerializeStructVariant, crate::ser::Error> { |
1234 | Err(crate::ser::Error::unsupported_type(Some(name))) |
1235 | } |
1236 | } |
1237 | |
1238 | struct ValueSerializeVec { |
1239 | vec: Vec<Value>, |
1240 | } |
1241 | |
1242 | impl ser::SerializeSeq for ValueSerializeVec { |
1243 | type Ok = Value; |
1244 | type Error = crate::ser::Error; |
1245 | |
1246 | fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), crate::ser::Error> |
1247 | where |
1248 | T: ser::Serialize, |
1249 | { |
1250 | self.vec.push(Value::try_from(value)?); |
1251 | Ok(()) |
1252 | } |
1253 | |
1254 | fn end(self) -> Result<Value, crate::ser::Error> { |
1255 | Ok(Value::Array(self.vec)) |
1256 | } |
1257 | } |
1258 | |
1259 | impl ser::SerializeTuple for ValueSerializeVec { |
1260 | type Ok = Value; |
1261 | type Error = crate::ser::Error; |
1262 | |
1263 | fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), crate::ser::Error> |
1264 | where |
1265 | T: ser::Serialize, |
1266 | { |
1267 | ser::SerializeSeq::serialize_element(self, value) |
1268 | } |
1269 | |
1270 | fn end(self) -> Result<Value, crate::ser::Error> { |
1271 | ser::SerializeSeq::end(self) |
1272 | } |
1273 | } |
1274 | |
1275 | impl ser::SerializeTupleStruct for ValueSerializeVec { |
1276 | type Ok = Value; |
1277 | type Error = crate::ser::Error; |
1278 | |
1279 | fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), crate::ser::Error> |
1280 | where |
1281 | T: ser::Serialize, |
1282 | { |
1283 | ser::SerializeSeq::serialize_element(self, value) |
1284 | } |
1285 | |
1286 | fn end(self) -> Result<Value, crate::ser::Error> { |
1287 | ser::SerializeSeq::end(self) |
1288 | } |
1289 | } |
1290 | |
1291 | impl ser::SerializeTupleVariant for ValueSerializeVec { |
1292 | type Ok = Value; |
1293 | type Error = crate::ser::Error; |
1294 | |
1295 | fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), crate::ser::Error> |
1296 | where |
1297 | T: ser::Serialize, |
1298 | { |
1299 | ser::SerializeSeq::serialize_element(self, value) |
1300 | } |
1301 | |
1302 | fn end(self) -> Result<Value, crate::ser::Error> { |
1303 | ser::SerializeSeq::end(self) |
1304 | } |
1305 | } |
1306 | |
1307 | pub(crate) struct SerializeMap { |
1308 | map: Table, |
1309 | next_key: Option<String>, |
1310 | } |
1311 | |
1312 | impl ser::SerializeMap for SerializeMap { |
1313 | type Ok = Table; |
1314 | type Error = crate::ser::Error; |
1315 | |
1316 | fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), crate::ser::Error> |
1317 | where |
1318 | T: ser::Serialize, |
1319 | { |
1320 | match Value::try_from(key)? { |
1321 | Value::String(s) => self.next_key = Some(s), |
1322 | _ => return Err(crate::ser::Error::key_not_string()), |
1323 | }; |
1324 | Ok(()) |
1325 | } |
1326 | |
1327 | fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), crate::ser::Error> |
1328 | where |
1329 | T: ser::Serialize, |
1330 | { |
1331 | let key = self.next_key.take(); |
1332 | let key = key.expect("serialize_value called before serialize_key" ); |
1333 | match Value::try_from(value) { |
1334 | Ok(value) => { |
1335 | self.map.insert(key, value); |
1336 | } |
1337 | Err(crate::ser::Error { |
1338 | inner: crate::edit::ser::Error::UnsupportedNone, |
1339 | }) => {} |
1340 | Err(e) => return Err(e), |
1341 | } |
1342 | Ok(()) |
1343 | } |
1344 | |
1345 | fn end(self) -> Result<Table, crate::ser::Error> { |
1346 | Ok(self.map) |
1347 | } |
1348 | } |
1349 | |
1350 | impl ser::SerializeStruct for SerializeMap { |
1351 | type Ok = Table; |
1352 | type Error = crate::ser::Error; |
1353 | |
1354 | fn serialize_field<T: ?Sized>( |
1355 | &mut self, |
1356 | key: &'static str, |
1357 | value: &T, |
1358 | ) -> Result<(), crate::ser::Error> |
1359 | where |
1360 | T: ser::Serialize, |
1361 | { |
1362 | ser::SerializeMap::serialize_key(self, key)?; |
1363 | ser::SerializeMap::serialize_value(self, value) |
1364 | } |
1365 | |
1366 | fn end(self) -> Result<Table, crate::ser::Error> { |
1367 | ser::SerializeMap::end(self) |
1368 | } |
1369 | } |
1370 | |
1371 | struct ValueSerializeMap { |
1372 | ser: SerializeMap, |
1373 | } |
1374 | |
1375 | impl ser::SerializeMap for ValueSerializeMap { |
1376 | type Ok = Value; |
1377 | type Error = crate::ser::Error; |
1378 | |
1379 | fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), crate::ser::Error> |
1380 | where |
1381 | T: ser::Serialize, |
1382 | { |
1383 | self.ser.serialize_key(key) |
1384 | } |
1385 | |
1386 | fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), crate::ser::Error> |
1387 | where |
1388 | T: ser::Serialize, |
1389 | { |
1390 | self.ser.serialize_value(value) |
1391 | } |
1392 | |
1393 | fn end(self) -> Result<Value, crate::ser::Error> { |
1394 | self.ser.end().map(op:Value::Table) |
1395 | } |
1396 | } |
1397 | |
1398 | impl ser::SerializeStruct for ValueSerializeMap { |
1399 | type Ok = Value; |
1400 | type Error = crate::ser::Error; |
1401 | |
1402 | fn serialize_field<T: ?Sized>( |
1403 | &mut self, |
1404 | key: &'static str, |
1405 | value: &T, |
1406 | ) -> Result<(), crate::ser::Error> |
1407 | where |
1408 | T: ser::Serialize, |
1409 | { |
1410 | ser::SerializeMap::serialize_key(self, key)?; |
1411 | ser::SerializeMap::serialize_value(self, value) |
1412 | } |
1413 | |
1414 | fn end(self) -> Result<Value, crate::ser::Error> { |
1415 | ser::SerializeMap::end(self) |
1416 | } |
1417 | } |
1418 | |
1419 | struct DatetimeOrTable<'a> { |
1420 | key: &'a mut String, |
1421 | } |
1422 | |
1423 | impl<'a, 'de> de::DeserializeSeed<'de> for DatetimeOrTable<'a> { |
1424 | type Value = bool; |
1425 | |
1426 | fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> |
1427 | where |
1428 | D: de::Deserializer<'de>, |
1429 | { |
1430 | deserializer.deserialize_any(self) |
1431 | } |
1432 | } |
1433 | |
1434 | impl<'a, 'de> de::Visitor<'de> for DatetimeOrTable<'a> { |
1435 | type Value = bool; |
1436 | |
1437 | fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { |
1438 | formatter.write_str("a string key" ) |
1439 | } |
1440 | |
1441 | fn visit_str<E>(self, s: &str) -> Result<bool, E> |
1442 | where |
1443 | E: de::Error, |
1444 | { |
1445 | if s == datetime::FIELD { |
1446 | Ok(true) |
1447 | } else { |
1448 | self.key.push_str(s); |
1449 | Ok(false) |
1450 | } |
1451 | } |
1452 | |
1453 | fn visit_string<E>(self, s: String) -> Result<bool, E> |
1454 | where |
1455 | E: de::Error, |
1456 | { |
1457 | if s == datetime::FIELD { |
1458 | Ok(true) |
1459 | } else { |
1460 | *self.key = s; |
1461 | Ok(false) |
1462 | } |
1463 | } |
1464 | } |
1465 | |
1466 | type ValueSerializeTupleVariant = ValueSerializeVariant<ValueSerializeVec>; |
1467 | type ValueSerializeStructVariant = ValueSerializeVariant<ValueSerializeMap>; |
1468 | |
1469 | struct ValueSerializeVariant<T> { |
1470 | variant: &'static str, |
1471 | inner: T, |
1472 | } |
1473 | |
1474 | impl ValueSerializeVariant<ValueSerializeVec> { |
1475 | pub(crate) fn tuple(variant: &'static str, len: usize) -> Self { |
1476 | Self { |
1477 | variant, |
1478 | inner: ValueSerializeVec { |
1479 | vec: Vec::with_capacity(len), |
1480 | }, |
1481 | } |
1482 | } |
1483 | } |
1484 | |
1485 | impl ValueSerializeVariant<ValueSerializeMap> { |
1486 | pub(crate) fn struct_(variant: &'static str, len: usize) -> Self { |
1487 | Self { |
1488 | variant, |
1489 | inner: ValueSerializeMap { |
1490 | ser: SerializeMap { |
1491 | map: Table::with_capacity(len), |
1492 | next_key: None, |
1493 | }, |
1494 | }, |
1495 | } |
1496 | } |
1497 | } |
1498 | |
1499 | impl serde::ser::SerializeTupleVariant for ValueSerializeVariant<ValueSerializeVec> { |
1500 | type Ok = crate::Value; |
1501 | type Error = crate::ser::Error; |
1502 | |
1503 | fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> |
1504 | where |
1505 | T: serde::ser::Serialize, |
1506 | { |
1507 | serde::ser::SerializeSeq::serialize_element(&mut self.inner, value) |
1508 | } |
1509 | |
1510 | fn end(self) -> Result<Self::Ok, Self::Error> { |
1511 | let inner: Value = serde::ser::SerializeSeq::end(self.inner)?; |
1512 | let mut table: Map = Table::new(); |
1513 | table.insert(self.variant.to_owned(), v:inner); |
1514 | Ok(Value::Table(table)) |
1515 | } |
1516 | } |
1517 | |
1518 | impl serde::ser::SerializeStructVariant for ValueSerializeVariant<ValueSerializeMap> { |
1519 | type Ok = crate::Value; |
1520 | type Error = crate::ser::Error; |
1521 | |
1522 | #[inline ] |
1523 | fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error> |
1524 | where |
1525 | T: serde::ser::Serialize + ?Sized, |
1526 | { |
1527 | serde::ser::SerializeStruct::serialize_field(&mut self.inner, key, value) |
1528 | } |
1529 | |
1530 | #[inline ] |
1531 | fn end(self) -> Result<Self::Ok, Self::Error> { |
1532 | let inner: Value = serde::ser::SerializeStruct::end(self.inner)?; |
1533 | let mut table: Map = Table::new(); |
1534 | table.insert(self.variant.to_owned(), v:inner); |
1535 | Ok(Value::Table(table)) |
1536 | } |
1537 | } |
1538 | |