]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_serialize/src/serialize.rs
Rollup merge of #86014 - cr1901:msp430-link, r=jonas-schievink
[rust.git] / compiler / rustc_serialize / src / serialize.rs
1 //! Support code for encoding and decoding types.
2
3 /*
4 Core encoding and decoding interfaces.
5 */
6
7 use std::borrow::Cow;
8 use std::cell::{Cell, RefCell};
9 use std::marker::PhantomData;
10 use std::path;
11 use std::rc::Rc;
12 use std::sync::Arc;
13
14 pub trait Encoder {
15     type Error;
16
17     // Primitive types:
18     fn emit_unit(&mut self) -> Result<(), Self::Error>;
19     fn emit_usize(&mut self, v: usize) -> Result<(), Self::Error>;
20     fn emit_u128(&mut self, v: u128) -> Result<(), Self::Error>;
21     fn emit_u64(&mut self, v: u64) -> Result<(), Self::Error>;
22     fn emit_u32(&mut self, v: u32) -> Result<(), Self::Error>;
23     fn emit_u16(&mut self, v: u16) -> Result<(), Self::Error>;
24     fn emit_u8(&mut self, v: u8) -> Result<(), Self::Error>;
25     fn emit_isize(&mut self, v: isize) -> Result<(), Self::Error>;
26     fn emit_i128(&mut self, v: i128) -> Result<(), Self::Error>;
27     fn emit_i64(&mut self, v: i64) -> Result<(), Self::Error>;
28     fn emit_i32(&mut self, v: i32) -> Result<(), Self::Error>;
29     fn emit_i16(&mut self, v: i16) -> Result<(), Self::Error>;
30     fn emit_i8(&mut self, v: i8) -> Result<(), Self::Error>;
31     fn emit_bool(&mut self, v: bool) -> Result<(), Self::Error>;
32     fn emit_f64(&mut self, v: f64) -> Result<(), Self::Error>;
33     fn emit_f32(&mut self, v: f32) -> Result<(), Self::Error>;
34     fn emit_char(&mut self, v: char) -> Result<(), Self::Error>;
35     fn emit_str(&mut self, v: &str) -> Result<(), Self::Error>;
36     fn emit_raw_bytes(&mut self, s: &[u8]) -> Result<(), Self::Error>;
37
38     // Compound types:
39     #[inline]
40     fn emit_enum<F>(&mut self, _name: &str, f: F) -> Result<(), Self::Error>
41     where
42         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
43     {
44         f(self)
45     }
46
47     fn emit_enum_variant<F>(
48         &mut self,
49         _v_name: &str,
50         v_id: usize,
51         _len: usize,
52         f: F,
53     ) -> Result<(), Self::Error>
54     where
55         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
56     {
57         self.emit_usize(v_id)?;
58         f(self)
59     }
60
61     #[inline]
62     fn emit_enum_variant_arg<F>(&mut self, _a_idx: usize, f: F) -> Result<(), Self::Error>
63     where
64         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
65     {
66         f(self)
67     }
68
69     fn emit_enum_struct_variant<F>(
70         &mut self,
71         v_name: &str,
72         v_id: usize,
73         len: usize,
74         f: F,
75     ) -> Result<(), Self::Error>
76     where
77         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
78     {
79         self.emit_enum_variant(v_name, v_id, len, f)
80     }
81
82     fn emit_enum_struct_variant_field<F>(
83         &mut self,
84         _f_name: &str,
85         f_idx: usize,
86         f: F,
87     ) -> Result<(), Self::Error>
88     where
89         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
90     {
91         self.emit_enum_variant_arg(f_idx, f)
92     }
93
94     #[inline]
95     fn emit_struct<F>(&mut self, _name: &str, _len: usize, f: F) -> Result<(), Self::Error>
96     where
97         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
98     {
99         f(self)
100     }
101
102     #[inline]
103     fn emit_struct_field<F>(
104         &mut self,
105         _f_name: &str,
106         _f_idx: usize,
107         f: F,
108     ) -> Result<(), Self::Error>
109     where
110         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
111     {
112         f(self)
113     }
114
115     #[inline]
116     fn emit_tuple<F>(&mut self, _len: usize, f: F) -> Result<(), Self::Error>
117     where
118         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
119     {
120         f(self)
121     }
122
123     #[inline]
124     fn emit_tuple_arg<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
125     where
126         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
127     {
128         f(self)
129     }
130
131     fn emit_tuple_struct<F>(&mut self, _name: &str, len: usize, f: F) -> Result<(), Self::Error>
132     where
133         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
134     {
135         self.emit_tuple(len, f)
136     }
137
138     fn emit_tuple_struct_arg<F>(&mut self, f_idx: usize, f: F) -> Result<(), Self::Error>
139     where
140         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
141     {
142         self.emit_tuple_arg(f_idx, f)
143     }
144
145     // Specialized types:
146     fn emit_option<F>(&mut self, f: F) -> Result<(), Self::Error>
147     where
148         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
149     {
150         self.emit_enum("Option", f)
151     }
152
153     #[inline]
154     fn emit_option_none(&mut self) -> Result<(), Self::Error> {
155         self.emit_enum_variant("None", 0, 0, |_| Ok(()))
156     }
157
158     fn emit_option_some<F>(&mut self, f: F) -> Result<(), Self::Error>
159     where
160         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
161     {
162         self.emit_enum_variant("Some", 1, 1, f)
163     }
164
165     fn emit_seq<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
166     where
167         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
168     {
169         self.emit_usize(len)?;
170         f(self)
171     }
172
173     #[inline]
174     fn emit_seq_elt<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
175     where
176         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
177     {
178         f(self)
179     }
180
181     fn emit_map<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
182     where
183         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
184     {
185         self.emit_usize(len)?;
186         f(self)
187     }
188
189     #[inline]
190     fn emit_map_elt_key<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
191     where
192         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
193     {
194         f(self)
195     }
196
197     #[inline]
198     fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
199     where
200         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
201     {
202         f(self)
203     }
204 }
205
206 pub trait Decoder {
207     type Error;
208
209     // Primitive types:
210     fn read_nil(&mut self) -> Result<(), Self::Error>;
211     fn read_usize(&mut self) -> Result<usize, Self::Error>;
212     fn read_u128(&mut self) -> Result<u128, Self::Error>;
213     fn read_u64(&mut self) -> Result<u64, Self::Error>;
214     fn read_u32(&mut self) -> Result<u32, Self::Error>;
215     fn read_u16(&mut self) -> Result<u16, Self::Error>;
216     fn read_u8(&mut self) -> Result<u8, Self::Error>;
217     fn read_isize(&mut self) -> Result<isize, Self::Error>;
218     fn read_i128(&mut self) -> Result<i128, Self::Error>;
219     fn read_i64(&mut self) -> Result<i64, Self::Error>;
220     fn read_i32(&mut self) -> Result<i32, Self::Error>;
221     fn read_i16(&mut self) -> Result<i16, Self::Error>;
222     fn read_i8(&mut self) -> Result<i8, Self::Error>;
223     fn read_bool(&mut self) -> Result<bool, Self::Error>;
224     fn read_f64(&mut self) -> Result<f64, Self::Error>;
225     fn read_f32(&mut self) -> Result<f32, Self::Error>;
226     fn read_char(&mut self) -> Result<char, Self::Error>;
227     fn read_str(&mut self) -> Result<Cow<'_, str>, Self::Error>;
228     fn read_raw_bytes_into(&mut self, s: &mut [u8]) -> Result<(), Self::Error>;
229
230     // Compound types:
231     #[inline]
232     fn read_enum<T, F>(&mut self, _name: &str, f: F) -> Result<T, Self::Error>
233     where
234         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
235     {
236         f(self)
237     }
238
239     #[inline]
240     fn read_enum_variant<T, F>(&mut self, _names: &[&str], mut f: F) -> Result<T, Self::Error>
241     where
242         F: FnMut(&mut Self, usize) -> Result<T, Self::Error>,
243     {
244         let disr = self.read_usize()?;
245         f(self, disr)
246     }
247
248     #[inline]
249     fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, f: F) -> Result<T, Self::Error>
250     where
251         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
252     {
253         f(self)
254     }
255
256     fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F) -> Result<T, Self::Error>
257     where
258         F: FnMut(&mut Self, usize) -> Result<T, Self::Error>,
259     {
260         self.read_enum_variant(names, f)
261     }
262
263     fn read_enum_struct_variant_field<T, F>(
264         &mut self,
265         _f_name: &str,
266         f_idx: usize,
267         f: F,
268     ) -> Result<T, Self::Error>
269     where
270         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
271     {
272         self.read_enum_variant_arg(f_idx, f)
273     }
274
275     #[inline]
276     fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, f: F) -> Result<T, Self::Error>
277     where
278         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
279     {
280         f(self)
281     }
282
283     #[inline]
284     fn read_struct_field<T, F>(
285         &mut self,
286         _f_name: &str,
287         _f_idx: usize,
288         f: F,
289     ) -> Result<T, Self::Error>
290     where
291         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
292     {
293         f(self)
294     }
295
296     #[inline]
297     fn read_tuple<T, F>(&mut self, _len: usize, f: F) -> Result<T, Self::Error>
298     where
299         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
300     {
301         f(self)
302     }
303
304     #[inline]
305     fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, f: F) -> Result<T, Self::Error>
306     where
307         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
308     {
309         f(self)
310     }
311
312     fn read_tuple_struct<T, F>(&mut self, _s_name: &str, len: usize, f: F) -> Result<T, Self::Error>
313     where
314         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
315     {
316         self.read_tuple(len, f)
317     }
318
319     fn read_tuple_struct_arg<T, F>(&mut self, a_idx: usize, f: F) -> Result<T, Self::Error>
320     where
321         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
322     {
323         self.read_tuple_arg(a_idx, f)
324     }
325
326     // Specialized types:
327     fn read_option<T, F>(&mut self, mut f: F) -> Result<T, Self::Error>
328     where
329         F: FnMut(&mut Self, bool) -> Result<T, Self::Error>,
330     {
331         self.read_enum("Option", move |this| {
332             this.read_enum_variant(&["None", "Some"], move |this, idx| match idx {
333                 0 => f(this, false),
334                 1 => f(this, true),
335                 _ => Err(this.error("read_option: expected 0 for None or 1 for Some")),
336             })
337         })
338     }
339
340     fn read_seq<T, F>(&mut self, f: F) -> Result<T, Self::Error>
341     where
342         F: FnOnce(&mut Self, usize) -> Result<T, Self::Error>,
343     {
344         let len = self.read_usize()?;
345         f(self, len)
346     }
347
348     #[inline]
349     fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error>
350     where
351         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
352     {
353         f(self)
354     }
355
356     fn read_map<T, F>(&mut self, f: F) -> Result<T, Self::Error>
357     where
358         F: FnOnce(&mut Self, usize) -> Result<T, Self::Error>,
359     {
360         let len = self.read_usize()?;
361         f(self, len)
362     }
363
364     #[inline]
365     fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error>
366     where
367         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
368     {
369         f(self)
370     }
371
372     #[inline]
373     fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error>
374     where
375         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
376     {
377         f(self)
378     }
379
380     // Failure
381     fn error(&mut self, err: &str) -> Self::Error;
382 }
383
384 /// Trait for types that can be serialized
385 ///
386 /// This can be implemented using the `Encodable`, `TyEncodable` and
387 /// `MetadataEncodable` macros.
388 ///
389 /// * `Encodable` should be used in crates that don't depend on
390 ///   `rustc_middle`.
391 /// * `MetadataEncodable` is used in `rustc_metadata` for types that contain
392 ///   `rustc_metadata::rmeta::Lazy`.
393 /// * `TyEncodable` should be used for types that are only serialized in crate
394 ///   metadata or the incremental cache. This is most types in `rustc_middle`.
395 pub trait Encodable<S: Encoder> {
396     fn encode(&self, s: &mut S) -> Result<(), S::Error>;
397 }
398
399 /// Trait for types that can be deserialized
400 ///
401 /// This can be implemented using the `Decodable`, `TyDecodable` and
402 /// `MetadataDecodable` macros.
403 ///
404 /// * `Decodable` should be used in crates that don't depend on
405 ///   `rustc_middle`.
406 /// * `MetadataDecodable` is used in `rustc_metadata` for types that contain
407 ///   `rustc_metadata::rmeta::Lazy`.
408 /// * `TyDecodable` should be used for types that are only serialized in crate
409 ///   metadata or the incremental cache. This is most types in `rustc_middle`.
410 pub trait Decodable<D: Decoder>: Sized {
411     fn decode(d: &mut D) -> Result<Self, D::Error>;
412 }
413
414 macro_rules! direct_serialize_impls {
415     ($($ty:ident $emit_method:ident $read_method:ident),*) => {
416         $(
417             impl<S: Encoder> Encodable<S> for $ty {
418                 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
419                     s.$emit_method(*self)
420                 }
421             }
422
423             impl<D: Decoder> Decodable<D> for $ty {
424                 fn decode(d: &mut D) -> Result<$ty, D::Error> {
425                     d.$read_method()
426                 }
427             }
428         )*
429     }
430 }
431
432 direct_serialize_impls! {
433     usize emit_usize read_usize,
434     u8 emit_u8 read_u8,
435     u16 emit_u16 read_u16,
436     u32 emit_u32 read_u32,
437     u64 emit_u64 read_u64,
438     u128 emit_u128 read_u128,
439     isize emit_isize read_isize,
440     i8 emit_i8 read_i8,
441     i16 emit_i16 read_i16,
442     i32 emit_i32 read_i32,
443     i64 emit_i64 read_i64,
444     i128 emit_i128 read_i128,
445     f32 emit_f32 read_f32,
446     f64 emit_f64 read_f64,
447     bool emit_bool read_bool,
448     char emit_char read_char
449 }
450
451 impl<S: Encoder> Encodable<S> for ::std::num::NonZeroU32 {
452     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
453         s.emit_u32(self.get())
454     }
455 }
456
457 impl<D: Decoder> Decodable<D> for ::std::num::NonZeroU32 {
458     fn decode(d: &mut D) -> Result<Self, D::Error> {
459         d.read_u32().map(|d| ::std::num::NonZeroU32::new(d).unwrap())
460     }
461 }
462
463 impl<S: Encoder> Encodable<S> for str {
464     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
465         s.emit_str(self)
466     }
467 }
468
469 impl<S: Encoder> Encodable<S> for &str {
470     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
471         s.emit_str(self)
472     }
473 }
474
475 impl<S: Encoder> Encodable<S> for String {
476     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
477         s.emit_str(&self[..])
478     }
479 }
480
481 impl<D: Decoder> Decodable<D> for String {
482     fn decode(d: &mut D) -> Result<String, D::Error> {
483         Ok(d.read_str()?.into_owned())
484     }
485 }
486
487 impl<S: Encoder> Encodable<S> for () {
488     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
489         s.emit_unit()
490     }
491 }
492
493 impl<D: Decoder> Decodable<D> for () {
494     fn decode(d: &mut D) -> Result<(), D::Error> {
495         d.read_nil()
496     }
497 }
498
499 impl<S: Encoder, T> Encodable<S> for PhantomData<T> {
500     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
501         s.emit_unit()
502     }
503 }
504
505 impl<D: Decoder, T> Decodable<D> for PhantomData<T> {
506     fn decode(d: &mut D) -> Result<PhantomData<T>, D::Error> {
507         d.read_nil()?;
508         Ok(PhantomData)
509     }
510 }
511
512 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Box<[T]> {
513     fn decode(d: &mut D) -> Result<Box<[T]>, D::Error> {
514         let v: Vec<T> = Decodable::decode(d)?;
515         Ok(v.into_boxed_slice())
516     }
517 }
518
519 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Rc<T> {
520     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
521         (**self).encode(s)
522     }
523 }
524
525 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Rc<T> {
526     fn decode(d: &mut D) -> Result<Rc<T>, D::Error> {
527         Ok(Rc::new(Decodable::decode(d)?))
528     }
529 }
530
531 impl<S: Encoder, T: Encodable<S>> Encodable<S> for [T] {
532     default fn encode(&self, s: &mut S) -> Result<(), S::Error> {
533         s.emit_seq(self.len(), |s| {
534             for (i, e) in self.iter().enumerate() {
535                 s.emit_seq_elt(i, |s| e.encode(s))?
536             }
537             Ok(())
538         })
539     }
540 }
541
542 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Vec<T> {
543     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
544         let slice: &[T] = self;
545         slice.encode(s)
546     }
547 }
548
549 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Vec<T> {
550     default fn decode(d: &mut D) -> Result<Vec<T>, D::Error> {
551         d.read_seq(|d, len| {
552             let mut v = Vec::with_capacity(len);
553             for i in 0..len {
554                 v.push(d.read_seq_elt(i, |d| Decodable::decode(d))?);
555             }
556             Ok(v)
557         })
558     }
559 }
560
561 impl<S: Encoder, T: Encodable<S>, const N: usize> Encodable<S> for [T; N] {
562     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
563         let slice: &[T] = self;
564         slice.encode(s)
565     }
566 }
567
568 impl<D: Decoder, const N: usize> Decodable<D> for [u8; N] {
569     fn decode(d: &mut D) -> Result<[u8; N], D::Error> {
570         d.read_seq(|d, len| {
571             assert!(len == N);
572             let mut v = [0u8; N];
573             for i in 0..len {
574                 v[i] = d.read_seq_elt(i, |d| Decodable::decode(d))?;
575             }
576             Ok(v)
577         })
578     }
579 }
580
581 impl<'a, S: Encoder, T: Encodable<S>> Encodable<S> for Cow<'a, [T]>
582 where
583     [T]: ToOwned<Owned = Vec<T>>,
584 {
585     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
586         let slice: &[T] = self;
587         slice.encode(s)
588     }
589 }
590
591 impl<D: Decoder, T: Decodable<D> + ToOwned> Decodable<D> for Cow<'static, [T]>
592 where
593     [T]: ToOwned<Owned = Vec<T>>,
594 {
595     fn decode(d: &mut D) -> Result<Cow<'static, [T]>, D::Error> {
596         let v: Vec<T> = Decodable::decode(d)?;
597         Ok(Cow::Owned(v))
598     }
599 }
600
601 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Option<T> {
602     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
603         s.emit_option(|s| match *self {
604             None => s.emit_option_none(),
605             Some(ref v) => s.emit_option_some(|s| v.encode(s)),
606         })
607     }
608 }
609
610 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Option<T> {
611     fn decode(d: &mut D) -> Result<Option<T>, D::Error> {
612         d.read_option(|d, b| if b { Ok(Some(Decodable::decode(d)?)) } else { Ok(None) })
613     }
614 }
615
616 impl<S: Encoder, T1: Encodable<S>, T2: Encodable<S>> Encodable<S> for Result<T1, T2> {
617     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
618         s.emit_enum("Result", |s| match *self {
619             Ok(ref v) => {
620                 s.emit_enum_variant("Ok", 0, 1, |s| s.emit_enum_variant_arg(0, |s| v.encode(s)))
621             }
622             Err(ref v) => {
623                 s.emit_enum_variant("Err", 1, 1, |s| s.emit_enum_variant_arg(0, |s| v.encode(s)))
624             }
625         })
626     }
627 }
628
629 impl<D: Decoder, T1: Decodable<D>, T2: Decodable<D>> Decodable<D> for Result<T1, T2> {
630     fn decode(d: &mut D) -> Result<Result<T1, T2>, D::Error> {
631         d.read_enum("Result", |d| {
632             d.read_enum_variant(&["Ok", "Err"], |d, disr| match disr {
633                 0 => Ok(Ok(d.read_enum_variant_arg(0, |d| T1::decode(d))?)),
634                 1 => Ok(Err(d.read_enum_variant_arg(0, |d| T2::decode(d))?)),
635                 _ => {
636                     panic!(
637                         "Encountered invalid discriminant while \
638                                 decoding `Result`."
639                     );
640                 }
641             })
642         })
643     }
644 }
645
646 macro_rules! peel {
647     ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
648 }
649
650 /// Evaluates to the number of tokens passed to it.
651 ///
652 /// Logarithmic counting: every one or two recursive expansions, the number of
653 /// tokens to count is divided by two, instead of being reduced by one.
654 /// Therefore, the recursion depth is the binary logarithm of the number of
655 /// tokens to count, and the expanded tree is likewise very small.
656 macro_rules! count {
657     ()                     => (0usize);
658     ($one:tt)              => (1usize);
659     ($($pairs:tt $_p:tt)*) => (count!($($pairs)*) << 1usize);
660     ($odd:tt $($rest:tt)*) => (count!($($rest)*) | 1usize);
661 }
662
663 macro_rules! tuple {
664     () => ();
665     ( $($name:ident,)+ ) => (
666         impl<D: Decoder, $($name: Decodable<D>),+> Decodable<D> for ($($name,)+) {
667             #[allow(non_snake_case)]
668             fn decode(d: &mut D) -> Result<($($name,)+), D::Error> {
669                 let len: usize = count!($($name)+);
670                 d.read_tuple(len, |d| {
671                     let mut i = 0;
672                     let ret = ($(d.read_tuple_arg({ i+=1; i-1 }, |d| -> Result<$name, D::Error> {
673                         Decodable::decode(d)
674                     })?,)+);
675                     Ok(ret)
676                 })
677             }
678         }
679         impl<S: Encoder, $($name: Encodable<S>),+> Encodable<S> for ($($name,)+) {
680             #[allow(non_snake_case)]
681             fn encode(&self, s: &mut S) -> Result<(), S::Error> {
682                 let ($(ref $name,)+) = *self;
683                 let mut n = 0;
684                 $(let $name = $name; n += 1;)+
685                 s.emit_tuple(n, |s| {
686                     let mut i = 0;
687                     $(s.emit_tuple_arg({ i+=1; i-1 }, |s| $name.encode(s))?;)+
688                     Ok(())
689                 })
690             }
691         }
692         peel! { $($name,)+ }
693     )
694 }
695
696 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
697
698 impl<S: Encoder> Encodable<S> for path::Path {
699     fn encode(&self, e: &mut S) -> Result<(), S::Error> {
700         self.to_str().unwrap().encode(e)
701     }
702 }
703
704 impl<S: Encoder> Encodable<S> for path::PathBuf {
705     fn encode(&self, e: &mut S) -> Result<(), S::Error> {
706         path::Path::encode(self, e)
707     }
708 }
709
710 impl<D: Decoder> Decodable<D> for path::PathBuf {
711     fn decode(d: &mut D) -> Result<path::PathBuf, D::Error> {
712         let bytes: String = Decodable::decode(d)?;
713         Ok(path::PathBuf::from(bytes))
714     }
715 }
716
717 impl<S: Encoder, T: Encodable<S> + Copy> Encodable<S> for Cell<T> {
718     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
719         self.get().encode(s)
720     }
721 }
722
723 impl<D: Decoder, T: Decodable<D> + Copy> Decodable<D> for Cell<T> {
724     fn decode(d: &mut D) -> Result<Cell<T>, D::Error> {
725         Ok(Cell::new(Decodable::decode(d)?))
726     }
727 }
728
729 // FIXME: #15036
730 // Should use `try_borrow`, returning a
731 // `encoder.error("attempting to Encode borrowed RefCell")`
732 // from `encode` when `try_borrow` returns `None`.
733
734 impl<S: Encoder, T: Encodable<S>> Encodable<S> for RefCell<T> {
735     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
736         self.borrow().encode(s)
737     }
738 }
739
740 impl<D: Decoder, T: Decodable<D>> Decodable<D> for RefCell<T> {
741     fn decode(d: &mut D) -> Result<RefCell<T>, D::Error> {
742         Ok(RefCell::new(Decodable::decode(d)?))
743     }
744 }
745
746 impl<S: Encoder, T: Encodable<S>> Encodable<S> for Arc<T> {
747     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
748         (**self).encode(s)
749     }
750 }
751
752 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Arc<T> {
753     fn decode(d: &mut D) -> Result<Arc<T>, D::Error> {
754         Ok(Arc::new(Decodable::decode(d)?))
755     }
756 }
757
758 impl<S: Encoder, T: ?Sized + Encodable<S>> Encodable<S> for Box<T> {
759     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
760         (**self).encode(s)
761     }
762 }
763 impl<D: Decoder, T: Decodable<D>> Decodable<D> for Box<T> {
764     fn decode(d: &mut D) -> Result<Box<T>, D::Error> {
765         Ok(box Decodable::decode(d)?)
766     }
767 }