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