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
//! Deserialization of internally tagged values.
//!
//! See [`ser::internal`](::ser::internal) for a description of this tagging
//! format.
//!
//! # Warning
//!
//! Deserialization of internally tagged values requires a self-describing
//! data format.

use de::seed::SeedFactory;
use util::de::content::{Content, ContentDeserializer, ContentVisitor};

use std;
use std::marker::PhantomData;

use serde;


/// Deserialize an internally tagged value.
///
/// The deserializer controls the underlying data format while the seed-factory
/// specifies the instructions (depending on the tag) on how the value should be
/// deserialized.
///
/// See [`de`](::de) for more information on
/// [`SeedFactory`](::de::SeedFactory) and implementations thereof.
///
/// See [`deserialize_seed`](deserialize_seed) for a version that allows you to
/// pass a `DeserializeSeed` to deserialize the tag. This version is equivalent
/// to `deserialize_seed(deserializer, tag_key, seed_factory, PhantomData<T>)`
pub fn deserialize<'de, T, D, F>(
    deserializer: D,
    tag_key: &'static str,
    seed_factory: F,
) -> Result<F::Value, D::Error>
where
    T: serde::Deserialize<'de>,
    D: serde::Deserializer<'de>,
    F: SeedFactory<'de, T>,
{
    deserialize_seed(deserializer, tag_key, seed_factory, PhantomData::<T>)
}


/// Deserialize an internally tagged value with the given tag-seed.
///
/// The deserializer controls the underlying data format while the seed-factory
/// specifies the instructions (depending on the tag) on how the value should be
/// deserialized.
///
/// See [`de`](::de) for more information on
/// [`SeedFactory`](::de::SeedFactory) and implementations thereof.
pub fn deserialize_seed<'de, D, F, S>(
    deserializer: D,
    tag_key: &'static str,
    seed_factory: F,
    tag_seed: S,
) -> Result<F::Value, D::Error>
where
    D: serde::Deserializer<'de>,
    F: SeedFactory<'de, S::Value>,
    S: serde::de::DeserializeSeed<'de>,
{
    deserializer.deserialize_any(Visitor::new(tag_key, seed_factory, tag_seed))
}


/// A visitor that can be used to deserialize an externally tagged value.
///
/// This visitor handles an externally tagged value, which is represented by a
/// map containing a single entry, where the key is the tag and the value is the
/// value that should be deserialized. Thus it will return an error if the
/// visited type is not a map.
///
/// The [`SeedFactory`](::de::SeedFactory) provided to this visitor
/// provides a `serde::de::DeserializeSeed` implementation depending on the tag,
/// which then determines how the value is going to be deserialized.
///
/// See [`de`](::de) for more information on
/// [`SeedFactory`](::de::SeedFactory) and implementations thereof.
pub struct Visitor<F, S> {
    seed_factory: F,
    tag_seed:     S,
    tag_key:      &'static str,
}

impl<F, S> Visitor<F, S> {
    /// Creates a new visitor with the given tag-key and
    /// [`SeedFactory`](::de::SeedFactory).
    pub fn new(tag_key: &'static str, seed_factory: F, tag_seed: S) -> Self {
        Visitor {
            seed_factory,
            tag_seed,
            tag_key,
        }
    }
}

impl<'de, F, S> serde::de::Visitor<'de> for Visitor<F, S>
where
    F: SeedFactory<'de, S::Value>,
    S: serde::de::DeserializeSeed<'de>,
{
    type Value = F::Value;

    fn expecting(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(fmt, "a tagged value")
    }

    fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
    where
        A: serde::de::SeqAccess<'de>,
    {
        use serde::de::DeserializeSeed;

        let (tag, val) = TaggedValueVisitor::new(self.tag_key).visit_seq(seq)?;

        self.seed_factory
            .seed(self.tag_seed.deserialize(ContentDeserializer::new(tag))?)?
            .deserialize(ContentDeserializer::new(val))
    }

    fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
    where
        A: serde::de::MapAccess<'de>,
    {
        use serde::de::DeserializeSeed;

        let (tag, val) = TaggedValueVisitor::new(self.tag_key).visit_map(map)?;

        self.seed_factory
            .seed(self.tag_seed.deserialize(ContentDeserializer::new(tag))?)?
            .deserialize(ContentDeserializer::new(val))
    }
}


struct TaggedValueVisitor {
    tag_key: &'static str,
}

impl TaggedValueVisitor {
    fn new(tag_key: &'static str) -> Self {
        TaggedValueVisitor { tag_key }
    }
}

impl<'de> serde::de::Visitor<'de> for TaggedValueVisitor {
    type Value = (Content<'de>, Content<'de>);

    fn expecting(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(fmt, "a tagged value")
    }

    fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
    where
        A: serde::de::SeqAccess<'de>,
    {
        use serde::de::value::SeqAccessDeserializer;
        use serde::de::{Deserialize, Error};

        let tag: Content = seq
            .next_element()?
            .ok_or_else(|| Error::missing_field(self.tag_key))?;

        let val = Content::deserialize(SeqAccessDeserializer::new(seq))?;

        Ok((tag, val))
    }

    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
    where
        A: serde::de::MapAccess<'de>,
    {
        use serde::de::Error;

        let mut tag = None;
        let mut val = Vec::with_capacity(map.size_hint().unwrap_or(128));

        while let Some(key) = map.next_key_seed(TagOrValueSeed::new(self.tag_key))? {
            match key {
                TagOrValue::Tag => {
                    if tag.is_some() {
                        return Err(Error::duplicate_field(self.tag_key));
                    }
                    tag = Some(map.next_value()?);
                },
                TagOrValue::Value(key) => {
                    val.push((key, map.next_value()?));
                },
            }
        }

        let tag = tag.ok_or_else(|| Error::missing_field(self.tag_key))?;

        Ok((tag, Content::Map(val)))
    }
}


enum TagOrValue<'de> {
    Tag,
    Value(Content<'de>),
}


struct TagOrValueSeed {
    tag_key: &'static str,
}

impl TagOrValueSeed {
    fn new(tag_key: &'static str) -> Self {
        TagOrValueSeed { tag_key }
    }
}

impl<'de> serde::de::DeserializeSeed<'de> for TagOrValueSeed {
    type Value = TagOrValue<'de>;

    fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
    where
        D: serde::de::Deserializer<'de>,
    {
        deserializer.deserialize_any(self)
    }
}

impl<'de> serde::de::Visitor<'de> for TagOrValueSeed {
    type Value = TagOrValue<'de>;

    fn expecting(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(fmt, "a tag `{}` or any other value", self.tag_key)
    }

    fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        ContentVisitor::new().visit_bool(v).map(TagOrValue::Value)
    }

    fn visit_i8<E>(self, v: i8) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        ContentVisitor::new().visit_i8(v).map(TagOrValue::Value)
    }

    fn visit_i16<E>(self, v: i16) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        ContentVisitor::new().visit_i16(v).map(TagOrValue::Value)
    }

    fn visit_i32<E>(self, v: i32) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        ContentVisitor::new().visit_i32(v).map(TagOrValue::Value)
    }

    fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        ContentVisitor::new().visit_i64(v).map(TagOrValue::Value)
    }

    fn visit_u8<E>(self, v: u8) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        ContentVisitor::new().visit_u8(v).map(TagOrValue::Value)
    }

    fn visit_u16<E>(self, v: u16) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        ContentVisitor::new().visit_u16(v).map(TagOrValue::Value)
    }

    fn visit_u32<E>(self, v: u32) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        ContentVisitor::new().visit_u32(v).map(TagOrValue::Value)
    }

    fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        ContentVisitor::new().visit_u64(v).map(TagOrValue::Value)
    }

    fn visit_f32<E>(self, v: f32) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        ContentVisitor::new().visit_f32(v).map(TagOrValue::Value)
    }

    fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        ContentVisitor::new().visit_f64(v).map(TagOrValue::Value)
    }

    fn visit_char<E>(self, v: char) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        ContentVisitor::new().visit_char(v).map(TagOrValue::Value)
    }

    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        if v == self.tag_key {
            Ok(TagOrValue::Tag)
        } else {
            ContentVisitor::new().visit_str(v).map(TagOrValue::Value)
        }
    }

    fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        if v == self.tag_key {
            Ok(TagOrValue::Tag)
        } else {
            ContentVisitor::new()
                .visit_borrowed_str(v)
                .map(TagOrValue::Value)
        }
    }

    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        if v == self.tag_key {
            Ok(TagOrValue::Tag)
        } else {
            ContentVisitor::new().visit_string(v).map(TagOrValue::Value)
        }
    }

    fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        if v == self.tag_key.as_bytes() {
            Ok(TagOrValue::Tag)
        } else {
            ContentVisitor::new().visit_bytes(v).map(TagOrValue::Value)
        }
    }

    fn visit_borrowed_bytes<E>(self, v: &'de [u8]) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        if v == self.tag_key.as_bytes() {
            Ok(TagOrValue::Tag)
        } else {
            ContentVisitor::new()
                .visit_borrowed_bytes(v)
                .map(TagOrValue::Value)
        }
    }

    fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        if v == self.tag_key.as_bytes() {
            Ok(TagOrValue::Tag)
        } else {
            ContentVisitor::new()
                .visit_byte_buf(v)
                .map(TagOrValue::Value)
        }
    }

    fn visit_none<E>(self) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        ContentVisitor::new().visit_none().map(TagOrValue::Value)
    }

    fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
    where
        D: serde::de::Deserializer<'de>,
    {
        ContentVisitor::new()
            .visit_some(deserializer)
            .map(TagOrValue::Value)
    }

    fn visit_unit<E>(self) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        ContentVisitor::new().visit_unit().map(TagOrValue::Value)
    }

    fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
    where
        D: serde::de::Deserializer<'de>,
    {
        ContentVisitor::new()
            .visit_newtype_struct(deserializer)
            .map(TagOrValue::Value)
    }

    fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
    where
        A: serde::de::SeqAccess<'de>,
    {
        ContentVisitor::new().visit_seq(seq).map(TagOrValue::Value)
    }

    fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
    where
        A: serde::de::MapAccess<'de>,
    {
        ContentVisitor::new().visit_map(map).map(TagOrValue::Value)
    }

    fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
    where
        A: serde::de::EnumAccess<'de>,
    {
        ContentVisitor::new()
            .visit_enum(data)
            .map(TagOrValue::Value)
    }
}