//! Support code for encoding and decoding types. /* Core encoding and decoding interfaces. */ use std::any; use std::borrow::Cow; use std::cell::{Cell, RefCell}; use std::marker::PhantomData; use std::path; use std::rc::Rc; use std::sync::Arc; pub trait Encoder { type Error; // Primitive types: fn emit_unit(&mut self) -> Result<(), Self::Error>; fn emit_usize(&mut self, v: usize) -> Result<(), Self::Error>; fn emit_u128(&mut self, v: u128) -> Result<(), Self::Error>; fn emit_u64(&mut self, v: u64) -> Result<(), Self::Error>; fn emit_u32(&mut self, v: u32) -> Result<(), Self::Error>; fn emit_u16(&mut self, v: u16) -> Result<(), Self::Error>; fn emit_u8(&mut self, v: u8) -> Result<(), Self::Error>; fn emit_isize(&mut self, v: isize) -> Result<(), Self::Error>; fn emit_i128(&mut self, v: i128) -> Result<(), Self::Error>; fn emit_i64(&mut self, v: i64) -> Result<(), Self::Error>; fn emit_i32(&mut self, v: i32) -> Result<(), Self::Error>; fn emit_i16(&mut self, v: i16) -> Result<(), Self::Error>; fn emit_i8(&mut self, v: i8) -> Result<(), Self::Error>; fn emit_bool(&mut self, v: bool) -> Result<(), Self::Error>; fn emit_f64(&mut self, v: f64) -> Result<(), Self::Error>; fn emit_f32(&mut self, v: f32) -> Result<(), Self::Error>; fn emit_char(&mut self, v: char) -> Result<(), Self::Error>; fn emit_str(&mut self, v: &str) -> Result<(), Self::Error>; // Compound types: #[inline] fn emit_enum(&mut self, _name: &str, f: F) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error>, { f(self) } fn emit_enum_variant( &mut self, _v_name: &str, v_id: usize, _len: usize, f: F, ) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error>, { self.emit_usize(v_id)?; f(self) } #[inline] fn emit_enum_variant_arg(&mut self, _a_idx: usize, f: F) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error>, { f(self) } fn emit_enum_struct_variant( &mut self, v_name: &str, v_id: usize, len: usize, f: F, ) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error>, { self.emit_enum_variant(v_name, v_id, len, f) } fn emit_enum_struct_variant_field( &mut self, _f_name: &str, f_idx: usize, f: F, ) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error>, { self.emit_enum_variant_arg(f_idx, f) } #[inline] fn emit_struct(&mut self, _name: &str, _len: usize, f: F) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error>, { f(self) } #[inline] fn emit_struct_field( &mut self, _f_name: &str, _f_idx: usize, f: F, ) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error>, { f(self) } #[inline] fn emit_tuple(&mut self, _len: usize, f: F) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error>, { f(self) } #[inline] fn emit_tuple_arg(&mut self, _idx: usize, f: F) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error>, { f(self) } fn emit_tuple_struct(&mut self, _name: &str, len: usize, f: F) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error>, { self.emit_tuple(len, f) } fn emit_tuple_struct_arg(&mut self, f_idx: usize, f: F) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error>, { self.emit_tuple_arg(f_idx, f) } // Specialized types: fn emit_option(&mut self, f: F) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error>, { self.emit_enum("Option", f) } #[inline] fn emit_option_none(&mut self) -> Result<(), Self::Error> { self.emit_enum_variant("None", 0, 0, |_| Ok(())) } fn emit_option_some(&mut self, f: F) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error>, { self.emit_enum_variant("Some", 1, 1, f) } fn emit_seq(&mut self, len: usize, f: F) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error>, { self.emit_usize(len)?; f(self) } #[inline] fn emit_seq_elt(&mut self, _idx: usize, f: F) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error>, { f(self) } fn emit_map(&mut self, len: usize, f: F) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error>, { self.emit_usize(len)?; f(self) } #[inline] fn emit_map_elt_key(&mut self, _idx: usize, f: F) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error>, { f(self) } #[inline] fn emit_map_elt_val(&mut self, _idx: usize, f: F) -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error>, { f(self) } } pub trait Decoder { type Error; // Primitive types: fn read_nil(&mut self) -> Result<(), Self::Error>; fn read_usize(&mut self) -> Result; fn read_u128(&mut self) -> Result; fn read_u64(&mut self) -> Result; fn read_u32(&mut self) -> Result; fn read_u16(&mut self) -> Result; fn read_u8(&mut self) -> Result; fn read_isize(&mut self) -> Result; fn read_i128(&mut self) -> Result; fn read_i64(&mut self) -> Result; fn read_i32(&mut self) -> Result; fn read_i16(&mut self) -> Result; fn read_i8(&mut self) -> Result; fn read_bool(&mut self) -> Result; fn read_f64(&mut self) -> Result; fn read_f32(&mut self) -> Result; fn read_char(&mut self) -> Result; fn read_str(&mut self) -> Result, Self::Error>; // Compound types: #[inline] fn read_enum(&mut self, _name: &str, f: F) -> Result where F: FnOnce(&mut Self) -> Result, { f(self) } #[inline] fn read_enum_variant(&mut self, _names: &[&str], mut f: F) -> Result where F: FnMut(&mut Self, usize) -> Result, { let disr = self.read_usize()?; f(self, disr) } #[inline] fn read_enum_variant_arg(&mut self, _a_idx: usize, f: F) -> Result where F: FnOnce(&mut Self) -> Result, { f(self) } fn read_enum_struct_variant(&mut self, names: &[&str], f: F) -> Result where F: FnMut(&mut Self, usize) -> Result, { self.read_enum_variant(names, f) } fn read_enum_struct_variant_field( &mut self, _f_name: &str, f_idx: usize, f: F, ) -> Result where F: FnOnce(&mut Self) -> Result, { self.read_enum_variant_arg(f_idx, f) } #[inline] fn read_struct(&mut self, _s_name: &str, _len: usize, f: F) -> Result where F: FnOnce(&mut Self) -> Result, { f(self) } #[inline] fn read_struct_field( &mut self, _f_name: &str, _f_idx: usize, f: F, ) -> Result where F: FnOnce(&mut Self) -> Result, { f(self) } #[inline] fn read_tuple(&mut self, _len: usize, f: F) -> Result where F: FnOnce(&mut Self) -> Result, { f(self) } #[inline] fn read_tuple_arg(&mut self, _a_idx: usize, f: F) -> Result where F: FnOnce(&mut Self) -> Result, { f(self) } fn read_tuple_struct(&mut self, _s_name: &str, len: usize, f: F) -> Result where F: FnOnce(&mut Self) -> Result, { self.read_tuple(len, f) } fn read_tuple_struct_arg(&mut self, a_idx: usize, f: F) -> Result where F: FnOnce(&mut Self) -> Result, { self.read_tuple_arg(a_idx, f) } // Specialized types: fn read_option(&mut self, mut f: F) -> Result where F: FnMut(&mut Self, bool) -> Result, { self.read_enum("Option", move |this| { this.read_enum_variant(&["None", "Some"], move |this, idx| match idx { 0 => f(this, false), 1 => f(this, true), _ => Err(this.error("read_option: expected 0 for None or 1 for Some")), }) }) } fn read_seq(&mut self, f: F) -> Result where F: FnOnce(&mut Self, usize) -> Result, { let len = self.read_usize()?; f(self, len) } #[inline] fn read_seq_elt(&mut self, _idx: usize, f: F) -> Result where F: FnOnce(&mut Self) -> Result, { f(self) } fn read_map(&mut self, f: F) -> Result where F: FnOnce(&mut Self, usize) -> Result, { let len = self.read_usize()?; f(self, len) } #[inline] fn read_map_elt_key(&mut self, _idx: usize, f: F) -> Result where F: FnOnce(&mut Self) -> Result, { f(self) } #[inline] fn read_map_elt_val(&mut self, _idx: usize, f: F) -> Result where F: FnOnce(&mut Self) -> Result, { f(self) } // Failure fn error(&mut self, err: &str) -> Self::Error; } pub trait Encodable { fn encode(&self, s: &mut S) -> Result<(), S::Error>; } pub trait Decodable: Sized { fn decode(d: &mut D) -> Result; } impl Encodable for usize { fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_usize(*self) } } impl Decodable for usize { fn decode(d: &mut D) -> Result { d.read_usize() } } impl Encodable for u8 { fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_u8(*self) } } impl Decodable for u8 { fn decode(d: &mut D) -> Result { d.read_u8() } } impl Encodable for u16 { fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_u16(*self) } } impl Decodable for u16 { fn decode(d: &mut D) -> Result { d.read_u16() } } impl Encodable for u32 { fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_u32(*self) } } impl Decodable for u32 { fn decode(d: &mut D) -> Result { d.read_u32() } } impl Encodable for ::std::num::NonZeroU32 { fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_u32(self.get()) } } impl Decodable for ::std::num::NonZeroU32 { fn decode(d: &mut D) -> Result { d.read_u32().map(|d| ::std::num::NonZeroU32::new(d).unwrap()) } } impl Encodable for u64 { fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_u64(*self) } } impl Decodable for u64 { fn decode(d: &mut D) -> Result { d.read_u64() } } impl Encodable for u128 { fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_u128(*self) } } impl Decodable for u128 { fn decode(d: &mut D) -> Result { d.read_u128() } } impl Encodable for isize { fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_isize(*self) } } impl Decodable for isize { fn decode(d: &mut D) -> Result { d.read_isize() } } impl Encodable for i8 { fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_i8(*self) } } impl Decodable for i8 { fn decode(d: &mut D) -> Result { d.read_i8() } } impl Encodable for i16 { fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_i16(*self) } } impl Decodable for i16 { fn decode(d: &mut D) -> Result { d.read_i16() } } impl Encodable for i32 { fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_i32(*self) } } impl Decodable for i32 { fn decode(d: &mut D) -> Result { d.read_i32() } } impl Encodable for i64 { fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_i64(*self) } } impl Decodable for i64 { fn decode(d: &mut D) -> Result { d.read_i64() } } impl Encodable for i128 { fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_i128(*self) } } impl Decodable for i128 { fn decode(d: &mut D) -> Result { d.read_i128() } } impl Encodable for str { fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_str(self) } } impl Encodable for String { fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_str(&self[..]) } } impl Decodable for String { fn decode(d: &mut D) -> Result { Ok(d.read_str()?.into_owned()) } } impl Encodable for f32 { fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_f32(*self) } } impl Decodable for f32 { fn decode(d: &mut D) -> Result { d.read_f32() } } impl Encodable for f64 { fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_f64(*self) } } impl Decodable for f64 { fn decode(d: &mut D) -> Result { d.read_f64() } } impl Encodable for bool { fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_bool(*self) } } impl Decodable for bool { fn decode(d: &mut D) -> Result { d.read_bool() } } impl Encodable for char { fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_char(*self) } } impl Decodable for char { fn decode(d: &mut D) -> Result { d.read_char() } } impl Encodable for () { fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_unit() } } impl Decodable for () { fn decode(d: &mut D) -> Result<(), D::Error> { d.read_nil() } } impl Encodable for PhantomData { fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_unit() } } impl Decodable for PhantomData { fn decode(d: &mut D) -> Result, D::Error> { d.read_nil()?; Ok(PhantomData) } } impl<'a, T: ?Sized + Encodable> Encodable for &'a T { fn encode(&self, s: &mut S) -> Result<(), S::Error> { (**self).encode(s) } } impl Encodable for Box { fn encode(&self, s: &mut S) -> Result<(), S::Error> { (**self).encode(s) } } impl Decodable for Box { fn decode(d: &mut D) -> Result, D::Error> { Ok(box Decodable::decode(d)?) } } impl Decodable for Box<[T]> { fn decode(d: &mut D) -> Result, D::Error> { let v: Vec = Decodable::decode(d)?; Ok(v.into_boxed_slice()) } } impl Encodable for Rc { fn encode(&self, s: &mut S) -> Result<(), S::Error> { (**self).encode(s) } } impl Decodable for Rc { fn decode(d: &mut D) -> Result, D::Error> { Ok(Rc::new(Decodable::decode(d)?)) } } impl Encodable for [T] { fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_seq(self.len(), |s| { for (i, e) in self.iter().enumerate() { s.emit_seq_elt(i, |s| e.encode(s))? } Ok(()) }) } } impl Encodable for Vec { fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_seq(self.len(), |s| { for (i, e) in self.iter().enumerate() { s.emit_seq_elt(i, |s| e.encode(s))? } Ok(()) }) } } impl Decodable for Vec { fn decode(d: &mut D) -> Result, D::Error> { d.read_seq(|d, len| { let mut v = Vec::with_capacity(len); for i in 0..len { v.push(d.read_seq_elt(i, |d| Decodable::decode(d))?); } Ok(v) }) } } impl<'a, T: Encodable> Encodable for Cow<'a, [T]> where [T]: ToOwned>, { fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_seq(self.len(), |s| { for (i, e) in self.iter().enumerate() { s.emit_seq_elt(i, |s| e.encode(s))? } Ok(()) }) } } impl Decodable for Cow<'static, [T]> where [T]: ToOwned>, { fn decode(d: &mut D) -> Result, D::Error> { d.read_seq(|d, len| { let mut v = Vec::with_capacity(len); for i in 0..len { v.push(d.read_seq_elt(i, |d| Decodable::decode(d))?); } Ok(Cow::Owned(v)) }) } } impl Encodable for Option { fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_option(|s| match *self { None => s.emit_option_none(), Some(ref v) => s.emit_option_some(|s| v.encode(s)), }) } } impl Decodable for Option { fn decode(d: &mut D) -> Result, D::Error> { d.read_option(|d, b| if b { Ok(Some(Decodable::decode(d)?)) } else { Ok(None) }) } } impl Encodable for Result { fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_enum("Result", |s| match *self { Ok(ref v) => { s.emit_enum_variant("Ok", 0, 1, |s| s.emit_enum_variant_arg(0, |s| v.encode(s))) } Err(ref v) => { s.emit_enum_variant("Err", 1, 1, |s| s.emit_enum_variant_arg(0, |s| v.encode(s))) } }) } } impl Decodable for Result { fn decode(d: &mut D) -> Result, D::Error> { d.read_enum("Result", |d| { d.read_enum_variant(&["Ok", "Err"], |d, disr| match disr { 0 => Ok(Ok(d.read_enum_variant_arg(0, |d| T1::decode(d))?)), 1 => Ok(Err(d.read_enum_variant_arg(0, |d| T2::decode(d))?)), _ => { panic!( "Encountered invalid discriminant while \ decoding `Result`." ); } }) }) } } macro_rules! peel { ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* }) } /// Evaluates to the number of tokens passed to it. /// /// Logarithmic counting: every one or two recursive expansions, the number of /// tokens to count is divided by two, instead of being reduced by one. /// Therefore, the recursion depth is the binary logarithm of the number of /// tokens to count, and the expanded tree is likewise very small. macro_rules! count { () => (0usize); ($one:tt) => (1usize); ($($pairs:tt $_p:tt)*) => (count!($($pairs)*) << 1usize); ($odd:tt $($rest:tt)*) => (count!($($rest)*) | 1usize); } macro_rules! tuple { () => (); ( $($name:ident,)+ ) => ( impl<$($name:Decodable),+> Decodable for ($($name,)+) { #[allow(non_snake_case)] fn decode(d: &mut D) -> Result<($($name,)+), D::Error> { let len: usize = count!($($name)+); d.read_tuple(len, |d| { let mut i = 0; let ret = ($(d.read_tuple_arg({ i+=1; i-1 }, |d| -> Result<$name, D::Error> { Decodable::decode(d) })?,)+); Ok(ret) }) } } impl<$($name:Encodable),+> Encodable for ($($name,)+) { #[allow(non_snake_case)] fn encode(&self, s: &mut S) -> Result<(), S::Error> { let ($(ref $name,)+) = *self; let mut n = 0; $(let $name = $name; n += 1;)+ s.emit_tuple(n, |s| { let mut i = 0; $(s.emit_tuple_arg({ i+=1; i-1 }, |s| $name.encode(s))?;)+ Ok(()) }) } } peel! { $($name,)+ } ) } tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, } impl Encodable for path::Path { fn encode(&self, e: &mut S) -> Result<(), S::Error> { self.to_str().unwrap().encode(e) } } impl Encodable for path::PathBuf { fn encode(&self, e: &mut S) -> Result<(), S::Error> { path::Path::encode(self, e) } } impl Decodable for path::PathBuf { fn decode(d: &mut D) -> Result { let bytes: String = Decodable::decode(d)?; Ok(path::PathBuf::from(bytes)) } } impl Encodable for Cell { fn encode(&self, s: &mut S) -> Result<(), S::Error> { self.get().encode(s) } } impl Decodable for Cell { fn decode(d: &mut D) -> Result, D::Error> { Ok(Cell::new(Decodable::decode(d)?)) } } // FIXME: #15036 // Should use `try_borrow`, returning a // `encoder.error("attempting to Encode borrowed RefCell")` // from `encode` when `try_borrow` returns `None`. impl Encodable for RefCell { fn encode(&self, s: &mut S) -> Result<(), S::Error> { self.borrow().encode(s) } } impl Decodable for RefCell { fn decode(d: &mut D) -> Result, D::Error> { Ok(RefCell::new(Decodable::decode(d)?)) } } impl Encodable for Arc { fn encode(&self, s: &mut S) -> Result<(), S::Error> { (**self).encode(s) } } impl Decodable for Arc { fn decode(d: &mut D) -> Result, D::Error> { Ok(Arc::new(Decodable::decode(d)?)) } } // ___________________________________________________________________________ // Specialization-based interface for multi-dispatch Encodable/Decodable. /// Implement this trait on your `{Encodable,Decodable}::Error` types /// to override the default panic behavior for missing specializations. pub trait SpecializationError { /// Creates an error for a missing method specialization. /// Defaults to panicking with type, trait & method names. /// `S` is the encoder/decoder state type, /// `T` is the type being encoded/decoded, and /// the arguments are the names of the trait /// and method that should've been overridden. fn not_found(trait_name: &'static str, method_name: &'static str) -> Self; } impl SpecializationError for E { default fn not_found(trait_name: &'static str, method_name: &'static str) -> E { panic!( "missing specialization: `<{} as {}<{}>>::{}` not overridden", any::type_name::(), trait_name, any::type_name::(), method_name ); } } /// Implement this trait on encoders, with `T` being the type /// you want to encode (employing `UseSpecializedEncodable`), /// using a strategy specific to the encoder. pub trait SpecializedEncoder: Encoder { /// Encode the value in a manner specific to this encoder state. fn specialized_encode(&mut self, value: &T) -> Result<(), Self::Error>; } impl SpecializedEncoder for E { default fn specialized_encode(&mut self, value: &T) -> Result<(), E::Error> { value.default_encode(self) } } /// Implement this trait on decoders, with `T` being the type /// you want to decode (employing `UseSpecializedDecodable`), /// using a strategy specific to the decoder. pub trait SpecializedDecoder: Decoder { /// Decode a value in a manner specific to this decoder state. fn specialized_decode(&mut self) -> Result; } impl SpecializedDecoder for D { default fn specialized_decode(&mut self) -> Result { T::default_decode(self) } } /// Implement this trait on your type to get an `Encodable` /// implementation which goes through `SpecializedEncoder`. pub trait UseSpecializedEncodable { /// Defaults to returning an error (see `SpecializationError`). fn default_encode(&self, _: &mut E) -> Result<(), E::Error> { Err(E::Error::not_found::("SpecializedEncoder", "specialized_encode")) } } impl Encodable for T { default fn encode(&self, e: &mut E) -> Result<(), E::Error> { E::specialized_encode(e, self) } } /// Implement this trait on your type to get an `Decodable` /// implementation which goes through `SpecializedDecoder`. pub trait UseSpecializedDecodable: Sized { /// Defaults to returning an error (see `SpecializationError`). fn default_decode(_: &mut D) -> Result { Err(D::Error::not_found::("SpecializedDecoder", "specialized_decode")) } } impl Decodable for T { default fn decode(d: &mut D) -> Result { D::specialized_decode(d) } } // Can't avoid specialization for &T and Box impls, // as proxy impls on them are blankets that conflict // with the Encodable and Decodable impls above, // which only have `default` on their methods // for this exact reason. // May be fixable in a simpler fashion via the // more complex lattice model for specialization. impl<'a, T: ?Sized + Encodable> UseSpecializedEncodable for &'a T {} impl UseSpecializedEncodable for Box {} impl UseSpecializedDecodable for Box {} impl<'a, T: Decodable> UseSpecializedDecodable for &'a T {} impl<'a, T: Decodable> UseSpecializedDecodable for &'a [T] {}