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<T: Decodable> Decodable for Box<[T]> {
639 fn decode<D: Decoder>(d: &mut D) -> Result<Box<[T]>, D::Error> {
640 let v: Vec<T> = Decodable::decode(d)?;
641 Ok(v.into_boxed_slice())
645 impl<T: Encodable> Encodable for Rc<T> {
646 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
651 impl<T: Decodable> Decodable for Rc<T> {
652 fn decode<D: Decoder>(d: &mut D) -> Result<Rc<T>, D::Error> {
653 Ok(Rc::new(Decodable::decode(d)?))
657 impl<T: Encodable> Encodable for [T] {
658 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
659 s.emit_seq(self.len(), |s| {
660 for (i, e) in self.iter().enumerate() {
661 s.emit_seq_elt(i, |s| e.encode(s))?
668 impl<T: Encodable> Encodable for Vec<T> {
669 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
670 s.emit_seq(self.len(), |s| {
671 for (i, e) in self.iter().enumerate() {
672 s.emit_seq_elt(i, |s| e.encode(s))?
679 impl<T: Decodable> Decodable for Vec<T> {
680 fn decode<D: Decoder>(d: &mut D) -> Result<Vec<T>, D::Error> {
681 d.read_seq(|d, len| {
682 let mut v = Vec::with_capacity(len);
684 v.push(d.read_seq_elt(i, |d| Decodable::decode(d))?);
691 impl Encodable for [u8; 20] {
692 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
693 s.emit_seq(self.len(), |s| {
694 for (i, e) in self.iter().enumerate() {
695 s.emit_seq_elt(i, |s| e.encode(s))?
702 impl Decodable for [u8; 20] {
703 fn decode<D: Decoder>(d: &mut D) -> Result<[u8; 20], D::Error> {
704 d.read_seq(|d, len| {
706 let mut v = [0u8; 20];
708 v[i] = d.read_seq_elt(i, |d| Decodable::decode(d))?;
715 impl<'a, T: Encodable> Encodable for Cow<'a, [T]>
717 [T]: ToOwned<Owned = Vec<T>>,
719 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
720 s.emit_seq(self.len(), |s| {
721 for (i, e) in self.iter().enumerate() {
722 s.emit_seq_elt(i, |s| e.encode(s))?
729 impl<T: Decodable + ToOwned> Decodable for Cow<'static, [T]>
731 [T]: ToOwned<Owned = Vec<T>>,
733 fn decode<D: Decoder>(d: &mut D) -> Result<Cow<'static, [T]>, D::Error> {
734 d.read_seq(|d, len| {
735 let mut v = Vec::with_capacity(len);
737 v.push(d.read_seq_elt(i, |d| Decodable::decode(d))?);
744 impl<T: Encodable> Encodable for Option<T> {
745 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
746 s.emit_option(|s| match *self {
747 None => s.emit_option_none(),
748 Some(ref v) => s.emit_option_some(|s| v.encode(s)),
753 impl<T: Decodable> Decodable for Option<T> {
754 fn decode<D: Decoder>(d: &mut D) -> Result<Option<T>, D::Error> {
755 d.read_option(|d, b| if b { Ok(Some(Decodable::decode(d)?)) } else { Ok(None) })
759 impl<T1: Encodable, T2: Encodable> Encodable for Result<T1, T2> {
760 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
761 s.emit_enum("Result", |s| match *self {
763 s.emit_enum_variant("Ok", 0, 1, |s| s.emit_enum_variant_arg(0, |s| v.encode(s)))
766 s.emit_enum_variant("Err", 1, 1, |s| s.emit_enum_variant_arg(0, |s| v.encode(s)))
772 impl<T1: Decodable, T2: Decodable> Decodable for Result<T1, T2> {
773 fn decode<D: Decoder>(d: &mut D) -> Result<Result<T1, T2>, D::Error> {
774 d.read_enum("Result", |d| {
775 d.read_enum_variant(&["Ok", "Err"], |d, disr| match disr {
776 0 => Ok(Ok(d.read_enum_variant_arg(0, |d| T1::decode(d))?)),
777 1 => Ok(Err(d.read_enum_variant_arg(0, |d| T2::decode(d))?)),
780 "Encountered invalid discriminant while \
790 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
793 /// Evaluates to the number of tokens passed to it.
795 /// Logarithmic counting: every one or two recursive expansions, the number of
796 /// tokens to count is divided by two, instead of being reduced by one.
797 /// Therefore, the recursion depth is the binary logarithm of the number of
798 /// tokens to count, and the expanded tree is likewise very small.
801 ($one:tt) => (1usize);
802 ($($pairs:tt $_p:tt)*) => (count!($($pairs)*) << 1usize);
803 ($odd:tt $($rest:tt)*) => (count!($($rest)*) | 1usize);
808 ( $($name:ident,)+ ) => (
809 impl<$($name:Decodable),+> Decodable for ($($name,)+) {
810 #[allow(non_snake_case)]
811 fn decode<D: Decoder>(d: &mut D) -> Result<($($name,)+), D::Error> {
812 let len: usize = count!($($name)+);
813 d.read_tuple(len, |d| {
815 let ret = ($(d.read_tuple_arg({ i+=1; i-1 }, |d| -> Result<$name, D::Error> {
822 impl<$($name:Encodable),+> Encodable for ($($name,)+) {
823 #[allow(non_snake_case)]
824 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
825 let ($(ref $name,)+) = *self;
827 $(let $name = $name; n += 1;)+
828 s.emit_tuple(n, |s| {
830 $(s.emit_tuple_arg({ i+=1; i-1 }, |s| $name.encode(s))?;)+
839 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
841 impl Encodable for path::Path {
842 fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> {
843 self.to_str().unwrap().encode(e)
847 impl Encodable for path::PathBuf {
848 fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> {
849 path::Path::encode(self, e)
853 impl Decodable for path::PathBuf {
854 fn decode<D: Decoder>(d: &mut D) -> Result<path::PathBuf, D::Error> {
855 let bytes: String = Decodable::decode(d)?;
856 Ok(path::PathBuf::from(bytes))
860 impl<T: Encodable + Copy> Encodable for Cell<T> {
861 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
866 impl<T: Decodable + Copy> Decodable for Cell<T> {
867 fn decode<D: Decoder>(d: &mut D) -> Result<Cell<T>, D::Error> {
868 Ok(Cell::new(Decodable::decode(d)?))
873 // Should use `try_borrow`, returning a
874 // `encoder.error("attempting to Encode borrowed RefCell")`
875 // from `encode` when `try_borrow` returns `None`.
877 impl<T: Encodable> Encodable for RefCell<T> {
878 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
879 self.borrow().encode(s)
883 impl<T: Decodable> Decodable for RefCell<T> {
884 fn decode<D: Decoder>(d: &mut D) -> Result<RefCell<T>, D::Error> {
885 Ok(RefCell::new(Decodable::decode(d)?))
889 impl<T: Encodable> Encodable for Arc<T> {
890 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
895 impl<T: Decodable> Decodable for Arc<T> {
896 fn decode<D: Decoder>(d: &mut D) -> Result<Arc<T>, D::Error> {
897 Ok(Arc::new(Decodable::decode(d)?))
901 // ___________________________________________________________________________
902 // Specialization-based interface for multi-dispatch Encodable/Decodable.
904 /// Implement this trait on your `{Encodable,Decodable}::Error` types
905 /// to override the default panic behavior for missing specializations.
906 pub trait SpecializationError {
907 /// Creates an error for a missing method specialization.
908 /// Defaults to panicking with type, trait & method names.
909 /// `S` is the encoder/decoder state type,
910 /// `T` is the type being encoded/decoded, and
911 /// the arguments are the names of the trait
912 /// and method that should've been overridden.
913 fn not_found<S, T: ?Sized>(trait_name: &'static str, method_name: &'static str) -> Self;
916 impl<E> SpecializationError for E {
917 default fn not_found<S, T: ?Sized>(trait_name: &'static str, method_name: &'static str) -> E {
919 "missing specialization: `<{} as {}<{}>>::{}` not overridden",
920 any::type_name::<S>(),
922 any::type_name::<T>(),
928 /// Implement this trait on encoders, with `T` being the type
929 /// you want to encode (employing `UseSpecializedEncodable`),
930 /// using a strategy specific to the encoder.
931 pub trait SpecializedEncoder<T: ?Sized + UseSpecializedEncodable>: Encoder {
932 /// Encode the value in a manner specific to this encoder state.
933 fn specialized_encode(&mut self, value: &T) -> Result<(), Self::Error>;
936 impl<E: Encoder, T: ?Sized + UseSpecializedEncodable> SpecializedEncoder<T> for E {
937 default fn specialized_encode(&mut self, value: &T) -> Result<(), E::Error> {
938 value.default_encode(self)
942 /// Implement this trait on decoders, with `T` being the type
943 /// you want to decode (employing `UseSpecializedDecodable`),
944 /// using a strategy specific to the decoder.
945 pub trait SpecializedDecoder<T: UseSpecializedDecodable>: Decoder {
946 /// Decode a value in a manner specific to this decoder state.
947 fn specialized_decode(&mut self) -> Result<T, Self::Error>;
950 impl<D: Decoder, T: UseSpecializedDecodable> SpecializedDecoder<T> for D {
951 default fn specialized_decode(&mut self) -> Result<T, D::Error> {
952 T::default_decode(self)
956 /// Implement this trait on your type to get an `Encodable`
957 /// implementation which goes through `SpecializedEncoder`.
958 pub trait UseSpecializedEncodable {
959 /// Defaults to returning an error (see `SpecializationError`).
960 fn default_encode<E: Encoder>(&self, _: &mut E) -> Result<(), E::Error> {
961 Err(E::Error::not_found::<E, Self>("SpecializedEncoder", "specialized_encode"))
965 impl<T: ?Sized + UseSpecializedEncodable> Encodable for T {
966 default fn encode<E: Encoder>(&self, e: &mut E) -> Result<(), E::Error> {
967 E::specialized_encode(e, self)
971 /// Implement this trait on your type to get an `Decodable`
972 /// implementation which goes through `SpecializedDecoder`.
973 pub trait UseSpecializedDecodable: Sized {
974 /// Defaults to returning an error (see `SpecializationError`).
975 fn default_decode<D: Decoder>(_: &mut D) -> Result<Self, D::Error> {
976 Err(D::Error::not_found::<D, Self>("SpecializedDecoder", "specialized_decode"))
980 impl<T: UseSpecializedDecodable> Decodable for T {
981 default fn decode<D: Decoder>(d: &mut D) -> Result<T, D::Error> {
982 D::specialized_decode(d)
986 // Can't avoid specialization for &T and Box<T> impls,
987 // as proxy impls on them are blankets that conflict
988 // with the Encodable and Decodable impls above,
989 // which only have `default` on their methods
990 // for this exact reason.
991 // May be fixable in a simpler fashion via the
992 // more complex lattice model for specialization.
993 impl<'a, T: ?Sized + Encodable> UseSpecializedEncodable for &'a T {
994 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
998 impl<T: ?Sized + Encodable> UseSpecializedEncodable for Box<T> {
999 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1003 impl<T: Decodable> UseSpecializedDecodable for Box<T> {
1004 fn default_decode<D: Decoder>(d: &mut D) -> Result<Box<T>, D::Error> {
1005 Ok(box Decodable::decode(d)?)
1008 impl<'a, T: Decodable> UseSpecializedDecodable for &'a T {}
1009 impl<'a, T: Decodable> UseSpecializedDecodable for &'a [T] {}