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>;
39 fn emit_enum<F>(&mut self, _name: &str, f: F) -> Result<(), Self::Error>
41 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
46 fn emit_enum_variant<F>(
52 ) -> Result<(), Self::Error>
54 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
56 self.emit_usize(v_id)?;
60 fn emit_enum_variant_arg<F>(&mut self, _a_idx: usize, f: F) -> Result<(), Self::Error>
62 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
67 fn emit_enum_struct_variant<F>(
73 ) -> Result<(), Self::Error>
75 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
77 self.emit_enum_variant(v_name, v_id, len, f)
80 fn emit_enum_struct_variant_field<F>(
85 ) -> Result<(), Self::Error>
87 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
89 self.emit_enum_variant_arg(f_idx, f)
92 fn emit_struct<F>(&mut self, _name: &str, _len: usize, f: F) -> Result<(), Self::Error>
94 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
99 fn emit_struct_field<F>(
104 ) -> Result<(), Self::Error>
106 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
111 fn emit_tuple<F>(&mut self, _len: usize, f: F) -> Result<(), Self::Error>
113 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
118 fn emit_tuple_arg<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
120 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
125 fn emit_tuple_struct<F>(&mut self, _name: &str, len: usize, f: F) -> Result<(), Self::Error>
127 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
129 self.emit_tuple(len, f)
132 fn emit_tuple_struct_arg<F>(&mut self, f_idx: usize, f: F) -> Result<(), Self::Error>
134 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
136 self.emit_tuple_arg(f_idx, f)
139 // Specialized types:
140 fn emit_option<F>(&mut self, f: F) -> Result<(), Self::Error>
142 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
144 self.emit_enum("Option", f)
148 fn emit_option_none(&mut self) -> Result<(), Self::Error> {
149 self.emit_enum_variant("None", 0, 0, |_| Ok(()))
152 fn emit_option_some<F>(&mut self, f: F) -> Result<(), Self::Error>
154 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
156 self.emit_enum_variant("Some", 1, 1, f)
159 fn emit_seq<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
161 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
163 self.emit_usize(len)?;
167 fn emit_seq_elt<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
169 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
174 fn emit_map<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
176 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
178 self.emit_usize(len)?;
182 fn emit_map_elt_key<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
184 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
189 fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
191 F: FnOnce(&mut Self) -> Result<(), Self::Error>,
201 fn read_nil(&mut self) -> Result<(), Self::Error>;
202 fn read_usize(&mut self) -> Result<usize, Self::Error>;
203 fn read_u128(&mut self) -> Result<u128, Self::Error>;
204 fn read_u64(&mut self) -> Result<u64, Self::Error>;
205 fn read_u32(&mut self) -> Result<u32, Self::Error>;
206 fn read_u16(&mut self) -> Result<u16, Self::Error>;
207 fn read_u8(&mut self) -> Result<u8, Self::Error>;
208 fn read_isize(&mut self) -> Result<isize, Self::Error>;
209 fn read_i128(&mut self) -> Result<i128, Self::Error>;
210 fn read_i64(&mut self) -> Result<i64, Self::Error>;
211 fn read_i32(&mut self) -> Result<i32, Self::Error>;
212 fn read_i16(&mut self) -> Result<i16, Self::Error>;
213 fn read_i8(&mut self) -> Result<i8, Self::Error>;
214 fn read_bool(&mut self) -> Result<bool, Self::Error>;
215 fn read_f64(&mut self) -> Result<f64, Self::Error>;
216 fn read_f32(&mut self) -> Result<f32, Self::Error>;
217 fn read_char(&mut self) -> Result<char, Self::Error>;
218 fn read_str(&mut self) -> Result<Cow<'_, str>, Self::Error>;
221 fn read_enum<T, F>(&mut self, _name: &str, f: F) -> Result<T, Self::Error>
223 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
228 fn read_enum_variant<T, F>(&mut self, _names: &[&str], mut f: F) -> Result<T, Self::Error>
230 F: FnMut(&mut Self, usize) -> Result<T, Self::Error>,
232 let disr = self.read_usize()?;
236 fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, f: F) -> Result<T, Self::Error>
238 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
243 fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F) -> Result<T, Self::Error>
245 F: FnMut(&mut Self, usize) -> Result<T, Self::Error>,
247 self.read_enum_variant(names, f)
250 fn read_enum_struct_variant_field<T, F>(
255 ) -> Result<T, Self::Error>
257 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
259 self.read_enum_variant_arg(f_idx, f)
262 fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, f: F) -> Result<T, Self::Error>
264 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
269 fn read_struct_field<T, F>(
274 ) -> Result<T, Self::Error>
276 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
281 fn read_tuple<T, F>(&mut self, _len: usize, f: F) -> Result<T, Self::Error>
283 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
288 fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, f: F) -> Result<T, Self::Error>
290 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
295 fn read_tuple_struct<T, F>(&mut self, _s_name: &str, len: usize, f: F) -> Result<T, Self::Error>
297 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
299 self.read_tuple(len, f)
302 fn read_tuple_struct_arg<T, F>(&mut self, a_idx: usize, f: F) -> Result<T, Self::Error>
304 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
306 self.read_tuple_arg(a_idx, f)
309 // Specialized types:
310 fn read_option<T, F>(&mut self, mut f: F) -> Result<T, Self::Error>
312 F: FnMut(&mut Self, bool) -> Result<T, Self::Error>,
314 self.read_enum("Option", move |this| {
315 this.read_enum_variant(&["None", "Some"], move |this, idx| match idx {
318 _ => Err(this.error("read_option: expected 0 for None or 1 for Some")),
323 fn read_seq<T, F>(&mut self, f: F) -> Result<T, Self::Error>
325 F: FnOnce(&mut Self, usize) -> Result<T, Self::Error>,
327 let len = self.read_usize()?;
331 fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error>
333 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
338 fn read_map<T, F>(&mut self, f: F) -> Result<T, Self::Error>
340 F: FnOnce(&mut Self, usize) -> Result<T, Self::Error>,
342 let len = self.read_usize()?;
346 fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error>
348 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
353 fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error>
355 F: FnOnce(&mut Self) -> Result<T, Self::Error>,
361 fn error(&mut self, err: &str) -> Self::Error;
364 pub trait Encodable {
365 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error>;
368 pub trait Decodable: Sized {
369 fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error>;
372 impl Encodable for usize {
373 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
378 impl Decodable for usize {
379 fn decode<D: Decoder>(d: &mut D) -> Result<usize, D::Error> {
384 impl Encodable for u8 {
385 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
390 impl Decodable for u8 {
391 fn decode<D: Decoder>(d: &mut D) -> Result<u8, D::Error> {
396 impl Encodable for u16 {
397 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
402 impl Decodable for u16 {
403 fn decode<D: Decoder>(d: &mut D) -> Result<u16, D::Error> {
408 impl Encodable for u32 {
409 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
414 impl Decodable for u32 {
415 fn decode<D: Decoder>(d: &mut D) -> Result<u32, D::Error> {
420 impl Encodable for ::std::num::NonZeroU32 {
421 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
422 s.emit_u32(self.get())
426 impl Decodable for ::std::num::NonZeroU32 {
427 fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
428 d.read_u32().map(|d| ::std::num::NonZeroU32::new(d).unwrap())
432 impl Encodable for u64 {
433 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
438 impl Decodable for u64 {
439 fn decode<D: Decoder>(d: &mut D) -> Result<u64, D::Error> {
444 impl Encodable for u128 {
445 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
450 impl Decodable for u128 {
451 fn decode<D: Decoder>(d: &mut D) -> Result<u128, D::Error> {
456 impl Encodable for isize {
457 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
462 impl Decodable for isize {
463 fn decode<D: Decoder>(d: &mut D) -> Result<isize, D::Error> {
468 impl Encodable for i8 {
469 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
474 impl Decodable for i8 {
475 fn decode<D: Decoder>(d: &mut D) -> Result<i8, D::Error> {
480 impl Encodable for i16 {
481 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
486 impl Decodable for i16 {
487 fn decode<D: Decoder>(d: &mut D) -> Result<i16, D::Error> {
492 impl Encodable for i32 {
493 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
498 impl Decodable for i32 {
499 fn decode<D: Decoder>(d: &mut D) -> Result<i32, D::Error> {
504 impl Encodable for i64 {
505 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
510 impl Decodable for i64 {
511 fn decode<D: Decoder>(d: &mut D) -> Result<i64, D::Error> {
516 impl Encodable for i128 {
517 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
522 impl Decodable for i128 {
523 fn decode<D: Decoder>(d: &mut D) -> Result<i128, D::Error> {
528 impl Encodable for str {
529 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
534 impl Encodable for String {
535 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
536 s.emit_str(&self[..])
540 impl Decodable for String {
541 fn decode<D: Decoder>(d: &mut D) -> Result<String, D::Error> {
542 Ok(d.read_str()?.into_owned())
546 impl Encodable for f32 {
547 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
552 impl Decodable for f32 {
553 fn decode<D: Decoder>(d: &mut D) -> Result<f32, D::Error> {
558 impl Encodable for f64 {
559 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
564 impl Decodable for f64 {
565 fn decode<D: Decoder>(d: &mut D) -> Result<f64, D::Error> {
570 impl Encodable for bool {
571 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
576 impl Decodable for bool {
577 fn decode<D: Decoder>(d: &mut D) -> Result<bool, D::Error> {
582 impl Encodable for char {
583 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
588 impl Decodable for char {
589 fn decode<D: Decoder>(d: &mut D) -> Result<char, D::Error> {
594 impl Encodable for () {
595 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
600 impl Decodable for () {
601 fn decode<D: Decoder>(d: &mut D) -> Result<(), D::Error> {
606 impl<T> Encodable for PhantomData<T> {
607 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
612 impl<T> Decodable for PhantomData<T> {
613 fn decode<D: Decoder>(d: &mut D) -> Result<PhantomData<T>, D::Error> {
619 impl<'a, T: ?Sized + Encodable> Encodable for &'a T {
620 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
625 impl<T: ?Sized + Encodable> Encodable for Box<T> {
626 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
631 impl<T: Decodable> Decodable for Box<T> {
632 fn decode<D: Decoder>(d: &mut D) -> Result<Box<T>, D::Error> {
633 Ok(box Decodable::decode(d)?)
637 impl<T: Decodable> Decodable for Box<[T]> {
638 fn decode<D: Decoder>(d: &mut D) -> Result<Box<[T]>, D::Error> {
639 let v: Vec<T> = Decodable::decode(d)?;
640 Ok(v.into_boxed_slice())
644 impl<T: Encodable> Encodable for Rc<T> {
645 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
650 impl<T: Decodable> Decodable for Rc<T> {
651 fn decode<D: Decoder>(d: &mut D) -> Result<Rc<T>, D::Error> {
652 Ok(Rc::new(Decodable::decode(d)?))
656 impl<T: Encodable> Encodable for [T] {
657 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
658 s.emit_seq(self.len(), |s| {
659 for (i, e) in self.iter().enumerate() {
660 s.emit_seq_elt(i, |s| e.encode(s))?
667 impl<T: Encodable> Encodable for Vec<T> {
668 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
669 s.emit_seq(self.len(), |s| {
670 for (i, e) in self.iter().enumerate() {
671 s.emit_seq_elt(i, |s| e.encode(s))?
678 impl<T: Decodable> Decodable for Vec<T> {
679 fn decode<D: Decoder>(d: &mut D) -> Result<Vec<T>, D::Error> {
680 d.read_seq(|d, len| {
681 let mut v = Vec::with_capacity(len);
683 v.push(d.read_seq_elt(i, |d| Decodable::decode(d))?);
690 impl<'a, T: Encodable> Encodable for Cow<'a, [T]>
692 [T]: ToOwned<Owned = Vec<T>>,
694 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
695 s.emit_seq(self.len(), |s| {
696 for (i, e) in self.iter().enumerate() {
697 s.emit_seq_elt(i, |s| e.encode(s))?
704 impl<T: Decodable + ToOwned> Decodable for Cow<'static, [T]>
706 [T]: ToOwned<Owned = Vec<T>>,
708 fn decode<D: Decoder>(d: &mut D) -> Result<Cow<'static, [T]>, D::Error> {
709 d.read_seq(|d, len| {
710 let mut v = Vec::with_capacity(len);
712 v.push(d.read_seq_elt(i, |d| Decodable::decode(d))?);
719 impl<T: Encodable> Encodable for Option<T> {
720 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
721 s.emit_option(|s| match *self {
722 None => s.emit_option_none(),
723 Some(ref v) => s.emit_option_some(|s| v.encode(s)),
728 impl<T: Decodable> Decodable for Option<T> {
729 fn decode<D: Decoder>(d: &mut D) -> Result<Option<T>, D::Error> {
730 d.read_option(|d, b| if b { Ok(Some(Decodable::decode(d)?)) } else { Ok(None) })
734 impl<T1: Encodable, T2: Encodable> Encodable for Result<T1, T2> {
735 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
736 s.emit_enum("Result", |s| match *self {
738 s.emit_enum_variant("Ok", 0, 1, |s| s.emit_enum_variant_arg(0, |s| v.encode(s)))
741 s.emit_enum_variant("Err", 1, 1, |s| s.emit_enum_variant_arg(0, |s| v.encode(s)))
747 impl<T1: Decodable, T2: Decodable> Decodable for Result<T1, T2> {
748 fn decode<D: Decoder>(d: &mut D) -> Result<Result<T1, T2>, D::Error> {
749 d.read_enum("Result", |d| {
750 d.read_enum_variant(&["Ok", "Err"], |d, disr| match disr {
751 0 => Ok(Ok(d.read_enum_variant_arg(0, |d| T1::decode(d))?)),
752 1 => Ok(Err(d.read_enum_variant_arg(0, |d| T2::decode(d))?)),
755 "Encountered invalid discriminant while \
765 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
768 /// Evaluates to the number of tokens passed to it.
770 /// Logarithmic counting: every one or two recursive expansions, the number of
771 /// tokens to count is divided by two, instead of being reduced by one.
772 /// Therefore, the recursion depth is the binary logarithm of the number of
773 /// tokens to count, and the expanded tree is likewise very small.
776 ($one:tt) => (1usize);
777 ($($pairs:tt $_p:tt)*) => (count!($($pairs)*) << 1usize);
778 ($odd:tt $($rest:tt)*) => (count!($($rest)*) | 1usize);
783 ( $($name:ident,)+ ) => (
784 impl<$($name:Decodable),+> Decodable for ($($name,)+) {
785 #[allow(non_snake_case)]
786 fn decode<D: Decoder>(d: &mut D) -> Result<($($name,)+), D::Error> {
787 let len: usize = count!($($name)+);
788 d.read_tuple(len, |d| {
790 let ret = ($(d.read_tuple_arg({ i+=1; i-1 }, |d| -> Result<$name, D::Error> {
797 impl<$($name:Encodable),+> Encodable for ($($name,)+) {
798 #[allow(non_snake_case)]
799 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
800 let ($(ref $name,)+) = *self;
802 $(let $name = $name; n += 1;)+
803 s.emit_tuple(n, |s| {
805 $(s.emit_tuple_arg({ i+=1; i-1 }, |s| $name.encode(s))?;)+
814 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
816 impl Encodable for path::Path {
817 fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> {
818 self.to_str().unwrap().encode(e)
822 impl Encodable for path::PathBuf {
823 fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> {
824 path::Path::encode(self, e)
828 impl Decodable for path::PathBuf {
829 fn decode<D: Decoder>(d: &mut D) -> Result<path::PathBuf, D::Error> {
830 let bytes: String = Decodable::decode(d)?;
831 Ok(path::PathBuf::from(bytes))
835 impl<T: Encodable + Copy> Encodable for Cell<T> {
836 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
841 impl<T: Decodable + Copy> Decodable for Cell<T> {
842 fn decode<D: Decoder>(d: &mut D) -> Result<Cell<T>, D::Error> {
843 Ok(Cell::new(Decodable::decode(d)?))
848 // Should use `try_borrow`, returning a
849 // `encoder.error("attempting to Encode borrowed RefCell")`
850 // from `encode` when `try_borrow` returns `None`.
852 impl<T: Encodable> Encodable for RefCell<T> {
853 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
854 self.borrow().encode(s)
858 impl<T: Decodable> Decodable for RefCell<T> {
859 fn decode<D: Decoder>(d: &mut D) -> Result<RefCell<T>, D::Error> {
860 Ok(RefCell::new(Decodable::decode(d)?))
864 impl<T: Encodable> Encodable for Arc<T> {
865 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
870 impl<T: Decodable> Decodable for Arc<T> {
871 fn decode<D: Decoder>(d: &mut D) -> Result<Arc<T>, D::Error> {
872 Ok(Arc::new(Decodable::decode(d)?))
876 // ___________________________________________________________________________
877 // Specialization-based interface for multi-dispatch Encodable/Decodable.
879 /// Implement this trait on your `{Encodable,Decodable}::Error` types
880 /// to override the default panic behavior for missing specializations.
881 pub trait SpecializationError {
882 /// Creates an error for a missing method specialization.
883 /// Defaults to panicking with type, trait & method names.
884 /// `S` is the encoder/decoder state type,
885 /// `T` is the type being encoded/decoded, and
886 /// the arguments are the names of the trait
887 /// and method that should've been overridden.
888 fn not_found<S, T: ?Sized>(trait_name: &'static str, method_name: &'static str) -> Self;
891 impl<E> SpecializationError for E {
892 default fn not_found<S, T: ?Sized>(trait_name: &'static str, method_name: &'static str) -> E {
894 "missing specialization: `<{} as {}<{}>>::{}` not overridden",
895 any::type_name::<S>(),
897 any::type_name::<T>(),
903 /// Implement this trait on encoders, with `T` being the type
904 /// you want to encode (employing `UseSpecializedEncodable`),
905 /// using a strategy specific to the encoder.
906 pub trait SpecializedEncoder<T: ?Sized + UseSpecializedEncodable>: Encoder {
907 /// Encode the value in a manner specific to this encoder state.
908 fn specialized_encode(&mut self, value: &T) -> Result<(), Self::Error>;
911 impl<E: Encoder, T: ?Sized + UseSpecializedEncodable> SpecializedEncoder<T> for E {
912 default fn specialized_encode(&mut self, value: &T) -> Result<(), E::Error> {
913 value.default_encode(self)
917 /// Implement this trait on decoders, with `T` being the type
918 /// you want to decode (employing `UseSpecializedDecodable`),
919 /// using a strategy specific to the decoder.
920 pub trait SpecializedDecoder<T: UseSpecializedDecodable>: Decoder {
921 /// Decode a value in a manner specific to this decoder state.
922 fn specialized_decode(&mut self) -> Result<T, Self::Error>;
925 impl<D: Decoder, T: UseSpecializedDecodable> SpecializedDecoder<T> for D {
926 default fn specialized_decode(&mut self) -> Result<T, D::Error> {
927 T::default_decode(self)
931 /// Implement this trait on your type to get an `Encodable`
932 /// implementation which goes through `SpecializedEncoder`.
933 pub trait UseSpecializedEncodable {
934 /// Defaults to returning an error (see `SpecializationError`).
935 fn default_encode<E: Encoder>(&self, _: &mut E) -> Result<(), E::Error> {
936 Err(E::Error::not_found::<E, Self>("SpecializedEncoder", "specialized_encode"))
940 impl<T: ?Sized + UseSpecializedEncodable> Encodable for T {
941 default fn encode<E: Encoder>(&self, e: &mut E) -> Result<(), E::Error> {
942 E::specialized_encode(e, self)
946 /// Implement this trait on your type to get an `Decodable`
947 /// implementation which goes through `SpecializedDecoder`.
948 pub trait UseSpecializedDecodable: Sized {
949 /// Defaults to returning an error (see `SpecializationError`).
950 fn default_decode<D: Decoder>(_: &mut D) -> Result<Self, D::Error> {
951 Err(D::Error::not_found::<D, Self>("SpecializedDecoder", "specialized_decode"))
955 impl<T: UseSpecializedDecodable> Decodable for T {
956 default fn decode<D: Decoder>(d: &mut D) -> Result<T, D::Error> {
957 D::specialized_decode(d)
961 // Can't avoid specialization for &T and Box<T> impls,
962 // as proxy impls on them are blankets that conflict
963 // with the Encodable and Decodable impls above,
964 // which only have `default` on their methods
965 // for this exact reason.
966 // May be fixable in a simpler fashion via the
967 // more complex lattice model for specialization.
968 impl<'a, T: ?Sized + Encodable> UseSpecializedEncodable for &'a T {}
969 impl<T: ?Sized + Encodable> UseSpecializedEncodable for Box<T> {}
970 impl<T: Decodable> UseSpecializedDecodable for Box<T> {}
971 impl<'a, T: Decodable> UseSpecializedDecodable for &'a T {}
972 impl<'a, T: Decodable> UseSpecializedDecodable for &'a [T] {}