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