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