]> git.lizzy.rs Git - rust.git/blob - src/librustc_serialize/serialize.rs
29c5737ad895abc8b834394fcb6f328ddefb1ee4
[rust.git] / src / librustc_serialize / 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     #[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
229     // Compound types:
230     #[inline]
231     fn read_enum<T, F>(&mut self, _name: &str, f: F) -> Result<T, Self::Error>
232     where
233         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
234     {
235         f(self)
236     }
237
238     #[inline]
239     fn read_enum_variant<T, F>(&mut self, _names: &[&str], mut f: F) -> Result<T, Self::Error>
240     where
241         F: FnMut(&mut Self, usize) -> Result<T, Self::Error>,
242     {
243         let disr = self.read_usize()?;
244         f(self, disr)
245     }
246
247     #[inline]
248     fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, f: F) -> Result<T, Self::Error>
249     where
250         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
251     {
252         f(self)
253     }
254
255     fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F) -> Result<T, Self::Error>
256     where
257         F: FnMut(&mut Self, usize) -> Result<T, Self::Error>,
258     {
259         self.read_enum_variant(names, f)
260     }
261
262     fn read_enum_struct_variant_field<T, F>(
263         &mut self,
264         _f_name: &str,
265         f_idx: usize,
266         f: F,
267     ) -> Result<T, Self::Error>
268     where
269         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
270     {
271         self.read_enum_variant_arg(f_idx, f)
272     }
273
274     #[inline]
275     fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, f: F) -> Result<T, Self::Error>
276     where
277         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
278     {
279         f(self)
280     }
281
282     #[inline]
283     fn read_struct_field<T, F>(
284         &mut self,
285         _f_name: &str,
286         _f_idx: usize,
287         f: F,
288     ) -> Result<T, Self::Error>
289     where
290         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
291     {
292         f(self)
293     }
294
295     #[inline]
296     fn read_tuple<T, F>(&mut self, _len: usize, f: F) -> Result<T, Self::Error>
297     where
298         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
299     {
300         f(self)
301     }
302
303     #[inline]
304     fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, f: F) -> Result<T, Self::Error>
305     where
306         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
307     {
308         f(self)
309     }
310
311     fn read_tuple_struct<T, F>(&mut self, _s_name: &str, len: usize, f: F) -> Result<T, Self::Error>
312     where
313         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
314     {
315         self.read_tuple(len, f)
316     }
317
318     fn read_tuple_struct_arg<T, F>(&mut self, a_idx: usize, f: F) -> Result<T, Self::Error>
319     where
320         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
321     {
322         self.read_tuple_arg(a_idx, f)
323     }
324
325     // Specialized types:
326     fn read_option<T, F>(&mut self, mut f: F) -> Result<T, Self::Error>
327     where
328         F: FnMut(&mut Self, bool) -> Result<T, Self::Error>,
329     {
330         self.read_enum("Option", move |this| {
331             this.read_enum_variant(&["None", "Some"], move |this, idx| match idx {
332                 0 => f(this, false),
333                 1 => f(this, true),
334                 _ => Err(this.error("read_option: expected 0 for None or 1 for Some")),
335             })
336         })
337     }
338
339     fn read_seq<T, F>(&mut self, f: F) -> Result<T, Self::Error>
340     where
341         F: FnOnce(&mut Self, usize) -> Result<T, Self::Error>,
342     {
343         let len = self.read_usize()?;
344         f(self, len)
345     }
346
347     #[inline]
348     fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error>
349     where
350         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
351     {
352         f(self)
353     }
354
355     fn read_map<T, F>(&mut self, f: F) -> Result<T, Self::Error>
356     where
357         F: FnOnce(&mut Self, usize) -> Result<T, Self::Error>,
358     {
359         let len = self.read_usize()?;
360         f(self, len)
361     }
362
363     #[inline]
364     fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error>
365     where
366         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
367     {
368         f(self)
369     }
370
371     #[inline]
372     fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error>
373     where
374         F: FnOnce(&mut Self) -> Result<T, Self::Error>,
375     {
376         f(self)
377     }
378
379     // Failure
380     fn error(&mut self, err: &str) -> Self::Error;
381 }
382
383 pub trait Encodable {
384     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error>;
385 }
386
387 pub trait Decodable: Sized {
388     fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error>;
389 }
390
391 impl Encodable for usize {
392     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
393         s.emit_usize(*self)
394     }
395 }
396
397 impl Decodable for usize {
398     fn decode<D: Decoder>(d: &mut D) -> Result<usize, D::Error> {
399         d.read_usize()
400     }
401 }
402
403 impl Encodable for u8 {
404     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
405         s.emit_u8(*self)
406     }
407 }
408
409 impl Decodable for u8 {
410     fn decode<D: Decoder>(d: &mut D) -> Result<u8, D::Error> {
411         d.read_u8()
412     }
413 }
414
415 impl Encodable for u16 {
416     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
417         s.emit_u16(*self)
418     }
419 }
420
421 impl Decodable for u16 {
422     fn decode<D: Decoder>(d: &mut D) -> Result<u16, D::Error> {
423         d.read_u16()
424     }
425 }
426
427 impl Encodable for u32 {
428     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
429         s.emit_u32(*self)
430     }
431 }
432
433 impl Decodable for u32 {
434     fn decode<D: Decoder>(d: &mut D) -> Result<u32, D::Error> {
435         d.read_u32()
436     }
437 }
438
439 impl Encodable for ::std::num::NonZeroU32 {
440     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
441         s.emit_u32(self.get())
442     }
443 }
444
445 impl Decodable for ::std::num::NonZeroU32 {
446     fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
447         d.read_u32().map(|d| ::std::num::NonZeroU32::new(d).unwrap())
448     }
449 }
450
451 impl Encodable for u64 {
452     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
453         s.emit_u64(*self)
454     }
455 }
456
457 impl Decodable for u64 {
458     fn decode<D: Decoder>(d: &mut D) -> Result<u64, D::Error> {
459         d.read_u64()
460     }
461 }
462
463 impl Encodable for u128 {
464     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
465         s.emit_u128(*self)
466     }
467 }
468
469 impl Decodable for u128 {
470     fn decode<D: Decoder>(d: &mut D) -> Result<u128, D::Error> {
471         d.read_u128()
472     }
473 }
474
475 impl Encodable for isize {
476     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
477         s.emit_isize(*self)
478     }
479 }
480
481 impl Decodable for isize {
482     fn decode<D: Decoder>(d: &mut D) -> Result<isize, D::Error> {
483         d.read_isize()
484     }
485 }
486
487 impl Encodable for i8 {
488     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
489         s.emit_i8(*self)
490     }
491 }
492
493 impl Decodable for i8 {
494     fn decode<D: Decoder>(d: &mut D) -> Result<i8, D::Error> {
495         d.read_i8()
496     }
497 }
498
499 impl Encodable for i16 {
500     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
501         s.emit_i16(*self)
502     }
503 }
504
505 impl Decodable for i16 {
506     fn decode<D: Decoder>(d: &mut D) -> Result<i16, D::Error> {
507         d.read_i16()
508     }
509 }
510
511 impl Encodable for i32 {
512     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
513         s.emit_i32(*self)
514     }
515 }
516
517 impl Decodable for i32 {
518     fn decode<D: Decoder>(d: &mut D) -> Result<i32, D::Error> {
519         d.read_i32()
520     }
521 }
522
523 impl Encodable for i64 {
524     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
525         s.emit_i64(*self)
526     }
527 }
528
529 impl Decodable for i64 {
530     fn decode<D: Decoder>(d: &mut D) -> Result<i64, D::Error> {
531         d.read_i64()
532     }
533 }
534
535 impl Encodable for i128 {
536     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
537         s.emit_i128(*self)
538     }
539 }
540
541 impl Decodable for i128 {
542     fn decode<D: Decoder>(d: &mut D) -> Result<i128, D::Error> {
543         d.read_i128()
544     }
545 }
546
547 impl Encodable for str {
548     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
549         s.emit_str(self)
550     }
551 }
552
553 impl Encodable for String {
554     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
555         s.emit_str(&self[..])
556     }
557 }
558
559 impl Decodable for String {
560     fn decode<D: Decoder>(d: &mut D) -> Result<String, D::Error> {
561         Ok(d.read_str()?.into_owned())
562     }
563 }
564
565 impl Encodable for f32 {
566     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
567         s.emit_f32(*self)
568     }
569 }
570
571 impl Decodable for f32 {
572     fn decode<D: Decoder>(d: &mut D) -> Result<f32, D::Error> {
573         d.read_f32()
574     }
575 }
576
577 impl Encodable for f64 {
578     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
579         s.emit_f64(*self)
580     }
581 }
582
583 impl Decodable for f64 {
584     fn decode<D: Decoder>(d: &mut D) -> Result<f64, D::Error> {
585         d.read_f64()
586     }
587 }
588
589 impl Encodable for bool {
590     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
591         s.emit_bool(*self)
592     }
593 }
594
595 impl Decodable for bool {
596     fn decode<D: Decoder>(d: &mut D) -> Result<bool, D::Error> {
597         d.read_bool()
598     }
599 }
600
601 impl Encodable for char {
602     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
603         s.emit_char(*self)
604     }
605 }
606
607 impl Decodable for char {
608     fn decode<D: Decoder>(d: &mut D) -> Result<char, D::Error> {
609         d.read_char()
610     }
611 }
612
613 impl Encodable for () {
614     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
615         s.emit_unit()
616     }
617 }
618
619 impl Decodable for () {
620     fn decode<D: Decoder>(d: &mut D) -> Result<(), D::Error> {
621         d.read_nil()
622     }
623 }
624
625 impl<T> Encodable for PhantomData<T> {
626     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
627         s.emit_unit()
628     }
629 }
630
631 impl<T> Decodable for PhantomData<T> {
632     fn decode<D: Decoder>(d: &mut D) -> Result<PhantomData<T>, D::Error> {
633         d.read_nil()?;
634         Ok(PhantomData)
635     }
636 }
637
638 impl<T: Decodable> Decodable for Box<[T]> {
639     fn decode<D: Decoder>(d: &mut D) -> Result<Box<[T]>, D::Error> {
640         let v: Vec<T> = Decodable::decode(d)?;
641         Ok(v.into_boxed_slice())
642     }
643 }
644
645 impl<T: Encodable> Encodable for Rc<T> {
646     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
647         (**self).encode(s)
648     }
649 }
650
651 impl<T: Decodable> Decodable for Rc<T> {
652     fn decode<D: Decoder>(d: &mut D) -> Result<Rc<T>, D::Error> {
653         Ok(Rc::new(Decodable::decode(d)?))
654     }
655 }
656
657 impl<T: Encodable> Encodable for [T] {
658     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
659         s.emit_seq(self.len(), |s| {
660             for (i, e) in self.iter().enumerate() {
661                 s.emit_seq_elt(i, |s| e.encode(s))?
662             }
663             Ok(())
664         })
665     }
666 }
667
668 impl<T: Encodable> Encodable for Vec<T> {
669     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
670         s.emit_seq(self.len(), |s| {
671             for (i, e) in self.iter().enumerate() {
672                 s.emit_seq_elt(i, |s| e.encode(s))?
673             }
674             Ok(())
675         })
676     }
677 }
678
679 impl<T: Decodable> Decodable for Vec<T> {
680     fn decode<D: Decoder>(d: &mut D) -> Result<Vec<T>, D::Error> {
681         d.read_seq(|d, len| {
682             let mut v = Vec::with_capacity(len);
683             for i in 0..len {
684                 v.push(d.read_seq_elt(i, |d| Decodable::decode(d))?);
685             }
686             Ok(v)
687         })
688     }
689 }
690
691 impl Encodable for [u8; 20] {
692     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
693         s.emit_seq(self.len(), |s| {
694             for (i, e) in self.iter().enumerate() {
695                 s.emit_seq_elt(i, |s| e.encode(s))?
696             }
697             Ok(())
698         })
699     }
700 }
701
702 impl Decodable for [u8; 20] {
703     fn decode<D: Decoder>(d: &mut D) -> Result<[u8; 20], D::Error> {
704         d.read_seq(|d, len| {
705             assert!(len == 20);
706             let mut v = [0u8; 20];
707             for i in 0..len {
708                 v[i] = d.read_seq_elt(i, |d| Decodable::decode(d))?;
709             }
710             Ok(v)
711         })
712     }
713 }
714
715 impl<'a, T: Encodable> Encodable for Cow<'a, [T]>
716 where
717     [T]: ToOwned<Owned = Vec<T>>,
718 {
719     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
720         s.emit_seq(self.len(), |s| {
721             for (i, e) in self.iter().enumerate() {
722                 s.emit_seq_elt(i, |s| e.encode(s))?
723             }
724             Ok(())
725         })
726     }
727 }
728
729 impl<T: Decodable + ToOwned> Decodable for Cow<'static, [T]>
730 where
731     [T]: ToOwned<Owned = Vec<T>>,
732 {
733     fn decode<D: Decoder>(d: &mut D) -> Result<Cow<'static, [T]>, D::Error> {
734         d.read_seq(|d, len| {
735             let mut v = Vec::with_capacity(len);
736             for i in 0..len {
737                 v.push(d.read_seq_elt(i, |d| Decodable::decode(d))?);
738             }
739             Ok(Cow::Owned(v))
740         })
741     }
742 }
743
744 impl<T: Encodable> Encodable for Option<T> {
745     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
746         s.emit_option(|s| match *self {
747             None => s.emit_option_none(),
748             Some(ref v) => s.emit_option_some(|s| v.encode(s)),
749         })
750     }
751 }
752
753 impl<T: Decodable> Decodable for Option<T> {
754     fn decode<D: Decoder>(d: &mut D) -> Result<Option<T>, D::Error> {
755         d.read_option(|d, b| if b { Ok(Some(Decodable::decode(d)?)) } else { Ok(None) })
756     }
757 }
758
759 impl<T1: Encodable, T2: Encodable> Encodable for Result<T1, T2> {
760     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
761         s.emit_enum("Result", |s| match *self {
762             Ok(ref v) => {
763                 s.emit_enum_variant("Ok", 0, 1, |s| s.emit_enum_variant_arg(0, |s| v.encode(s)))
764             }
765             Err(ref v) => {
766                 s.emit_enum_variant("Err", 1, 1, |s| s.emit_enum_variant_arg(0, |s| v.encode(s)))
767             }
768         })
769     }
770 }
771
772 impl<T1: Decodable, T2: Decodable> Decodable for Result<T1, T2> {
773     fn decode<D: Decoder>(d: &mut D) -> Result<Result<T1, T2>, D::Error> {
774         d.read_enum("Result", |d| {
775             d.read_enum_variant(&["Ok", "Err"], |d, disr| match disr {
776                 0 => Ok(Ok(d.read_enum_variant_arg(0, |d| T1::decode(d))?)),
777                 1 => Ok(Err(d.read_enum_variant_arg(0, |d| T2::decode(d))?)),
778                 _ => {
779                     panic!(
780                         "Encountered invalid discriminant while \
781                                 decoding `Result`."
782                     );
783                 }
784             })
785         })
786     }
787 }
788
789 macro_rules! peel {
790     ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
791 }
792
793 /// Evaluates to the number of tokens passed to it.
794 ///
795 /// Logarithmic counting: every one or two recursive expansions, the number of
796 /// tokens to count is divided by two, instead of being reduced by one.
797 /// Therefore, the recursion depth is the binary logarithm of the number of
798 /// tokens to count, and the expanded tree is likewise very small.
799 macro_rules! count {
800     ()                     => (0usize);
801     ($one:tt)              => (1usize);
802     ($($pairs:tt $_p:tt)*) => (count!($($pairs)*) << 1usize);
803     ($odd:tt $($rest:tt)*) => (count!($($rest)*) | 1usize);
804 }
805
806 macro_rules! tuple {
807     () => ();
808     ( $($name:ident,)+ ) => (
809         impl<$($name:Decodable),+> Decodable for ($($name,)+) {
810             #[allow(non_snake_case)]
811             fn decode<D: Decoder>(d: &mut D) -> Result<($($name,)+), D::Error> {
812                 let len: usize = count!($($name)+);
813                 d.read_tuple(len, |d| {
814                     let mut i = 0;
815                     let ret = ($(d.read_tuple_arg({ i+=1; i-1 }, |d| -> Result<$name, D::Error> {
816                         Decodable::decode(d)
817                     })?,)+);
818                     Ok(ret)
819                 })
820             }
821         }
822         impl<$($name:Encodable),+> Encodable for ($($name,)+) {
823             #[allow(non_snake_case)]
824             fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
825                 let ($(ref $name,)+) = *self;
826                 let mut n = 0;
827                 $(let $name = $name; n += 1;)+
828                 s.emit_tuple(n, |s| {
829                     let mut i = 0;
830                     $(s.emit_tuple_arg({ i+=1; i-1 }, |s| $name.encode(s))?;)+
831                     Ok(())
832                 })
833             }
834         }
835         peel! { $($name,)+ }
836     )
837 }
838
839 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
840
841 impl Encodable for path::Path {
842     fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> {
843         self.to_str().unwrap().encode(e)
844     }
845 }
846
847 impl Encodable for path::PathBuf {
848     fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> {
849         path::Path::encode(self, e)
850     }
851 }
852
853 impl Decodable for path::PathBuf {
854     fn decode<D: Decoder>(d: &mut D) -> Result<path::PathBuf, D::Error> {
855         let bytes: String = Decodable::decode(d)?;
856         Ok(path::PathBuf::from(bytes))
857     }
858 }
859
860 impl<T: Encodable + Copy> Encodable for Cell<T> {
861     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
862         self.get().encode(s)
863     }
864 }
865
866 impl<T: Decodable + Copy> Decodable for Cell<T> {
867     fn decode<D: Decoder>(d: &mut D) -> Result<Cell<T>, D::Error> {
868         Ok(Cell::new(Decodable::decode(d)?))
869     }
870 }
871
872 // FIXME: #15036
873 // Should use `try_borrow`, returning a
874 // `encoder.error("attempting to Encode borrowed RefCell")`
875 // from `encode` when `try_borrow` returns `None`.
876
877 impl<T: Encodable> Encodable for RefCell<T> {
878     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
879         self.borrow().encode(s)
880     }
881 }
882
883 impl<T: Decodable> Decodable for RefCell<T> {
884     fn decode<D: Decoder>(d: &mut D) -> Result<RefCell<T>, D::Error> {
885         Ok(RefCell::new(Decodable::decode(d)?))
886     }
887 }
888
889 impl<T: Encodable> Encodable for Arc<T> {
890     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
891         (**self).encode(s)
892     }
893 }
894
895 impl<T: Decodable> Decodable for Arc<T> {
896     fn decode<D: Decoder>(d: &mut D) -> Result<Arc<T>, D::Error> {
897         Ok(Arc::new(Decodable::decode(d)?))
898     }
899 }
900
901 // ___________________________________________________________________________
902 // Specialization-based interface for multi-dispatch Encodable/Decodable.
903
904 /// Implement this trait on your `{Encodable,Decodable}::Error` types
905 /// to override the default panic behavior for missing specializations.
906 pub trait SpecializationError {
907     /// Creates an error for a missing method specialization.
908     /// Defaults to panicking with type, trait & method names.
909     /// `S` is the encoder/decoder state type,
910     /// `T` is the type being encoded/decoded, and
911     /// the arguments are the names of the trait
912     /// and method that should've been overridden.
913     fn not_found<S, T: ?Sized>(trait_name: &'static str, method_name: &'static str) -> Self;
914 }
915
916 impl<E> SpecializationError for E {
917     default fn not_found<S, T: ?Sized>(trait_name: &'static str, method_name: &'static str) -> E {
918         panic!(
919             "missing specialization: `<{} as {}<{}>>::{}` not overridden",
920             any::type_name::<S>(),
921             trait_name,
922             any::type_name::<T>(),
923             method_name
924         );
925     }
926 }
927
928 /// Implement this trait on encoders, with `T` being the type
929 /// you want to encode (employing `UseSpecializedEncodable`),
930 /// using a strategy specific to the encoder.
931 pub trait SpecializedEncoder<T: ?Sized + UseSpecializedEncodable>: Encoder {
932     /// Encode the value in a manner specific to this encoder state.
933     fn specialized_encode(&mut self, value: &T) -> Result<(), Self::Error>;
934 }
935
936 impl<E: Encoder, T: ?Sized + UseSpecializedEncodable> SpecializedEncoder<T> for E {
937     default fn specialized_encode(&mut self, value: &T) -> Result<(), E::Error> {
938         value.default_encode(self)
939     }
940 }
941
942 /// Implement this trait on decoders, with `T` being the type
943 /// you want to decode (employing `UseSpecializedDecodable`),
944 /// using a strategy specific to the decoder.
945 pub trait SpecializedDecoder<T: UseSpecializedDecodable>: Decoder {
946     /// Decode a value in a manner specific to this decoder state.
947     fn specialized_decode(&mut self) -> Result<T, Self::Error>;
948 }
949
950 impl<D: Decoder, T: UseSpecializedDecodable> SpecializedDecoder<T> for D {
951     default fn specialized_decode(&mut self) -> Result<T, D::Error> {
952         T::default_decode(self)
953     }
954 }
955
956 /// Implement this trait on your type to get an `Encodable`
957 /// implementation which goes through `SpecializedEncoder`.
958 pub trait UseSpecializedEncodable {
959     /// Defaults to returning an error (see `SpecializationError`).
960     fn default_encode<E: Encoder>(&self, _: &mut E) -> Result<(), E::Error> {
961         Err(E::Error::not_found::<E, Self>("SpecializedEncoder", "specialized_encode"))
962     }
963 }
964
965 impl<T: ?Sized + UseSpecializedEncodable> Encodable for T {
966     default fn encode<E: Encoder>(&self, e: &mut E) -> Result<(), E::Error> {
967         E::specialized_encode(e, self)
968     }
969 }
970
971 /// Implement this trait on your type to get an `Decodable`
972 /// implementation which goes through `SpecializedDecoder`.
973 pub trait UseSpecializedDecodable: Sized {
974     /// Defaults to returning an error (see `SpecializationError`).
975     fn default_decode<D: Decoder>(_: &mut D) -> Result<Self, D::Error> {
976         Err(D::Error::not_found::<D, Self>("SpecializedDecoder", "specialized_decode"))
977     }
978 }
979
980 impl<T: UseSpecializedDecodable> Decodable for T {
981     default fn decode<D: Decoder>(d: &mut D) -> Result<T, D::Error> {
982         D::specialized_decode(d)
983     }
984 }
985
986 // Can't avoid specialization for &T and Box<T> impls,
987 // as proxy impls on them are blankets that conflict
988 // with the Encodable and Decodable impls above,
989 // which only have `default` on their methods
990 // for this exact reason.
991 // May be fixable in a simpler fashion via the
992 // more complex lattice model for specialization.
993 impl<'a, T: ?Sized + Encodable> UseSpecializedEncodable for &'a T {
994     fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
995         (**self).encode(s)
996     }
997 }
998 impl<T: ?Sized + Encodable> UseSpecializedEncodable for Box<T> {
999     fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1000         (**self).encode(s)
1001     }
1002 }
1003 impl<T: Decodable> UseSpecializedDecodable for Box<T> {
1004     fn default_decode<D: Decoder>(d: &mut D) -> Result<Box<T>, D::Error> {
1005         Ok(box Decodable::decode(d)?)
1006     }
1007 }
1008 impl<'a, T: Decodable> UseSpecializedDecodable for &'a T {}
1009 impl<'a, T: Decodable> UseSpecializedDecodable for &'a [T] {}