serde_tagged/ser/
external.rs

1//! Serialization of externally tagged values.
2//!
3//! Tagging values externally will apply the tag via a mapping from tag to
4//! value, thus serializing a tagged value with the functionality provided in
5//! this module will always result in a map-object with a single entry.
6//!
7//! This format is similar to the externally-tagged enum format provided by
8//! serde, however allows for various tag types (not only `str` and `u32`).
9//!
10//! # Examples serializing to JSON
11//!
12//! ## A primitive
13//!
14//! Serializing a value
15//!
16//! ```
17//! # extern crate serde_json;
18//! # extern crate serde_tagged;
19//! #
20//! # fn main() {
21//! let foo: i32 = 42;
22//!
23//! let mut serializer = serde_json::Serializer::new(std::io::stdout());
24//! serde_tagged::ser::external::serialize(&mut serializer, "bar", &foo).unwrap();
25//! # }
26//! ```
27//!
28//! with a tag value of `"bar"` will produce
29//!
30//! ```json
31//! { "bar": 42 }
32//! ```
33//!
34//! ## A Simple struct
35//!
36//! Serializing a value `foo` with
37//!
38//! ```
39//! # #[macro_use]
40//! # extern crate serde_derive;
41//! # extern crate serde_json;
42//! # extern crate serde_tagged;
43//! #
44//! #[derive(Serialize)]
45//! struct Foo {
46//!     bar: &'static str,
47//! }
48//!
49//! # fn main() {
50//! let foo = Foo { bar: "baz" };
51//!
52//! let mut serializer = serde_json::Serializer::new(std::io::stdout());
53//! serde_tagged::ser::external::serialize(&mut serializer, "my-tag", &foo).unwrap();
54//! # }
55//! ```
56//!
57//! with a tag-value of `"my-tag"` will produce the following JSON output:
58//!
59//! ```json
60//! { "my-tag": { "bar": "baz" } }
61//! ```
62//!
63
64use std::fmt::Display;
65
66use serde;
67
68use ser::HasDelegate;
69use util::ser::content::{Content, ContentSerializer};
70use util::ser::forward;
71
72/// Applies a tag externally to the specified value and serializes them using
73/// the provided serializer.
74///
75/// The tag-value pair will be serialized as a map with one entry, where the tag
76/// will be the key. The specified serializer performs the actual serialization
77/// and thus controls the data format. For more information on this tag-format,
78/// see the [module documentation](::ser::external).
79///
80/// # Note
81///
82/// You should prefer this method to the [`Serializer`](Serializer).
83pub fn serialize<S, T: ?Sized, V: ?Sized>(
84    serializer: S,
85    tag: &T,
86    value: &V,
87) -> Result<S::Ok, S::Error>
88where
89    S: serde::Serializer,
90    T: serde::Serialize,
91    V: serde::Serialize,
92{
93    use serde::Serialize;
94
95    let tagged = Tagged { tag, value };
96    tagged.serialize(serializer)
97}
98
99struct Tagged<'a, V: ?Sized + 'a, T: ?Sized + 'a> {
100    tag:   &'a T,
101    value: &'a V,
102}
103
104impl<'a, V: ?Sized, T: ?Sized> serde::Serialize for Tagged<'a, V, T>
105where
106    T: serde::Serialize,
107    V: serde::Serialize,
108{
109    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
110    where
111        S: serde::Serializer,
112    {
113        use serde::ser::SerializeMap;
114
115        let mut state = serializer.serialize_map(Some(1))?;
116        state.serialize_entry(self.tag, self.value)?;
117        state.end()
118    }
119}
120
121
122/// A serializer that applies a tag externally to the provided value and
123/// serializes them as key-value pair.
124///
125/// The tag-value pair will be serialized as a map with one entry, where the tag
126/// will be the key. This serializer will simply call the appropriate functions
127/// on the underlying `Serializer` that is responsible for the data format. For
128/// more information on this tag-format, see the
129/// [module documentation](::ser::external).
130///
131/// # Warning
132///
133/// You should prefer the [`serialize`](serialize) function over this serializer
134/// implementation. To serialize key-value pairs, the serializer implementation
135/// may need to allocate memory on the heap. This can be avoided in the
136/// [`serialize`](serialize) function.
137pub struct Serializer<'a, S, T: ?Sized + 'a> {
138    delegate: S,
139    tag:      &'a T,
140}
141
142impl<'a, S, T: ?Sized> Serializer<'a, S, T>
143where
144    S: serde::Serializer,
145    T: serde::Serialize + 'a,
146{
147    /// Creates a new Serializer with the specified tag and underlying
148    /// serializer.
149    pub fn new(delegate: S, tag: &'a T) -> Self {
150        Serializer { delegate, tag }
151    }
152
153    fn serialize_as_map_value<V: ?Sized>(self, value: &V) -> Result<S::Ok, S::Error>
154    where
155        V: serde::Serialize,
156    {
157        use serde::ser::SerializeMap;
158
159        let mut state = self.delegate.serialize_map(Some(1))?;
160        state.serialize_entry(self.tag, value)?;
161        state.end()
162    }
163}
164
165impl<'a, S, T: ?Sized> HasDelegate for Serializer<'a, S, T>
166where
167    S: serde::Serializer,
168    T: serde::Serialize + 'a,
169{
170    type Ok = S::Ok;
171    type Error = S::Error;
172    type Delegate = S;
173
174    fn delegate(self) -> S {
175        self.delegate
176    }
177}
178
179impl<'a, S, T: ?Sized> serde::Serializer for Serializer<'a, S, T>
180where
181    S: serde::Serializer,
182    T: serde::Serialize + 'a,
183{
184    type Ok = S::Ok;
185    type Error = S::Error;
186
187    type SerializeSeq = SerializeSeqAsMapValue<S::SerializeMap>;
188    type SerializeTuple = SerializeTupleAsMapValue<S::SerializeMap>;
189    type SerializeTupleStruct = SerializeTupleStructAsMapValue<S::SerializeMap>;
190    type SerializeMap = SerializeMapAsMapValue<S::SerializeMap>;
191    type SerializeStruct = SerializeStructAsMapValue<S::SerializeMap>;
192    type SerializeTupleVariant = SerializeTupleVariantAsMapValue<S::SerializeMap>;
193    type SerializeStructVariant = SerializeStructVariantAsMapValue<S::SerializeMap>;
194
195    fn serialize_bool(self, value: bool) -> Result<Self::Ok, Self::Error> {
196        self.serialize_as_map_value(&value)
197    }
198
199    fn serialize_i8(self, value: i8) -> Result<Self::Ok, Self::Error> {
200        self.serialize_as_map_value(&value)
201    }
202
203    fn serialize_i16(self, value: i16) -> Result<Self::Ok, Self::Error> {
204        self.serialize_as_map_value(&value)
205    }
206
207    fn serialize_i32(self, value: i32) -> Result<Self::Ok, Self::Error> {
208        self.serialize_as_map_value(&value)
209    }
210
211    fn serialize_i64(self, value: i64) -> Result<Self::Ok, Self::Error> {
212        self.serialize_as_map_value(&value)
213    }
214
215    fn serialize_u8(self, value: u8) -> Result<Self::Ok, Self::Error> {
216        self.serialize_as_map_value(&value)
217    }
218
219    fn serialize_u16(self, value: u16) -> Result<Self::Ok, Self::Error> {
220        self.serialize_as_map_value(&value)
221    }
222
223    fn serialize_u32(self, value: u32) -> Result<Self::Ok, Self::Error> {
224        self.serialize_as_map_value(&value)
225    }
226
227    fn serialize_u64(self, value: u64) -> Result<Self::Ok, Self::Error> {
228        self.serialize_as_map_value(&value)
229    }
230
231    fn serialize_f32(self, value: f32) -> Result<Self::Ok, Self::Error> {
232        self.serialize_as_map_value(&value)
233    }
234
235    fn serialize_f64(self, value: f64) -> Result<Self::Ok, Self::Error> {
236        self.serialize_as_map_value(&value)
237    }
238
239    fn serialize_char(self, value: char) -> Result<Self::Ok, Self::Error> {
240        self.serialize_as_map_value(&value)
241    }
242
243    fn serialize_str(self, value: &str) -> Result<Self::Ok, Self::Error> {
244        self.serialize_as_map_value(value)
245    }
246
247    fn serialize_bytes(self, value: &[u8]) -> Result<Self::Ok, Self::Error> {
248        self.serialize_as_map_value(&forward::Bytes(value))
249    }
250
251    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
252        self.serialize_as_map_value(&forward::None)
253    }
254
255    fn serialize_some<V: ?Sized>(self, value: &V) -> Result<Self::Ok, Self::Error>
256    where
257        V: serde::Serialize,
258    {
259        self.serialize_as_map_value(&forward::Some(value))
260    }
261
262    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
263        self.serialize_as_map_value(&forward::Unit)
264    }
265
266    fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok, Self::Error> {
267        self.serialize_as_map_value(&forward::UnitStruct(name))
268    }
269
270    fn serialize_unit_variant(
271        self,
272        name: &'static str,
273        variant_index: u32,
274        variant: &'static str,
275    ) -> Result<Self::Ok, Self::Error> {
276        self.serialize_as_map_value(&forward::UnitVariant(name, variant_index, variant))
277    }
278
279    fn serialize_newtype_struct<V: ?Sized>(
280        self,
281        name: &'static str,
282        value: &V,
283    ) -> Result<Self::Ok, Self::Error>
284    where
285        V: serde::Serialize,
286    {
287        self.serialize_as_map_value(&forward::NewtypeStruct(name, value))
288    }
289
290    fn serialize_newtype_variant<V: ?Sized>(
291        self,
292        name: &'static str,
293        variant_index: u32,
294        variant: &'static str,
295        value: &V,
296    ) -> Result<Self::Ok, Self::Error>
297    where
298        V: serde::Serialize,
299    {
300        self.serialize_as_map_value(&forward::NewtypeVariant(
301            name,
302            variant_index,
303            variant,
304            value,
305        ))
306    }
307
308    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
309        use serde::ser::SerializeMap;
310
311        let mut state = self.delegate.serialize_map(Some(1))?;
312        state.serialize_key(self.tag)?;
313
314        Ok(SerializeSeqAsMapValue::new(state, len))
315    }
316
317    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
318        use serde::ser::SerializeMap;
319
320        let mut state = self.delegate.serialize_map(Some(1))?;
321        state.serialize_key(self.tag)?;
322
323        Ok(SerializeTupleAsMapValue::new(state, len))
324    }
325
326    fn serialize_tuple_struct(
327        self,
328        name: &'static str,
329        len: usize,
330    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
331        use serde::ser::SerializeMap;
332
333        let mut state = self.delegate.serialize_map(Some(1))?;
334        state.serialize_key(self.tag)?;
335
336        Ok(SerializeTupleStructAsMapValue::new(state, name, len))
337    }
338
339    fn serialize_tuple_variant(
340        self,
341        name: &'static str,
342        variant_index: u32,
343        variant: &'static str,
344        len: usize,
345    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
346        use serde::ser::SerializeMap;
347
348        let mut state = self.delegate.serialize_map(Some(1))?;
349        state.serialize_key(self.tag)?;
350
351        Ok(SerializeTupleVariantAsMapValue::new(
352            state,
353            name,
354            variant_index,
355            variant,
356            len,
357        ))
358    }
359
360    fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
361        use serde::ser::SerializeMap;
362
363        let mut state = self.delegate.serialize_map(Some(1))?;
364        state.serialize_key(self.tag)?;
365
366        Ok(SerializeMapAsMapValue::new(state, len))
367    }
368
369    fn serialize_struct(
370        self,
371        name: &'static str,
372        len: usize,
373    ) -> Result<Self::SerializeStruct, Self::Error> {
374        use serde::ser::SerializeMap;
375
376        let mut state = self.delegate.serialize_map(Some(1))?;
377        state.serialize_key(self.tag)?;
378
379        Ok(SerializeStructAsMapValue::new(state, name, len))
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, Self::Error> {
389        use serde::ser::SerializeMap;
390
391        let mut state = self.delegate.serialize_map(Some(1))?;
392        state.serialize_key(self.tag)?;
393
394        Ok(SerializeStructVariantAsMapValue::new(
395            state,
396            name,
397            variant_index,
398            variant,
399            len,
400        ))
401    }
402
403    fn collect_seq<I>(self, iter: I) -> Result<Self::Ok, Self::Error>
404    where
405        I: IntoIterator,
406        <I as IntoIterator>::Item: serde::Serialize,
407    {
408        self.serialize_as_map_value(&forward::CollectSeq::new(iter))
409    }
410
411    fn collect_map<K, V, I>(self, iter: I) -> Result<Self::Ok, Self::Error>
412    where
413        K: serde::Serialize,
414        V: serde::Serialize,
415        I: IntoIterator<Item = (K, V)>,
416    {
417        self.serialize_as_map_value(&forward::CollectMap::new(iter))
418    }
419
420    fn collect_str<V: ?Sized>(self, value: &V) -> Result<Self::Ok, Self::Error>
421    where
422        V: Display,
423    {
424        self.serialize_as_map_value(&forward::CollectStr(value))
425    }
426
427    fn is_human_readable(&self) -> bool {
428        self.delegate.is_human_readable()
429    }
430}
431
432
433/// Implementation of `SerializeSeq` to capture the sequence and then serialize
434/// it as map value.
435#[doc(hidden)]
436pub struct SerializeSeqAsMapValue<S> {
437    map:      S,
438    elements: Vec<Content>,
439}
440
441impl<S> SerializeSeqAsMapValue<S> {
442    fn new(map: S, len: Option<usize>) -> Self {
443        let elements = match len {
444            Some(len) => Vec::with_capacity(len),
445            None => Vec::new(),
446        };
447
448        SerializeSeqAsMapValue { map, elements }
449    }
450}
451
452impl<S> serde::ser::SerializeSeq for SerializeSeqAsMapValue<S>
453where
454    S: serde::ser::SerializeMap,
455{
456    type Ok = S::Ok;
457    type Error = S::Error;
458
459    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
460    where
461        T: serde::ser::Serialize,
462    {
463        let value = value.serialize(ContentSerializer::<S::Error>::new())?;
464        self.elements.push(value);
465        Ok(())
466    }
467
468    fn end(mut self) -> Result<Self::Ok, Self::Error> {
469        self.map.serialize_value(&Content::Seq(self.elements))?;
470        self.map.end()
471    }
472}
473
474
475/// Implementation of `SerializeTuple` to capture the tuple and then serialize
476/// it as map value.
477#[doc(hidden)]
478pub struct SerializeTupleAsMapValue<S> {
479    map:      S,
480    elements: Vec<Content>,
481}
482
483impl<S> SerializeTupleAsMapValue<S> {
484    fn new(map: S, len: usize) -> Self {
485        SerializeTupleAsMapValue {
486            map:      map,
487            elements: Vec::with_capacity(len),
488        }
489    }
490}
491
492impl<S> serde::ser::SerializeTuple for SerializeTupleAsMapValue<S>
493where
494    S: serde::ser::SerializeMap,
495{
496    type Ok = S::Ok;
497    type Error = S::Error;
498
499    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
500    where
501        T: serde::ser::Serialize,
502    {
503        let value = value.serialize(ContentSerializer::<S::Error>::new())?;
504        self.elements.push(value);
505        Ok(())
506    }
507
508    fn end(mut self) -> Result<Self::Ok, Self::Error> {
509        let value = Content::Tuple(self.elements);
510        self.map.serialize_value(&value)?;
511        self.map.end()
512    }
513}
514
515
516/// Implementation of `SerializeTupleStruct` to capture the tuple-struct and
517/// then serialize it as map value.
518#[doc(hidden)]
519pub struct SerializeTupleStructAsMapValue<S> {
520    map:      S,
521    name:     &'static str,
522    elements: Vec<Content>,
523}
524
525impl<S> SerializeTupleStructAsMapValue<S> {
526    fn new(map: S, name: &'static str, len: usize) -> Self {
527        SerializeTupleStructAsMapValue {
528            map:      map,
529            name:     name,
530            elements: Vec::with_capacity(len),
531        }
532    }
533}
534
535impl<S> serde::ser::SerializeTupleStruct for SerializeTupleStructAsMapValue<S>
536where
537    S: serde::ser::SerializeMap,
538{
539    type Ok = S::Ok;
540    type Error = S::Error;
541
542    fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
543    where
544        T: serde::ser::Serialize,
545    {
546        let value = value.serialize(ContentSerializer::<S::Error>::new())?;
547        self.elements.push(value);
548        Ok(())
549    }
550
551    fn end(mut self) -> Result<Self::Ok, Self::Error> {
552        let value = Content::TupleStruct(self.name, self.elements);
553        self.map.serialize_value(&value)?;
554        self.map.end()
555    }
556}
557
558
559/// Implementation of `SerializeTupleVariant` to capture the tuple-variant and
560/// then serialize it as map value.
561#[doc(hidden)]
562pub struct SerializeTupleVariantAsMapValue<S> {
563    map:           S,
564    name:          &'static str,
565    variant_index: u32,
566    variant:       &'static str,
567    elements:      Vec<Content>,
568}
569
570impl<S> SerializeTupleVariantAsMapValue<S> {
571    fn new(
572        map: S,
573        name: &'static str,
574        variant_index: u32,
575        variant: &'static str,
576        len: usize,
577    ) -> Self {
578        SerializeTupleVariantAsMapValue {
579            map:           map,
580            name:          name,
581            variant_index: variant_index,
582            variant:       variant,
583            elements:      Vec::with_capacity(len),
584        }
585    }
586}
587
588impl<S> serde::ser::SerializeTupleVariant for SerializeTupleVariantAsMapValue<S>
589where
590    S: serde::ser::SerializeMap,
591{
592    type Ok = S::Ok;
593    type Error = S::Error;
594
595    fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
596    where
597        T: serde::ser::Serialize,
598    {
599        let value = value.serialize(ContentSerializer::<S::Error>::new())?;
600        self.elements.push(value);
601        Ok(())
602    }
603
604    fn end(mut self) -> Result<Self::Ok, Self::Error> {
605        let value =
606            Content::TupleVariant(self.name, self.variant_index, self.variant, self.elements);
607
608        self.map.serialize_value(&value)?;
609        self.map.end()
610    }
611}
612
613
614/// Implementation of `SerializeMap` to capture the map and then serialize it as
615/// map value.
616#[doc(hidden)]
617pub struct SerializeMapAsMapValue<S> {
618    map:      S,
619    elements: Vec<(Content, Content)>,
620}
621
622impl<S> SerializeMapAsMapValue<S> {
623    fn new(map: S, len: Option<usize>) -> Self {
624        let elements = match len {
625            Some(len) => Vec::with_capacity(len),
626            None => Vec::new(),
627        };
628
629        SerializeMapAsMapValue { elements, map }
630    }
631}
632
633impl<S> serde::ser::SerializeMap for SerializeMapAsMapValue<S>
634where
635    S: serde::ser::SerializeMap,
636{
637    type Ok = S::Ok;
638    type Error = S::Error;
639
640    fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Self::Error>
641    where
642        T: serde::Serialize,
643    {
644        let key = key.serialize(ContentSerializer::<S::Error>::new())?;
645        self.elements.push((key, Content::None));
646        Ok(())
647    }
648
649    fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
650    where
651        T: serde::Serialize,
652    {
653        let value = value.serialize(ContentSerializer::<S::Error>::new())?;
654        self.elements.last_mut().unwrap().1 = value;
655        Ok(())
656    }
657
658    fn end(mut self) -> Result<Self::Ok, Self::Error> {
659        self.map.serialize_value(&Content::Map(self.elements))?;
660        self.map.end()
661    }
662}
663
664
665/// Implementation of `SerializeMap` to capture the struct and then serialize it
666/// as map value.
667#[doc(hidden)]
668pub struct SerializeStructAsMapValue<S> {
669    map:    S,
670    name:   &'static str,
671    fields: Vec<(&'static str, Content)>,
672}
673
674impl<S> SerializeStructAsMapValue<S> {
675    fn new(map: S, name: &'static str, len: usize) -> Self {
676        SerializeStructAsMapValue {
677            map:    map,
678            name:   name,
679            fields: Vec::with_capacity(len),
680        }
681    }
682}
683
684impl<S> serde::ser::SerializeStruct for SerializeStructAsMapValue<S>
685where
686    S: serde::ser::SerializeMap,
687{
688    type Ok = S::Ok;
689    type Error = S::Error;
690
691    fn serialize_field<T: ?Sized>(
692        &mut self,
693        name: &'static str,
694        value: &T,
695    ) -> Result<(), Self::Error>
696    where
697        T: serde::Serialize,
698    {
699        let value = value.serialize(ContentSerializer::<S::Error>::new())?;
700        self.fields.push((name, value));
701        Ok(())
702    }
703
704    fn end(mut self) -> Result<Self::Ok, Self::Error> {
705        let value = Content::Struct(self.name, self.fields);
706        self.map.serialize_value(&value)?;
707        self.map.end()
708    }
709}
710
711
712/// Implementation of `SerializeMap` to capture the struct-variant and then
713/// serialize it as map value.
714#[doc(hidden)]
715pub struct SerializeStructVariantAsMapValue<S> {
716    map:           S,
717    name:          &'static str,
718    variant_index: u32,
719    variant:       &'static str,
720    fields:        Vec<(&'static str, Content)>,
721}
722
723impl<S> SerializeStructVariantAsMapValue<S> {
724    fn new(
725        map: S,
726        name: &'static str,
727        variant_index: u32,
728        variant: &'static str,
729        len: usize,
730    ) -> Self {
731        SerializeStructVariantAsMapValue {
732            map:           map,
733            name:          name,
734            variant_index: variant_index,
735            variant:       variant,
736            fields:        Vec::with_capacity(len),
737        }
738    }
739}
740
741impl<S> serde::ser::SerializeStructVariant for SerializeStructVariantAsMapValue<S>
742where
743    S: serde::ser::SerializeMap,
744{
745    type Ok = S::Ok;
746    type Error = S::Error;
747
748    fn serialize_field<T: ?Sized>(
749        &mut self,
750        name: &'static str,
751        value: &T,
752    ) -> Result<(), Self::Error>
753    where
754        T: serde::Serialize,
755    {
756        let value = value.serialize(ContentSerializer::<S::Error>::new())?;
757        self.fields.push((name, value));
758        Ok(())
759    }
760
761    fn end(mut self) -> Result<Self::Ok, Self::Error> {
762        let value =
763            Content::StructVariant(self.name, self.variant_index, self.variant, self.fields);
764        self.map.serialize_value(&value)?;
765        self.map.end()
766    }
767}