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.
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.
11 //! Support code for encoding and decoding types.
14 Core encoding and decoding interfaces.
19 use std::marker::PhantomData;
22 use std::cell::{Cell, RefCell};
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>;
49 fn emit_enum<F>(&mut self, _name: &str, f: F) -> Result<(), Self::Error>
50 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
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>
58 self.emit_usize(v_id)?;
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>
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>
71 self.emit_enum_variant(v_name, v_id, len, f)
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>
77 self.emit_enum_variant_arg(f_idx, f)
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>
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>
92 fn emit_tuple<F>(&mut self, _len: usize, f: F) -> Result<(), Self::Error>
93 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
98 fn emit_tuple_arg<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
99 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
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>
107 self.emit_tuple(len, f)
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>
113 self.emit_tuple_arg(f_idx, f)
116 // Specialized types:
117 fn emit_option<F>(&mut self, f: F) -> Result<(), Self::Error>
118 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
120 self.emit_enum("Option", f)
124 fn emit_option_none(&mut self) -> Result<(), Self::Error> {
125 self.emit_enum_variant("None", 0, 0, |_| Ok(()))
128 fn emit_option_some<F>(&mut self, f: F) -> Result<(), Self::Error>
129 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
131 self.emit_enum_variant("Some", 1, 1, f)
134 fn emit_seq<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
135 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
137 self.emit_usize(len)?;
141 fn emit_seq_elt<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
142 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
147 fn emit_map<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
148 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
150 self.emit_usize(len)?;
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>
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>
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>;
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>
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>
200 let disr = self.read_usize()?;
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>
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>
213 self.read_enum_variant(names, f)
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>
219 self.read_enum_variant_arg(f_idx, f)
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>
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>
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>
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>
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>
249 self.read_tuple(len, f)
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>
255 self.read_tuple_arg(a_idx, f)
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>
262 self.read_enum("Option", move |this| {
263 this.read_enum_variant(&["None", "Some"], move |this, idx| {
267 _ => Err(this.error("read_option: expected 0 for None or 1 for Some")),
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>
276 let len = self.read_usize()?;
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>
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>
289 let len = self.read_usize()?;
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>
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>
306 fn error(&mut self, err: &str) -> Self::Error;
309 pub trait Encodable {
310 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error>;
313 pub trait Decodable: Sized {
314 fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error>;
317 impl Encodable for usize {
318 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
323 impl Decodable for usize {
324 fn decode<D: Decoder>(d: &mut D) -> Result<usize, D::Error> {
329 impl Encodable for u8 {
330 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
335 impl Decodable for u8 {
336 fn decode<D: Decoder>(d: &mut D) -> Result<u8, D::Error> {
341 impl Encodable for u16 {
342 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
347 impl Decodable for u16 {
348 fn decode<D: Decoder>(d: &mut D) -> Result<u16, D::Error> {
353 impl Encodable for u32 {
354 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
359 impl Decodable for u32 {
360 fn decode<D: Decoder>(d: &mut D) -> Result<u32, D::Error> {
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())
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())
377 impl Encodable for u64 {
378 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
383 impl Decodable for u64 {
384 fn decode<D: Decoder>(d: &mut D) -> Result<u64, D::Error> {
389 impl Encodable for u128 {
390 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
395 impl Decodable for u128 {
396 fn decode<D: Decoder>(d: &mut D) -> Result<u128, D::Error> {
401 impl Encodable for isize {
402 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
407 impl Decodable for isize {
408 fn decode<D: Decoder>(d: &mut D) -> Result<isize, D::Error> {
413 impl Encodable for i8 {
414 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
419 impl Decodable for i8 {
420 fn decode<D: Decoder>(d: &mut D) -> Result<i8, D::Error> {
425 impl Encodable for i16 {
426 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
431 impl Decodable for i16 {
432 fn decode<D: Decoder>(d: &mut D) -> Result<i16, D::Error> {
437 impl Encodable for i32 {
438 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
443 impl Decodable for i32 {
444 fn decode<D: Decoder>(d: &mut D) -> Result<i32, D::Error> {
449 impl Encodable for i64 {
450 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
455 impl Decodable for i64 {
456 fn decode<D: Decoder>(d: &mut D) -> Result<i64, D::Error> {
461 impl Encodable for i128 {
462 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
467 impl Decodable for i128 {
468 fn decode<D: Decoder>(d: &mut D) -> Result<i128, D::Error> {
473 impl Encodable for str {
474 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
479 impl Encodable for String {
480 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
481 s.emit_str(&self[..])
485 impl Decodable for String {
486 fn decode<D: Decoder>(d: &mut D) -> Result<String, D::Error> {
487 Ok(d.read_str()?.into_owned())
491 impl Encodable for f32 {
492 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
497 impl Decodable for f32 {
498 fn decode<D: Decoder>(d: &mut D) -> Result<f32, D::Error> {
503 impl Encodable for f64 {
504 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
509 impl Decodable for f64 {
510 fn decode<D: Decoder>(d: &mut D) -> Result<f64, D::Error> {
515 impl Encodable for bool {
516 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
521 impl Decodable for bool {
522 fn decode<D: Decoder>(d: &mut D) -> Result<bool, D::Error> {
527 impl Encodable for char {
528 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
533 impl Decodable for char {
534 fn decode<D: Decoder>(d: &mut D) -> Result<char, D::Error> {
539 impl Encodable for () {
540 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
545 impl Decodable for () {
546 fn decode<D: Decoder>(d: &mut D) -> Result<(), D::Error> {
551 impl<T> Encodable for PhantomData<T> {
552 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
557 impl<T> Decodable for PhantomData<T> {
558 fn decode<D: Decoder>(d: &mut D) -> Result<PhantomData<T>, D::Error> {
564 impl<'a, T: ?Sized + Encodable> Encodable for &'a T {
565 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
570 impl<T: ?Sized + Encodable> Encodable for Box<T> {
571 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
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)?)
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())
589 impl<T:Encodable> Encodable for Rc<T> {
590 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
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)?))
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))?
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))?
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);
628 v.push(d.read_seq_elt(i, |d| Decodable::decode(d))?);
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))?
646 impl<T:Decodable+ToOwned> Decodable for Cow<'static, [T]>
647 where [T]: ToOwned<Owned = Vec<T>>
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);
653 v.push(d.read_seq_elt(i, |d| Decodable::decode(d))?);
661 impl<T:Encodable> Encodable for Option<T> {
662 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
665 None => s.emit_option_none(),
666 Some(ref v) => s.emit_option_some(|s| v.encode(s)),
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| {
676 Ok(Some(Decodable::decode(d)?))
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| {
689 s.emit_enum_variant("Ok", 0, 1, |s| {
690 s.emit_enum_variant_arg(0, |s| {
696 s.emit_enum_variant("Err", 1, 1, |s| {
697 s.emit_enum_variant_arg(0, |s| {
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| {
713 Ok(Ok(d.read_enum_variant_arg(0, |d| {
718 Ok(Err(d.read_enum_variant_arg(0, |d| {
723 panic!("Encountered invalid discriminant while \
724 decoding `Result`.");
733 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
736 /// Evaluates to the number of identifiers passed to it, for example: `count_idents!(a, b, c) == 3
737 macro_rules! count_idents {
739 ($_i:ident, $($rest:ident,)*) => { 1 + count_idents!($($rest,)*) }
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| {
751 let ret = ($(d.read_tuple_arg({ i+=1; i-1 }, |d| -> Result<$name, D::Error> {
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;
763 $(let $name = $name; n += 1;)*
764 s.emit_tuple(n, |s| {
766 $(s.emit_tuple_arg({ i+=1; i-1 }, |s| $name.encode(s))?;)*
775 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
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)
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))
790 impl<T: Encodable + Copy> Encodable for Cell<T> {
791 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
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)?))
803 // Should use `try_borrow`, returning a
804 // `encoder.error("attempting to Encode borrowed RefCell")`
805 // from `encode` when `try_borrow` returns `None`.
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)
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)?))
819 impl<T:Encodable> Encodable for Arc<T> {
820 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
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)?))
831 // ___________________________________________________________________________
832 // Specialization-based interface for multi-dispatch Encodable/Decodable.
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;
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>() },
851 unsafe { intrinsics::type_name::<T>() },
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>;
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)
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>;
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)
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"))
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)
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"))
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)
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> {}