serde_tagged/ser/adj/
tuple.rs

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