This repository has been archived by the owner on Sep 24, 2022. It is now read-only.
/
de.rs
2293 lines (2086 loc) · 73.9 KB
/
de.rs
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Deserializing TOML into Rust structures.
//!
//! This module contains all the Serde support for deserializing TOML documents
//! into Rust structures. Note that some top-level functions here are also
//! provided at the top of the crate.
use std::borrow::Cow;
use std::collections::HashMap;
use std::error;
use std::f64;
use std::fmt;
use std::iter;
use std::marker::PhantomData;
use std::mem::discriminant;
use std::str;
use std::vec;
use serde::de;
use serde::de::value::BorrowedStrDeserializer;
use serde::de::IntoDeserializer;
use crate::datetime;
use crate::spanned;
use crate::tokens::{Error as TokenError, Span, Token, Tokenizer};
/// Type Alias for a TOML Table pair
type TablePair<'a> = ((Span, Cow<'a, str>), Value<'a>);
/// Deserializes a byte slice into a type.
///
/// This function will attempt to interpret `bytes` as UTF-8 data and then
/// deserialize `T` from the TOML document provided.
pub fn from_slice<'de, T>(bytes: &'de [u8]) -> Result<T, Error>
where
T: de::Deserialize<'de>,
{
match str::from_utf8(bytes) {
Ok(s) => from_str(s),
Err(e) => Err(Error::custom(None, e.to_string())),
}
}
/// Deserializes a string into a type.
///
/// This function will attempt to interpret `s` as a TOML document and
/// deserialize `T` from the document.
///
/// # Examples
///
/// ```
/// use serde_derive::Deserialize;
///
/// #[derive(Deserialize)]
/// struct Config {
/// title: String,
/// owner: Owner,
/// }
///
/// #[derive(Deserialize)]
/// struct Owner {
/// name: String,
/// }
///
/// fn main() {
/// let config: Config = toml::from_str(r#"
/// title = 'TOML Example'
///
/// [owner]
/// name = 'Lisa'
/// "#).unwrap();
///
/// assert_eq!(config.title, "TOML Example");
/// assert_eq!(config.owner.name, "Lisa");
/// }
/// ```
pub fn from_str<'de, T>(s: &'de str) -> Result<T, Error>
where
T: de::Deserialize<'de>,
{
let mut d = Deserializer::new(s);
let ret = T::deserialize(&mut d)?;
d.end()?;
Ok(ret)
}
/// Errors that can occur when deserializing a type.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Error {
inner: Box<ErrorInner>,
}
#[derive(Debug, PartialEq, Eq, Clone)]
struct ErrorInner {
kind: ErrorKind,
line: Option<usize>,
col: usize,
at: Option<usize>,
message: String,
key: Vec<String>,
}
/// Errors that can occur when deserializing a type.
#[derive(Debug, PartialEq, Eq, Clone)]
enum ErrorKind {
/// EOF was reached when looking for a value
UnexpectedEof,
/// An invalid character not allowed in a string was found
InvalidCharInString(char),
/// An invalid character was found as an escape
InvalidEscape(char),
/// An invalid character was found in a hex escape
InvalidHexEscape(char),
/// An invalid escape value was specified in a hex escape in a string.
///
/// Valid values are in the plane of unicode codepoints.
InvalidEscapeValue(u32),
/// A newline in a string was encountered when one was not allowed.
NewlineInString,
/// An unexpected character was encountered, typically when looking for a
/// value.
Unexpected(char),
/// An unterminated string was found where EOF was found before the ending
/// EOF mark.
UnterminatedString,
/// A newline was found in a table key.
NewlineInTableKey,
/// A number failed to parse
NumberInvalid,
/// A date or datetime was invalid
DateInvalid,
/// Wanted one sort of token, but found another.
Wanted {
/// Expected token type
expected: &'static str,
/// Actually found token type
found: &'static str,
},
/// An array was decoded but the types inside of it were mixed, which is
/// disallowed by TOML.
MixedArrayType,
/// A duplicate table definition was found.
DuplicateTable(String),
/// A previously defined table was redefined as an array.
RedefineAsArray,
/// An empty table key was found.
EmptyTableKey,
/// Multiline strings are not allowed for key
MultilineStringKey,
/// A custom error which could be generated when deserializing a particular
/// type.
Custom,
/// A tuple with a certain number of elements was expected but something
/// else was found.
ExpectedTuple(usize),
/// Expected table keys to be in increasing tuple index order, but something
/// else was found.
ExpectedTupleIndex {
/// Expected index.
expected: usize,
/// Key that was specified.
found: String,
},
/// An empty table was expected but entries were found
ExpectedEmptyTable,
/// Dotted key attempted to extend something that is not a table.
DottedKeyInvalidType,
/// An unexpected key was encountered.
///
/// Used when deserializing a struct with a limited set of fields.
UnexpectedKeys {
/// The unexpected keys.
keys: Vec<String>,
/// Keys that may be specified.
available: &'static [&'static str],
},
#[doc(hidden)]
__Nonexhaustive,
}
/// Deserialization implementation for TOML.
pub struct Deserializer<'a> {
require_newline_after_table: bool,
allow_duplciate_after_longer_table: bool,
input: &'a str,
tokens: Tokenizer<'a>,
}
impl<'de, 'b> de::Deserializer<'de> for &'b mut Deserializer<'de> {
type Error = Error;
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error>
where
V: de::Visitor<'de>,
{
let mut tables = self.tables()?;
let table_indices = build_table_indices(&tables);
let table_pindices = build_table_pindices(&tables);
let res = visitor.visit_map(MapVisitor {
values: Vec::new().into_iter().peekable(),
next_value: None,
depth: 0,
cur: 0,
cur_parent: 0,
max: tables.len(),
table_indices: &table_indices,
table_pindices: &table_pindices,
tables: &mut tables,
array: false,
de: self,
});
res.map_err(|mut err| {
// Errors originating from this library (toml), have an offset
// attached to them already. Other errors, like those originating
// from serde (like "missing field") or from a custom deserializer,
// do not have offsets on them. Here, we do a best guess at their
// location, by attributing them to the "current table" (the last
// item in `tables`).
err.fix_offset(|| tables.last().map(|table| table.at));
err.fix_linecol(|at| self.to_linecol(at));
err
})
}
// Called when the type to deserialize is an enum, as opposed to a field in the type.
fn deserialize_enum<V>(
self,
_name: &'static str,
_variants: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Error>
where
V: de::Visitor<'de>,
{
let (value, name) = self.string_or_table()?;
match value.e {
E::String(val) => visitor.visit_enum(val.into_deserializer()),
E::InlineTable(values) => {
if values.len() != 1 {
Err(Error::from_kind(
Some(value.start),
ErrorKind::Wanted {
expected: "exactly 1 element",
found: if values.is_empty() {
"zero elements"
} else {
"more than 1 element"
},
},
))
} else {
visitor.visit_enum(InlineTableDeserializer {
values: values.into_iter(),
next_value: None,
})
}
}
E::DottedTable(_) => visitor.visit_enum(DottedTableDeserializer {
name: name.expect("Expected table header to be passed."),
value,
}),
e => Err(Error::from_kind(
Some(value.start),
ErrorKind::Wanted {
expected: "string or table",
found: e.type_name(),
},
)),
}
}
fn deserialize_struct<V>(
self,
name: &'static str,
fields: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Error>
where
V: de::Visitor<'de>,
{
if name == spanned::NAME && fields == [spanned::START, spanned::END, spanned::VALUE] {
let start = 0;
let end = self.input.len();
let res = visitor.visit_map(SpannedDeserializer {
phantom_data: PhantomData,
start: Some(start),
value: Some(self),
end: Some(end),
});
return res;
}
self.deserialize_any(visitor)
}
serde::forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string seq
bytes byte_buf map unit newtype_struct
ignored_any unit_struct tuple_struct tuple option identifier
}
}
// Builds a datastructure that allows for efficient sublinear lookups.
// The returned HashMap contains a mapping from table header (like [a.b.c])
// to list of tables with that precise name. The tables are being identified
// by their index in the passed slice. We use a list as the implementation
// uses this data structure for arrays as well as tables,
// so if any top level [[name]] array contains multiple entries,
// there are multiple entires in the list.
// The lookup is performed in the `SeqAccess` implementation of `MapVisitor`.
// The lists are ordered, which we exploit in the search code by using
// bisection.
fn build_table_indices<'de>(tables: &[Table<'de>]) -> HashMap<Vec<Cow<'de, str>>, Vec<usize>> {
let mut res = HashMap::new();
for (i, table) in tables.iter().enumerate() {
let header = table.header.iter().map(|v| v.1.clone()).collect::<Vec<_>>();
res.entry(header).or_insert(Vec::new()).push(i);
}
res
}
// Builds a datastructure that allows for efficient sublinear lookups.
// The returned HashMap contains a mapping from table header (like [a.b.c])
// to list of tables whose name at least starts with the specified
// name. So searching for [a.b] would give both [a.b.c.d] as well as [a.b.e].
// The tables are being identified by their index in the passed slice.
//
// A list is used for two reasons: First, the implementation also
// stores arrays in the same data structure and any top level array
// of size 2 or greater creates multiple entries in the list with the
// same shared name. Second, there can be multiple tables sharing
// the same prefix.
//
// The lookup is performed in the `MapAccess` implementation of `MapVisitor`.
// The lists are ordered, which we exploit in the search code by using
// bisection.
fn build_table_pindices<'de>(tables: &[Table<'de>]) -> HashMap<Vec<Cow<'de, str>>, Vec<usize>> {
let mut res = HashMap::new();
for (i, table) in tables.iter().enumerate() {
let header = table.header.iter().map(|v| v.1.clone()).collect::<Vec<_>>();
for len in 0..=header.len() {
res.entry(header[..len].to_owned())
.or_insert(Vec::new())
.push(i);
}
}
res
}
fn headers_equal<'a, 'b>(hdr_a: &[(Span, Cow<'a, str>)], hdr_b: &[(Span, Cow<'b, str>)]) -> bool {
if hdr_a.len() != hdr_b.len() {
return false;
}
hdr_a.iter().zip(hdr_b.iter()).all(|(h1, h2)| h1.1 == h2.1)
}
struct Table<'a> {
at: usize,
header: Vec<(Span, Cow<'a, str>)>,
values: Option<Vec<TablePair<'a>>>,
array: bool,
}
struct MapVisitor<'de, 'b> {
values: iter::Peekable<vec::IntoIter<TablePair<'de>>>,
next_value: Option<TablePair<'de>>,
depth: usize,
cur: usize,
cur_parent: usize,
max: usize,
table_indices: &'b HashMap<Vec<Cow<'de, str>>, Vec<usize>>,
table_pindices: &'b HashMap<Vec<Cow<'de, str>>, Vec<usize>>,
tables: &'b mut [Table<'de>],
array: bool,
de: &'b mut Deserializer<'de>,
}
impl<'de, 'b> de::MapAccess<'de> for MapVisitor<'de, 'b> {
type Error = Error;
fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error>
where
K: de::DeserializeSeed<'de>,
{
if self.cur_parent == self.max || self.cur == self.max {
return Ok(None);
}
loop {
assert!(self.next_value.is_none());
if let Some((key, value)) = self.values.next() {
let ret = seed.deserialize(StrDeserializer::spanned(key.clone()))?;
self.next_value = Some((key, value));
return Ok(Some(ret));
}
let next_table = {
let prefix_stripped = self.tables[self.cur_parent].header[..self.depth]
.iter()
.map(|v| v.1.clone())
.collect::<Vec<_>>();
self.table_pindices
.get(&prefix_stripped)
.and_then(|entries| {
let start = entries.binary_search(&self.cur).unwrap_or_else(|v| v);
if start == entries.len() || entries[start] < self.cur {
return None;
}
entries[start..]
.iter()
.copied()
.filter(|i| *i < self.max)
.map(|i| (i, &self.tables[i]))
.find(|(_, table)| table.values.is_some())
.map(|p| p.0)
})
};
let pos = match next_table {
Some(pos) => pos,
None => return Ok(None),
};
self.cur = pos;
// Test to see if we're duplicating our parent's table, and if so
// then this is an error in the toml format
if self.cur_parent != pos {
if headers_equal(
&self.tables[self.cur_parent].header,
&self.tables[pos].header,
) {
let at = self.tables[pos].at;
let name = self.tables[pos]
.header
.iter()
.map(|k| k.1.to_owned())
.collect::<Vec<_>>()
.join(".");
return Err(self.de.error(at, ErrorKind::DuplicateTable(name)));
}
// If we're here we know we should share the same prefix, and if
// the longer table was defined first then we want to narrow
// down our parent's length if possible to ensure that we catch
// duplicate tables defined afterwards.
if !self.de.allow_duplciate_after_longer_table {
let parent_len = self.tables[self.cur_parent].header.len();
let cur_len = self.tables[pos].header.len();
if cur_len < parent_len {
self.cur_parent = pos;
}
}
}
let table = &mut self.tables[pos];
// If we're not yet at the appropriate depth for this table then we
// just next the next portion of its header and then continue
// decoding.
if self.depth != table.header.len() {
let key = &table.header[self.depth];
let key = seed.deserialize(StrDeserializer::spanned(key.clone()))?;
return Ok(Some(key));
}
// Rule out cases like:
//
// [[foo.bar]]
// [[foo]]
if table.array {
let kind = ErrorKind::RedefineAsArray;
return Err(self.de.error(table.at, kind));
}
self.values = table
.values
.take()
.expect("Unable to read table values")
.into_iter()
.peekable();
}
}
fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error>
where
V: de::DeserializeSeed<'de>,
{
if let Some((k, v)) = self.next_value.take() {
match seed.deserialize(ValueDeserializer::new(v)) {
Ok(v) => return Ok(v),
Err(mut e) => {
e.add_key_context(&k.1);
return Err(e);
}
}
}
let array =
self.tables[self.cur].array && self.depth == self.tables[self.cur].header.len() - 1;
self.cur += 1;
let res = seed.deserialize(MapVisitor {
values: Vec::new().into_iter().peekable(),
next_value: None,
depth: self.depth + if array { 0 } else { 1 },
cur_parent: self.cur - 1,
cur: 0,
max: self.max,
array,
table_indices: &*self.table_indices,
table_pindices: &*self.table_pindices,
tables: &mut *self.tables,
de: &mut *self.de,
});
res.map_err(|mut e| {
e.add_key_context(&self.tables[self.cur - 1].header[self.depth].1);
e
})
}
}
impl<'de, 'b> de::SeqAccess<'de> for MapVisitor<'de, 'b> {
type Error = Error;
fn next_element_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error>
where
K: de::DeserializeSeed<'de>,
{
assert!(self.next_value.is_none());
assert!(self.values.next().is_none());
if self.cur_parent == self.max {
return Ok(None);
}
let header_stripped = self.tables[self.cur_parent]
.header
.iter()
.map(|v| v.1.clone())
.collect::<Vec<_>>();
let start_idx = self.cur_parent + 1;
let next = self
.table_indices
.get(&header_stripped)
.and_then(|entries| {
let start = entries.binary_search(&start_idx).unwrap_or_else(|v| v);
if start == entries.len() || entries[start] < start_idx {
return None;
}
entries[start..]
.iter()
.copied()
.filter(|i| *i < self.max)
.map(|i| (i, &self.tables[i]))
.find(|(_, table)| table.array)
.map(|p| p.0)
})
.unwrap_or(self.max);
let ret = seed.deserialize(MapVisitor {
values: self.tables[self.cur_parent]
.values
.take()
.expect("Unable to read table values")
.into_iter()
.peekable(),
next_value: None,
depth: self.depth + 1,
cur_parent: self.cur_parent,
max: next,
cur: 0,
array: false,
table_indices: &*self.table_indices,
table_pindices: &*self.table_pindices,
tables: &mut self.tables,
de: &mut self.de,
})?;
self.cur_parent = next;
Ok(Some(ret))
}
}
impl<'de, 'b> de::Deserializer<'de> for MapVisitor<'de, 'b> {
type Error = Error;
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error>
where
V: de::Visitor<'de>,
{
if self.array {
visitor.visit_seq(self)
} else {
visitor.visit_map(self)
}
}
// `None` is interpreted as a missing field so be sure to implement `Some`
// as a present field.
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error>
where
V: de::Visitor<'de>,
{
visitor.visit_some(self)
}
fn deserialize_newtype_struct<V>(
self,
_name: &'static str,
visitor: V,
) -> Result<V::Value, Error>
where
V: de::Visitor<'de>,
{
visitor.visit_newtype_struct(self)
}
fn deserialize_struct<V>(
mut self,
name: &'static str,
fields: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Error>
where
V: de::Visitor<'de>,
{
if name == spanned::NAME
&& fields == [spanned::START, spanned::END, spanned::VALUE]
&& !(self.array && !self.values.peek().is_none())
{
// TODO we can't actually emit spans here for the *entire* table/array
// due to the format that toml uses. Setting the start and end to 0 is
// *detectable* (and no reasonable span would look like that),
// it would be better to expose this in the API via proper
// ADTs like Option<T>.
let start = 0;
let end = 0;
let res = visitor.visit_map(SpannedDeserializer {
phantom_data: PhantomData,
start: Some(start),
value: Some(self),
end: Some(end),
});
return res;
}
self.deserialize_any(visitor)
}
fn deserialize_enum<V>(
self,
_name: &'static str,
_variants: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Error>
where
V: de::Visitor<'de>,
{
if self.tables.len() != 1 {
return Err(Error::custom(
Some(self.cur),
"enum table must contain exactly one table".into(),
));
}
let table = &mut self.tables[0];
let values = table.values.take().expect("table has no values?");
if table.header.len() == 0 {
return Err(self.de.error(self.cur, ErrorKind::EmptyTableKey));
}
let name = table.header[table.header.len() - 1].1.to_owned();
visitor.visit_enum(DottedTableDeserializer {
name,
value: Value {
e: E::DottedTable(values),
start: 0,
end: 0,
},
})
}
serde::forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string seq
bytes byte_buf map unit identifier
ignored_any unit_struct tuple_struct tuple
}
}
struct StrDeserializer<'a> {
span: Option<Span>,
key: Cow<'a, str>,
}
impl<'a> StrDeserializer<'a> {
fn spanned(inner: (Span, Cow<'a, str>)) -> StrDeserializer<'a> {
StrDeserializer {
span: Some(inner.0),
key: inner.1,
}
}
fn new(key: Cow<'a, str>) -> StrDeserializer<'a> {
StrDeserializer { span: None, key }
}
}
impl<'a, 'b> de::IntoDeserializer<'a, Error> for StrDeserializer<'a> {
type Deserializer = Self;
fn into_deserializer(self) -> Self::Deserializer {
self
}
}
impl<'de> de::Deserializer<'de> for StrDeserializer<'de> {
type Error = Error;
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error>
where
V: de::Visitor<'de>,
{
match self.key {
Cow::Borrowed(s) => visitor.visit_borrowed_str(s),
Cow::Owned(s) => visitor.visit_string(s),
}
}
fn deserialize_struct<V>(
self,
name: &'static str,
fields: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Error>
where
V: de::Visitor<'de>,
{
if name == spanned::NAME && fields == [spanned::START, spanned::END, spanned::VALUE] {
if let Some(span) = self.span {
return visitor.visit_map(SpannedDeserializer {
phantom_data: PhantomData,
start: Some(span.start),
value: Some(StrDeserializer::new(self.key)),
end: Some(span.end),
});
}
}
self.deserialize_any(visitor)
}
serde::forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string seq
bytes byte_buf map option unit newtype_struct
ignored_any unit_struct tuple_struct tuple enum identifier
}
}
struct ValueDeserializer<'a> {
value: Value<'a>,
validate_struct_keys: bool,
}
impl<'a> ValueDeserializer<'a> {
fn new(value: Value<'a>) -> ValueDeserializer<'a> {
ValueDeserializer {
value,
validate_struct_keys: false,
}
}
fn with_struct_key_validation(mut self) -> Self {
self.validate_struct_keys = true;
self
}
}
impl<'de> de::Deserializer<'de> for ValueDeserializer<'de> {
type Error = Error;
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error>
where
V: de::Visitor<'de>,
{
let start = self.value.start;
let res = match self.value.e {
E::Integer(i) => visitor.visit_i64(i),
E::Boolean(b) => visitor.visit_bool(b),
E::Float(f) => visitor.visit_f64(f),
E::String(Cow::Borrowed(s)) => visitor.visit_borrowed_str(s),
E::String(Cow::Owned(s)) => visitor.visit_string(s),
E::Datetime(s) => visitor.visit_map(DatetimeDeserializer {
date: s,
visited: false,
}),
E::Array(values) => {
let mut s = de::value::SeqDeserializer::new(values.into_iter());
let ret = visitor.visit_seq(&mut s)?;
s.end()?;
Ok(ret)
}
E::InlineTable(values) | E::DottedTable(values) => {
visitor.visit_map(InlineTableDeserializer {
values: values.into_iter(),
next_value: None,
})
}
};
res.map_err(|mut err| {
// Attribute the error to whatever value returned the error.
err.fix_offset(|| Some(start));
err
})
}
fn deserialize_struct<V>(
self,
name: &'static str,
fields: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Error>
where
V: de::Visitor<'de>,
{
if name == datetime::NAME && fields == [datetime::FIELD] {
if let E::Datetime(s) = self.value.e {
return visitor.visit_map(DatetimeDeserializer {
date: s,
visited: false,
});
}
}
if self.validate_struct_keys {
match self.value.e {
E::InlineTable(ref values) | E::DottedTable(ref values) => {
let extra_fields = values
.iter()
.filter_map(|key_value| {
let (ref key, ref _val) = *key_value;
if !fields.contains(&&*(key.1)) {
Some(key.clone())
} else {
None
}
})
.collect::<Vec<_>>();
if !extra_fields.is_empty() {
return Err(Error::from_kind(
Some(self.value.start),
ErrorKind::UnexpectedKeys {
keys: extra_fields
.iter()
.map(|k| k.1.to_string())
.collect::<Vec<_>>(),
available: fields,
},
));
}
}
_ => {}
}
}
if name == spanned::NAME && fields == [spanned::START, spanned::END, spanned::VALUE] {
let start = self.value.start;
let end = self.value.end;
return visitor.visit_map(SpannedDeserializer {
phantom_data: PhantomData,
start: Some(start),
value: Some(self.value),
end: Some(end),
});
}
self.deserialize_any(visitor)
}
// `None` is interpreted as a missing field so be sure to implement `Some`
// as a present field.
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error>
where
V: de::Visitor<'de>,
{
visitor.visit_some(self)
}
fn deserialize_enum<V>(
self,
_name: &'static str,
_variants: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Error>
where
V: de::Visitor<'de>,
{
match self.value.e {
E::String(val) => visitor.visit_enum(val.into_deserializer()),
E::InlineTable(values) => {
if values.len() != 1 {
Err(Error::from_kind(
Some(self.value.start),
ErrorKind::Wanted {
expected: "exactly 1 element",
found: if values.is_empty() {
"zero elements"
} else {
"more than 1 element"
},
},
))
} else {
visitor.visit_enum(InlineTableDeserializer {
values: values.into_iter(),
next_value: None,
})
}
}
e => Err(Error::from_kind(
Some(self.value.start),
ErrorKind::Wanted {
expected: "string or inline table",
found: e.type_name(),
},
)),
}
}
fn deserialize_newtype_struct<V>(
self,
_name: &'static str,
visitor: V,
) -> Result<V::Value, Error>
where
V: de::Visitor<'de>,
{
visitor.visit_newtype_struct(self)
}
serde::forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string seq
bytes byte_buf map unit identifier
ignored_any unit_struct tuple_struct tuple
}
}
impl<'de, 'b> de::IntoDeserializer<'de, Error> for MapVisitor<'de, 'b> {
type Deserializer = MapVisitor<'de, 'b>;
fn into_deserializer(self) -> Self::Deserializer {
self
}
}
impl<'de, 'b> de::IntoDeserializer<'de, Error> for &'b mut Deserializer<'de> {
type Deserializer = Self;
fn into_deserializer(self) -> Self::Deserializer {
self
}
}
impl<'de> de::IntoDeserializer<'de, Error> for Value<'de> {
type Deserializer = ValueDeserializer<'de>;
fn into_deserializer(self) -> Self::Deserializer {
ValueDeserializer::new(self)
}
}
struct SpannedDeserializer<'de, T: de::IntoDeserializer<'de, Error>> {
phantom_data: PhantomData<&'de ()>,
start: Option<usize>,
end: Option<usize>,
value: Option<T>,
}
impl<'de, T> de::MapAccess<'de> for SpannedDeserializer<'de, T>
where