1 //! Support code for encoding and decoding types.
4 Core encoding and decoding interfaces.
9 use std::marker::PhantomData;
12 use std::cell::{Cell, RefCell};
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>
40 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
45 fn emit_enum_variant<F>(&mut self, _v_name: &str, v_id: usize, _len: usize, f: F)
46 -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error>
48 self.emit_usize(v_id)?;
52 fn emit_enum_variant_arg<F>(&mut self, _a_idx: usize, f: F) -> Result<(), Self::Error>
53 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
58 fn emit_enum_struct_variant<F>(&mut self, v_name: &str, v_id: usize, len: usize, f: F)
59 -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error>
61 self.emit_enum_variant(v_name, v_id, len, f)
64 fn emit_enum_struct_variant_field<F>(&mut self, _f_name: &str, f_idx: usize, f: F)
65 -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error>
67 self.emit_enum_variant_arg(f_idx, f)
70 fn emit_struct<F>(&mut self, _name: &str, _len: usize, f: F) -> Result<(), Self::Error>
71 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
76 fn emit_struct_field<F>(&mut self, _f_name: &str, _f_idx: usize, f: F)
77 -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error>
82 fn emit_tuple<F>(&mut self, _len: usize, f: F) -> Result<(), Self::Error>
83 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
88 fn emit_tuple_arg<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
89 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
94 fn emit_tuple_struct<F>(&mut self, _name: &str, len: usize, f: F) -> Result<(), Self::Error>
95 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
97 self.emit_tuple(len, f)
100 fn emit_tuple_struct_arg<F>(&mut self, f_idx: usize, f: F) -> Result<(), Self::Error>
101 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
103 self.emit_tuple_arg(f_idx, f)
106 // Specialized types:
107 fn emit_option<F>(&mut self, f: F) -> Result<(), Self::Error>
108 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
110 self.emit_enum("Option", f)
114 fn emit_option_none(&mut self) -> Result<(), Self::Error> {
115 self.emit_enum_variant("None", 0, 0, |_| Ok(()))
118 fn emit_option_some<F>(&mut self, f: F) -> Result<(), Self::Error>
119 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
121 self.emit_enum_variant("Some", 1, 1, f)
124 fn emit_seq<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
125 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
127 self.emit_usize(len)?;
131 fn emit_seq_elt<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
132 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
137 fn emit_map<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
138 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
140 self.emit_usize(len)?;
144 fn emit_map_elt_key<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
145 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
150 fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
151 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
161 fn read_nil(&mut self) -> Result<(), Self::Error>;
162 fn read_usize(&mut self) -> Result<usize, Self::Error>;
163 fn read_u128(&mut self) -> Result<u128, Self::Error>;
164 fn read_u64(&mut self) -> Result<u64, Self::Error>;
165 fn read_u32(&mut self) -> Result<u32, Self::Error>;
166 fn read_u16(&mut self) -> Result<u16, Self::Error>;
167 fn read_u8(&mut self) -> Result<u8, Self::Error>;
168 fn read_isize(&mut self) -> Result<isize, Self::Error>;
169 fn read_i128(&mut self) -> Result<i128, Self::Error>;
170 fn read_i64(&mut self) -> Result<i64, Self::Error>;
171 fn read_i32(&mut self) -> Result<i32, Self::Error>;
172 fn read_i16(&mut self) -> Result<i16, Self::Error>;
173 fn read_i8(&mut self) -> Result<i8, Self::Error>;
174 fn read_bool(&mut self) -> Result<bool, Self::Error>;
175 fn read_f64(&mut self) -> Result<f64, Self::Error>;
176 fn read_f32(&mut self) -> Result<f32, Self::Error>;
177 fn read_char(&mut self) -> Result<char, Self::Error>;
178 fn read_str(&mut self) -> Result<Cow<'_, str>, Self::Error>;
181 fn read_enum<T, F>(&mut self, _name: &str, f: F) -> Result<T, Self::Error>
182 where F: FnOnce(&mut Self) -> Result<T, Self::Error>
187 fn read_enum_variant<T, F>(&mut self, _names: &[&str], mut f: F) -> Result<T, Self::Error>
188 where F: FnMut(&mut Self, usize) -> Result<T, Self::Error>
190 let disr = self.read_usize()?;
194 fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, f: F) -> Result<T, Self::Error>
195 where F: FnOnce(&mut Self) -> Result<T, Self::Error>
200 fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F) -> Result<T, Self::Error>
201 where F: FnMut(&mut Self, usize) -> Result<T, Self::Error>
203 self.read_enum_variant(names, f)
206 fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, f_idx: usize, f: F)
207 -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error>
209 self.read_enum_variant_arg(f_idx, f)
212 fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, f: F) -> Result<T, Self::Error>
213 where F: FnOnce(&mut Self) -> Result<T, Self::Error>
218 fn read_struct_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, f: F)
219 -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error>
224 fn read_tuple<T, F>(&mut self, _len: usize, f: F) -> Result<T, Self::Error>
225 where F: FnOnce(&mut Self) -> Result<T, Self::Error>
230 fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, f: F) -> Result<T, Self::Error>
231 where F: FnOnce(&mut Self) -> Result<T, Self::Error>
236 fn read_tuple_struct<T, F>(&mut self, _s_name: &str, len: usize, f: F) -> Result<T, Self::Error>
237 where F: FnOnce(&mut Self) -> Result<T, Self::Error>
239 self.read_tuple(len, f)
242 fn read_tuple_struct_arg<T, F>(&mut self, a_idx: usize, f: F) -> Result<T, Self::Error>
243 where F: FnOnce(&mut Self) -> Result<T, Self::Error>
245 self.read_tuple_arg(a_idx, f)
248 // Specialized types:
249 fn read_option<T, F>(&mut self, mut f: F) -> Result<T, Self::Error>
250 where F: FnMut(&mut Self, bool) -> Result<T, Self::Error>
252 self.read_enum("Option", move |this| {
253 this.read_enum_variant(&["None", "Some"], move |this, idx| {
257 _ => Err(this.error("read_option: expected 0 for None or 1 for Some")),
263 fn read_seq<T, F>(&mut self, f: F) -> Result<T, Self::Error>
264 where F: FnOnce(&mut Self, usize) -> Result<T, Self::Error>
266 let len = self.read_usize()?;
270 fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error>
271 where F: FnOnce(&mut Self) -> Result<T, Self::Error>
276 fn read_map<T, F>(&mut self, f: F) -> Result<T, Self::Error>
277 where F: FnOnce(&mut Self, usize) -> Result<T, Self::Error>
279 let len = self.read_usize()?;
283 fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error>
284 where F: FnOnce(&mut Self) -> Result<T, Self::Error>
289 fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error>
290 where F: FnOnce(&mut Self) -> Result<T, Self::Error>
296 fn error(&mut self, err: &str) -> Self::Error;
299 pub trait Encodable {
300 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error>;
303 pub trait Decodable: Sized {
304 fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error>;
307 impl Encodable for usize {
308 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
313 impl Decodable for usize {
314 fn decode<D: Decoder>(d: &mut D) -> Result<usize, D::Error> {
319 impl Encodable for u8 {
320 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
325 impl Decodable for u8 {
326 fn decode<D: Decoder>(d: &mut D) -> Result<u8, D::Error> {
331 impl Encodable for u16 {
332 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
337 impl Decodable for u16 {
338 fn decode<D: Decoder>(d: &mut D) -> Result<u16, D::Error> {
343 impl Encodable for u32 {
344 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
349 impl Decodable for u32 {
350 fn decode<D: Decoder>(d: &mut D) -> Result<u32, D::Error> {
355 impl Encodable for ::std::num::NonZeroU32 {
356 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
357 s.emit_u32(self.get())
361 impl Decodable for ::std::num::NonZeroU32 {
362 fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
363 d.read_u32().map(|d| ::std::num::NonZeroU32::new(d).unwrap())
367 impl Encodable for u64 {
368 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
373 impl Decodable for u64 {
374 fn decode<D: Decoder>(d: &mut D) -> Result<u64, D::Error> {
379 impl Encodable for u128 {
380 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
385 impl Decodable for u128 {
386 fn decode<D: Decoder>(d: &mut D) -> Result<u128, D::Error> {
391 impl Encodable for isize {
392 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
397 impl Decodable for isize {
398 fn decode<D: Decoder>(d: &mut D) -> Result<isize, D::Error> {
403 impl Encodable for i8 {
404 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
409 impl Decodable for i8 {
410 fn decode<D: Decoder>(d: &mut D) -> Result<i8, D::Error> {
415 impl Encodable for i16 {
416 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
421 impl Decodable for i16 {
422 fn decode<D: Decoder>(d: &mut D) -> Result<i16, D::Error> {
427 impl Encodable for i32 {
428 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
433 impl Decodable for i32 {
434 fn decode<D: Decoder>(d: &mut D) -> Result<i32, D::Error> {
439 impl Encodable for i64 {
440 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
445 impl Decodable for i64 {
446 fn decode<D: Decoder>(d: &mut D) -> Result<i64, D::Error> {
451 impl Encodable for i128 {
452 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
457 impl Decodable for i128 {
458 fn decode<D: Decoder>(d: &mut D) -> Result<i128, D::Error> {
463 impl Encodable for str {
464 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
469 impl Encodable for String {
470 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
471 s.emit_str(&self[..])
475 impl Decodable for String {
476 fn decode<D: Decoder>(d: &mut D) -> Result<String, D::Error> {
477 Ok(d.read_str()?.into_owned())
481 impl Encodable for f32 {
482 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
487 impl Decodable for f32 {
488 fn decode<D: Decoder>(d: &mut D) -> Result<f32, D::Error> {
493 impl Encodable for f64 {
494 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
499 impl Decodable for f64 {
500 fn decode<D: Decoder>(d: &mut D) -> Result<f64, D::Error> {
505 impl Encodable for bool {
506 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
511 impl Decodable for bool {
512 fn decode<D: Decoder>(d: &mut D) -> Result<bool, D::Error> {
517 impl Encodable for char {
518 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
523 impl Decodable for char {
524 fn decode<D: Decoder>(d: &mut D) -> Result<char, D::Error> {
529 impl Encodable for () {
530 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
535 impl Decodable for () {
536 fn decode<D: Decoder>(d: &mut D) -> Result<(), D::Error> {
541 impl<T> Encodable for PhantomData<T> {
542 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
547 impl<T> Decodable for PhantomData<T> {
548 fn decode<D: Decoder>(d: &mut D) -> Result<PhantomData<T>, D::Error> {
554 impl<'a, T: ?Sized + Encodable> Encodable for &'a T {
555 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
560 impl<T: ?Sized + Encodable> Encodable for Box<T> {
561 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
566 impl< T: Decodable> Decodable for Box<T> {
567 fn decode<D: Decoder>(d: &mut D) -> Result<Box<T>, D::Error> {
568 Ok(box Decodable::decode(d)?)
572 impl< T: Decodable> Decodable for Box<[T]> {
573 fn decode<D: Decoder>(d: &mut D) -> Result<Box<[T]>, D::Error> {
574 let v: Vec<T> = Decodable::decode(d)?;
575 Ok(v.into_boxed_slice())
579 impl<T:Encodable> Encodable for Rc<T> {
580 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
585 impl<T:Decodable> Decodable for Rc<T> {
586 fn decode<D: Decoder>(d: &mut D) -> Result<Rc<T>, D::Error> {
587 Ok(Rc::new(Decodable::decode(d)?))
591 impl<T:Encodable> Encodable for [T] {
592 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
593 s.emit_seq(self.len(), |s| {
594 for (i, e) in self.iter().enumerate() {
595 s.emit_seq_elt(i, |s| e.encode(s))?
602 impl<T:Encodable> Encodable for Vec<T> {
603 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
604 s.emit_seq(self.len(), |s| {
605 for (i, e) in self.iter().enumerate() {
606 s.emit_seq_elt(i, |s| e.encode(s))?
613 impl<T:Decodable> Decodable for Vec<T> {
614 fn decode<D: Decoder>(d: &mut D) -> Result<Vec<T>, D::Error> {
615 d.read_seq(|d, len| {
616 let mut v = Vec::with_capacity(len);
618 v.push(d.read_seq_elt(i, |d| Decodable::decode(d))?);
625 impl<'a, T:Encodable> Encodable for Cow<'a, [T]> where [T]: ToOwned<Owned = Vec<T>> {
626 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
627 s.emit_seq(self.len(), |s| {
628 for (i, e) in self.iter().enumerate() {
629 s.emit_seq_elt(i, |s| e.encode(s))?
636 impl<T:Decodable+ToOwned> Decodable for Cow<'static, [T]>
637 where [T]: ToOwned<Owned = Vec<T>>
639 fn decode<D: Decoder>(d: &mut D) -> Result<Cow<'static, [T]>, D::Error> {
640 d.read_seq(|d, len| {
641 let mut v = Vec::with_capacity(len);
643 v.push(d.read_seq_elt(i, |d| Decodable::decode(d))?);
651 impl<T:Encodable> Encodable for Option<T> {
652 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
655 None => s.emit_option_none(),
656 Some(ref v) => s.emit_option_some(|s| v.encode(s)),
662 impl<T:Decodable> Decodable for Option<T> {
663 fn decode<D: Decoder>(d: &mut D) -> Result<Option<T>, D::Error> {
664 d.read_option(|d, b| {
666 Ok(Some(Decodable::decode(d)?))
674 impl<T1: Encodable, T2: Encodable> Encodable for Result<T1, T2> {
675 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
676 s.emit_enum("Result", |s| {
679 s.emit_enum_variant("Ok", 0, 1, |s| {
680 s.emit_enum_variant_arg(0, |s| {
686 s.emit_enum_variant("Err", 1, 1, |s| {
687 s.emit_enum_variant_arg(0, |s| {
697 impl<T1:Decodable, T2:Decodable> Decodable for Result<T1, T2> {
698 fn decode<D: Decoder>(d: &mut D) -> Result<Result<T1, T2>, D::Error> {
699 d.read_enum("Result", |d| {
700 d.read_enum_variant(&["Ok", "Err"], |d, disr| {
703 Ok(Ok(d.read_enum_variant_arg(0, |d| {
708 Ok(Err(d.read_enum_variant_arg(0, |d| {
713 panic!("Encountered invalid discriminant while \
714 decoding `Result`.");
723 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
726 /// Evaluates to the number of identifiers passed to it, for example: `count_idents!(a, b, c) == 3
727 macro_rules! count_idents {
729 ($_i:ident, $($rest:ident,)*) => { 1 + count_idents!($($rest,)*) }
734 ( $($name:ident,)+ ) => (
735 impl<$($name:Decodable),*> Decodable for ($($name,)*) {
736 #[allow(non_snake_case)]
737 fn decode<D: Decoder>(d: &mut D) -> Result<($($name,)*), D::Error> {
738 let len: usize = count_idents!($($name,)*);
739 d.read_tuple(len, |d| {
741 let ret = ($(d.read_tuple_arg({ i+=1; i-1 }, |d| -> Result<$name, D::Error> {
748 impl<$($name:Encodable),*> Encodable for ($($name,)*) {
749 #[allow(non_snake_case)]
750 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
751 let ($(ref $name,)*) = *self;
753 $(let $name = $name; n += 1;)*
754 s.emit_tuple(n, |s| {
756 $(s.emit_tuple_arg({ i+=1; i-1 }, |s| $name.encode(s))?;)*
765 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
767 impl Encodable for path::Path {
768 fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> {
769 self.to_str().unwrap().encode(e)
773 impl Encodable for path::PathBuf {
774 fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> {
775 path::Path::encode(self, e)
779 impl Decodable for path::PathBuf {
780 fn decode<D: Decoder>(d: &mut D) -> Result<path::PathBuf, D::Error> {
781 let bytes: String = Decodable::decode(d)?;
782 Ok(path::PathBuf::from(bytes))
786 impl<T: Encodable + Copy> Encodable for Cell<T> {
787 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
792 impl<T: Decodable + Copy> Decodable for Cell<T> {
793 fn decode<D: Decoder>(d: &mut D) -> Result<Cell<T>, D::Error> {
794 Ok(Cell::new(Decodable::decode(d)?))
799 // Should use `try_borrow`, returning a
800 // `encoder.error("attempting to Encode borrowed RefCell")`
801 // from `encode` when `try_borrow` returns `None`.
803 impl<T: Encodable> Encodable for RefCell<T> {
804 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
805 self.borrow().encode(s)
809 impl<T: Decodable> Decodable for RefCell<T> {
810 fn decode<D: Decoder>(d: &mut D) -> Result<RefCell<T>, D::Error> {
811 Ok(RefCell::new(Decodable::decode(d)?))
815 impl<T:Encodable> Encodable for Arc<T> {
816 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
821 impl<T:Decodable> Decodable for Arc<T> {
822 fn decode<D: Decoder>(d: &mut D) -> Result<Arc<T>, D::Error> {
823 Ok(Arc::new(Decodable::decode(d)?))
827 // ___________________________________________________________________________
828 // Specialization-based interface for multi-dispatch Encodable/Decodable.
830 /// Implement this trait on your `{Encodable,Decodable}::Error` types
831 /// to override the default panic behavior for missing specializations.
832 pub trait SpecializationError {
833 /// Creates an error for a missing method specialization.
834 /// Defaults to panicking with type, trait & method names.
835 /// `S` is the encoder/decoder state type,
836 /// `T` is the type being encoded/decoded, and
837 /// the arguments are the names of the trait
838 /// and method that should've been overridden.
839 fn not_found<S, T: ?Sized>(trait_name: &'static str, method_name: &'static str) -> Self;
842 impl<E> SpecializationError for E {
843 default fn not_found<S, T: ?Sized>(trait_name: &'static str, method_name: &'static str) -> E {
844 panic!("missing specialization: `<{} as {}<{}>>::{}` not overridden",
845 unsafe { intrinsics::type_name::<S>() },
847 unsafe { intrinsics::type_name::<T>() },
852 /// Implement this trait on encoders, with `T` being the type
853 /// you want to encode (employing `UseSpecializedEncodable`),
854 /// using a strategy specific to the encoder.
855 pub trait SpecializedEncoder<T: ?Sized + UseSpecializedEncodable>: Encoder {
856 /// Encode the value in a manner specific to this encoder state.
857 fn specialized_encode(&mut self, value: &T) -> Result<(), Self::Error>;
860 impl<E: Encoder, T: ?Sized + UseSpecializedEncodable> SpecializedEncoder<T> for E {
861 default fn specialized_encode(&mut self, value: &T) -> Result<(), E::Error> {
862 value.default_encode(self)
866 /// Implement this trait on decoders, with `T` being the type
867 /// you want to decode (employing `UseSpecializedDecodable`),
868 /// using a strategy specific to the decoder.
869 pub trait SpecializedDecoder<T: UseSpecializedDecodable>: Decoder {
870 /// Decode a value in a manner specific to this decoder state.
871 fn specialized_decode(&mut self) -> Result<T, Self::Error>;
874 impl<D: Decoder, T: UseSpecializedDecodable> SpecializedDecoder<T> for D {
875 default fn specialized_decode(&mut self) -> Result<T, D::Error> {
876 T::default_decode(self)
880 /// Implement this trait on your type to get an `Encodable`
881 /// implementation which goes through `SpecializedEncoder`.
882 pub trait UseSpecializedEncodable {
883 /// Defaults to returning an error (see `SpecializationError`).
884 fn default_encode<E: Encoder>(&self, _: &mut E) -> Result<(), E::Error> {
885 Err(E::Error::not_found::<E, Self>("SpecializedEncoder", "specialized_encode"))
889 impl<T: ?Sized + UseSpecializedEncodable> Encodable for T {
890 default fn encode<E: Encoder>(&self, e: &mut E) -> Result<(), E::Error> {
891 E::specialized_encode(e, self)
895 /// Implement this trait on your type to get an `Decodable`
896 /// implementation which goes through `SpecializedDecoder`.
897 pub trait UseSpecializedDecodable: Sized {
898 /// Defaults to returning an error (see `SpecializationError`).
899 fn default_decode<D: Decoder>(_: &mut D) -> Result<Self, D::Error> {
900 Err(D::Error::not_found::<D, Self>("SpecializedDecoder", "specialized_decode"))
904 impl<T: UseSpecializedDecodable> Decodable for T {
905 default fn decode<D: Decoder>(d: &mut D) -> Result<T, D::Error> {
906 D::specialized_decode(d)
910 // Can't avoid specialization for &T and Box<T> impls,
911 // as proxy impls on them are blankets that conflict
912 // with the Encodable and Decodable impls above,
913 // which only have `default` on their methods
914 // for this exact reason.
915 // May be fixable in a simpler fashion via the
916 // more complex lattice model for specialization.
917 impl<'a, T: ?Sized + Encodable> UseSpecializedEncodable for &'a T {}
918 impl<T: ?Sized + Encodable> UseSpecializedEncodable for Box<T> {}
919 impl<T: Decodable> UseSpecializedDecodable for Box<T> {}
920 impl<'a, T: Decodable> UseSpecializedDecodable for &'a T {}
921 impl<'a, T: Decodable> UseSpecializedDecodable for &'a [T] {}