1 //! Support code for encoding and decoding types.
4 Core encoding and decoding interfaces.
9 use std::cell::{Cell, RefCell};
10 use std::marker::PhantomData;
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>;
40 fn emit_enum<F>(&mut self, _name: &str, f: F) -> Result<(), Self::Error>
42 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
47 fn emit_enum_variant<F>(
53 ) -> Result<(), Self::Error>
55 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
57 self.emit_usize(v_id)?;
62 fn emit_enum_variant_arg<F>(&mut self, _a_idx: usize, f: F) -> Result<(), Self::Error>
64 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
69 fn emit_enum_struct_variant<F>(
75 ) -> Result<(), Self::Error>
77 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
79 self.emit_enum_variant(v_name, v_id, len, f)
82 fn emit_enum_struct_variant_field<F>(
87 ) -> Result<(), Self::Error>
89 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
91 self.emit_enum_variant_arg(f_idx, f)
95 fn emit_struct<F>(&mut self, _name: &str, _len: usize, f: F) -> Result<(), Self::Error>
97 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
103 fn emit_struct_field<F>(
108 ) -> Result<(), Self::Error>
110 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
116 fn emit_tuple<F>(&mut self, _len: usize, f: F) -> Result<(), Self::Error>
118 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
124 fn emit_tuple_arg<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
126 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
131 fn emit_tuple_struct<F>(&mut self, _name: &str, len: usize, f: F) -> Result<(), Self::Error>
133 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
135 self.emit_tuple(len, f)
138 fn emit_tuple_struct_arg<F>(&mut self, f_idx: usize, f: F) -> Result<(), Self::Error>
140 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
142 self.emit_tuple_arg(f_idx, f)
145 // Specialized types:
146 fn emit_option<F>(&mut self, f: F) -> Result<(), Self::Error>
148 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
150 self.emit_enum("Option", f)
154 fn emit_option_none(&mut self) -> Result<(), Self::Error> {
155 self.emit_enum_variant("None", 0, 0, |_| Ok(()))
158 fn emit_option_some<F>(&mut self, f: F) -> Result<(), Self::Error>
160 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
162 self.emit_enum_variant("Some", 1, 1, f)
165 fn emit_seq<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
167 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
169 self.emit_usize(len)?;
174 fn emit_seq_elt<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
176 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
181 fn emit_map<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
183 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
185 self.emit_usize(len)?;
190 fn emit_map_elt_key<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
192 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
198 fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
200 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
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>;
231 fn read_enum<T, F>(&mut self, _name: &str, f: F) -> Result<T, Self::Error>
233 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
239 fn read_enum_variant<T, F>(&mut self, _names: &[&str], mut f: F) -> Result<T, Self::Error>
241 F: FnMut(&mut Self, usize) -> Result<T, Self::Error>,
243 let disr = self.read_usize()?;
248 fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, f: F) -> Result<T, Self::Error>
250 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
255 fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F) -> Result<T, Self::Error>
257 F: FnMut(&mut Self, usize) -> Result<T, Self::Error>,
259 self.read_enum_variant(names, f)
262 fn read_enum_struct_variant_field<T, F>(
267 ) -> Result<T, Self::Error>
269 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
271 self.read_enum_variant_arg(f_idx, f)
275 fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, f: F) -> Result<T, Self::Error>
277 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
283 fn read_struct_field<T, F>(
288 ) -> Result<T, Self::Error>
290 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
296 fn read_tuple<T, F>(&mut self, _len: usize, f: F) -> Result<T, Self::Error>
298 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
304 fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, f: F) -> Result<T, Self::Error>
306 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
311 fn read_tuple_struct<T, F>(&mut self, _s_name: &str, len: usize, f: F) -> Result<T, Self::Error>
313 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
315 self.read_tuple(len, f)
318 fn read_tuple_struct_arg<T, F>(&mut self, a_idx: usize, f: F) -> Result<T, Self::Error>
320 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
322 self.read_tuple_arg(a_idx, f)
325 // Specialized types:
326 fn read_option<T, F>(&mut self, mut f: F) -> Result<T, Self::Error>
328 F: FnMut(&mut Self, bool) -> Result<T, Self::Error>,
330 self.read_enum("Option", move |this| {
331 this.read_enum_variant(&["None", "Some"], move |this, idx| match idx {
334 _ => Err(this.error("read_option: expected 0 for None or 1 for Some")),
339 fn read_seq<T, F>(&mut self, f: F) -> Result<T, Self::Error>
341 F: FnOnce(&mut Self, usize) -> Result<T, Self::Error>,
343 let len = self.read_usize()?;
348 fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error>
350 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
355 fn read_map<T, F>(&mut self, f: F) -> Result<T, Self::Error>
357 F: FnOnce(&mut Self, usize) -> Result<T, Self::Error>,
359 let len = self.read_usize()?;
364 fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error>
366 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
372 fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error>
374 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
380 fn error(&mut self, err: &str) -> Self::Error;
383 pub trait Encodable {
384 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error>;
387 pub trait Decodable: Sized {
388 fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error>;
391 impl Encodable for usize {
392 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
397 impl Decodable for usize {
398 fn decode<D: Decoder>(d: &mut D) -> Result<usize, D::Error> {
403 impl Encodable for u8 {
404 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
409 impl Decodable for u8 {
410 fn decode<D: Decoder>(d: &mut D) -> Result<u8, D::Error> {
415 impl Encodable for u16 {
416 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
421 impl Decodable for u16 {
422 fn decode<D: Decoder>(d: &mut D) -> Result<u16, D::Error> {
427 impl Encodable for u32 {
428 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
433 impl Decodable for u32 {
434 fn decode<D: Decoder>(d: &mut D) -> Result<u32, D::Error> {
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())
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())
451 impl Encodable for u64 {
452 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
457 impl Decodable for u64 {
458 fn decode<D: Decoder>(d: &mut D) -> Result<u64, D::Error> {
463 impl Encodable for u128 {
464 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
469 impl Decodable for u128 {
470 fn decode<D: Decoder>(d: &mut D) -> Result<u128, D::Error> {
475 impl Encodable for isize {
476 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
481 impl Decodable for isize {
482 fn decode<D: Decoder>(d: &mut D) -> Result<isize, D::Error> {
487 impl Encodable for i8 {
488 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
493 impl Decodable for i8 {
494 fn decode<D: Decoder>(d: &mut D) -> Result<i8, D::Error> {
499 impl Encodable for i16 {
500 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
505 impl Decodable for i16 {
506 fn decode<D: Decoder>(d: &mut D) -> Result<i16, D::Error> {
511 impl Encodable for i32 {
512 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
517 impl Decodable for i32 {
518 fn decode<D: Decoder>(d: &mut D) -> Result<i32, D::Error> {
523 impl Encodable for i64 {
524 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
529 impl Decodable for i64 {
530 fn decode<D: Decoder>(d: &mut D) -> Result<i64, D::Error> {
535 impl Encodable for i128 {
536 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
541 impl Decodable for i128 {
542 fn decode<D: Decoder>(d: &mut D) -> Result<i128, D::Error> {
547 impl Encodable for str {
548 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
553 impl Encodable for String {
554 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
555 s.emit_str(&self[..])
559 impl Decodable for String {
560 fn decode<D: Decoder>(d: &mut D) -> Result<String, D::Error> {
561 Ok(d.read_str()?.into_owned())
565 impl Encodable for f32 {
566 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
571 impl Decodable for f32 {
572 fn decode<D: Decoder>(d: &mut D) -> Result<f32, D::Error> {
577 impl Encodable for f64 {
578 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
583 impl Decodable for f64 {
584 fn decode<D: Decoder>(d: &mut D) -> Result<f64, D::Error> {
589 impl Encodable for bool {
590 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
595 impl Decodable for bool {
596 fn decode<D: Decoder>(d: &mut D) -> Result<bool, D::Error> {
601 impl Encodable for char {
602 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
607 impl Decodable for char {
608 fn decode<D: Decoder>(d: &mut D) -> Result<char, D::Error> {
613 impl Encodable for () {
614 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
619 impl Decodable for () {
620 fn decode<D: Decoder>(d: &mut D) -> Result<(), D::Error> {
625 impl<T> Encodable for PhantomData<T> {
626 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
631 impl<T> Decodable for PhantomData<T> {
632 fn decode<D: Decoder>(d: &mut D) -> Result<PhantomData<T>, D::Error> {
638 impl<'a, T: ?Sized + Encodable> Encodable for &'a T {
639 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
644 impl<T: ?Sized + Encodable> Encodable for Box<T> {
645 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
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)?)
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())
663 impl<T: Encodable> Encodable for Rc<T> {
664 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
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)?))
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))?
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))?
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);
702 v.push(d.read_seq_elt(i, |d| Decodable::decode(d))?);
709 impl<'a, T: Encodable> Encodable for Cow<'a, [T]>
711 [T]: ToOwned<Owned = Vec<T>>,
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))?
723 impl<T: Decodable + ToOwned> Decodable for Cow<'static, [T]>
725 [T]: ToOwned<Owned = Vec<T>>,
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);
731 v.push(d.read_seq_elt(i, |d| Decodable::decode(d))?);
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)),
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) })
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 {
757 s.emit_enum_variant("Ok", 0, 1, |s| s.emit_enum_variant_arg(0, |s| v.encode(s)))
760 s.emit_enum_variant("Err", 1, 1, |s| s.emit_enum_variant_arg(0, |s| v.encode(s)))
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))?)),
774 "Encountered invalid discriminant while \
784 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
787 /// Evaluates to the number of tokens passed to it.
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.
795 ($one:tt) => (1usize);
796 ($($pairs:tt $_p:tt)*) => (count!($($pairs)*) << 1usize);
797 ($odd:tt $($rest:tt)*) => (count!($($rest)*) | 1usize);
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| {
809 let ret = ($(d.read_tuple_arg({ i+=1; i-1 }, |d| -> Result<$name, D::Error> {
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;
821 $(let $name = $name; n += 1;)+
822 s.emit_tuple(n, |s| {
824 $(s.emit_tuple_arg({ i+=1; i-1 }, |s| $name.encode(s))?;)+
833 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
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)
841 impl Encodable for path::PathBuf {
842 fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> {
843 path::Path::encode(self, e)
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))
854 impl<T: Encodable + Copy> Encodable for Cell<T> {
855 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
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)?))
867 // Should use `try_borrow`, returning a
868 // `encoder.error("attempting to Encode borrowed RefCell")`
869 // from `encode` when `try_borrow` returns `None`.
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)
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)?))
883 impl<T: Encodable> Encodable for Arc<T> {
884 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
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)?))
895 // ___________________________________________________________________________
896 // Specialization-based interface for multi-dispatch Encodable/Decodable.
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;
910 impl<E> SpecializationError for E {
911 default fn not_found<S, T: ?Sized>(trait_name: &'static str, method_name: &'static str) -> E {
913 "missing specialization: `<{} as {}<{}>>::{}` not overridden",
914 any::type_name::<S>(),
916 any::type_name::<T>(),
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>;
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)
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>;
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)
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"))
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)
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"))
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)
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] {}