]> git.lizzy.rs Git - rust.git/blob - src/libserialize/serialize.rs
rustc_span: return an impl Iterator instead of a Vec from macro_backtrace.
[rust.git] / src / libserialize / serialize.rs
1 //! Support code for encoding and decoding types.
2
3 /*
4 Core encoding and decoding interfaces.
5 */
6
7 use std::any;
8 use std::borrow::Cow;
9 use std::cell::{Cell, RefCell};
10 use std::marker::PhantomData;
11 use std::path;
12 use std::rc::Rc;
13 use std::sync::Arc;
14
15 pub trait Encoder {
16     type Error;
17
18     // Primitive types:
19     fn emit_unit(&mut self) -> Result<(), Self::Error>;
20     fn emit_usize(&mut self, v: usize) -> Result<(), Self::Error>;
21     fn emit_u128(&mut self, v: u128) -> Result<(), Self::Error>;
22     fn emit_u64(&mut self, v: u64) -> Result<(), Self::Error>;
23     fn emit_u32(&mut self, v: u32) -> Result<(), Self::Error>;
24     fn emit_u16(&mut self, v: u16) -> Result<(), Self::Error>;
25     fn emit_u8(&mut self, v: u8) -> Result<(), Self::Error>;
26     fn emit_isize(&mut self, v: isize) -> Result<(), Self::Error>;
27     fn emit_i128(&mut self, v: i128) -> Result<(), Self::Error>;
28     fn emit_i64(&mut self, v: i64) -> Result<(), Self::Error>;
29     fn emit_i32(&mut self, v: i32) -> Result<(), Self::Error>;
30     fn emit_i16(&mut self, v: i16) -> Result<(), Self::Error>;
31     fn emit_i8(&mut self, v: i8) -> Result<(), Self::Error>;
32     fn emit_bool(&mut self, v: bool) -> Result<(), Self::Error>;
33     fn emit_f64(&mut self, v: f64) -> Result<(), Self::Error>;
34     fn emit_f32(&mut self, v: f32) -> Result<(), Self::Error>;
35     fn emit_char(&mut self, v: char) -> Result<(), Self::Error>;
36     fn emit_str(&mut self, v: &str) -> Result<(), Self::Error>;
37
38     // Compound types:
39     fn emit_enum<F>(&mut self, _name: &str, f: F) -> Result<(), Self::Error>
40     where
41         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
42     {
43         f(self)
44     }
45
46     fn emit_enum_variant<F>(
47         &mut self,
48         _v_name: &str,
49         v_id: usize,
50         _len: usize,
51         f: F,
52     ) -> Result<(), Self::Error>
53     where
54         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
55     {
56         self.emit_usize(v_id)?;
57         f(self)
58     }
59
60     fn emit_enum_variant_arg<F>(&mut self, _a_idx: usize, f: F) -> Result<(), Self::Error>
61     where
62         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
63     {
64         f(self)
65     }
66
67     fn emit_enum_struct_variant<F>(
68         &mut self,
69         v_name: &str,
70         v_id: usize,
71         len: usize,
72         f: F,
73     ) -> Result<(), Self::Error>
74     where
75         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
76     {
77         self.emit_enum_variant(v_name, v_id, len, f)
78     }
79
80     fn emit_enum_struct_variant_field<F>(
81         &mut self,
82         _f_name: &str,
83         f_idx: usize,
84         f: F,
85     ) -> Result<(), Self::Error>
86     where
87         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
88     {
89         self.emit_enum_variant_arg(f_idx, f)
90     }
91
92     fn emit_struct<F>(&mut self, _name: &str, _len: usize, f: F) -> Result<(), Self::Error>
93     where
94         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
95     {
96         f(self)
97     }
98
99     fn emit_struct_field<F>(
100         &mut self,
101         _f_name: &str,
102         _f_idx: usize,
103         f: F,
104     ) -> Result<(), Self::Error>
105     where
106         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
107     {
108         f(self)
109     }
110
111     fn emit_tuple<F>(&mut self, _len: usize, f: F) -> Result<(), Self::Error>
112     where
113         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
114     {
115         f(self)
116     }
117
118     fn emit_tuple_arg<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
119     where
120         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
121     {
122         f(self)
123     }
124
125     fn emit_tuple_struct<F>(&mut self, _name: &str, len: usize, f: F) -> Result<(), Self::Error>
126     where
127         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
128     {
129         self.emit_tuple(len, f)
130     }
131
132     fn emit_tuple_struct_arg<F>(&mut self, f_idx: usize, f: F) -> Result<(), Self::Error>
133     where
134         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
135     {
136         self.emit_tuple_arg(f_idx, f)
137     }
138
139     // Specialized types:
140     fn emit_option<F>(&mut self, f: F) -> Result<(), Self::Error>
141     where
142         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
143     {
144         self.emit_enum("Option", f)
145     }
146
147     #[inline]
148     fn emit_option_none(&mut self) -> Result<(), Self::Error> {
149         self.emit_enum_variant("None", 0, 0, |_| Ok(()))
150     }
151
152     fn emit_option_some<F>(&mut self, f: F) -> Result<(), Self::Error>
153     where
154         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
155     {
156         self.emit_enum_variant("Some", 1, 1, f)
157     }
158
159     fn emit_seq<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
160     where
161         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
162     {
163         self.emit_usize(len)?;
164         f(self)
165     }
166
167     fn emit_seq_elt<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
168     where
169         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
170     {
171         f(self)
172     }
173
174     fn emit_map<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
175     where
176         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
177     {
178         self.emit_usize(len)?;
179         f(self)
180     }
181
182     fn emit_map_elt_key<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
183     where
184         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
185     {
186         f(self)
187     }
188
189     fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
190     where
191         F: FnOnce(&mut Self) -> Result<(), Self::Error>,
192     {
193         f(self)
194     }
195 }
196
197 pub trait Decoder {
198     type Error;
199
200     // Primitive types:
201     fn read_nil(&mut self) -> Result<(), Self::Error>;
202     fn read_usize(&mut self) -> Result<usize, Self::Error>;
203     fn read_u128(&mut self) -> Result<u128, Self::Error>;
204     fn read_u64(&mut self) -> Result<u64, Self::Error>;
205     fn read_u32(&mut self) -> Result<u32, Self::Error>;
206     fn read_u16(&mut self) -> Result<u16, Self::Error>;
207     fn read_u8(&mut self) -> Result<u8, Self::Error>;
208     fn read_isize(&mut self) -> Result<isize, Self::Error>;
209     fn read_i128(&mut self) -> Result<i128, Self::Error>;
210     fn read_i64(&mut self) -> Result<i64, Self::Error>;
211     fn read_i32(&mut self) -> Result<i32, Self::Error>;
212     fn read_i16(&mut self) -> Result<i16, Self::Error>;
213     fn read_i8(&mut self) -> Result<i8, Self::Error>;
214     fn read_bool(&mut self) -> Result<bool, Self::Error>;
215     fn read_f64(&mut self) -> Result<f64, Self::Error>;
216     fn read_f32(&mut self) -> Result<f32, Self::Error>;
217     fn read_char(&mut self) -> Result<char, Self::Error>;
218     fn read_str(&mut self) -> Result<Cow<'_, str>, Self::Error>;
219
220     // Compound types:
221     fn read_enum<T, F>(&mut self, _name: &str, f: F) -> Result<T, Self::Error>
222     where
223         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
224     {
225         f(self)
226     }
227
228     fn read_enum_variant<T, F>(&mut self, _names: &[&str], mut f: F) -> Result<T, Self::Error>
229     where
230         F: FnMut(&mut Self, usize) -> Result<T, Self::Error>,
231     {
232         let disr = self.read_usize()?;
233         f(self, disr)
234     }
235
236     fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, f: F) -> Result<T, Self::Error>
237     where
238         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
239     {
240         f(self)
241     }
242
243     fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F) -> Result<T, Self::Error>
244     where
245         F: FnMut(&mut Self, usize) -> Result<T, Self::Error>,
246     {
247         self.read_enum_variant(names, f)
248     }
249
250     fn read_enum_struct_variant_field<T, F>(
251         &mut self,
252         _f_name: &str,
253         f_idx: usize,
254         f: F,
255     ) -> Result<T, Self::Error>
256     where
257         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
258     {
259         self.read_enum_variant_arg(f_idx, f)
260     }
261
262     fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, f: F) -> Result<T, Self::Error>
263     where
264         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
265     {
266         f(self)
267     }
268
269     fn read_struct_field<T, F>(
270         &mut self,
271         _f_name: &str,
272         _f_idx: usize,
273         f: F,
274     ) -> Result<T, Self::Error>
275     where
276         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
277     {
278         f(self)
279     }
280
281     fn read_tuple<T, F>(&mut self, _len: usize, f: F) -> Result<T, Self::Error>
282     where
283         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
284     {
285         f(self)
286     }
287
288     fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, f: F) -> Result<T, Self::Error>
289     where
290         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
291     {
292         f(self)
293     }
294
295     fn read_tuple_struct<T, F>(&mut self, _s_name: &str, len: usize, f: F) -> Result<T, Self::Error>
296     where
297         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
298     {
299         self.read_tuple(len, f)
300     }
301
302     fn read_tuple_struct_arg<T, F>(&mut self, a_idx: usize, f: F) -> Result<T, Self::Error>
303     where
304         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
305     {
306         self.read_tuple_arg(a_idx, f)
307     }
308
309     // Specialized types:
310     fn read_option<T, F>(&mut self, mut f: F) -> Result<T, Self::Error>
311     where
312         F: FnMut(&mut Self, bool) -> Result<T, Self::Error>,
313     {
314         self.read_enum("Option", move |this| {
315             this.read_enum_variant(&["None", "Some"], move |this, idx| match idx {
316                 0 => f(this, false),
317                 1 => f(this, true),
318                 _ => Err(this.error("read_option: expected 0 for None or 1 for Some")),
319             })
320         })
321     }
322
323     fn read_seq<T, F>(&mut self, f: F) -> Result<T, Self::Error>
324     where
325         F: FnOnce(&mut Self, usize) -> Result<T, Self::Error>,
326     {
327         let len = self.read_usize()?;
328         f(self, len)
329     }
330
331     fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error>
332     where
333         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
334     {
335         f(self)
336     }
337
338     fn read_map<T, F>(&mut self, f: F) -> Result<T, Self::Error>
339     where
340         F: FnOnce(&mut Self, usize) -> Result<T, Self::Error>,
341     {
342         let len = self.read_usize()?;
343         f(self, len)
344     }
345
346     fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error>
347     where
348         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
349     {
350         f(self)
351     }
352
353     fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error>
354     where
355         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
356     {
357         f(self)
358     }
359
360     // Failure
361     fn error(&mut self, err: &str) -> Self::Error;
362 }
363
364 pub trait Encodable {
365     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error>;
366 }
367
368 pub trait Decodable: Sized {
369     fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error>;
370 }
371
372 impl Encodable for usize {
373     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
374         s.emit_usize(*self)
375     }
376 }
377
378 impl Decodable for usize {
379     fn decode<D: Decoder>(d: &mut D) -> Result<usize, D::Error> {
380         d.read_usize()
381     }
382 }
383
384 impl Encodable for u8 {
385     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
386         s.emit_u8(*self)
387     }
388 }
389
390 impl Decodable for u8 {
391     fn decode<D: Decoder>(d: &mut D) -> Result<u8, D::Error> {
392         d.read_u8()
393     }
394 }
395
396 impl Encodable for u16 {
397     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
398         s.emit_u16(*self)
399     }
400 }
401
402 impl Decodable for u16 {
403     fn decode<D: Decoder>(d: &mut D) -> Result<u16, D::Error> {
404         d.read_u16()
405     }
406 }
407
408 impl Encodable for u32 {
409     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
410         s.emit_u32(*self)
411     }
412 }
413
414 impl Decodable for u32 {
415     fn decode<D: Decoder>(d: &mut D) -> Result<u32, D::Error> {
416         d.read_u32()
417     }
418 }
419
420 impl Encodable for ::std::num::NonZeroU32 {
421     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
422         s.emit_u32(self.get())
423     }
424 }
425
426 impl Decodable for ::std::num::NonZeroU32 {
427     fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
428         d.read_u32().map(|d| ::std::num::NonZeroU32::new(d).unwrap())
429     }
430 }
431
432 impl Encodable for u64 {
433     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
434         s.emit_u64(*self)
435     }
436 }
437
438 impl Decodable for u64 {
439     fn decode<D: Decoder>(d: &mut D) -> Result<u64, D::Error> {
440         d.read_u64()
441     }
442 }
443
444 impl Encodable for u128 {
445     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
446         s.emit_u128(*self)
447     }
448 }
449
450 impl Decodable for u128 {
451     fn decode<D: Decoder>(d: &mut D) -> Result<u128, D::Error> {
452         d.read_u128()
453     }
454 }
455
456 impl Encodable for isize {
457     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
458         s.emit_isize(*self)
459     }
460 }
461
462 impl Decodable for isize {
463     fn decode<D: Decoder>(d: &mut D) -> Result<isize, D::Error> {
464         d.read_isize()
465     }
466 }
467
468 impl Encodable for i8 {
469     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
470         s.emit_i8(*self)
471     }
472 }
473
474 impl Decodable for i8 {
475     fn decode<D: Decoder>(d: &mut D) -> Result<i8, D::Error> {
476         d.read_i8()
477     }
478 }
479
480 impl Encodable for i16 {
481     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
482         s.emit_i16(*self)
483     }
484 }
485
486 impl Decodable for i16 {
487     fn decode<D: Decoder>(d: &mut D) -> Result<i16, D::Error> {
488         d.read_i16()
489     }
490 }
491
492 impl Encodable for i32 {
493     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
494         s.emit_i32(*self)
495     }
496 }
497
498 impl Decodable for i32 {
499     fn decode<D: Decoder>(d: &mut D) -> Result<i32, D::Error> {
500         d.read_i32()
501     }
502 }
503
504 impl Encodable for i64 {
505     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
506         s.emit_i64(*self)
507     }
508 }
509
510 impl Decodable for i64 {
511     fn decode<D: Decoder>(d: &mut D) -> Result<i64, D::Error> {
512         d.read_i64()
513     }
514 }
515
516 impl Encodable for i128 {
517     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
518         s.emit_i128(*self)
519     }
520 }
521
522 impl Decodable for i128 {
523     fn decode<D: Decoder>(d: &mut D) -> Result<i128, D::Error> {
524         d.read_i128()
525     }
526 }
527
528 impl Encodable for str {
529     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
530         s.emit_str(self)
531     }
532 }
533
534 impl Encodable for String {
535     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
536         s.emit_str(&self[..])
537     }
538 }
539
540 impl Decodable for String {
541     fn decode<D: Decoder>(d: &mut D) -> Result<String, D::Error> {
542         Ok(d.read_str()?.into_owned())
543     }
544 }
545
546 impl Encodable for f32 {
547     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
548         s.emit_f32(*self)
549     }
550 }
551
552 impl Decodable for f32 {
553     fn decode<D: Decoder>(d: &mut D) -> Result<f32, D::Error> {
554         d.read_f32()
555     }
556 }
557
558 impl Encodable for f64 {
559     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
560         s.emit_f64(*self)
561     }
562 }
563
564 impl Decodable for f64 {
565     fn decode<D: Decoder>(d: &mut D) -> Result<f64, D::Error> {
566         d.read_f64()
567     }
568 }
569
570 impl Encodable for bool {
571     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
572         s.emit_bool(*self)
573     }
574 }
575
576 impl Decodable for bool {
577     fn decode<D: Decoder>(d: &mut D) -> Result<bool, D::Error> {
578         d.read_bool()
579     }
580 }
581
582 impl Encodable for char {
583     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
584         s.emit_char(*self)
585     }
586 }
587
588 impl Decodable for char {
589     fn decode<D: Decoder>(d: &mut D) -> Result<char, D::Error> {
590         d.read_char()
591     }
592 }
593
594 impl Encodable for () {
595     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
596         s.emit_unit()
597     }
598 }
599
600 impl Decodable for () {
601     fn decode<D: Decoder>(d: &mut D) -> Result<(), D::Error> {
602         d.read_nil()
603     }
604 }
605
606 impl<T> Encodable for PhantomData<T> {
607     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
608         s.emit_unit()
609     }
610 }
611
612 impl<T> Decodable for PhantomData<T> {
613     fn decode<D: Decoder>(d: &mut D) -> Result<PhantomData<T>, D::Error> {
614         d.read_nil()?;
615         Ok(PhantomData)
616     }
617 }
618
619 impl<'a, T: ?Sized + Encodable> Encodable for &'a T {
620     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
621         (**self).encode(s)
622     }
623 }
624
625 impl<T: ?Sized + Encodable> Encodable for Box<T> {
626     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
627         (**self).encode(s)
628     }
629 }
630
631 impl<T: Decodable> Decodable for Box<T> {
632     fn decode<D: Decoder>(d: &mut D) -> Result<Box<T>, D::Error> {
633         Ok(box Decodable::decode(d)?)
634     }
635 }
636
637 impl<T: Decodable> Decodable for Box<[T]> {
638     fn decode<D: Decoder>(d: &mut D) -> Result<Box<[T]>, D::Error> {
639         let v: Vec<T> = Decodable::decode(d)?;
640         Ok(v.into_boxed_slice())
641     }
642 }
643
644 impl<T: Encodable> Encodable for Rc<T> {
645     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
646         (**self).encode(s)
647     }
648 }
649
650 impl<T: Decodable> Decodable for Rc<T> {
651     fn decode<D: Decoder>(d: &mut D) -> Result<Rc<T>, D::Error> {
652         Ok(Rc::new(Decodable::decode(d)?))
653     }
654 }
655
656 impl<T: Encodable> Encodable for [T] {
657     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
658         s.emit_seq(self.len(), |s| {
659             for (i, e) in self.iter().enumerate() {
660                 s.emit_seq_elt(i, |s| e.encode(s))?
661             }
662             Ok(())
663         })
664     }
665 }
666
667 impl<T: Encodable> Encodable for Vec<T> {
668     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
669         s.emit_seq(self.len(), |s| {
670             for (i, e) in self.iter().enumerate() {
671                 s.emit_seq_elt(i, |s| e.encode(s))?
672             }
673             Ok(())
674         })
675     }
676 }
677
678 impl<T: Decodable> Decodable for Vec<T> {
679     fn decode<D: Decoder>(d: &mut D) -> Result<Vec<T>, D::Error> {
680         d.read_seq(|d, len| {
681             let mut v = Vec::with_capacity(len);
682             for i in 0..len {
683                 v.push(d.read_seq_elt(i, |d| Decodable::decode(d))?);
684             }
685             Ok(v)
686         })
687     }
688 }
689
690 impl<'a, T: Encodable> Encodable for Cow<'a, [T]>
691 where
692     [T]: ToOwned<Owned = Vec<T>>,
693 {
694     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
695         s.emit_seq(self.len(), |s| {
696             for (i, e) in self.iter().enumerate() {
697                 s.emit_seq_elt(i, |s| e.encode(s))?
698             }
699             Ok(())
700         })
701     }
702 }
703
704 impl<T: Decodable + ToOwned> Decodable for Cow<'static, [T]>
705 where
706     [T]: ToOwned<Owned = Vec<T>>,
707 {
708     fn decode<D: Decoder>(d: &mut D) -> Result<Cow<'static, [T]>, D::Error> {
709         d.read_seq(|d, len| {
710             let mut v = Vec::with_capacity(len);
711             for i in 0..len {
712                 v.push(d.read_seq_elt(i, |d| Decodable::decode(d))?);
713             }
714             Ok(Cow::Owned(v))
715         })
716     }
717 }
718
719 impl<T: Encodable> Encodable for Option<T> {
720     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
721         s.emit_option(|s| match *self {
722             None => s.emit_option_none(),
723             Some(ref v) => s.emit_option_some(|s| v.encode(s)),
724         })
725     }
726 }
727
728 impl<T: Decodable> Decodable for Option<T> {
729     fn decode<D: Decoder>(d: &mut D) -> Result<Option<T>, D::Error> {
730         d.read_option(|d, b| if b { Ok(Some(Decodable::decode(d)?)) } else { Ok(None) })
731     }
732 }
733
734 impl<T1: Encodable, T2: Encodable> Encodable for Result<T1, T2> {
735     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
736         s.emit_enum("Result", |s| match *self {
737             Ok(ref v) => {
738                 s.emit_enum_variant("Ok", 0, 1, |s| s.emit_enum_variant_arg(0, |s| v.encode(s)))
739             }
740             Err(ref v) => {
741                 s.emit_enum_variant("Err", 1, 1, |s| s.emit_enum_variant_arg(0, |s| v.encode(s)))
742             }
743         })
744     }
745 }
746
747 impl<T1: Decodable, T2: Decodable> Decodable for Result<T1, T2> {
748     fn decode<D: Decoder>(d: &mut D) -> Result<Result<T1, T2>, D::Error> {
749         d.read_enum("Result", |d| {
750             d.read_enum_variant(&["Ok", "Err"], |d, disr| match disr {
751                 0 => Ok(Ok(d.read_enum_variant_arg(0, |d| T1::decode(d))?)),
752                 1 => Ok(Err(d.read_enum_variant_arg(0, |d| T2::decode(d))?)),
753                 _ => {
754                     panic!(
755                         "Encountered invalid discriminant while \
756                                 decoding `Result`."
757                     );
758                 }
759             })
760         })
761     }
762 }
763
764 macro_rules! peel {
765     ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
766 }
767
768 /// Evaluates to the number of tokens passed to it.
769 ///
770 /// Logarithmic counting: every one or two recursive expansions, the number of
771 /// tokens to count is divided by two, instead of being reduced by one.
772 /// Therefore, the recursion depth is the binary logarithm of the number of
773 /// tokens to count, and the expanded tree is likewise very small.
774 macro_rules! count {
775     ()                     => (0usize);
776     ($one:tt)              => (1usize);
777     ($($pairs:tt $_p:tt)*) => (count!($($pairs)*) << 1usize);
778     ($odd:tt $($rest:tt)*) => (count!($($rest)*) | 1usize);
779 }
780
781 macro_rules! tuple {
782     () => ();
783     ( $($name:ident,)+ ) => (
784         impl<$($name:Decodable),+> Decodable for ($($name,)+) {
785             #[allow(non_snake_case)]
786             fn decode<D: Decoder>(d: &mut D) -> Result<($($name,)+), D::Error> {
787                 let len: usize = count!($($name)+);
788                 d.read_tuple(len, |d| {
789                     let mut i = 0;
790                     let ret = ($(d.read_tuple_arg({ i+=1; i-1 }, |d| -> Result<$name, D::Error> {
791                         Decodable::decode(d)
792                     })?,)+);
793                     Ok(ret)
794                 })
795             }
796         }
797         impl<$($name:Encodable),+> Encodable for ($($name,)+) {
798             #[allow(non_snake_case)]
799             fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
800                 let ($(ref $name,)+) = *self;
801                 let mut n = 0;
802                 $(let $name = $name; n += 1;)+
803                 s.emit_tuple(n, |s| {
804                     let mut i = 0;
805                     $(s.emit_tuple_arg({ i+=1; i-1 }, |s| $name.encode(s))?;)+
806                     Ok(())
807                 })
808             }
809         }
810         peel! { $($name,)+ }
811     )
812 }
813
814 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
815
816 impl Encodable for path::Path {
817     fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> {
818         self.to_str().unwrap().encode(e)
819     }
820 }
821
822 impl Encodable for path::PathBuf {
823     fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> {
824         path::Path::encode(self, e)
825     }
826 }
827
828 impl Decodable for path::PathBuf {
829     fn decode<D: Decoder>(d: &mut D) -> Result<path::PathBuf, D::Error> {
830         let bytes: String = Decodable::decode(d)?;
831         Ok(path::PathBuf::from(bytes))
832     }
833 }
834
835 impl<T: Encodable + Copy> Encodable for Cell<T> {
836     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
837         self.get().encode(s)
838     }
839 }
840
841 impl<T: Decodable + Copy> Decodable for Cell<T> {
842     fn decode<D: Decoder>(d: &mut D) -> Result<Cell<T>, D::Error> {
843         Ok(Cell::new(Decodable::decode(d)?))
844     }
845 }
846
847 // FIXME: #15036
848 // Should use `try_borrow`, returning a
849 // `encoder.error("attempting to Encode borrowed RefCell")`
850 // from `encode` when `try_borrow` returns `None`.
851
852 impl<T: Encodable> Encodable for RefCell<T> {
853     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
854         self.borrow().encode(s)
855     }
856 }
857
858 impl<T: Decodable> Decodable for RefCell<T> {
859     fn decode<D: Decoder>(d: &mut D) -> Result<RefCell<T>, D::Error> {
860         Ok(RefCell::new(Decodable::decode(d)?))
861     }
862 }
863
864 impl<T: Encodable> Encodable for Arc<T> {
865     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
866         (**self).encode(s)
867     }
868 }
869
870 impl<T: Decodable> Decodable for Arc<T> {
871     fn decode<D: Decoder>(d: &mut D) -> Result<Arc<T>, D::Error> {
872         Ok(Arc::new(Decodable::decode(d)?))
873     }
874 }
875
876 // ___________________________________________________________________________
877 // Specialization-based interface for multi-dispatch Encodable/Decodable.
878
879 /// Implement this trait on your `{Encodable,Decodable}::Error` types
880 /// to override the default panic behavior for missing specializations.
881 pub trait SpecializationError {
882     /// Creates an error for a missing method specialization.
883     /// Defaults to panicking with type, trait & method names.
884     /// `S` is the encoder/decoder state type,
885     /// `T` is the type being encoded/decoded, and
886     /// the arguments are the names of the trait
887     /// and method that should've been overridden.
888     fn not_found<S, T: ?Sized>(trait_name: &'static str, method_name: &'static str) -> Self;
889 }
890
891 impl<E> SpecializationError for E {
892     default fn not_found<S, T: ?Sized>(trait_name: &'static str, method_name: &'static str) -> E {
893         panic!(
894             "missing specialization: `<{} as {}<{}>>::{}` not overridden",
895             any::type_name::<S>(),
896             trait_name,
897             any::type_name::<T>(),
898             method_name
899         );
900     }
901 }
902
903 /// Implement this trait on encoders, with `T` being the type
904 /// you want to encode (employing `UseSpecializedEncodable`),
905 /// using a strategy specific to the encoder.
906 pub trait SpecializedEncoder<T: ?Sized + UseSpecializedEncodable>: Encoder {
907     /// Encode the value in a manner specific to this encoder state.
908     fn specialized_encode(&mut self, value: &T) -> Result<(), Self::Error>;
909 }
910
911 impl<E: Encoder, T: ?Sized + UseSpecializedEncodable> SpecializedEncoder<T> for E {
912     default fn specialized_encode(&mut self, value: &T) -> Result<(), E::Error> {
913         value.default_encode(self)
914     }
915 }
916
917 /// Implement this trait on decoders, with `T` being the type
918 /// you want to decode (employing `UseSpecializedDecodable`),
919 /// using a strategy specific to the decoder.
920 pub trait SpecializedDecoder<T: UseSpecializedDecodable>: Decoder {
921     /// Decode a value in a manner specific to this decoder state.
922     fn specialized_decode(&mut self) -> Result<T, Self::Error>;
923 }
924
925 impl<D: Decoder, T: UseSpecializedDecodable> SpecializedDecoder<T> for D {
926     default fn specialized_decode(&mut self) -> Result<T, D::Error> {
927         T::default_decode(self)
928     }
929 }
930
931 /// Implement this trait on your type to get an `Encodable`
932 /// implementation which goes through `SpecializedEncoder`.
933 pub trait UseSpecializedEncodable {
934     /// Defaults to returning an error (see `SpecializationError`).
935     fn default_encode<E: Encoder>(&self, _: &mut E) -> Result<(), E::Error> {
936         Err(E::Error::not_found::<E, Self>("SpecializedEncoder", "specialized_encode"))
937     }
938 }
939
940 impl<T: ?Sized + UseSpecializedEncodable> Encodable for T {
941     default fn encode<E: Encoder>(&self, e: &mut E) -> Result<(), E::Error> {
942         E::specialized_encode(e, self)
943     }
944 }
945
946 /// Implement this trait on your type to get an `Decodable`
947 /// implementation which goes through `SpecializedDecoder`.
948 pub trait UseSpecializedDecodable: Sized {
949     /// Defaults to returning an error (see `SpecializationError`).
950     fn default_decode<D: Decoder>(_: &mut D) -> Result<Self, D::Error> {
951         Err(D::Error::not_found::<D, Self>("SpecializedDecoder", "specialized_decode"))
952     }
953 }
954
955 impl<T: UseSpecializedDecodable> Decodable for T {
956     default fn decode<D: Decoder>(d: &mut D) -> Result<T, D::Error> {
957         D::specialized_decode(d)
958     }
959 }
960
961 // Can't avoid specialization for &T and Box<T> impls,
962 // as proxy impls on them are blankets that conflict
963 // with the Encodable and Decodable impls above,
964 // which only have `default` on their methods
965 // for this exact reason.
966 // May be fixable in a simpler fashion via the
967 // more complex lattice model for specialization.
968 impl<'a, T: ?Sized + Encodable> UseSpecializedEncodable for &'a T {}
969 impl<T: ?Sized + Encodable> UseSpecializedEncodable for Box<T> {}
970 impl<T: Decodable> UseSpecializedDecodable for Box<T> {}
971 impl<'a, T: Decodable> UseSpecializedDecodable for &'a T {}
972 impl<'a, T: Decodable> UseSpecializedDecodable for &'a [T] {}