rustc_serialize/
serialize.rs

1// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution and at
3// http://rust-lang.org/COPYRIGHT.
4//
5// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8// option. This file may not be copied, modified, or distributed
9// except according to those terms.
10
11//! Support code for encoding and decoding types.
12//!
13//! In order to allow extensibility in both what types can be encoded and how
14//! they are encoded, encoding and decoding are split into two part each. An
15//! implementation of the Encodable trait knows how to turn a specific type into
16//! a generic form, and then uses an implementation of the Encoder trait to turn
17//! this into concrete output (such as a JSON string). Decoder and Decodable do
18//! the same for decoding.
19
20/*
21Core encoding and decoding interfaces.
22*/
23
24use std::cell::{Cell, RefCell};
25use std::ffi::OsString;
26use std::path;
27use std::rc::Rc;
28use std::sync::Arc;
29use std::marker::PhantomData;
30use std::borrow::Cow;
31
32use cap_capacity;
33
34/// Trait for writing out an encoding when serializing.
35///
36/// This trait provides methods to encode basic types and generic forms of
37/// collections.  Implementations of `Encodable` use it to perform the actual
38/// encoding of a type.
39///
40/// It is unspecified what is done with the encoding - it could be stored in a
41/// variable, or written directly to a file, for example.
42///
43/// Encoders can expect to only have a single "root" method call made on this
44/// trait. Non-trivial types will call one of the collection-emitting methods,
45/// passing a function that may call other methods on the trait, but once the
46/// collection-emitting method has returned, encoding should be complete.
47pub trait Encoder {
48    /// The error type for method results.
49    type Error;
50
51    // Primitive types:
52    /// Emit a nil value.
53    ///
54    /// For example, this might be stored as the null keyword in JSON.
55    fn emit_nil(&mut self) -> Result<(), Self::Error>;
56
57    /// Emit a usize value.
58    fn emit_usize(&mut self, v: usize) -> Result<(), Self::Error>;
59
60    /// Emit a u64 value.
61    fn emit_u64(&mut self, v: u64) -> Result<(), Self::Error>;
62
63    /// Emit a u32 value.
64    fn emit_u32(&mut self, v: u32) -> Result<(), Self::Error>;
65
66    /// Emit a u16 value.
67    fn emit_u16(&mut self, v: u16) -> Result<(), Self::Error>;
68
69    /// Emit a u8 value.
70    fn emit_u8(&mut self, v: u8) -> Result<(), Self::Error>;
71
72    /// Emit a isize value.
73    fn emit_isize(&mut self, v: isize) -> Result<(), Self::Error>;
74
75    /// Emit a i64 value.
76    fn emit_i64(&mut self, v: i64) -> Result<(), Self::Error>;
77
78    /// Emit a i32 value.
79    fn emit_i32(&mut self, v: i32) -> Result<(), Self::Error>;
80
81    /// Emit a i16 value.
82    fn emit_i16(&mut self, v: i16) -> Result<(), Self::Error>;
83
84    /// Emit a i8 value.
85    fn emit_i8(&mut self, v: i8) -> Result<(), Self::Error>;
86
87    /// Emit a bool value.
88    ///
89    /// For example, this might be stored as the true and false keywords in
90    /// JSON.
91    fn emit_bool(&mut self, v: bool) -> Result<(), Self::Error>;
92
93    /// Emit a f64 value.
94    fn emit_f64(&mut self, v: f64) -> Result<(), Self::Error>;
95
96    /// Emit a f32 value.
97    fn emit_f32(&mut self, v: f32) -> Result<(), Self::Error>;
98
99    /// Emit a char value.
100    ///
101    /// Note that strings should be emitted using `emit_str`, not as a sequence
102    /// of `emit_char` calls.
103    fn emit_char(&mut self, v: char) -> Result<(), Self::Error>;
104
105    /// Emit a string value.
106    fn emit_str(&mut self, v: &str) -> Result<(), Self::Error>;
107
108    // Compound types:
109    /// Emit an enumeration value.
110    ///
111    /// * `name` indicates the enumeration type name.
112    /// * `f` is a function that will call `emit_enum_variant` or
113    ///   `emit_enum_struct_variant` as appropriate to write the actual value.
114    fn emit_enum<F>(&mut self, name: &str, f: F) -> Result<(), Self::Error>
115        where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
116
117    /// Emit a enumeration variant value with no or unnamed data.
118    ///
119    /// This should only be called from a function passed to `emit_enum`.
120    /// Variants with named data should use `emit_enum_struct_variant`.
121    ///
122    /// * `v_name` is the variant name
123    /// * `v_id` is the numeric identifier for the variant.
124    /// * `len` is the number of data items associated with the variant.
125    /// * `f` is a function that will call `emit_enum_variant_arg` for each data
126    ///   item. It may not be called if len is 0.
127    ///
128    /// # Examples
129    ///
130    /// ```
131    /// use rustc_serialize::Encodable;
132    /// use rustc_serialize::Encoder;
133    ///
134    /// enum Message {
135    ///     Quit,
136    ///     ChangeColor(i32, i32, i32),
137    /// }
138    ///
139    /// impl Encodable for Message {
140    ///     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
141    ///         s.emit_enum("Message", |s| {
142    ///             match *self {
143    ///                 Message::Quit => {
144    ///                     s.emit_enum_variant("Quit", 0, 0, |s| Ok(()))
145    ///                 }
146    ///                 Message::ChangeColor(r, g, b) => {
147    ///                     s.emit_enum_variant("ChangeColor", 1, 3, |s| {
148    ///                         try!(s.emit_enum_variant_arg(0, |s| {
149    ///                             s.emit_i32(r)
150    ///                         }));
151    ///                         try!(s.emit_enum_variant_arg(1, |s| {
152    ///                             s.emit_i32(g)
153    ///                         }));
154    ///                         try!(s.emit_enum_variant_arg(2, |s| {
155    ///                             s.emit_i32(b)
156    ///                         }));
157    ///                         Ok(())
158    ///                     })
159    ///                 }
160    ///             }
161    ///         })
162    ///     }
163    /// }
164    /// ```
165    fn emit_enum_variant<F>(&mut self, v_name: &str,
166                            v_id: usize,
167                            len: usize,
168                            f: F) -> Result<(), Self::Error>
169        where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
170
171    /// Emit an unnamed data item for an enumeration variant.
172    ///
173    /// This should only be called from a function passed to
174    /// `emit_enum_variant`.
175    ///
176    /// * `a_idx` is the (zero-based) index of the data item.
177    /// * `f` is a function that will call the appropriate emit method to encode
178    ///   the data object.
179    ///
180    /// Note that variant data items must be emitted in order - starting with
181    /// index `0` and finishing with index `len-1`.
182    fn emit_enum_variant_arg<F>(&mut self, a_idx: usize, f: F)
183                                -> Result<(), Self::Error>
184        where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
185
186    /// Emit a enumeration variant value with no or named data.
187    ///
188    /// This should only be called from a function passed to `emit_enum`.
189    /// Variants with unnamed data should use `emit_enum_variant`.
190    ///
191    /// * `v_name` is the variant name.
192    /// * `v_id` is the numeric identifier for the variant.
193    /// * `len` is the number of data items associated with the variant.
194    /// * `f` is a function that will call `emit_enum_struct_variant_field` for
195    ///   each data item. It may not be called if `len` is `0`.
196    ///
197    /// # Examples
198    ///
199    /// ```
200    /// use rustc_serialize::Encodable;
201    /// use rustc_serialize::Encoder;
202    ///
203    /// enum Message {
204    ///     Quit,
205    ///     Move { x: i32, y: i32 },
206    /// }
207    ///
208    /// impl Encodable for Message {
209    ///     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
210    ///         s.emit_enum("Message", |s| {
211    ///             match *self {
212    ///                 Message::Quit => {
213    ///                     s.emit_enum_struct_variant("Quit", 0, 0, |s| Ok(()))
214    ///                 }
215    ///                 Message::Move { x: x, y: y } => {
216    ///                     s.emit_enum_struct_variant("Move", 1, 2, |s| {
217    ///                         try!(s.emit_enum_struct_variant_field("x", 0, |s| {
218    ///                             s.emit_i32(x)
219    ///                         }));
220    ///                         try!(s.emit_enum_struct_variant_field("y", 1, |s| {
221    ///                             s.emit_i32(y)
222    ///                         }));
223    ///                         Ok(())
224    ///                     })
225    ///                 }
226    ///             }
227    ///         })
228    ///     }
229    /// }
230    /// ```
231    fn emit_enum_struct_variant<F>(&mut self, v_name: &str,
232                                   v_id: usize,
233                                   len: usize,
234                                   f: F) -> Result<(), Self::Error>
235        where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
236
237    /// Emit a named data item for an enumeration variant.
238    ///
239    /// This should only be called from a function passed to
240    /// `emit_enum_struct_variant`.
241    ///
242    /// * `f_name` is the name of the data item field.
243    /// * `f_idx` is its (zero-based) index.
244    /// * `f` is a function that will call the appropriate emit method to encode
245    ///   the data object.
246    ///
247    /// Note that fields must be emitted in order - starting with index `0` and
248    /// finishing with index `len-1`.
249    fn emit_enum_struct_variant_field<F>(&mut self,
250                                         f_name: &str,
251                                         f_idx: usize,
252                                         f: F) -> Result<(), Self::Error>
253        where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
254
255    /// Emit a struct value.
256    ///
257    /// * `name` is the name of the struct.
258    /// * `len` is the number of members.
259    /// * `f` is a function that calls `emit_struct_field` for each member.
260    ///
261    /// # Examples
262    ///
263    /// ```
264    /// use rustc_serialize::Encodable;
265    /// use rustc_serialize::Encoder;
266    ///
267    /// struct Point {
268    ///     x: i32,
269    ///     y: i32,
270    /// }
271    ///
272    /// impl Encodable for Point {
273    ///     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
274    ///         s.emit_struct("Point", 2, |s| {
275    ///             try!(s.emit_struct_field("x", 0, |s| {
276    ///                 s.emit_i32(self.x)
277    ///             }));
278    ///             try!(s.emit_struct_field("y", 1, |s| {
279    ///                 s.emit_i32(self.y)
280    ///             }));
281    ///             Ok(())
282    ///         })
283    ///     }
284    /// }
285    /// ```
286    fn emit_struct<F>(&mut self, name: &str, len: usize, f: F)
287                      -> Result<(), Self::Error>
288        where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
289    /// Emit a field item for a struct.
290    ///
291    /// This should only be called from a function passed to `emit_struct`.
292    ///
293    /// * `f_name` is the name of the data item field.
294    /// * `f_idx` is its (zero-based) index.
295    /// * `f` is a function that will call the appropriate emit method to encode
296    ///   the data object.
297    ///
298    /// Note that fields must be emitted in order - starting with index `0` and
299    /// finishing with index `len-1`.
300    fn emit_struct_field<F>(&mut self, f_name: &str, f_idx: usize, f: F)
301                            -> Result<(), Self::Error>
302        where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
303
304    /// Emit a tuple value.
305    ///
306    /// * `len` is the number of items in the tuple.
307    /// * `f` is a function that calls `emit_tuple_arg` for each member.
308    ///
309    /// Note that external `Encodable` implementations should not normally need
310    /// to use this method directly; it is meant for the use of this module's
311    /// own implementation of `Encodable` for tuples.
312    fn emit_tuple<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
313        where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
314
315    /// Emit a data item for a tuple.
316    ///
317    /// This should only be called from a function passed to `emit_tuple`.
318    ///
319    /// * `idx` is the (zero-based) index of the data item.
320    /// * `f` is a function that will call the appropriate emit method to encode
321    ///   the data object.
322    ///
323    /// Note that tuple items must be emitted in order - starting with index `0`
324    /// and finishing with index `len-1`.
325    fn emit_tuple_arg<F>(&mut self, idx: usize, f: F) -> Result<(), Self::Error>
326        where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
327
328    /// Emit a tuple struct value.
329    ///
330    /// * `name` is the name of the tuple struct.
331    /// * `len` is the number of items in the tuple struct.
332    /// * `f` is a function that calls `emit_tuple_struct_arg` for each member.
333    ///
334    /// # Examples
335    ///
336    /// ```
337    /// use rustc_serialize::Encodable;
338    /// use rustc_serialize::Encoder;
339    ///
340    /// struct Pair(i32,i32);
341    ///
342    /// impl Encodable for Pair {
343    ///     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
344    ///         let Pair(first,second) = *self;
345    ///         s.emit_tuple_struct("Pair", 2, |s| {
346    ///             try!(s.emit_tuple_arg(0, |s| {
347    ///                 s.emit_i32(first)
348    ///             }));
349    ///             try!(s.emit_tuple_arg(1, |s| {
350    ///                 s.emit_i32(second)
351    ///             }));
352    ///             Ok(())
353    ///         })
354    ///     }
355    /// }
356    /// ```
357    fn emit_tuple_struct<F>(&mut self, name: &str, len: usize, f: F)
358                            -> Result<(), Self::Error>
359        where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
360
361    /// Emit a data item for a tuple struct.
362    ///
363    /// This should only be called from a function passed to
364    /// `emit_tuple_struct`.
365    ///
366    /// * `f_idx` is the (zero-based) index of the data item.
367    /// * `f` is a function that will call the appropriate emit method to encode
368    ///   the data object.
369    ///
370    /// Note that tuple items must be emitted in order - starting with index `0`
371    /// and finishing with index `len-1`.
372    fn emit_tuple_struct_arg<F>(&mut self, f_idx: usize, f: F)
373                                -> Result<(), Self::Error>
374        where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
375
376    // Specialized types:
377    /// Emit an optional value.
378    ///
379    /// `f` is a function that will call either `emit_option_none` or
380    /// `emit_option_some` as appropriate.
381    ///
382    /// This method allows encoders to handle `Option<T>` values specially,
383    /// rather than using the generic enum methods, because many encoding
384    /// formats have a built-in "optional" concept.
385    ///
386    /// Note that external `Encodable` implementations should not normally need
387    /// to use this method directly; it is meant for the use of this module's
388    /// own implementation of `Encodable` for `Option<T>`.
389    fn emit_option<F>(&mut self, f: F) -> Result<(), Self::Error>
390        where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
391
392    /// Emit the `None` optional value.
393    ///
394    /// This should only be called from a function passed to `emit_option`.
395    fn emit_option_none(&mut self) -> Result<(), Self::Error>;
396
397    /// Emit the `Some(x)` optional value.
398    ///
399    /// `f` is a function that will call the appropriate emit method to encode
400    /// the data object.
401    ///
402    /// This should only be called from a function passed to `emit_option`.
403    fn emit_option_some<F>(&mut self, f: F) -> Result<(), Self::Error>
404        where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
405
406    /// Emit a sequence of values.
407    ///
408    /// This should be used for both array-like ordered sequences and set-like
409    /// unordered ones.
410    ///
411    /// * `len` is the number of values in the sequence.
412    /// * `f` is a function that will call `emit_seq_elt` for each value in the
413    ///   sequence.
414    fn emit_seq<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
415        where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
416
417    /// Emit an element in a sequence.
418    ///
419    /// This should only be called from a function passed to `emit_seq`.
420    ///
421    /// * `idx` is the (zero-based) index of the value in the sequence.
422    /// * `f` is a function that will call the appropriate emit method to encode
423    ///   the data object.
424    ///
425    /// Note that sequence elements must be emitted in order - starting with
426    /// index `0` and finishing with index `len-1`.
427    fn emit_seq_elt<F>(&mut self, idx: usize, f: F) -> Result<(), Self::Error>
428        where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
429
430    /// Emit an associative container (map).
431    ///
432    /// * `len` is the number of entries in the map.
433    /// * `f` is a function that will call `emit_map_elt_key` and
434    ///   `emit_map_elt_val` for each entry in the map.
435    ///
436    /// # Examples
437    ///
438    /// ```
439    /// use rustc_serialize::Encodable;
440    /// use rustc_serialize::Encoder;
441    ///
442    /// struct SimpleMap<K,V> {
443    ///     entries: Vec<(K,V)>,
444    /// }
445    ///
446    /// impl<K:Encodable,V:Encodable> Encodable for SimpleMap<K,V> {
447    ///     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
448    ///         s.emit_map(self.entries.len(), |s| {
449    ///             for (i, e) in self.entries.iter().enumerate() {
450    ///                 let (ref k, ref v) = *e;
451    ///                 try!(s.emit_map_elt_key(i, |s| k.encode(s)));
452    ///                 try!(s.emit_map_elt_val(i, |s| v.encode(s)));
453    ///             }
454    ///             Ok(())
455    ///         })
456    ///     }
457    /// }
458    /// ```
459    fn emit_map<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
460        where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
461
462    /// Emit the key for an entry in a map.
463    ///
464    /// This should only be called from a function passed to `emit_map`.
465    ///
466    /// * `idx` is the (zero-based) index of the entry in the map
467    /// * `f` is a function that will call the appropriate emit method to encode
468    ///   the key.
469    ///
470    /// Note that map entries must be emitted in order - starting with index `0`
471    /// and finishing with index `len-1` - and for each entry, the key should be
472    /// emitted followed immediately by the value.
473    fn emit_map_elt_key<F>(&mut self, idx: usize, f: F) -> Result<(), Self::Error>
474        where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
475
476    /// Emit the value for an entry in a map.
477    ///
478    /// This should only be called from a function passed to `emit_map`.
479    ///
480    /// * `idx` is the (zero-based) index of the entry in the map
481    /// * `f` is a function that will call the appropriate emit method to encode
482    ///   the value.
483    ///
484    /// Note that map entries must be emitted in order - starting with index `0`
485    /// and finishing with index `len-1` - and for each entry, the key should be
486    /// emitted followed immediately by the value.
487    fn emit_map_elt_val<F>(&mut self, idx: usize, f: F) -> Result<(), Self::Error>
488        where F: FnOnce(&mut Self) -> Result<(), Self::Error>;
489}
490
491/// Trait for reading in an encoding for deserialization.
492///
493/// This trait provides methods to decode basic types and generic forms of
494/// collections.  Implementations of `Decodable` use it to perform the actual
495/// decoding of a type.
496///
497/// Note that, as is typical with deserialization, the design of this API
498/// assumes you know in advance the form of the data you are decoding (ie: what
499/// type is encoded).
500///
501/// Decoders can expect to only have a single "root" method call made on this
502/// trait. Non-trivial types will call one of the collection-reading methods,
503/// passing a function that may call other methods on the trait, but once the
504/// collection-reading method has returned, decoding should be complete.
505pub trait Decoder {
506    /// The error type for method results.
507    type Error;
508
509    // Primitive types:
510    /// Read a nil value.
511    fn read_nil(&mut self) -> Result<(), Self::Error>;
512
513    /// Read a usize value.
514    fn read_usize(&mut self) -> Result<usize, Self::Error>;
515
516    /// Read a u64 value.
517    fn read_u64(&mut self) -> Result<u64, Self::Error>;
518
519    /// Read a u32 value.
520    fn read_u32(&mut self) -> Result<u32, Self::Error>;
521
522    /// Read a u16 value.
523    fn read_u16(&mut self) -> Result<u16, Self::Error>;
524
525    /// Read a u8 value.
526    fn read_u8(&mut self) -> Result<u8, Self::Error>;
527
528    /// Read a isize value.
529    fn read_isize(&mut self) -> Result<isize, Self::Error>;
530
531    /// Read a i64 value.
532    fn read_i64(&mut self) -> Result<i64, Self::Error>;
533
534    /// Read a i32 value.
535    fn read_i32(&mut self) -> Result<i32, Self::Error>;
536
537    /// Read a i16 value.
538    fn read_i16(&mut self) -> Result<i16, Self::Error>;
539
540    /// Read a i8 value.
541    fn read_i8(&mut self) -> Result<i8, Self::Error>;
542
543    /// Read a bool value.
544    fn read_bool(&mut self) -> Result<bool, Self::Error>;
545
546    /// Read a f64 value.
547    fn read_f64(&mut self) -> Result<f64, Self::Error>;
548
549    /// Read a f32 value.
550    fn read_f32(&mut self) -> Result<f32, Self::Error>;
551
552    /// Read a char value.
553    fn read_char(&mut self) -> Result<char, Self::Error>;
554
555    /// Read a string value.
556    fn read_str(&mut self) -> Result<String, Self::Error>;
557
558    // Compound types:
559    /// Read an enumeration value.
560    ///
561    /// * `name` indicates the enumeration type name. It may be used to
562    ///   sanity-check the data being read.
563    /// * `f` is a function that will call `read_enum_variant` (or
564    ///   `read_enum_struct_variant`) to read the actual value.
565    fn read_enum<T, F>(&mut self, name: &str, f: F) -> Result<T, Self::Error>
566        where F: FnOnce(&mut Self) -> Result<T, Self::Error>;
567
568    /// Read an enumeration value.
569    ///
570    /// * `names` is a list of the enumeration variant names.
571    /// * `f` is a function that will call `read_enum_variant_arg` or
572    ///   `read_enum_struct_variant_field` as appropriate to read the
573    ///   associated values. It will be passed the index into `names` for the
574    ///   variant that is encoded.
575    fn read_enum_variant<T, F>(&mut self, names: &[&str], f: F)
576                               -> Result<T, Self::Error>
577        where F: FnMut(&mut Self, usize) -> Result<T, Self::Error>;
578
579    /// Read an unnamed data item for an enumeration variant.
580    ///
581    /// This should only be called from a function passed to `read_enum_variant`
582    /// or `read_enum_struct_variant`, and only when the index provided to that
583    /// function indicates that the variant has associated unnamed data. It
584    /// should be called once for each associated data item.
585    ///
586    /// * `a_idx` is the (zero-based) index of the data item.
587    /// * `f` is a function that will call the appropriate read method to deocde
588    ///   the data object.
589    ///
590    /// Note that variant data items must be read in order - starting with index
591    /// `0` and finishing with index `len-1`. Implementations may use `a_idx`,
592    /// the call order or both to select the correct data to decode.
593    fn read_enum_variant_arg<T, F>(&mut self, a_idx: usize, f: F)
594                                   -> Result<T, Self::Error>
595        where F: FnOnce(&mut Self) -> Result<T, Self::Error>;
596
597    /// Read an enumeration value.
598    ///
599    /// This is identical to `read_enum_variant`, and is only provided for
600    /// symmetry with the `Encoder` API.
601    fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F)
602                                      -> Result<T, Self::Error>
603        where F: FnMut(&mut Self, usize) -> Result<T, Self::Error>;
604
605    /// Read a named data item for an enumeration variant.
606    ///
607    /// This should only be called from a function passed to `read_enum_variant`
608    /// or `read_enum_struct_variant`, and only when the index provided to that
609    /// function indicates that the variant has associated named data. It should
610    /// be called once for each associated field.
611    ///
612    /// * `f_name` is the name of the field.
613    /// * `f_idx` is the (zero-based) index of the data item.
614    /// * `f` is a function that will call the appropriate read method to deocde
615    ///   the data object.
616    ///
617    /// Note that fields must be read in order - starting with index `0` and
618    /// finishing with index `len-1`. Implementations may use `f_idx`, `f_name`,
619    /// the call order or any combination to choose the correct data to decode,
620    /// and may (but are not required to) return an error if these are
621    /// inconsistent.
622    fn read_enum_struct_variant_field<T, F>(&mut self,
623                                            f_name: &str,
624                                            f_idx: usize,
625                                            f: F)
626                                            -> Result<T, Self::Error>
627        where F: FnOnce(&mut Self) -> Result<T, Self::Error>;
628
629    /// Read an struct value.
630    ///
631    /// * `s_name` indicates the struct type name. It may be used to
632    ///   sanity-check the data being read.
633    /// * `len` indicates the number of fields in the struct.
634    /// * `f` is a function that will call `read_struct_field` for each field in
635    ///   the struct.
636    fn read_struct<T, F>(&mut self, s_name: &str, len: usize, f: F)
637                         -> Result<T, Self::Error>
638        where F: FnOnce(&mut Self) -> Result<T, Self::Error>;
639
640    /// Read a field for a struct value.
641    ///
642    /// This should only be called from a function passed to `read_struct`. It
643    /// should be called once for each associated field.
644    ///
645    /// * `f_name` is the name of the field.
646    /// * `f_idx` is the (zero-based) index of the data item.
647    /// * `f` is a function that will call the appropriate read method to deocde
648    ///   the data object.
649    ///
650    /// Note that fields must be read in order - starting with index `0` and
651    /// finishing with index `len-1`. Implementations may use `f_idx`, `f_name`,
652    /// the call order or any combination to choose the correct data to decode,
653    /// and may (but are not required to) return an error if these are
654    /// inconsistent.
655    fn read_struct_field<T, F>(&mut self,
656                               f_name: &str,
657                               f_idx: usize,
658                               f: F)
659                               -> Result<T, Self::Error>
660        where F: FnOnce(&mut Self) -> Result<T, Self::Error>;
661
662    /// Read a tuple value.
663    ///
664    /// * `len` is the number of items in the tuple.
665    /// * `f` is a function that will call `read_tuple_arg` for each item in the
666    ///   tuple.
667    ///
668    /// Note that external `Decodable` implementations should not normally need
669    /// to use this method directly; it is meant for the use of this module's
670    /// own implementation of `Decodable` for tuples.
671    fn read_tuple<T, F>(&mut self, len: usize, f: F) -> Result<T, Self::Error>
672        where F: FnOnce(&mut Self) -> Result<T, Self::Error>;
673
674    /// Read a data item for a tuple.
675    ///
676    /// This should only be called from a function passed to `read_tuple`.
677    ///
678    /// * `a_idx` is the (zero-based) index of the data item.
679    /// * `f` is a function that will call the appropriate read method to encode
680    ///   the data object.
681    ///
682    /// Note that tuple items must be read in order - starting with index `0`
683    /// and finishing with index `len-1`.
684    fn read_tuple_arg<T, F>(&mut self, a_idx: usize, f: F)
685                            -> Result<T, Self::Error>
686        where F: FnOnce(&mut Self) -> Result<T, Self::Error>;
687
688    /// Read a tuple struct value.
689    ///
690    /// * `s_name` is the name of the tuple struct.
691    /// * `len` is the number of items in the tuple struct.
692    /// * `f` is a function that calls `read_tuple_struct_arg` for each member.
693    fn read_tuple_struct<T, F>(&mut self, s_name: &str, len: usize, f: F)
694                               -> Result<T, Self::Error>
695        where F: FnOnce(&mut Self) -> Result<T, Self::Error>;
696
697    /// Read a data item for a tuple struct.
698    ///
699    /// This should only be called from a function passed to
700    /// `read_tuple_struct`.
701    ///
702    /// * `a_idx` is the (zero-based) index of the data item.
703    /// * `f` is a function that will call the appropriate read method to encode
704    ///   the data object.
705    ///
706    /// Note that tuple struct items must be read in order - starting with index
707    /// `0` and finishing with index `len-1`.
708    fn read_tuple_struct_arg<T, F>(&mut self, a_idx: usize, f: F)
709                                   -> Result<T, Self::Error>
710        where F: FnOnce(&mut Self) -> Result<T, Self::Error>;
711
712    // Specialized types:
713    /// Read an optional value.
714    ///
715    /// `f` is a function that will will be passed be passed `false` if the
716    /// value is unset, and `true` if it is set. If the function is passed
717    /// `true`, it will call the appropriate read methods to read the associated
718    /// data type.
719    ///
720    /// This method allows decoders to handle `Option<T>` values specially,
721    /// rather than using the generic enum methods, because many encoding
722    /// formats have a built-in "optional" concept.
723    ///
724    /// Note that external `Decodable` implementations should not normally need
725    /// to use this method directly; it is meant for the use of this module's
726    /// own implementation of `Decodable` for `Option<T>`.
727    fn read_option<T, F>(&mut self, f: F) -> Result<T, Self::Error>
728        where F: FnMut(&mut Self, bool) -> Result<T, Self::Error>;
729
730    /// Read a sequence of values.
731    ///
732    /// This should be used for both array-like ordered sequences and set-like
733    /// unordered ones.
734    ///
735    /// * `f` is a function that will be passed the length of the sequence, and
736    ///   will call `read_seq_elt` for each value in the sequence.
737    fn read_seq<T, F>(&mut self, f: F) -> Result<T, Self::Error>
738        where F: FnOnce(&mut Self, usize) -> Result<T, Self::Error>;
739
740    /// Read an element in the sequence.
741    ///
742    /// This should only be called from a function passed to `read_seq`.
743    ///
744    /// * `idx` is the (zero-based) index of the value in the sequence.
745    /// * `f` is a function that will call the appropriate read method to decode
746    ///   the data object.
747    ///
748    /// Note that sequence elements must be read in order - starting with index
749    /// `0` and finishing with index `len-1`.
750    fn read_seq_elt<T, F>(&mut self, idx: usize, f: F) -> Result<T, Self::Error>
751        where F: FnOnce(&mut Self) -> Result<T, Self::Error>;
752
753    /// Read an associative container (map).
754    ///
755    /// * `f` is a function that will be passed the number of entries in the
756    ///   map, and will call `read_map_elt_key` and `read_map_elt_val` to decode
757    ///   each entry.
758    fn read_map<T, F>(&mut self, f: F) -> Result<T, Self::Error>
759        where F: FnOnce(&mut Self, usize) -> Result<T, Self::Error>;
760
761    /// Read the key for an entry in a map.
762    ///
763    /// This should only be called from a function passed to `read_map`.
764    ///
765    /// * `idx` is the (zero-based) index of the entry in the map
766    /// * `f` is a function that will call the appropriate read method to decode
767    ///   the key.
768    ///
769    /// Note that map entries must be read in order - starting with index `0`
770    /// and finishing with index `len-1` - and for each entry, the key should be
771    /// read followed immediately by the value.
772    fn read_map_elt_key<T, F>(&mut self, idx: usize, f: F)
773                              -> Result<T, Self::Error>
774        where F: FnOnce(&mut Self) -> Result<T, Self::Error>;
775
776    /// Read the value for an entry in a map.
777    ///
778    /// This should only be called from a function passed to `read_map`.
779    ///
780    /// * `idx` is the (zero-based) index of the entry in the map
781    /// * `f` is a function that will call the appropriate read method to decode
782    ///   the value.
783    ///
784    /// Note that map entries must be read in order - starting with index `0`
785    /// and finishing with index `len-1` - and for each entry, the key should be
786    /// read followed immediately by the value.
787    fn read_map_elt_val<T, F>(&mut self, idx: usize, f: F)
788                              -> Result<T, Self::Error>
789        where F: FnOnce(&mut Self) -> Result<T, Self::Error>;
790
791    // Failure
792    /// Record a decoding error.
793    ///
794    /// This allows `Decodable` implementations to report an error using a
795    /// `Decoder` implementation's error type when inconsistent data is read.
796    /// For example, when reading a fixed-length array and the wrong length is
797    /// given by `read_seq`.
798    fn error(&mut self, err: &str) -> Self::Error;
799}
800
801/// Trait for serializing a type.
802///
803/// This can be implemented for custom data types to allow them to be encoded
804/// with `Encoder` implementations. Most of Rust's built-in or standard data
805/// types (like `i32` and `Vec<T>`) have `Encodable` implementations provided by
806/// this module.
807///
808/// Note that, in general, you should let the compiler implement this for you by
809/// using the `derive(RustcEncodable)` attribute.
810///
811/// # Examples
812///
813/// ```rust
814/// extern crate rustc_serialize;
815///
816/// #[derive(RustcEncodable)]
817/// struct Point {
818///     x: i32,
819///     y: i32,
820/// }
821/// # fn main() {}
822/// ```
823///
824/// This generates code equivalent to:
825///
826/// ```rust
827/// extern crate rustc_serialize;
828/// use rustc_serialize::Encodable;
829/// use rustc_serialize::Encoder;
830///
831/// struct Point {
832///     x: i32,
833///     y: i32,
834/// }
835///
836/// impl Encodable for Point {
837///     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
838///         s.emit_struct("Point", 2, |s| {
839///             try!(s.emit_struct_field("x", 0, |s| {
840///                 s.emit_i32(self.x)
841///             }));
842///             try!(s.emit_struct_field("y", 1, |s| {
843///                 s.emit_i32(self.y)
844///             }));
845///             Ok(())
846///         })
847///     }
848/// }
849/// # fn main() {}
850/// ```
851pub trait Encodable {
852    /// Serialize a value using an `Encoder`.
853    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error>;
854}
855
856/// Trait for deserializing a type.
857///
858/// This can be implemented for custom data types to allow them to be decoded
859/// with `Decoder` implementations. Most of Rust's built-in or standard data
860/// types (like `i32` and `Vec<T>`) have `Decodable` implementations provided by
861/// this module.
862///
863/// Note that, in general, you should let the compiler implement this for you by
864/// using the `derive(RustcDecodable)` attribute.
865///
866/// # Examples
867///
868/// ```rust
869/// extern crate rustc_serialize;
870///
871/// #[derive(RustcDecodable)]
872/// struct Point {
873///     x: i32,
874///     y: i32,
875/// }
876/// # fn main() {}
877/// ```
878///
879/// This generates code equivalent to:
880///
881/// ```rust
882/// extern crate rustc_serialize;
883/// use rustc_serialize::Decodable;
884/// use rustc_serialize::Decoder;
885///
886/// struct Point {
887///     x: i32,
888///     y: i32,
889/// }
890///
891/// impl Decodable for Point {
892///     fn decode<D: Decoder>(d: &mut D) -> Result<Point, D::Error> {
893///         d.read_struct("Point", 2, |d| {
894///             let x = try!(d.read_struct_field("x", 0, |d| { d.read_i32() }));
895///             let y = try!(d.read_struct_field("y", 1, |d| { d.read_i32() }));
896///             Ok(Point{ x: x, y: y })
897///         })
898///     }
899/// }
900/// # fn main() {}
901/// ```
902pub trait Decodable: Sized {
903    /// Deserialize a value using a `Decoder`.
904    fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error>;
905}
906
907impl Encodable for usize {
908    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
909        s.emit_usize(*self)
910    }
911}
912
913impl Decodable for usize {
914    fn decode<D: Decoder>(d: &mut D) -> Result<usize, D::Error> {
915        d.read_usize()
916    }
917}
918
919impl Encodable for u8 {
920    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
921        s.emit_u8(*self)
922    }
923}
924
925impl Decodable for u8 {
926    fn decode<D: Decoder>(d: &mut D) -> Result<u8, D::Error> {
927        d.read_u8()
928    }
929}
930
931impl Encodable for u16 {
932    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
933        s.emit_u16(*self)
934    }
935}
936
937impl Decodable for u16 {
938    fn decode<D: Decoder>(d: &mut D) -> Result<u16, D::Error> {
939        d.read_u16()
940    }
941}
942
943impl Encodable for u32 {
944    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
945        s.emit_u32(*self)
946    }
947}
948
949impl Decodable for u32 {
950    fn decode<D: Decoder>(d: &mut D) -> Result<u32, D::Error> {
951        d.read_u32()
952    }
953}
954
955impl Encodable for u64 {
956    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
957        s.emit_u64(*self)
958    }
959}
960
961impl Decodable for u64 {
962    fn decode<D: Decoder>(d: &mut D) -> Result<u64, D::Error> {
963        d.read_u64()
964    }
965}
966
967impl Encodable for isize {
968    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
969        s.emit_isize(*self)
970    }
971}
972
973impl Decodable for isize {
974    fn decode<D: Decoder>(d: &mut D) -> Result<isize, D::Error> {
975        d.read_isize()
976    }
977}
978
979impl Encodable for i8 {
980    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
981        s.emit_i8(*self)
982    }
983}
984
985impl Decodable for i8 {
986    fn decode<D: Decoder>(d: &mut D) -> Result<i8, D::Error> {
987        d.read_i8()
988    }
989}
990
991impl Encodable for i16 {
992    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
993        s.emit_i16(*self)
994    }
995}
996
997impl Decodable for i16 {
998    fn decode<D: Decoder>(d: &mut D) -> Result<i16, D::Error> {
999        d.read_i16()
1000    }
1001}
1002
1003impl Encodable for i32 {
1004    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1005        s.emit_i32(*self)
1006    }
1007}
1008
1009impl Decodable for i32 {
1010    fn decode<D: Decoder>(d: &mut D) -> Result<i32, D::Error> {
1011        d.read_i32()
1012    }
1013}
1014
1015impl Encodable for i64 {
1016    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1017        s.emit_i64(*self)
1018    }
1019}
1020
1021impl Decodable for i64 {
1022    fn decode<D: Decoder>(d: &mut D) -> Result<i64, D::Error> {
1023        d.read_i64()
1024    }
1025}
1026
1027impl Encodable for str {
1028    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1029        s.emit_str(self)
1030    }
1031}
1032
1033impl Encodable for String {
1034    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1035        s.emit_str(self)
1036    }
1037}
1038
1039impl Decodable for String {
1040    fn decode<D: Decoder>(d: &mut D) -> Result<String, D::Error> {
1041        d.read_str()
1042    }
1043}
1044
1045impl Encodable for f32 {
1046    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1047        s.emit_f32(*self)
1048    }
1049}
1050
1051impl Decodable for f32 {
1052    fn decode<D: Decoder>(d: &mut D) -> Result<f32, D::Error> {
1053        d.read_f32()
1054    }
1055}
1056
1057impl Encodable for f64 {
1058    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1059        s.emit_f64(*self)
1060    }
1061}
1062
1063impl Decodable for f64 {
1064    fn decode<D: Decoder>(d: &mut D) -> Result<f64, D::Error> {
1065        d.read_f64()
1066    }
1067}
1068
1069impl Encodable for bool {
1070    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1071        s.emit_bool(*self)
1072    }
1073}
1074
1075impl Decodable for bool {
1076    fn decode<D: Decoder>(d: &mut D) -> Result<bool, D::Error> {
1077        d.read_bool()
1078    }
1079}
1080
1081impl Encodable for char {
1082    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1083        s.emit_char(*self)
1084    }
1085}
1086
1087impl Decodable for char {
1088    fn decode<D: Decoder>(d: &mut D) -> Result<char, D::Error> {
1089        d.read_char()
1090    }
1091}
1092
1093impl Encodable for () {
1094    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1095        s.emit_nil()
1096    }
1097}
1098
1099impl Decodable for () {
1100    fn decode<D: Decoder>(d: &mut D) -> Result<(), D::Error> {
1101        d.read_nil()
1102    }
1103}
1104
1105impl<'a, T: ?Sized + Encodable> Encodable for &'a T {
1106    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1107        (**self).encode(s)
1108    }
1109}
1110
1111impl<T: ?Sized + Encodable> Encodable for Box<T> {
1112    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1113        (**self).encode(s)
1114    }
1115}
1116
1117impl< T: Decodable> Decodable for Box<T> {
1118    fn decode<D: Decoder>(d: &mut D) -> Result<Box<T>, D::Error> {
1119        Ok(Box::new(try!(Decodable::decode(d))))
1120    }
1121}
1122
1123impl< T: Decodable> Decodable for Box<[T]> {
1124    fn decode<D: Decoder>(d: &mut D) -> Result<Box<[T]>, D::Error> {
1125        let v: Vec<T> = try!(Decodable::decode(d));
1126        Ok(v.into_boxed_slice())
1127    }
1128}
1129
1130impl<T:Encodable> Encodable for Rc<T> {
1131    #[inline]
1132    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1133        (**self).encode(s)
1134    }
1135}
1136
1137impl<T:Decodable> Decodable for Rc<T> {
1138    #[inline]
1139    fn decode<D: Decoder>(d: &mut D) -> Result<Rc<T>, D::Error> {
1140        Ok(Rc::new(try!(Decodable::decode(d))))
1141    }
1142}
1143
1144impl<'a, T:Encodable + ToOwned + ?Sized> Encodable for Cow<'a, T> {
1145    #[inline]
1146    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1147        (**self).encode(s)
1148    }
1149}
1150
1151impl<'a, T: ?Sized> Decodable for Cow<'a, T>
1152    where T: ToOwned, T::Owned: Decodable
1153{
1154    #[inline]
1155    fn decode<D: Decoder>(d: &mut D) -> Result<Cow<'a, T>, D::Error> {
1156        Ok(Cow::Owned(try!(Decodable::decode(d))))
1157    }
1158}
1159
1160impl<T:Encodable> Encodable for [T] {
1161    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1162        s.emit_seq(self.len(), |s| {
1163            for (i, e) in self.iter().enumerate() {
1164                try!(s.emit_seq_elt(i, |s| e.encode(s)))
1165            }
1166            Ok(())
1167        })
1168    }
1169}
1170
1171impl<T:Encodable> Encodable for Vec<T> {
1172    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1173        s.emit_seq(self.len(), |s| {
1174            for (i, e) in self.iter().enumerate() {
1175                try!(s.emit_seq_elt(i, |s| e.encode(s)))
1176            }
1177            Ok(())
1178        })
1179    }
1180}
1181
1182impl<T:Decodable> Decodable for Vec<T> {
1183    fn decode<D: Decoder>(d: &mut D) -> Result<Vec<T>, D::Error> {
1184        d.read_seq(|d, len| {
1185            let mut v = Vec::with_capacity(cap_capacity::<T>(len));
1186            for i in 0..len {
1187                v.push(try!(d.read_seq_elt(i, |d| Decodable::decode(d))));
1188            }
1189            Ok(v)
1190        })
1191    }
1192}
1193
1194impl<T:Encodable> Encodable for Option<T> {
1195    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1196        s.emit_option(|s| {
1197            match *self {
1198                None => s.emit_option_none(),
1199                Some(ref v) => s.emit_option_some(|s| v.encode(s)),
1200            }
1201        })
1202    }
1203}
1204
1205impl<T:Decodable> Decodable for Option<T> {
1206    fn decode<D: Decoder>(d: &mut D) -> Result<Option<T>, D::Error> {
1207        d.read_option(|d, b| {
1208            if b {
1209                Ok(Some(try!(Decodable::decode(d))))
1210            } else {
1211                Ok(None)
1212            }
1213        })
1214    }
1215}
1216
1217impl<T:Encodable, E:Encodable> Encodable for Result<T, E> {
1218    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1219        s.emit_enum("Result", |s| {
1220            match *self {
1221                Ok(ref v) => {
1222                    s.emit_enum_variant("Ok", 0, 1, |s| {
1223                        try!(s.emit_enum_variant_arg(0, |s| {
1224                            v.encode(s)
1225                        }));
1226                        Ok(())
1227                    })
1228                }
1229                Err(ref v) => {
1230                    s.emit_enum_variant("Err", 1, 1, |s| {
1231                        try!(s.emit_enum_variant_arg(0, |s| {
1232                            v.encode(s)
1233                        }));
1234                        Ok(())
1235                    })
1236                }
1237            }
1238        })
1239    }
1240}
1241
1242impl<T: Decodable, E: Decodable> Decodable for Result<T, E> {
1243    fn decode<D: Decoder>(d: &mut D) -> Result<Result<T, E>, D::Error> {
1244        d.read_enum("Result", |d| {
1245            d.read_enum_variant(&["Ok", "Err"], |d, idx| {
1246                match idx {
1247                    0 => {
1248                        d.read_enum_variant_arg(0, |d| {
1249                            T::decode(d)
1250                        }).map(|v| Ok(v))
1251                    }
1252                    1 => {
1253                        d.read_enum_variant_arg(0, |d| {
1254                            E::decode(d)
1255                        }).map(|v| Err(v))
1256                    }
1257                    _ => panic!("Internal error"),
1258                }
1259            })
1260        })
1261    }
1262}
1263
1264impl<T> Encodable for PhantomData<T> {
1265    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1266        s.emit_nil()
1267    }
1268}
1269
1270impl<T> Decodable for PhantomData<T> {
1271    fn decode<D: Decoder>(_d: &mut D) -> Result<PhantomData<T>, D::Error> {
1272        Ok(PhantomData)
1273    }
1274}
1275
1276macro_rules! peel {
1277    ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
1278}
1279
1280/// Evaluates to the number of identifiers passed to it, for example:
1281/// `count_idents!(a, b, c) == 3
1282macro_rules! count_idents {
1283    () => { 0 };
1284    ($_i:ident, $($rest:ident,)*) => { 1 + count_idents!($($rest,)*) }
1285}
1286
1287macro_rules! tuple {
1288    () => ();
1289    ( $($name:ident,)+ ) => (
1290        impl<$($name:Decodable),*> Decodable for ($($name,)*) {
1291            fn decode<D: Decoder>(d: &mut D) -> Result<($($name,)*), D::Error> {
1292                let len: usize = count_idents!($($name,)*);
1293                d.read_tuple(len, |d| {
1294                    let mut i = 0;
1295                    let ret = ($(try!(d.read_tuple_arg({ i+=1; i-1 },
1296                                                       |d| -> Result<$name,D::Error> {
1297                        Decodable::decode(d)
1298                    })),)*);
1299                    return Ok(ret);
1300                })
1301            }
1302        }
1303        impl<$($name:Encodable),*> Encodable for ($($name,)*) {
1304            #[allow(non_snake_case)]
1305            fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1306                let ($(ref $name,)*) = *self;
1307                let mut n = 0;
1308                $(let $name = $name; n += 1;)*
1309                s.emit_tuple(n, |s| {
1310                    let mut i = 0;
1311                    $(try!(s.emit_tuple_arg({ i+=1; i-1 }, |s| $name.encode(s)));)*
1312                    Ok(())
1313                })
1314            }
1315        }
1316        peel! { $($name,)* }
1317    )
1318}
1319
1320tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
1321
1322macro_rules! array {
1323    () => ();
1324    ($len:expr, $($idx:expr,)*) => {
1325        impl<T:Decodable> Decodable for [T; $len] {
1326            fn decode<D: Decoder>(d: &mut D) -> Result<[T; $len], D::Error> {
1327                d.read_seq(|d, len| {
1328                    if len != $len {
1329                        return Err(d.error("wrong array length"));
1330                    }
1331                    Ok([$(
1332                        try!(d.read_seq_elt($len - $idx - 1,
1333                                            |d| Decodable::decode(d)))
1334                    ),*])
1335                })
1336            }
1337        }
1338
1339        impl<T:Encodable> Encodable for [T; $len] {
1340            fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1341                s.emit_seq($len, |s| {
1342                    for i in 0..$len {
1343                        try!(s.emit_seq_elt(i, |s| self[i].encode(s)));
1344                    }
1345                    Ok(())
1346                })
1347            }
1348        }
1349        array! { $($idx,)* }
1350    }
1351}
1352
1353array! {
1354    32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16,
1355    15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0,
1356}
1357
1358impl Encodable for path::Path {
1359    #[cfg(target_os = "redox")]
1360    fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> {
1361        self.as_os_str().to_str().unwrap().encode(e)
1362    }
1363    #[cfg(unix)]
1364    fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> {
1365        use std::os::unix::prelude::*;
1366        self.as_os_str().as_bytes().encode(e)
1367    }
1368    #[cfg(windows)]
1369    fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> {
1370        use std::os::windows::prelude::*;
1371        let v = self.as_os_str().encode_wide().collect::<Vec<_>>();
1372        v.encode(e)
1373    }
1374}
1375
1376impl Encodable for path::PathBuf {
1377    fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> {
1378        (**self).encode(e)
1379    }
1380}
1381
1382impl Decodable for path::PathBuf {
1383    #[cfg(target_os = "redox")]
1384    fn decode<D: Decoder>(d: &mut D) -> Result<path::PathBuf, D::Error> {
1385        let string: String = try!(Decodable::decode(d));
1386        let s: OsString = OsString::from(string);
1387        let mut p = path::PathBuf::new();
1388        p.push(s);
1389        Ok(p)
1390    }
1391    #[cfg(unix)]
1392    fn decode<D: Decoder>(d: &mut D) -> Result<path::PathBuf, D::Error> {
1393        use std::os::unix::prelude::*;
1394        let bytes: Vec<u8> = try!(Decodable::decode(d));
1395        let s: OsString = OsStringExt::from_vec(bytes);
1396        let mut p = path::PathBuf::new();
1397        p.push(s);
1398        Ok(p)
1399    }
1400    #[cfg(windows)]
1401    fn decode<D: Decoder>(d: &mut D) -> Result<path::PathBuf, D::Error> {
1402        use std::os::windows::prelude::*;
1403        let bytes: Vec<u16> = try!(Decodable::decode(d));
1404        let s: OsString = OsStringExt::from_wide(&bytes);
1405        let mut p = path::PathBuf::new();
1406        p.push(s);
1407        Ok(p)
1408    }
1409}
1410
1411impl<T: Encodable + Copy> Encodable for Cell<T> {
1412    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1413        self.get().encode(s)
1414    }
1415}
1416
1417impl<T: Decodable + Copy> Decodable for Cell<T> {
1418    fn decode<D: Decoder>(d: &mut D) -> Result<Cell<T>, D::Error> {
1419        Ok(Cell::new(try!(Decodable::decode(d))))
1420    }
1421}
1422
1423// FIXME: #15036
1424// Should use `try_borrow`, returning a
1425// `encoder.error("attempting to Encode borrowed RefCell")`
1426// from `encode` when `try_borrow` returns `None`.
1427
1428impl<T: Encodable> Encodable for RefCell<T> {
1429    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1430        self.borrow().encode(s)
1431    }
1432}
1433
1434impl<T: Decodable> Decodable for RefCell<T> {
1435    fn decode<D: Decoder>(d: &mut D) -> Result<RefCell<T>, D::Error> {
1436        Ok(RefCell::new(try!(Decodable::decode(d))))
1437    }
1438}
1439
1440impl<T:Encodable> Encodable for Arc<T> {
1441    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1442        (**self).encode(s)
1443    }
1444}
1445
1446impl<T:Decodable+Send+Sync> Decodable for Arc<T> {
1447    fn decode<D: Decoder>(d: &mut D) -> Result<Arc<T>, D::Error> {
1448        Ok(Arc::new(try!(Decodable::decode(d))))
1449    }
1450}
1451
1452// ___________________________________________________________________________
1453// Helper routines
1454
1455/// Trait with helper functions for implementing `Encodable`.
1456///
1457/// This trait is implemented for everything that implements `Encoder`.
1458/// `Encodable` implementations can make use of it to make their implementations
1459/// easier.
1460pub trait EncoderHelpers: Encoder {
1461    /// Emit a vector as a sequence.
1462    ///
1463    /// Storing sequences as vectors is a common pattern. This method makes
1464    /// encoding such sequences easier by wrapping the calls to
1465    /// `Encoder::emit_seq` and `Encoder::emit_seq_elt`.
1466    ///
1467    /// # Examples
1468    ///
1469    /// ```
1470    /// use rustc_serialize::Encodable;
1471    /// use rustc_serialize::Encoder;
1472    /// use rustc_serialize::EncoderHelpers;
1473    ///
1474    /// struct NumberSequence {
1475    ///     elements: Vec<i32>,
1476    /// }
1477    ///
1478    /// impl Encodable for NumberSequence {
1479    ///     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1480    ///         s.emit_struct("NumberSequence", 1, |s| {
1481    ///             s.emit_struct_field("elements", 0, |s| {
1482    ///                 s.emit_from_vec(&self.elements, |s,e| {
1483    ///                     s.emit_i32(*e)
1484    ///                 })
1485    ///             })
1486    ///         })
1487    ///     }
1488    /// }
1489    /// ```
1490    fn emit_from_vec<T, F>(&mut self, v: &[T], f: F)
1491                           -> Result<(), <Self as Encoder>::Error>
1492        where F: FnMut(&mut Self, &T) -> Result<(), <Self as Encoder>::Error>;
1493}
1494
1495impl<S:Encoder> EncoderHelpers for S {
1496    fn emit_from_vec<T, F>(&mut self, v: &[T], mut f: F) -> Result<(), S::Error> where
1497        F: FnMut(&mut S, &T) -> Result<(), S::Error>,
1498    {
1499        self.emit_seq(v.len(), |this| {
1500            for (i, e) in v.iter().enumerate() {
1501                try!(this.emit_seq_elt(i, |this| {
1502                    f(this, e)
1503                }));
1504            }
1505            Ok(())
1506        })
1507    }
1508}
1509
1510/// Trait with helper functions for implementing `Decodable`.
1511///
1512/// This trait is implemented for everything that implements `Decoder`.
1513/// `Decodable` implementations can make use of it to make their implementations
1514/// easier.
1515pub trait DecoderHelpers: Decoder {
1516    /// Read a sequence into a vector.
1517    ///
1518    /// Storing sequences as vectors is a common pattern. This method makes
1519    /// deserializing such sequences easier by wrapping the calls to
1520    /// `Decoder::read_seq` and `Decoder::read_seq_elt`.
1521    ///
1522    /// # Examples
1523    ///
1524    /// ```
1525    /// use rustc_serialize::Decodable;
1526    /// use rustc_serialize::Decoder;
1527    /// use rustc_serialize::DecoderHelpers;
1528    ///
1529    /// struct NumberSequence {
1530    ///     elements: Vec<i32>,
1531    /// }
1532    ///
1533    /// impl Decodable for NumberSequence {
1534    ///     fn decode<D: Decoder>(d: &mut D) -> Result<NumberSequence, D::Error> {
1535    ///         d.read_struct("NumberSequence", 2, |d| {
1536    ///             Ok(NumberSequence{
1537    ///                 elements: try!(d.read_struct_field("elements", 0, |d| {
1538    ///                     d.read_to_vec(|d| { d.read_i32() })
1539    ///                 }))
1540    ///             })
1541    ///         })
1542    ///     }
1543    /// }
1544    /// ```
1545    fn read_to_vec<T, F>(&mut self, f: F)
1546                         -> Result<Vec<T>, <Self as Decoder>::Error> where
1547        F: FnMut(&mut Self) -> Result<T, <Self as Decoder>::Error>;
1548}
1549
1550impl<D: Decoder> DecoderHelpers for D {
1551    fn read_to_vec<T, F>(&mut self, mut f: F) -> Result<Vec<T>, D::Error> where F:
1552        FnMut(&mut D) -> Result<T, D::Error>,
1553    {
1554        self.read_seq(|this, len| {
1555            let mut v = Vec::with_capacity(cap_capacity::<T>(len));
1556            for i in 0..len {
1557                v.push(try!(this.read_seq_elt(i, |this| f(this))));
1558            }
1559            Ok(v)
1560        })
1561    }
1562}
1563
1564#[test]
1565#[allow(unused_variables)]
1566fn capacity_rules() {
1567    use std::usize::MAX;
1568    use std::collections::{HashMap, HashSet};
1569
1570    struct MyDecoder;
1571    impl Decoder for MyDecoder {
1572        type Error = ();
1573
1574        // Primitive types:
1575        fn read_nil(&mut self) -> Result<(), Self::Error> { Err(()) }
1576        fn read_usize(&mut self) -> Result<usize, Self::Error> { Err(()) }
1577        fn read_u64(&mut self) -> Result<u64, Self::Error> { Err(()) }
1578        fn read_u32(&mut self) -> Result<u32, Self::Error> { Err(()) }
1579        fn read_u16(&mut self) -> Result<u16, Self::Error> { Err(()) }
1580        fn read_u8(&mut self) -> Result<u8, Self::Error> { Err(()) }
1581        fn read_isize(&mut self) -> Result<isize, Self::Error> { Err(()) }
1582        fn read_i64(&mut self) -> Result<i64, Self::Error> { Err(()) }
1583        fn read_i32(&mut self) -> Result<i32, Self::Error> { Err(()) }
1584        fn read_i16(&mut self) -> Result<i16, Self::Error> { Err(()) }
1585        fn read_i8(&mut self) -> Result<i8, Self::Error> { Err(()) }
1586        fn read_bool(&mut self) -> Result<bool, Self::Error> { Err(()) }
1587        fn read_f64(&mut self) -> Result<f64, Self::Error> { Err(()) }
1588        fn read_f32(&mut self) -> Result<f32, Self::Error> { Err(()) }
1589        fn read_char(&mut self) -> Result<char, Self::Error> { Err(()) }
1590        fn read_str(&mut self) -> Result<String, Self::Error> { Err(()) }
1591
1592        // Compound types:
1593        fn read_enum<T, F>(&mut self, name: &str, f: F) -> Result<T, Self::Error>
1594            where F: FnOnce(&mut Self) -> Result<T, Self::Error> { Err(()) }
1595
1596        fn read_enum_variant<T, F>(&mut self, names: &[&str], f: F)
1597                                   -> Result<T, Self::Error>
1598            where F: FnMut(&mut Self, usize) -> Result<T, Self::Error> { Err(()) }
1599        fn read_enum_variant_arg<T, F>(&mut self, a_idx: usize, f: F)
1600                                       -> Result<T, Self::Error>
1601            where F: FnOnce(&mut Self) -> Result<T, Self::Error> { Err(()) }
1602
1603        fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F)
1604                                          -> Result<T, Self::Error>
1605            where F: FnMut(&mut Self, usize) -> Result<T, Self::Error> { Err(()) }
1606        fn read_enum_struct_variant_field<T, F>(&mut self,
1607                                                f_name: &str,
1608                                                f_idx: usize,
1609                                                f: F)
1610                                                -> Result<T, Self::Error>
1611            where F: FnOnce(&mut Self) -> Result<T, Self::Error> { Err(()) }
1612
1613        fn read_struct<T, F>(&mut self, s_name: &str, len: usize, f: F)
1614                             -> Result<T, Self::Error>
1615            where F: FnOnce(&mut Self) -> Result<T, Self::Error> { Err(()) }
1616        fn read_struct_field<T, F>(&mut self,
1617                                   f_name: &str,
1618                                   f_idx: usize,
1619                                   f: F)
1620                                   -> Result<T, Self::Error>
1621            where F: FnOnce(&mut Self) -> Result<T, Self::Error> { Err(()) }
1622
1623        fn read_tuple<T, F>(&mut self, len: usize, f: F) -> Result<T, Self::Error>
1624            where F: FnOnce(&mut Self) -> Result<T, Self::Error> { Err(()) }
1625        fn read_tuple_arg<T, F>(&mut self, a_idx: usize, f: F)
1626                                -> Result<T, Self::Error>
1627            where F: FnOnce(&mut Self) -> Result<T, Self::Error> { Err(()) }
1628
1629        fn read_tuple_struct<T, F>(&mut self, s_name: &str, len: usize, f: F)
1630                                   -> Result<T, Self::Error>
1631            where F: FnOnce(&mut Self) -> Result<T, Self::Error> { Err(()) }
1632        fn read_tuple_struct_arg<T, F>(&mut self, a_idx: usize, f: F)
1633                                       -> Result<T, Self::Error>
1634            where F: FnOnce(&mut Self) -> Result<T, Self::Error> { Err(()) }
1635
1636        // Specialized types:
1637        fn read_option<T, F>(&mut self, f: F) -> Result<T, Self::Error>
1638            where F: FnMut(&mut Self, bool) -> Result<T, Self::Error> { Err(()) }
1639
1640        fn read_seq<T, F>(&mut self, f: F) -> Result<T, Self::Error>
1641            where F: FnOnce(&mut Self, usize) -> Result<T, Self::Error> {
1642                f(self, MAX)
1643            }
1644        fn read_seq_elt<T, F>(&mut self, idx: usize, f: F) -> Result<T, Self::Error>
1645            where F: FnOnce(&mut Self) -> Result<T, Self::Error> { Err(()) }
1646
1647        fn read_map<T, F>(&mut self, f: F) -> Result<T, Self::Error>
1648            where F: FnOnce(&mut Self, usize) -> Result<T, Self::Error> {
1649            f(self, MAX)
1650        }
1651        fn read_map_elt_key<T, F>(&mut self, idx: usize, f: F)
1652                                  -> Result<T, Self::Error>
1653            where F: FnOnce(&mut Self) -> Result<T, Self::Error> { Err(()) }
1654        fn read_map_elt_val<T, F>(&mut self, idx: usize, f: F)
1655                                  -> Result<T, Self::Error>
1656            where F: FnOnce(&mut Self) -> Result<T, Self::Error> { Err(()) }
1657
1658        // Failure
1659        fn error(&mut self, err: &str) -> Self::Error { () }
1660    }
1661
1662    let mut dummy = MyDecoder;
1663    let vec_result: Result<Vec<u8>, ()> = Decodable::decode(&mut dummy);
1664    assert!(vec_result.is_err());
1665
1666    let map_result: Result<HashMap<u8, u8>, ()> = Decodable::decode(&mut dummy);
1667    assert!(map_result.is_err());
1668
1669    let set_result: Result<HashSet<u8>, ()> = Decodable::decode(&mut dummy);
1670    assert!(set_result.is_err());
1671}