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.
21 use std::cell::{Cell, RefCell};
28 fn emit_unit(&mut self) -> Result<(), Self::Error>;
29 fn emit_usize(&mut self, v: usize) -> Result<(), Self::Error>;
30 fn emit_u128(&mut self, v: u128) -> Result<(), Self::Error>;
31 fn emit_u64(&mut self, v: u64) -> Result<(), Self::Error>;
32 fn emit_u32(&mut self, v: u32) -> Result<(), Self::Error>;
33 fn emit_u16(&mut self, v: u16) -> Result<(), Self::Error>;
34 fn emit_u8(&mut self, v: u8) -> Result<(), Self::Error>;
35 fn emit_isize(&mut self, v: isize) -> Result<(), Self::Error>;
36 fn emit_i128(&mut self, v: i128) -> Result<(), Self::Error>;
37 fn emit_i64(&mut self, v: i64) -> Result<(), Self::Error>;
38 fn emit_i32(&mut self, v: i32) -> Result<(), Self::Error>;
39 fn emit_i16(&mut self, v: i16) -> Result<(), Self::Error>;
40 fn emit_i8(&mut self, v: i8) -> Result<(), Self::Error>;
41 fn emit_bool(&mut self, v: bool) -> Result<(), Self::Error>;
42 fn emit_f64(&mut self, v: f64) -> Result<(), Self::Error>;
43 fn emit_f32(&mut self, v: f32) -> Result<(), Self::Error>;
44 fn emit_char(&mut self, v: char) -> Result<(), Self::Error>;
45 fn emit_str(&mut self, v: &str) -> Result<(), Self::Error>;
48 fn emit_enum<F>(&mut self, _name: &str, f: F) -> Result<(), Self::Error>
49 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
54 fn emit_enum_variant<F>(&mut self, _v_name: &str, v_id: usize, _len: usize, f: F)
55 -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error>
57 self.emit_usize(v_id)?;
61 fn emit_enum_variant_arg<F>(&mut self, _a_idx: usize, f: F) -> Result<(), Self::Error>
62 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
67 fn emit_enum_struct_variant<F>(&mut self, v_name: &str, v_id: usize, len: usize, f: F)
68 -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error>
70 self.emit_enum_variant(v_name, v_id, len, f)
73 fn emit_enum_struct_variant_field<F>(&mut self, _f_name: &str, f_idx: usize, f: F)
74 -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error>
76 self.emit_enum_variant_arg(f_idx, f)
79 fn emit_struct<F>(&mut self, _name: &str, _len: usize, f: F) -> Result<(), Self::Error>
80 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
85 fn emit_struct_field<F>(&mut self, _f_name: &str, _f_idx: usize, f: F)
86 -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error>
91 fn emit_tuple<F>(&mut self, _len: usize, f: F) -> Result<(), Self::Error>
92 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
97 fn emit_tuple_arg<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
98 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
103 fn emit_tuple_struct<F>(&mut self, _name: &str, len: usize, f: F) -> Result<(), Self::Error>
104 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
106 self.emit_tuple(len, f)
109 fn emit_tuple_struct_arg<F>(&mut self, f_idx: usize, f: F) -> Result<(), Self::Error>
110 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
112 self.emit_tuple_arg(f_idx, f)
115 // Specialized types:
116 fn emit_option<F>(&mut self, f: F) -> Result<(), Self::Error>
117 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
119 self.emit_enum("Option", f)
123 fn emit_option_none(&mut self) -> Result<(), Self::Error> {
124 self.emit_enum_variant("None", 0, 0, |_| Ok(()))
127 fn emit_option_some<F>(&mut self, f: F) -> Result<(), Self::Error>
128 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
130 self.emit_enum_variant("Some", 1, 1, f)
133 fn emit_seq<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
134 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
136 self.emit_usize(len)?;
140 fn emit_seq_elt<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
141 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
146 fn emit_map<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
147 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
149 self.emit_usize(len)?;
153 fn emit_map_elt_key<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
154 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
159 fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
160 where F: FnOnce(&mut Self) -> Result<(), Self::Error>
170 fn read_nil(&mut self) -> Result<(), Self::Error>;
171 fn read_usize(&mut self) -> Result<usize, Self::Error>;
172 fn read_u128(&mut self) -> Result<u128, Self::Error>;
173 fn read_u64(&mut self) -> Result<u64, Self::Error>;
174 fn read_u32(&mut self) -> Result<u32, Self::Error>;
175 fn read_u16(&mut self) -> Result<u16, Self::Error>;
176 fn read_u8(&mut self) -> Result<u8, Self::Error>;
177 fn read_isize(&mut self) -> Result<isize, Self::Error>;
178 fn read_i128(&mut self) -> Result<i128, Self::Error>;
179 fn read_i64(&mut self) -> Result<i64, Self::Error>;
180 fn read_i32(&mut self) -> Result<i32, Self::Error>;
181 fn read_i16(&mut self) -> Result<i16, Self::Error>;
182 fn read_i8(&mut self) -> Result<i8, Self::Error>;
183 fn read_bool(&mut self) -> Result<bool, Self::Error>;
184 fn read_f64(&mut self) -> Result<f64, Self::Error>;
185 fn read_f32(&mut self) -> Result<f32, Self::Error>;
186 fn read_char(&mut self) -> Result<char, Self::Error>;
187 fn read_str(&mut self) -> Result<Cow<str>, Self::Error>;
190 fn read_enum<T, F>(&mut self, _name: &str, f: F) -> Result<T, Self::Error>
191 where F: FnOnce(&mut Self) -> Result<T, Self::Error>
196 fn read_enum_variant<T, F>(&mut self, _names: &[&str], mut f: F) -> Result<T, Self::Error>
197 where F: FnMut(&mut Self, usize) -> Result<T, Self::Error>
199 let disr = self.read_usize()?;
203 fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, f: F) -> Result<T, Self::Error>
204 where F: FnOnce(&mut Self) -> Result<T, Self::Error>
209 fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F) -> Result<T, Self::Error>
210 where F: FnMut(&mut Self, usize) -> Result<T, Self::Error>
212 self.read_enum_variant(names, f)
215 fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, f_idx: usize, f: F)
216 -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error>
218 self.read_enum_variant_arg(f_idx, f)
221 fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, f: F) -> Result<T, Self::Error>
222 where F: FnOnce(&mut Self) -> Result<T, Self::Error>
227 fn read_struct_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, f: F)
228 -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error>
233 fn read_tuple<T, F>(&mut self, _len: usize, f: F) -> Result<T, Self::Error>
234 where F: FnOnce(&mut Self) -> Result<T, Self::Error>
239 fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, f: F) -> Result<T, Self::Error>
240 where F: FnOnce(&mut Self) -> Result<T, Self::Error>
245 fn read_tuple_struct<T, F>(&mut self, _s_name: &str, len: usize, f: F) -> Result<T, Self::Error>
246 where F: FnOnce(&mut Self) -> Result<T, Self::Error>
248 self.read_tuple(len, f)
251 fn read_tuple_struct_arg<T, F>(&mut self, a_idx: usize, f: F) -> Result<T, Self::Error>
252 where F: FnOnce(&mut Self) -> Result<T, Self::Error>
254 self.read_tuple_arg(a_idx, f)
257 // Specialized types:
258 fn read_option<T, F>(&mut self, mut f: F) -> Result<T, Self::Error>
259 where F: FnMut(&mut Self, bool) -> Result<T, Self::Error>
261 self.read_enum("Option", move |this| {
262 this.read_enum_variant(&["None", "Some"], move |this, idx| {
266 _ => Err(this.error("read_option: expected 0 for None or 1 for Some")),
272 fn read_seq<T, F>(&mut self, f: F) -> Result<T, Self::Error>
273 where F: FnOnce(&mut Self, usize) -> Result<T, Self::Error>
275 let len = self.read_usize()?;
279 fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error>
280 where F: FnOnce(&mut Self) -> Result<T, Self::Error>
285 fn read_map<T, F>(&mut self, f: F) -> Result<T, Self::Error>
286 where F: FnOnce(&mut Self, usize) -> Result<T, Self::Error>
288 let len = self.read_usize()?;
292 fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error>
293 where F: FnOnce(&mut Self) -> Result<T, Self::Error>
298 fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error>
299 where F: FnOnce(&mut Self) -> Result<T, Self::Error>
305 fn error(&mut self, err: &str) -> Self::Error;
308 pub trait Encodable {
309 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error>;
312 pub trait Decodable: Sized {
313 fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error>;
316 impl Encodable for usize {
317 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
322 impl Decodable for usize {
323 fn decode<D: Decoder>(d: &mut D) -> Result<usize, D::Error> {
328 impl Encodable for u8 {
329 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
334 impl Decodable for u8 {
335 fn decode<D: Decoder>(d: &mut D) -> Result<u8, D::Error> {
340 impl Encodable for u16 {
341 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
346 impl Decodable for u16 {
347 fn decode<D: Decoder>(d: &mut D) -> Result<u16, D::Error> {
352 impl Encodable for u32 {
353 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
358 impl Decodable for u32 {
359 fn decode<D: Decoder>(d: &mut D) -> Result<u32, D::Error> {
364 impl Encodable for ::std::num::NonZeroU32 {
365 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
366 s.emit_u32(self.get())
370 impl Decodable for ::std::num::NonZeroU32 {
371 fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
372 d.read_u32().map(|d| ::std::num::NonZeroU32::new(d).unwrap())
376 impl Encodable for u64 {
377 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
382 impl Decodable for u64 {
383 fn decode<D: Decoder>(d: &mut D) -> Result<u64, D::Error> {
388 impl Encodable for u128 {
389 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
394 impl Decodable for u128 {
395 fn decode<D: Decoder>(d: &mut D) -> Result<u128, D::Error> {
400 impl Encodable for isize {
401 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
406 impl Decodable for isize {
407 fn decode<D: Decoder>(d: &mut D) -> Result<isize, D::Error> {
412 impl Encodable for i8 {
413 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
418 impl Decodable for i8 {
419 fn decode<D: Decoder>(d: &mut D) -> Result<i8, D::Error> {
424 impl Encodable for i16 {
425 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
430 impl Decodable for i16 {
431 fn decode<D: Decoder>(d: &mut D) -> Result<i16, D::Error> {
436 impl Encodable for i32 {
437 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
442 impl Decodable for i32 {
443 fn decode<D: Decoder>(d: &mut D) -> Result<i32, D::Error> {
448 impl Encodable for i64 {
449 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
454 impl Decodable for i64 {
455 fn decode<D: Decoder>(d: &mut D) -> Result<i64, D::Error> {
460 impl Encodable for i128 {
461 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
466 impl Decodable for i128 {
467 fn decode<D: Decoder>(d: &mut D) -> Result<i128, D::Error> {
472 impl Encodable for str {
473 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
478 impl Encodable for String {
479 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
480 s.emit_str(&self[..])
484 impl Decodable for String {
485 fn decode<D: Decoder>(d: &mut D) -> Result<String, D::Error> {
486 Ok(d.read_str()?.into_owned())
490 impl Encodable for f32 {
491 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
496 impl Decodable for f32 {
497 fn decode<D: Decoder>(d: &mut D) -> Result<f32, D::Error> {
502 impl Encodable for f64 {
503 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
508 impl Decodable for f64 {
509 fn decode<D: Decoder>(d: &mut D) -> Result<f64, D::Error> {
514 impl Encodable for bool {
515 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
520 impl Decodable for bool {
521 fn decode<D: Decoder>(d: &mut D) -> Result<bool, D::Error> {
526 impl Encodable for char {
527 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
532 impl Decodable for char {
533 fn decode<D: Decoder>(d: &mut D) -> Result<char, D::Error> {
538 impl Encodable for () {
539 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
544 impl Decodable for () {
545 fn decode<D: Decoder>(d: &mut D) -> Result<(), D::Error> {
550 impl<'a, T: ?Sized + Encodable> Encodable for &'a T {
551 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
556 impl<T: ?Sized + Encodable> Encodable for Box<T> {
557 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
562 impl< T: Decodable> Decodable for Box<T> {
563 fn decode<D: Decoder>(d: &mut D) -> Result<Box<T>, D::Error> {
564 Ok(box Decodable::decode(d)?)
568 impl< T: Decodable> Decodable for Box<[T]> {
569 fn decode<D: Decoder>(d: &mut D) -> Result<Box<[T]>, D::Error> {
570 let v: Vec<T> = Decodable::decode(d)?;
571 Ok(v.into_boxed_slice())
575 impl<T:Encodable> Encodable for Rc<T> {
576 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
581 impl<T:Decodable> Decodable for Rc<T> {
582 fn decode<D: Decoder>(d: &mut D) -> Result<Rc<T>, D::Error> {
583 Ok(Rc::new(Decodable::decode(d)?))
587 impl<T:Encodable> Encodable for [T] {
588 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
589 s.emit_seq(self.len(), |s| {
590 for (i, e) in self.iter().enumerate() {
591 s.emit_seq_elt(i, |s| e.encode(s))?
598 impl<T:Encodable> Encodable for Vec<T> {
599 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
600 s.emit_seq(self.len(), |s| {
601 for (i, e) in self.iter().enumerate() {
602 s.emit_seq_elt(i, |s| e.encode(s))?
609 impl<T:Decodable> Decodable for Vec<T> {
610 fn decode<D: Decoder>(d: &mut D) -> Result<Vec<T>, D::Error> {
611 d.read_seq(|d, len| {
612 let mut v = Vec::with_capacity(len);
614 v.push(d.read_seq_elt(i, |d| Decodable::decode(d))?);
621 impl<'a, T:Encodable> Encodable for Cow<'a, [T]> where [T]: ToOwned<Owned = Vec<T>> {
622 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
623 s.emit_seq(self.len(), |s| {
624 for (i, e) in self.iter().enumerate() {
625 s.emit_seq_elt(i, |s| e.encode(s))?
632 impl<T:Decodable+ToOwned> Decodable for Cow<'static, [T]>
633 where [T]: ToOwned<Owned = Vec<T>>
635 fn decode<D: Decoder>(d: &mut D) -> Result<Cow<'static, [T]>, D::Error> {
636 d.read_seq(|d, len| {
637 let mut v = Vec::with_capacity(len);
639 v.push(d.read_seq_elt(i, |d| Decodable::decode(d))?);
647 impl<T:Encodable> Encodable for Option<T> {
648 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
651 None => s.emit_option_none(),
652 Some(ref v) => s.emit_option_some(|s| v.encode(s)),
658 impl<T:Decodable> Decodable for Option<T> {
659 fn decode<D: Decoder>(d: &mut D) -> Result<Option<T>, D::Error> {
660 d.read_option(|d, b| {
662 Ok(Some(Decodable::decode(d)?))
670 impl<T1: Encodable, T2: Encodable> Encodable for Result<T1, T2> {
671 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
672 s.emit_enum("Result", |s| {
675 s.emit_enum_variant("Ok", 0, 1, |s| {
676 s.emit_enum_variant_arg(0, |s| {
682 s.emit_enum_variant("Err", 1, 1, |s| {
683 s.emit_enum_variant_arg(0, |s| {
693 impl<T1:Decodable, T2:Decodable> Decodable for Result<T1, T2> {
694 fn decode<D: Decoder>(d: &mut D) -> Result<Result<T1, T2>, D::Error> {
695 d.read_enum("Result", |d| {
696 d.read_enum_variant(&["Ok", "Err"], |d, disr| {
699 Ok(Ok(d.read_enum_variant_arg(0, |d| {
704 Ok(Err(d.read_enum_variant_arg(0, |d| {
709 panic!("Encountered invalid discriminant while \
710 decoding `Result`.");
719 ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
722 /// Evaluates to the number of identifiers passed to it, for example: `count_idents!(a, b, c) == 3
723 macro_rules! count_idents {
725 ($_i:ident, $($rest:ident,)*) => { 1 + count_idents!($($rest,)*) }
730 ( $($name:ident,)+ ) => (
731 impl<$($name:Decodable),*> Decodable for ($($name,)*) {
732 #[allow(non_snake_case)]
733 fn decode<D: Decoder>(d: &mut D) -> Result<($($name,)*), D::Error> {
734 let len: usize = count_idents!($($name,)*);
735 d.read_tuple(len, |d| {
737 let ret = ($(d.read_tuple_arg({ i+=1; i-1 }, |d| -> Result<$name, D::Error> {
744 impl<$($name:Encodable),*> Encodable for ($($name,)*) {
745 #[allow(non_snake_case)]
746 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
747 let ($(ref $name,)*) = *self;
749 $(let $name = $name; n += 1;)*
750 s.emit_tuple(n, |s| {
752 $(s.emit_tuple_arg({ i+=1; i-1 }, |s| $name.encode(s))?;)*
761 tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
763 impl Encodable for path::PathBuf {
764 fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> {
765 self.to_str().unwrap().encode(e)
769 impl Decodable for path::PathBuf {
770 fn decode<D: Decoder>(d: &mut D) -> Result<path::PathBuf, D::Error> {
771 let bytes: String = Decodable::decode(d)?;
772 Ok(path::PathBuf::from(bytes))
776 impl<T: Encodable + Copy> Encodable for Cell<T> {
777 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
782 impl<T: Decodable + Copy> Decodable for Cell<T> {
783 fn decode<D: Decoder>(d: &mut D) -> Result<Cell<T>, D::Error> {
784 Ok(Cell::new(Decodable::decode(d)?))
789 // Should use `try_borrow`, returning a
790 // `encoder.error("attempting to Encode borrowed RefCell")`
791 // from `encode` when `try_borrow` returns `None`.
793 impl<T: Encodable> Encodable for RefCell<T> {
794 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
795 self.borrow().encode(s)
799 impl<T: Decodable> Decodable for RefCell<T> {
800 fn decode<D: Decoder>(d: &mut D) -> Result<RefCell<T>, D::Error> {
801 Ok(RefCell::new(Decodable::decode(d)?))
805 impl<T:Encodable> Encodable for Arc<T> {
806 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
811 impl<T:Decodable> Decodable for Arc<T> {
812 fn decode<D: Decoder>(d: &mut D) -> Result<Arc<T>, D::Error> {
813 Ok(Arc::new(Decodable::decode(d)?))
817 // ___________________________________________________________________________
818 // Specialization-based interface for multi-dispatch Encodable/Decodable.
820 /// Implement this trait on your `{Encodable,Decodable}::Error` types
821 /// to override the default panic behavior for missing specializations.
822 pub trait SpecializationError {
823 /// Create an error for a missing method specialization.
824 /// Defaults to panicking with type, trait & method names.
825 /// `S` is the encoder/decoder state type,
826 /// `T` is the type being encoded/decoded, and
827 /// the arguments are the names of the trait
828 /// and method that should've been overridden.
829 fn not_found<S, T: ?Sized>(trait_name: &'static str, method_name: &'static str) -> Self;
832 impl<E> SpecializationError for E {
833 default fn not_found<S, T: ?Sized>(trait_name: &'static str, method_name: &'static str) -> E {
834 panic!("missing specialization: `<{} as {}<{}>>::{}` not overridden",
835 unsafe { intrinsics::type_name::<S>() },
837 unsafe { intrinsics::type_name::<T>() },
842 /// Implement this trait on encoders, with `T` being the type
843 /// you want to encode (employing `UseSpecializedEncodable`),
844 /// using a strategy specific to the encoder.
845 pub trait SpecializedEncoder<T: ?Sized + UseSpecializedEncodable>: Encoder {
846 /// Encode the value in a manner specific to this encoder state.
847 fn specialized_encode(&mut self, value: &T) -> Result<(), Self::Error>;
850 impl<E: Encoder, T: ?Sized + UseSpecializedEncodable> SpecializedEncoder<T> for E {
851 default fn specialized_encode(&mut self, value: &T) -> Result<(), E::Error> {
852 value.default_encode(self)
856 /// Implement this trait on decoders, with `T` being the type
857 /// you want to decode (employing `UseSpecializedDecodable`),
858 /// using a strategy specific to the decoder.
859 pub trait SpecializedDecoder<T: UseSpecializedDecodable>: Decoder {
860 /// Decode a value in a manner specific to this decoder state.
861 fn specialized_decode(&mut self) -> Result<T, Self::Error>;
864 impl<D: Decoder, T: UseSpecializedDecodable> SpecializedDecoder<T> for D {
865 default fn specialized_decode(&mut self) -> Result<T, D::Error> {
866 T::default_decode(self)
870 /// Implement this trait on your type to get an `Encodable`
871 /// implementation which goes through `SpecializedEncoder`.
872 pub trait UseSpecializedEncodable {
873 /// Defaults to returning an error (see `SpecializationError`).
874 fn default_encode<E: Encoder>(&self, _: &mut E) -> Result<(), E::Error> {
875 Err(E::Error::not_found::<E, Self>("SpecializedEncoder", "specialized_encode"))
879 impl<T: ?Sized + UseSpecializedEncodable> Encodable for T {
880 default fn encode<E: Encoder>(&self, e: &mut E) -> Result<(), E::Error> {
881 E::specialized_encode(e, self)
885 /// Implement this trait on your type to get an `Decodable`
886 /// implementation which goes through `SpecializedDecoder`.
887 pub trait UseSpecializedDecodable: Sized {
888 /// Defaults to returning an error (see `SpecializationError`).
889 fn default_decode<D: Decoder>(_: &mut D) -> Result<Self, D::Error> {
890 Err(D::Error::not_found::<D, Self>("SpecializedDecoder", "specialized_decode"))
894 impl<T: UseSpecializedDecodable> Decodable for T {
895 default fn decode<D: Decoder>(d: &mut D) -> Result<T, D::Error> {
896 D::specialized_decode(d)
900 // Can't avoid specialization for &T and Box<T> impls,
901 // as proxy impls on them are blankets that conflict
902 // with the Encodable and Decodable impls above,
903 // which only have `default` on their methods
904 // for this exact reason.
905 // May be fixable in a simpler fashion via the
906 // more complex lattice model for specialization.
907 impl<'a, T: ?Sized + Encodable> UseSpecializedEncodable for &'a T {}
908 impl<T: ?Sized + Encodable> UseSpecializedEncodable for Box<T> {}
909 impl<T: Decodable> UseSpecializedDecodable for Box<T> {}