serde_tagged/util/ser/
content.rs

1// This file is adapted from `serde`, specifically the module `content` in
2// https://github.com/serde-rs/serde/blob/v1.0.27/serde/src/private/ser.rs
3//
4// The original copyright notice:
5// > Copyright 2017 Serde Developers
6// >
7// > Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
8// > http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
9// > <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
10// > option. This file may not be copied, modified, or distributed
11// > except according to those terms.
12//
13// The mentioned license files for the original can be found at
14// https://github.com/serde-rs/serde/blob/v1.0.27/LICENSE-APACHE
15// https://github.com/serde-rs/serde/blob/v1.0.27/LICENSE-MIT
16//
17// The original MIT license file:
18// > Copyright (c) 2014 The Rust Project Developers
19// > 
20// > Permission is hereby granted, free of charge, to any
21// > person obtaining a copy of this software and associated
22// > documentation files (the "Software"), to deal in the
23// > Software without restriction, including without
24// > limitation the rights to use, copy, modify, merge,
25// > publish, distribute, sublicense, and/or sell copies of
26// > the Software, and to permit persons to whom the Software
27// > is furnished to do so, subject to the following
28// > conditions:
29// > 
30// > The above copyright notice and this permission notice
31// > shall be included in all copies or substantial portions
32// > of the Software.
33// > 
34// > THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
35// > ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
36// > TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
37// > PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
38// > SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
39// > CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
40// > OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
41// > IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
42// > DEALINGS IN THE SOFTWARE.
43// 
44// Changes made to the original module:
45// - re-formatted code using rustfmt (appearance, replaced try! with ?)
46// - changed import, absolute and relative paths for compatibility
47// - removed types and respecitve impls for:
48//   - `SerializeTupleVariantAsMapValue`
49//   - `SerializeStructVariantAsMapValue`
50// - changed visibility of types and constructor-functions to `pub`
51
52
53use std::marker::PhantomData;
54
55use serde::ser::{self, Serialize, Serializer};
56
57#[derive(Debug)]
58pub enum Content {
59    Bool(bool),
60
61    U8(u8),
62    U16(u16),
63    U32(u32),
64    U64(u64),
65
66    I8(i8),
67    I16(i16),
68    I32(i32),
69    I64(i64),
70
71    F32(f32),
72    F64(f64),
73
74    Char(char),
75    String(String),
76    Bytes(Vec<u8>),
77
78    None,
79    Some(Box<Content>),
80
81    Unit,
82    UnitStruct(&'static str),
83    UnitVariant(&'static str, u32, &'static str),
84    NewtypeStruct(&'static str, Box<Content>),
85    NewtypeVariant(&'static str, u32, &'static str, Box<Content>),
86
87    Seq(Vec<Content>),
88    Tuple(Vec<Content>),
89    TupleStruct(&'static str, Vec<Content>),
90    TupleVariant(&'static str, u32, &'static str, Vec<Content>),
91    Map(Vec<(Content, Content)>),
92    Struct(&'static str, Vec<(&'static str, Content)>),
93    StructVariant(
94        &'static str,
95        u32,
96        &'static str,
97        Vec<(&'static str, Content)>,
98    ),
99}
100
101impl Serialize for Content {
102    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
103    where
104        S: Serializer,
105    {
106        match *self {
107            Content::Bool(b) => serializer.serialize_bool(b),
108            Content::U8(u) => serializer.serialize_u8(u),
109            Content::U16(u) => serializer.serialize_u16(u),
110            Content::U32(u) => serializer.serialize_u32(u),
111            Content::U64(u) => serializer.serialize_u64(u),
112            Content::I8(i) => serializer.serialize_i8(i),
113            Content::I16(i) => serializer.serialize_i16(i),
114            Content::I32(i) => serializer.serialize_i32(i),
115            Content::I64(i) => serializer.serialize_i64(i),
116            Content::F32(f) => serializer.serialize_f32(f),
117            Content::F64(f) => serializer.serialize_f64(f),
118            Content::Char(c) => serializer.serialize_char(c),
119            Content::String(ref s) => serializer.serialize_str(s),
120            Content::Bytes(ref b) => serializer.serialize_bytes(b),
121            Content::None => serializer.serialize_none(),
122            Content::Some(ref c) => serializer.serialize_some(&**c),
123            Content::Unit => serializer.serialize_unit(),
124            Content::UnitStruct(n) => serializer.serialize_unit_struct(n),
125            Content::UnitVariant(n, i, v) => serializer.serialize_unit_variant(n, i, v),
126            Content::NewtypeStruct(n, ref c) => serializer.serialize_newtype_struct(n, &**c),
127            Content::NewtypeVariant(n, i, v, ref c) => {
128                serializer.serialize_newtype_variant(n, i, v, &**c)
129            },
130            Content::Seq(ref elements) => elements.serialize(serializer),
131            Content::Tuple(ref elements) => {
132                use serde::ser::SerializeTuple;
133                let mut tuple = serializer.serialize_tuple(elements.len())?;
134                for e in elements {
135                    tuple.serialize_element(e)?;
136                }
137                tuple.end()
138            },
139            Content::TupleStruct(n, ref fields) => {
140                use serde::ser::SerializeTupleStruct;
141                let mut ts = serializer.serialize_tuple_struct(n, fields.len())?;
142                for f in fields {
143                    ts.serialize_field(f)?;
144                }
145                ts.end()
146            },
147            Content::TupleVariant(n, i, v, ref fields) => {
148                use serde::ser::SerializeTupleVariant;
149                let mut tv = serializer.serialize_tuple_variant(n, i, v, fields.len())?;
150                for f in fields {
151                    tv.serialize_field(f)?;
152                }
153                tv.end()
154            },
155            Content::Map(ref entries) => {
156                use serde::ser::SerializeMap;
157                let mut map = serializer.serialize_map(Some(entries.len()))?;
158                for (k, v) in entries {
159                    map.serialize_entry(k, v)?;
160                }
161                map.end()
162            },
163            Content::Struct(n, ref fields) => {
164                use serde::ser::SerializeStruct;
165                let mut s = serializer.serialize_struct(n, fields.len())?;
166                for (k, v) in fields {
167                    s.serialize_field(k, v)?;
168                }
169                s.end()
170            },
171            Content::StructVariant(n, i, v, ref fields) => {
172                use serde::ser::SerializeStructVariant;
173                let mut sv = serializer.serialize_struct_variant(n, i, v, fields.len())?;
174                for (k, v) in fields {
175                    sv.serialize_field(k, v)?;
176                }
177                sv.end()
178            },
179        }
180    }
181}
182
183pub struct ContentSerializer<E> {
184    error: PhantomData<E>,
185}
186
187impl<E> ContentSerializer<E> {
188    pub fn new() -> Self {
189        ContentSerializer { error: PhantomData }
190    }
191}
192
193impl<E> Serializer for ContentSerializer<E>
194where
195    E: ser::Error,
196{
197    type Ok = Content;
198    type Error = E;
199
200    type SerializeSeq = SerializeSeq<E>;
201    type SerializeTuple = SerializeTuple<E>;
202    type SerializeTupleStruct = SerializeTupleStruct<E>;
203    type SerializeTupleVariant = SerializeTupleVariant<E>;
204    type SerializeMap = SerializeMap<E>;
205    type SerializeStruct = SerializeStruct<E>;
206    type SerializeStructVariant = SerializeStructVariant<E>;
207
208    fn serialize_bool(self, v: bool) -> Result<Content, E> {
209        Ok(Content::Bool(v))
210    }
211
212    fn serialize_i8(self, v: i8) -> Result<Content, E> {
213        Ok(Content::I8(v))
214    }
215
216    fn serialize_i16(self, v: i16) -> Result<Content, E> {
217        Ok(Content::I16(v))
218    }
219
220    fn serialize_i32(self, v: i32) -> Result<Content, E> {
221        Ok(Content::I32(v))
222    }
223
224    fn serialize_i64(self, v: i64) -> Result<Content, E> {
225        Ok(Content::I64(v))
226    }
227
228    fn serialize_u8(self, v: u8) -> Result<Content, E> {
229        Ok(Content::U8(v))
230    }
231
232    fn serialize_u16(self, v: u16) -> Result<Content, E> {
233        Ok(Content::U16(v))
234    }
235
236    fn serialize_u32(self, v: u32) -> Result<Content, E> {
237        Ok(Content::U32(v))
238    }
239
240    fn serialize_u64(self, v: u64) -> Result<Content, E> {
241        Ok(Content::U64(v))
242    }
243
244    fn serialize_f32(self, v: f32) -> Result<Content, E> {
245        Ok(Content::F32(v))
246    }
247
248    fn serialize_f64(self, v: f64) -> Result<Content, E> {
249        Ok(Content::F64(v))
250    }
251
252    fn serialize_char(self, v: char) -> Result<Content, E> {
253        Ok(Content::Char(v))
254    }
255
256    fn serialize_str(self, value: &str) -> Result<Content, E> {
257        Ok(Content::String(value.to_owned()))
258    }
259
260    fn serialize_bytes(self, value: &[u8]) -> Result<Content, E> {
261        Ok(Content::Bytes(value.to_owned()))
262    }
263
264    fn serialize_none(self) -> Result<Content, E> {
265        Ok(Content::None)
266    }
267
268    fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Content, E>
269    where
270        T: Serialize,
271    {
272        Ok(Content::Some(Box::new(value.serialize(self)?)))
273    }
274
275    fn serialize_unit(self) -> Result<Content, E> {
276        Ok(Content::Unit)
277    }
278
279    fn serialize_unit_struct(self, name: &'static str) -> Result<Content, E> {
280        Ok(Content::UnitStruct(name))
281    }
282
283    fn serialize_unit_variant(
284        self,
285        name: &'static str,
286        variant_index: u32,
287        variant: &'static str,
288    ) -> Result<Content, E> {
289        Ok(Content::UnitVariant(name, variant_index, variant))
290    }
291
292    fn serialize_newtype_struct<T: ?Sized>(
293        self,
294        name: &'static str,
295        value: &T,
296    ) -> Result<Content, E>
297    where
298        T: Serialize,
299    {
300        Ok(Content::NewtypeStruct(
301            name,
302            Box::new(value.serialize(self)?),
303        ))
304    }
305
306    fn serialize_newtype_variant<T: ?Sized>(
307        self,
308        name: &'static str,
309        variant_index: u32,
310        variant: &'static str,
311        value: &T,
312    ) -> Result<Content, E>
313    where
314        T: Serialize,
315    {
316        Ok(Content::NewtypeVariant(
317            name,
318            variant_index,
319            variant,
320            Box::new(value.serialize(self)?),
321        ))
322    }
323
324    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, E> {
325        Ok(SerializeSeq {
326            elements: Vec::with_capacity(len.unwrap_or(0)),
327            error:    PhantomData,
328        })
329    }
330
331    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, E> {
332        Ok(SerializeTuple {
333            elements: Vec::with_capacity(len),
334            error:    PhantomData,
335        })
336    }
337
338    fn serialize_tuple_struct(
339        self,
340        name: &'static str,
341        len: usize,
342    ) -> Result<Self::SerializeTupleStruct, E> {
343        Ok(SerializeTupleStruct {
344            name:   name,
345            fields: Vec::with_capacity(len),
346            error:  PhantomData,
347        })
348    }
349
350    fn serialize_tuple_variant(
351        self,
352        name: &'static str,
353        variant_index: u32,
354        variant: &'static str,
355        len: usize,
356    ) -> Result<Self::SerializeTupleVariant, E> {
357        Ok(SerializeTupleVariant {
358            name:          name,
359            variant_index: variant_index,
360            variant:       variant,
361            fields:        Vec::with_capacity(len),
362            error:         PhantomData,
363        })
364    }
365
366    fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, E> {
367        Ok(SerializeMap {
368            entries: Vec::with_capacity(len.unwrap_or(0)),
369            key:     None,
370            error:   PhantomData,
371        })
372    }
373
374    fn serialize_struct(self, name: &'static str, len: usize) -> Result<Self::SerializeStruct, E> {
375        Ok(SerializeStruct {
376            name:   name,
377            fields: Vec::with_capacity(len),
378            error:  PhantomData,
379        })
380    }
381
382    fn serialize_struct_variant(
383        self,
384        name: &'static str,
385        variant_index: u32,
386        variant: &'static str,
387        len: usize,
388    ) -> Result<Self::SerializeStructVariant, E> {
389        Ok(SerializeStructVariant {
390            name:          name,
391            variant_index: variant_index,
392            variant:       variant,
393            fields:        Vec::with_capacity(len),
394            error:         PhantomData,
395        })
396    }
397}
398
399pub struct SerializeSeq<E> {
400    elements: Vec<Content>,
401    error:    PhantomData<E>,
402}
403
404impl<E> ser::SerializeSeq for SerializeSeq<E>
405where
406    E: ser::Error,
407{
408    type Ok = Content;
409    type Error = E;
410
411    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), E>
412    where
413        T: Serialize,
414    {
415        let value = value.serialize(ContentSerializer::<E>::new())?;
416        self.elements.push(value);
417        Ok(())
418    }
419
420    fn end(self) -> Result<Content, E> {
421        Ok(Content::Seq(self.elements))
422    }
423}
424
425pub struct SerializeTuple<E> {
426    elements: Vec<Content>,
427    error:    PhantomData<E>,
428}
429
430impl<E> ser::SerializeTuple for SerializeTuple<E>
431where
432    E: ser::Error,
433{
434    type Ok = Content;
435    type Error = E;
436
437    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), E>
438    where
439        T: Serialize,
440    {
441        let value = value.serialize(ContentSerializer::<E>::new())?;
442        self.elements.push(value);
443        Ok(())
444    }
445
446    fn end(self) -> Result<Content, E> {
447        Ok(Content::Tuple(self.elements))
448    }
449}
450
451pub struct SerializeTupleStruct<E> {
452    name:   &'static str,
453    fields: Vec<Content>,
454    error:  PhantomData<E>,
455}
456
457impl<E> ser::SerializeTupleStruct for SerializeTupleStruct<E>
458where
459    E: ser::Error,
460{
461    type Ok = Content;
462    type Error = E;
463
464    fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), E>
465    where
466        T: Serialize,
467    {
468        let value = value.serialize(ContentSerializer::<E>::new())?;
469        self.fields.push(value);
470        Ok(())
471    }
472
473    fn end(self) -> Result<Content, E> {
474        Ok(Content::TupleStruct(self.name, self.fields))
475    }
476}
477
478pub struct SerializeTupleVariant<E> {
479    name:          &'static str,
480    variant_index: u32,
481    variant:       &'static str,
482    fields:        Vec<Content>,
483    error:         PhantomData<E>,
484}
485
486impl<E> ser::SerializeTupleVariant for SerializeTupleVariant<E>
487where
488    E: ser::Error,
489{
490    type Ok = Content;
491    type Error = E;
492
493    fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), E>
494    where
495        T: Serialize,
496    {
497        let value = value.serialize(ContentSerializer::<E>::new())?;
498        self.fields.push(value);
499        Ok(())
500    }
501
502    fn end(self) -> Result<Content, E> {
503        Ok(Content::TupleVariant(
504            self.name,
505            self.variant_index,
506            self.variant,
507            self.fields,
508        ))
509    }
510}
511
512pub struct SerializeMap<E> {
513    entries: Vec<(Content, Content)>,
514    key:     Option<Content>,
515    error:   PhantomData<E>,
516}
517
518impl<E> ser::SerializeMap for SerializeMap<E>
519where
520    E: ser::Error,
521{
522    type Ok = Content;
523    type Error = E;
524
525    fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), E>
526    where
527        T: Serialize,
528    {
529        let key = key.serialize(ContentSerializer::<E>::new())?;
530        self.key = Some(key);
531        Ok(())
532    }
533
534    fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), E>
535    where
536        T: Serialize,
537    {
538        let key = self.key
539            .take()
540            .expect("serialize_value called before serialize_key");
541        let value = value.serialize(ContentSerializer::<E>::new())?;
542        self.entries.push((key, value));
543        Ok(())
544    }
545
546    fn end(self) -> Result<Content, E> {
547        Ok(Content::Map(self.entries))
548    }
549
550    fn serialize_entry<K: ?Sized, V: ?Sized>(&mut self, key: &K, value: &V) -> Result<(), E>
551    where
552        K: Serialize,
553        V: Serialize,
554    {
555        let key = key.serialize(ContentSerializer::<E>::new())?;
556        let value = value.serialize(ContentSerializer::<E>::new())?;
557        self.entries.push((key, value));
558        Ok(())
559    }
560}
561
562pub struct SerializeStruct<E> {
563    name:   &'static str,
564    fields: Vec<(&'static str, Content)>,
565    error:  PhantomData<E>,
566}
567
568impl<E> ser::SerializeStruct for SerializeStruct<E>
569where
570    E: ser::Error,
571{
572    type Ok = Content;
573    type Error = E;
574
575    fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), E>
576    where
577        T: Serialize,
578    {
579        let value = value.serialize(ContentSerializer::<E>::new())?;
580        self.fields.push((key, value));
581        Ok(())
582    }
583
584    fn end(self) -> Result<Content, E> {
585        Ok(Content::Struct(self.name, self.fields))
586    }
587}
588
589pub struct SerializeStructVariant<E> {
590    name:          &'static str,
591    variant_index: u32,
592    variant:       &'static str,
593    fields:        Vec<(&'static str, Content)>,
594    error:         PhantomData<E>,
595}
596
597impl<E> ser::SerializeStructVariant for SerializeStructVariant<E>
598where
599    E: ser::Error,
600{
601    type Ok = Content;
602    type Error = E;
603
604    fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), E>
605    where
606        T: Serialize,
607    {
608        let value = value.serialize(ContentSerializer::<E>::new())?;
609        self.fields.push((key, value));
610        Ok(())
611    }
612
613    fn end(self) -> Result<Content, E> {
614        Ok(Content::StructVariant(
615            self.name,
616            self.variant_index,
617            self.variant,
618            self.fields,
619        ))
620    }
621}