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