From 726eea9a97ba1cf6b77fdc8f535240ff27d7d665 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Fri, 7 Apr 2017 09:46:45 -0700 Subject: [PATCH] Separate out the private functionality This makes it easier when clicking through [src] links from rustdoc, not having to sift through public and internal code combined together. --- serde/src/de/content.rs | 1340 ----------------------- serde/src/de/mod.rs | 6 - serde/src/de/private.rs | 176 ---- serde/src/lib.rs | 6 +- serde/src/macros.rs | 159 --- serde/src/private/de.rs | 1520 +++++++++++++++++++++++++++ serde/src/private/macros.rs | 126 +++ serde/src/private/mod.rs | 4 + serde/src/private/ser.rs | 944 +++++++++++++++++ serde/src/ser/content.rs | 607 ----------- serde/src/ser/impls.rs | 31 + serde/src/ser/impossible.rs | 2 +- serde/src/ser/mod.rs | 8 +- serde/src/ser/private.rs | 333 ------ serde_codegen_internals/src/attr.rs | 4 +- serde_derive/src/de.rs | 36 +- serde_derive/src/ser.rs | 2 +- 17 files changed, 2653 insertions(+), 2651 deletions(-) delete mode 100644 serde/src/de/content.rs delete mode 100644 serde/src/de/private.rs create mode 100644 serde/src/private/de.rs create mode 100644 serde/src/private/macros.rs create mode 100644 serde/src/private/mod.rs create mode 100644 serde/src/private/ser.rs delete mode 100644 serde/src/ser/content.rs delete mode 100644 serde/src/ser/private.rs diff --git a/serde/src/de/content.rs b/serde/src/de/content.rs deleted file mode 100644 index 62f71d10..00000000 --- a/serde/src/de/content.rs +++ /dev/null @@ -1,1340 +0,0 @@ -// This module is doc(hidden) and nothing here should be used outside of -// generated code. -// -// We will iterate on the implementation for a few releases and only have to -// worry about backward compatibility for the `untagged` and `tag` attributes -// rather than for this entire mechanism. -// -// This issue is tracking making some of this stuff public: -// https://github.com/serde-rs/serde/issues/741 - -#![doc(hidden)] - -use core::cmp; -use core::fmt; -use core::marker::PhantomData; - -#[cfg(all(not(feature = "std"), feature = "collections"))] -use collections::{String, Vec}; - -#[cfg(all(feature = "alloc", not(feature = "std")))] -use alloc::boxed::Box; - -use de::{self, Deserialize, DeserializeSeed, Deserializer, Visitor, SeqVisitor, MapVisitor, - EnumVisitor, Unexpected}; - -/// Used from generated code to buffer the contents of the Deserializer when -/// deserializing untagged enums and internally tagged enums. -/// -/// Not public API. Use serde-value instead. -#[derive(Debug)] -pub enum Content { - Bool(bool), - - U8(u8), - U16(u16), - U32(u32), - U64(u64), - - I8(i8), - I16(i16), - I32(i32), - I64(i64), - - F32(f32), - F64(f64), - - Char(char), - String(String), - Bytes(Vec), - - None, - Some(Box), - - Unit, - Newtype(Box), - Seq(Vec), - Map(Vec<(Content, Content)>), -} - -impl Content { - fn unexpected(&self) -> Unexpected { - match *self { - Content::Bool(b) => Unexpected::Bool(b), - Content::U8(n) => Unexpected::Unsigned(n as u64), - Content::U16(n) => Unexpected::Unsigned(n as u64), - Content::U32(n) => Unexpected::Unsigned(n as u64), - Content::U64(n) => Unexpected::Unsigned(n), - Content::I8(n) => Unexpected::Signed(n as i64), - Content::I16(n) => Unexpected::Signed(n as i64), - Content::I32(n) => Unexpected::Signed(n as i64), - Content::I64(n) => Unexpected::Signed(n), - Content::F32(f) => Unexpected::Float(f as f64), - Content::F64(f) => Unexpected::Float(f), - Content::Char(c) => Unexpected::Char(c), - Content::String(ref s) => Unexpected::Str(s), - Content::Bytes(ref b) => Unexpected::Bytes(b), - Content::None | Content::Some(_) => Unexpected::Option, - Content::Unit => Unexpected::Unit, - Content::Newtype(_) => Unexpected::NewtypeStruct, - Content::Seq(_) => Unexpected::Seq, - Content::Map(_) => Unexpected::Map, - } - } -} - -impl<'de> Deserialize<'de> for Content { - fn deserialize(deserializer: D) -> Result - where D: Deserializer<'de> - { - // Untagged and internally tagged enums are only supported in - // self-describing formats. - deserializer.deserialize(ContentVisitor) - } -} - -struct ContentVisitor; - -impl<'de> Visitor<'de> for ContentVisitor { - type Value = Content; - - fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.write_str("any value") - } - - fn visit_bool(self, value: bool) -> Result - where F: de::Error - { - Ok(Content::Bool(value)) - } - - fn visit_i8(self, value: i8) -> Result - where F: de::Error - { - Ok(Content::I8(value)) - } - - fn visit_i16(self, value: i16) -> Result - where F: de::Error - { - Ok(Content::I16(value)) - } - - fn visit_i32(self, value: i32) -> Result - where F: de::Error - { - Ok(Content::I32(value)) - } - - fn visit_i64(self, value: i64) -> Result - where F: de::Error - { - Ok(Content::I64(value)) - } - - fn visit_u8(self, value: u8) -> Result - where F: de::Error - { - Ok(Content::U8(value)) - } - - fn visit_u16(self, value: u16) -> Result - where F: de::Error - { - Ok(Content::U16(value)) - } - - fn visit_u32(self, value: u32) -> Result - where F: de::Error - { - Ok(Content::U32(value)) - } - - fn visit_u64(self, value: u64) -> Result - where F: de::Error - { - Ok(Content::U64(value)) - } - - fn visit_f32(self, value: f32) -> Result - where F: de::Error - { - Ok(Content::F32(value)) - } - - fn visit_f64(self, value: f64) -> Result - where F: de::Error - { - Ok(Content::F64(value)) - } - - fn visit_char(self, value: char) -> Result - where F: de::Error - { - Ok(Content::Char(value)) - } - - fn visit_str(self, value: &str) -> Result - where F: de::Error - { - Ok(Content::String(value.into())) - } - - fn visit_string(self, value: String) -> Result - where F: de::Error - { - Ok(Content::String(value)) - } - - fn visit_bytes(self, value: &[u8]) -> Result - where F: de::Error - { - Ok(Content::Bytes(value.into())) - } - - fn visit_byte_buf(self, value: Vec) -> Result - where F: de::Error - { - Ok(Content::Bytes(value)) - } - - fn visit_unit(self) -> Result - where F: de::Error - { - Ok(Content::Unit) - } - - fn visit_none(self) -> Result - where F: de::Error - { - Ok(Content::None) - } - - fn visit_some(self, deserializer: D) -> Result - where D: Deserializer<'de> - { - Deserialize::deserialize(deserializer).map(|v| Content::Some(Box::new(v))) - } - - fn visit_newtype_struct(self, deserializer: D) -> Result - where D: Deserializer<'de> - { - Deserialize::deserialize(deserializer).map(|v| Content::Newtype(Box::new(v))) - } - - fn visit_seq(self, mut visitor: V) -> Result - where V: SeqVisitor<'de> - { - let mut vec = Vec::with_capacity(cmp::min(visitor.size_hint().0, 4096)); - while let Some(e) = try!(visitor.visit()) { - vec.push(e); - } - Ok(Content::Seq(vec)) - } - - fn visit_map(self, mut visitor: V) -> Result - where V: MapVisitor<'de> - { - let mut vec = Vec::with_capacity(cmp::min(visitor.size_hint().0, 4096)); - while let Some(kv) = try!(visitor.visit()) { - vec.push(kv); - } - Ok(Content::Map(vec)) - } - - fn visit_enum(self, _visitor: V) -> Result - where V: EnumVisitor<'de> - { - Err(de::Error::custom("untagged and internally tagged enums do not support enum input")) - } -} - -/// This is the type of the map keys in an internally tagged enum. -/// -/// Not public API. -pub enum TagOrContent { - Tag, - Content(Content), -} - -struct TagOrContentVisitor { - name: &'static str, -} - -impl TagOrContentVisitor { - fn new(name: &'static str) -> Self { - TagOrContentVisitor { name: name } - } -} - -impl<'de> DeserializeSeed<'de> for TagOrContentVisitor { - type Value = TagOrContent; - - fn deserialize(self, deserializer: D) -> Result - where D: Deserializer<'de> - { - // Internally tagged enums are only supported in self-describing - // formats. - deserializer.deserialize(self) - } -} - -impl<'de> Visitor<'de> for TagOrContentVisitor { - type Value = TagOrContent; - - fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - write!(fmt, "a type tag `{}` or any other value", self.name) - } - - fn visit_bool(self, value: bool) -> Result - where F: de::Error - { - ContentVisitor.visit_bool(value).map(TagOrContent::Content) - } - - fn visit_i8(self, value: i8) -> Result - where F: de::Error - { - ContentVisitor.visit_i8(value).map(TagOrContent::Content) - } - - fn visit_i16(self, value: i16) -> Result - where F: de::Error - { - ContentVisitor.visit_i16(value).map(TagOrContent::Content) - } - - fn visit_i32(self, value: i32) -> Result - where F: de::Error - { - ContentVisitor.visit_i32(value).map(TagOrContent::Content) - } - - fn visit_i64(self, value: i64) -> Result - where F: de::Error - { - ContentVisitor.visit_i64(value).map(TagOrContent::Content) - } - - fn visit_u8(self, value: u8) -> Result - where F: de::Error - { - ContentVisitor.visit_u8(value).map(TagOrContent::Content) - } - - fn visit_u16(self, value: u16) -> Result - where F: de::Error - { - ContentVisitor.visit_u16(value).map(TagOrContent::Content) - } - - fn visit_u32(self, value: u32) -> Result - where F: de::Error - { - ContentVisitor.visit_u32(value).map(TagOrContent::Content) - } - - fn visit_u64(self, value: u64) -> Result - where F: de::Error - { - ContentVisitor.visit_u64(value).map(TagOrContent::Content) - } - - fn visit_f32(self, value: f32) -> Result - where F: de::Error - { - ContentVisitor.visit_f32(value).map(TagOrContent::Content) - } - - fn visit_f64(self, value: f64) -> Result - where F: de::Error - { - ContentVisitor.visit_f64(value).map(TagOrContent::Content) - } - - fn visit_char(self, value: char) -> Result - where F: de::Error - { - ContentVisitor.visit_char(value).map(TagOrContent::Content) - } - - fn visit_str(self, value: &str) -> Result - where F: de::Error - { - if value == self.name { - Ok(TagOrContent::Tag) - } else { - ContentVisitor.visit_str(value).map(TagOrContent::Content) - } - } - - fn visit_string(self, value: String) -> Result - where F: de::Error - { - if value == self.name { - Ok(TagOrContent::Tag) - } else { - ContentVisitor.visit_string(value).map(TagOrContent::Content) - } - } - - fn visit_bytes(self, value: &[u8]) -> Result - where F: de::Error - { - if value == self.name.as_bytes() { - Ok(TagOrContent::Tag) - } else { - ContentVisitor.visit_bytes(value).map(TagOrContent::Content) - } - } - - fn visit_byte_buf(self, value: Vec) -> Result - where F: de::Error - { - if value == self.name.as_bytes() { - Ok(TagOrContent::Tag) - } else { - ContentVisitor.visit_byte_buf(value).map(TagOrContent::Content) - } - } - - fn visit_unit(self) -> Result - where F: de::Error - { - ContentVisitor.visit_unit().map(TagOrContent::Content) - } - - fn visit_none(self) -> Result - where F: de::Error - { - ContentVisitor.visit_none().map(TagOrContent::Content) - } - - fn visit_some(self, deserializer: D) -> Result - where D: Deserializer<'de> - { - ContentVisitor.visit_some(deserializer).map(TagOrContent::Content) - } - - fn visit_newtype_struct(self, deserializer: D) -> Result - where D: Deserializer<'de> - { - ContentVisitor.visit_newtype_struct(deserializer).map(TagOrContent::Content) - } - - fn visit_seq(self, visitor: V) -> Result - where V: SeqVisitor<'de> - { - ContentVisitor.visit_seq(visitor).map(TagOrContent::Content) - } - - fn visit_map(self, visitor: V) -> Result - where V: MapVisitor<'de> - { - ContentVisitor.visit_map(visitor).map(TagOrContent::Content) - } - - fn visit_enum(self, visitor: V) -> Result - where V: EnumVisitor<'de> - { - ContentVisitor.visit_enum(visitor).map(TagOrContent::Content) - } -} - -/// Used by generated code to deserialize an internally tagged enum. -/// -/// Not public API. -pub struct TaggedContent { - pub tag: T, - pub content: Content, -} - -/// Not public API. -pub struct TaggedContentVisitor { - tag_name: &'static str, - tag: PhantomData, -} - -impl TaggedContentVisitor { - /// Visitor for the content of an internally tagged enum with the given tag - /// name. - pub fn new(name: &'static str) -> Self { - TaggedContentVisitor { - tag_name: name, - tag: PhantomData, - } - } -} - -impl<'de, T> DeserializeSeed<'de> for TaggedContentVisitor - where T: Deserialize<'de> -{ - type Value = TaggedContent; - - fn deserialize(self, deserializer: D) -> Result - where D: Deserializer<'de> - { - // Internally tagged enums are only supported in self-describing - // formats. - deserializer.deserialize(self) - } -} - -impl<'de, T> Visitor<'de> for TaggedContentVisitor - where T: Deserialize<'de> -{ - type Value = TaggedContent; - - fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.write_str("any value") - } - - fn visit_map(self, mut visitor: V) -> Result - where V: MapVisitor<'de> - { - let mut tag = None; - let mut vec = Vec::with_capacity(cmp::min(visitor.size_hint().0, 4096)); - while let Some(k) = try!(visitor.visit_key_seed(TagOrContentVisitor::new(self.tag_name))) { - match k { - TagOrContent::Tag => { - if tag.is_some() { - return Err(de::Error::duplicate_field(self.tag_name)); - } - tag = Some(try!(visitor.visit_value())); - } - TagOrContent::Content(k) => { - let v = try!(visitor.visit_value()); - vec.push((k, v)); - } - } - } - match tag { - None => Err(de::Error::missing_field(self.tag_name)), - Some(tag) => { - Ok(TaggedContent { - tag: tag, - content: Content::Map(vec), - }) - } - } - } -} - -/// Used by generated code to deserialize an adjacently tagged enum. -/// -/// Not public API. -pub enum TagOrContentField { - Tag, - Content, -} - -/// Not public API. -pub struct TagOrContentFieldVisitor { - pub tag: &'static str, - pub content: &'static str, -} - -impl<'de> DeserializeSeed<'de> for TagOrContentFieldVisitor { - type Value = TagOrContentField; - - fn deserialize(self, deserializer: D) -> Result - where D: Deserializer<'de> - { - deserializer.deserialize_str(self) - } -} - -impl<'de> Visitor<'de> for TagOrContentFieldVisitor { - type Value = TagOrContentField; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - write!(formatter, "{:?} or {:?}", self.tag, self.content) - } - - fn visit_str(self, field: &str) -> Result - where E: de::Error - { - if field == self.tag { - Ok(TagOrContentField::Tag) - } else if field == self.content { - Ok(TagOrContentField::Content) - } else { - Err(de::Error::invalid_value(Unexpected::Str(field), &self)) - } - } -} - -/// Not public API -pub struct ContentDeserializer { - content: Content, - err: PhantomData, -} - -/// Used when deserializing an internally tagged enum because the content will -/// be used exactly once. -impl<'de, E> Deserializer<'de> for ContentDeserializer - where E: de::Error -{ - type Error = E; - - fn deserialize(self, visitor: V) -> Result - where V: Visitor<'de> - { - match self.content { - Content::Bool(v) => visitor.visit_bool(v), - Content::U8(v) => visitor.visit_u8(v), - Content::U16(v) => visitor.visit_u16(v), - Content::U32(v) => visitor.visit_u32(v), - Content::U64(v) => visitor.visit_u64(v), - Content::I8(v) => visitor.visit_i8(v), - Content::I16(v) => visitor.visit_i16(v), - Content::I32(v) => visitor.visit_i32(v), - Content::I64(v) => visitor.visit_i64(v), - Content::F32(v) => visitor.visit_f32(v), - Content::F64(v) => visitor.visit_f64(v), - Content::Char(v) => visitor.visit_char(v), - Content::String(v) => visitor.visit_string(v), - Content::Unit => visitor.visit_unit(), - Content::None => visitor.visit_none(), - Content::Some(v) => visitor.visit_some(ContentDeserializer::new(*v)), - Content::Newtype(v) => visitor.visit_newtype_struct(ContentDeserializer::new(*v)), - Content::Seq(v) => { - let seq = v.into_iter().map(ContentDeserializer::new); - let mut seq_visitor = de::value::SeqDeserializer::new(seq); - let value = try!(visitor.visit_seq(&mut seq_visitor)); - try!(seq_visitor.end()); - Ok(value) - } - Content::Map(v) => { - let map = v.into_iter().map(|(k, v)| { - (ContentDeserializer::new(k), - ContentDeserializer::new(v)) - }); - let mut map_visitor = de::value::MapDeserializer::new(map); - let value = try!(visitor.visit_map(&mut map_visitor)); - try!(map_visitor.end()); - Ok(value) - } - Content::Bytes(v) => visitor.visit_byte_buf(v), - } - } - - fn deserialize_option(self, visitor: V) -> Result - where V: Visitor<'de> - { - match self.content { - Content::None => visitor.visit_none(), - Content::Some(v) => visitor.visit_some(ContentDeserializer::new(*v)), - Content::Unit => visitor.visit_unit(), - _ => visitor.visit_some(self), - } - } - - fn deserialize_newtype_struct(self, _name: &str, visitor: V) -> Result - where V: Visitor<'de> - { - visitor.visit_newtype_struct(self) - } - - fn deserialize_enum(self, - _name: &str, - _variants: &'static [&'static str], - visitor: V) - -> Result - where V: Visitor<'de> - { - let (variant, value) = match self.content { - Content::Map(value) => { - let mut iter = value.into_iter(); - let (variant, value) = match iter.next() { - Some(v) => v, - None => { - return Err(de::Error::invalid_value(de::Unexpected::Map, - &"map with a single key")); - } - }; - // enums are encoded in json as maps with a single key:value pair - if iter.next().is_some() { - return Err(de::Error::invalid_value(de::Unexpected::Map, - &"map with a single key")); - } - (variant, Some(value)) - } - Content::String(variant) => (Content::String(variant), None), - other => { - return Err(de::Error::invalid_type(other.unexpected(), &"string or map")); - } - }; - - visitor.visit_enum(EnumDeserializer { - variant: variant, - value: value, - err: PhantomData, - }) - } - - forward_to_deserialize! { - bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq - seq_fixed_size bytes byte_buf map unit_struct tuple_struct struct - struct_field tuple ignored_any - } -} - -impl ContentDeserializer { - /// private API, don't use - pub fn new(content: Content) -> Self { - ContentDeserializer { - content: content, - err: PhantomData, - } - } -} - -struct EnumDeserializer - where E: de::Error -{ - variant: Content, - value: Option, - err: PhantomData, -} - -impl<'de, E> de::EnumVisitor<'de> for EnumDeserializer - where E: de::Error -{ - type Error = E; - type Variant = VariantDeserializer; - - fn visit_variant_seed(self, - seed: V) - -> Result<(V::Value, VariantDeserializer), Self::Error> - where V: de::DeserializeSeed<'de> - { - let visitor = VariantDeserializer { - value: self.value, - err: PhantomData, - }; - seed.deserialize(ContentDeserializer::new(self.variant)).map(|v| (v, visitor)) - } -} - -struct VariantDeserializer - where E: de::Error -{ - value: Option, - err: PhantomData, -} - -impl<'de, E> de::VariantVisitor<'de> for VariantDeserializer - where E: de::Error -{ - type Error = E; - - fn visit_unit(self) -> Result<(), E> { - match self.value { - Some(value) => de::Deserialize::deserialize(ContentDeserializer::new(value)), - None => Ok(()), - } - } - - fn visit_newtype_seed(self, seed: T) -> Result - where T: de::DeserializeSeed<'de> - { - match self.value { - Some(value) => seed.deserialize(ContentDeserializer::new(value)), - None => Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"newtype variant")), - } - } - - fn visit_tuple(self, _len: usize, visitor: V) -> Result - where V: de::Visitor<'de> - { - match self.value { - Some(Content::Seq(v)) => { - de::Deserializer::deserialize(SeqDeserializer::new(v), visitor) - } - Some(other) => Err(de::Error::invalid_type(other.unexpected(), &"tuple variant")), - None => Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"tuple variant")), - } - } - - fn visit_struct(self, - _fields: &'static [&'static str], - visitor: V) - -> Result - where V: de::Visitor<'de> - { - match self.value { - Some(Content::Map(v)) => { - de::Deserializer::deserialize(MapDeserializer::new(v), visitor) - } - Some(other) => Err(de::Error::invalid_type(other.unexpected(), &"struct variant")), - _ => Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"struct variant")), - } - } -} - -struct SeqDeserializer - where E: de::Error -{ - iter: as IntoIterator>::IntoIter, - err: PhantomData, -} - -impl SeqDeserializer - where E: de::Error -{ - fn new(vec: Vec) -> Self { - SeqDeserializer { - iter: vec.into_iter(), - err: PhantomData, - } - } -} - -impl<'de, E> de::Deserializer<'de> for SeqDeserializer - where E: de::Error -{ - type Error = E; - - #[inline] - fn deserialize(mut self, visitor: V) -> Result - where V: de::Visitor<'de> - { - let len = self.iter.len(); - if len == 0 { - visitor.visit_unit() - } else { - let ret = try!(visitor.visit_seq(&mut self)); - let remaining = self.iter.len(); - if remaining == 0 { - Ok(ret) - } else { - Err(de::Error::invalid_length(len, &"fewer elements in array")) - } - } - } - - forward_to_deserialize! { - bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option - seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct - tuple_struct struct struct_field tuple enum ignored_any - } -} - -impl<'de, E> de::SeqVisitor<'de> for SeqDeserializer - where E: de::Error -{ - type Error = E; - - fn visit_seed(&mut self, seed: T) -> Result, Self::Error> - where T: de::DeserializeSeed<'de> - { - match self.iter.next() { - Some(value) => seed.deserialize(ContentDeserializer::new(value)).map(Some), - None => Ok(None), - } - } - - fn size_hint(&self) -> (usize, Option) { - self.iter.size_hint() - } -} - -struct MapDeserializer - where E: de::Error -{ - iter: as IntoIterator>::IntoIter, - value: Option, - err: PhantomData, -} - -impl MapDeserializer - where E: de::Error -{ - fn new(map: Vec<(Content, Content)>) -> Self { - MapDeserializer { - iter: map.into_iter(), - value: None, - err: PhantomData, - } - } -} - -impl<'de, E> de::MapVisitor<'de> for MapDeserializer - where E: de::Error -{ - type Error = E; - - fn visit_key_seed(&mut self, seed: T) -> Result, Self::Error> - where T: de::DeserializeSeed<'de> - { - match self.iter.next() { - Some((key, value)) => { - self.value = Some(value); - seed.deserialize(ContentDeserializer::new(key)).map(Some) - } - None => Ok(None), - } - } - - fn visit_value_seed(&mut self, seed: T) -> Result - where T: de::DeserializeSeed<'de> - { - match self.value.take() { - Some(value) => seed.deserialize(ContentDeserializer::new(value)), - None => Err(de::Error::custom("value is missing")), - } - } - - fn size_hint(&self) -> (usize, Option) { - self.iter.size_hint() - } -} - -impl<'de, E> de::Deserializer<'de> for MapDeserializer - where E: de::Error -{ - type Error = E; - - #[inline] - fn deserialize(self, visitor: V) -> Result - where V: de::Visitor<'de> - { - visitor.visit_map(self) - } - - forward_to_deserialize! { - bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option - seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct - tuple_struct struct struct_field tuple enum ignored_any - } -} - - -/// Not public API. -pub struct ContentRefDeserializer<'a, E> { - content: &'a Content, - err: PhantomData, -} - -/// Used when deserializing an untagged enum because the content may need to be -/// used more than once. -impl<'de, 'a, E> Deserializer<'de> for ContentRefDeserializer<'a, E> - where E: de::Error -{ - type Error = E; - - fn deserialize(self, visitor: V) -> Result - where V: Visitor<'de> - { - match *self.content { - Content::Bool(v) => visitor.visit_bool(v), - Content::U8(v) => visitor.visit_u8(v), - Content::U16(v) => visitor.visit_u16(v), - Content::U32(v) => visitor.visit_u32(v), - Content::U64(v) => visitor.visit_u64(v), - Content::I8(v) => visitor.visit_i8(v), - Content::I16(v) => visitor.visit_i16(v), - Content::I32(v) => visitor.visit_i32(v), - Content::I64(v) => visitor.visit_i64(v), - Content::F32(v) => visitor.visit_f32(v), - Content::F64(v) => visitor.visit_f64(v), - Content::Char(v) => visitor.visit_char(v), - Content::String(ref v) => visitor.visit_str(v), - Content::Unit => visitor.visit_unit(), - Content::None => visitor.visit_none(), - Content::Some(ref v) => visitor.visit_some(ContentRefDeserializer::new(v)), - Content::Newtype(ref v) => visitor.visit_newtype_struct(ContentRefDeserializer::new(v)), - Content::Seq(ref v) => { - let seq = v.into_iter().map(ContentRefDeserializer::new); - let mut seq_visitor = de::value::SeqDeserializer::new(seq); - let value = try!(visitor.visit_seq(&mut seq_visitor)); - try!(seq_visitor.end()); - Ok(value) - } - Content::Map(ref v) => { - let map = v.into_iter().map(|&(ref k, ref v)| { - (ContentRefDeserializer::new(k), - ContentRefDeserializer::new(v)) - }); - let mut map_visitor = de::value::MapDeserializer::new(map); - let value = try!(visitor.visit_map(&mut map_visitor)); - try!(map_visitor.end()); - Ok(value) - } - Content::Bytes(ref v) => visitor.visit_bytes(v), - } - } - - fn deserialize_option(self, visitor: V) -> Result - where V: Visitor<'de> - { - match *self.content { - Content::None => visitor.visit_none(), - Content::Some(ref v) => visitor.visit_some(ContentRefDeserializer::new(v)), - Content::Unit => visitor.visit_unit(), - _ => visitor.visit_some(self), - } - } - - fn deserialize_newtype_struct(self, _name: &str, visitor: V) -> Result - where V: Visitor<'de> - { - visitor.visit_newtype_struct(self) - } - - fn deserialize_enum(self, - _name: &str, - _variants: &'static [&'static str], - visitor: V) - -> Result - where V: Visitor<'de> - { - let (variant, value) = match *self.content { - Content::Map(ref value) => { - let mut iter = value.into_iter(); - let &(ref variant, ref value) = match iter.next() { - Some(v) => v, - None => { - return Err(de::Error::invalid_value(de::Unexpected::Map, - &"map with a single key")); - } - }; - // enums are encoded in json as maps with a single key:value pair - if iter.next().is_some() { - return Err(de::Error::invalid_value(de::Unexpected::Map, - &"map with a single key")); - } - (variant, Some(value)) - } - ref s @ Content::String(_) => (s, None), - ref other => { - return Err(de::Error::invalid_type(other.unexpected(), &"string or map")); - } - }; - - visitor.visit_enum(EnumRefDeserializer { - variant: variant, - value: value, - err: PhantomData, - }) - } - - forward_to_deserialize! { - bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq - seq_fixed_size bytes byte_buf map unit_struct tuple_struct struct - struct_field tuple ignored_any - } -} - -impl<'a, E> ContentRefDeserializer<'a, E> { - /// private API, don't use - pub fn new(content: &'a Content) -> Self { - ContentRefDeserializer { - content: content, - err: PhantomData, - } - } -} - -struct EnumRefDeserializer<'a, E> - where E: de::Error -{ - variant: &'a Content, - value: Option<&'a Content>, - err: PhantomData, -} - -impl<'de, 'a, E> de::EnumVisitor<'de> for EnumRefDeserializer<'a, E> - where E: de::Error -{ - type Error = E; - type Variant = VariantRefDeserializer<'a, Self::Error>; - - fn visit_variant_seed(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> - where V: de::DeserializeSeed<'de> - { - let visitor = VariantRefDeserializer { - value: self.value, - err: PhantomData, - }; - seed.deserialize(ContentRefDeserializer::new(self.variant)).map(|v| (v, visitor)) - } -} - -struct VariantRefDeserializer<'a, E> - where E: de::Error -{ - value: Option<&'a Content>, - err: PhantomData, -} - -impl<'de, 'a, E> de::VariantVisitor<'de> for VariantRefDeserializer<'a, E> - where E: de::Error -{ - type Error = E; - - fn visit_unit(self) -> Result<(), E> { - match self.value { - Some(value) => de::Deserialize::deserialize(ContentRefDeserializer::new(value)), - None => Ok(()), - } - } - - fn visit_newtype_seed(self, seed: T) -> Result - where T: de::DeserializeSeed<'de> - { - match self.value { - Some(value) => seed.deserialize(ContentRefDeserializer::new(value)), - None => Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"newtype variant")), - } - } - - fn visit_tuple(self, _len: usize, visitor: V) -> Result - where V: de::Visitor<'de> - { - match self.value { - Some(&Content::Seq(ref v)) => { - de::Deserializer::deserialize(SeqRefDeserializer::new(v), visitor) - } - Some(other) => Err(de::Error::invalid_type(other.unexpected(), &"tuple variant")), - None => Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"tuple variant")), - } - } - - fn visit_struct(self, - _fields: &'static [&'static str], - visitor: V) - -> Result - where V: de::Visitor<'de> - { - match self.value { - Some(&Content::Map(ref v)) => { - de::Deserializer::deserialize(MapRefDeserializer::new(v), visitor) - } - Some(other) => Err(de::Error::invalid_type(other.unexpected(), &"struct variant")), - _ => Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"struct variant")), - } - } -} - -struct SeqRefDeserializer<'a, E> - where E: de::Error -{ - iter: <&'a [Content] as IntoIterator>::IntoIter, - err: PhantomData, -} - -impl<'a, E> SeqRefDeserializer<'a, E> - where E: de::Error -{ - fn new(vec: &'a [Content]) -> Self { - SeqRefDeserializer { - iter: vec.into_iter(), - err: PhantomData, - } - } -} - -impl<'de, 'a, E> de::Deserializer<'de> for SeqRefDeserializer<'a, E> - where E: de::Error -{ - type Error = E; - - #[inline] - fn deserialize(mut self, visitor: V) -> Result - where V: de::Visitor<'de> - { - let len = self.iter.len(); - if len == 0 { - visitor.visit_unit() - } else { - let ret = try!(visitor.visit_seq(&mut self)); - let remaining = self.iter.len(); - if remaining == 0 { - Ok(ret) - } else { - Err(de::Error::invalid_length(len, &"fewer elements in array")) - } - } - } - - forward_to_deserialize! { - bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option - seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct - tuple_struct struct struct_field tuple enum ignored_any - } -} - -impl<'de, 'a, E> de::SeqVisitor<'de> for SeqRefDeserializer<'a, E> - where E: de::Error -{ - type Error = E; - - fn visit_seed(&mut self, seed: T) -> Result, Self::Error> - where T: de::DeserializeSeed<'de> - { - match self.iter.next() { - Some(value) => seed.deserialize(ContentRefDeserializer::new(value)).map(Some), - None => Ok(None), - } - } - - fn size_hint(&self) -> (usize, Option) { - self.iter.size_hint() - } -} - -struct MapRefDeserializer<'a, E> - where E: de::Error -{ - iter: <&'a [(Content, Content)] as IntoIterator>::IntoIter, - value: Option<&'a Content>, - err: PhantomData, -} - -impl<'a, E> MapRefDeserializer<'a, E> - where E: de::Error -{ - fn new(map: &'a [(Content, Content)]) -> Self { - MapRefDeserializer { - iter: map.into_iter(), - value: None, - err: PhantomData, - } - } -} - -impl<'de, 'a, E> de::MapVisitor<'de> for MapRefDeserializer<'a, E> - where E: de::Error -{ - type Error = E; - - fn visit_key_seed(&mut self, seed: T) -> Result, Self::Error> - where T: de::DeserializeSeed<'de> - { - match self.iter.next() { - Some(&(ref key, ref value)) => { - self.value = Some(value); - seed.deserialize(ContentRefDeserializer::new(key)).map(Some) - } - None => Ok(None), - } - } - - fn visit_value_seed(&mut self, seed: T) -> Result - where T: de::DeserializeSeed<'de> - { - match self.value.take() { - Some(value) => seed.deserialize(ContentRefDeserializer::new(value)), - None => Err(de::Error::custom("value is missing")), - } - } - - fn size_hint(&self) -> (usize, Option) { - self.iter.size_hint() - } -} - -impl<'de, 'a, E> de::Deserializer<'de> for MapRefDeserializer<'a, E> - where E: de::Error -{ - type Error = E; - - #[inline] - fn deserialize(self, visitor: V) -> Result - where V: de::Visitor<'de> - { - visitor.visit_map(self) - } - - forward_to_deserialize! { - bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option - seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct - tuple_struct struct struct_field tuple enum ignored_any - } -} - -impl<'de, E> de::value::ValueDeserializer<'de, E> for ContentDeserializer - where E: de::Error -{ - type Deserializer = Self; - - fn into_deserializer(self) -> Self { - self - } -} - -impl<'de, 'a, E> de::value::ValueDeserializer<'de, E> for ContentRefDeserializer<'a, E> - where E: de::Error -{ - type Deserializer = Self; - - fn into_deserializer(self) -> Self { - self - } -} - -/// Visitor for deserializing an internally tagged unit variant. -/// -/// Not public API. -pub struct InternallyTaggedUnitVisitor<'a> { - type_name: &'a str, - variant_name: &'a str, -} - -impl<'a> InternallyTaggedUnitVisitor<'a> { - /// Not public API. - pub fn new(type_name: &'a str, variant_name: &'a str) -> Self { - InternallyTaggedUnitVisitor { - type_name: type_name, - variant_name: variant_name, - } - } -} - -impl<'de, 'a> Visitor<'de> for InternallyTaggedUnitVisitor<'a> { - type Value = (); - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - write!(formatter, "unit variant {}::{}", self.type_name, self.variant_name) - } - - fn visit_map(self, _: V) -> Result<(), V::Error> - where V: MapVisitor<'de> - { - Ok(()) - } -} - -/// Visitor for deserializing an untagged unit variant. -/// -/// Not public API. -pub struct UntaggedUnitVisitor<'a> { - type_name: &'a str, - variant_name: &'a str, -} - -impl<'a> UntaggedUnitVisitor<'a> { - /// Not public API. - pub fn new(type_name: &'a str, variant_name: &'a str) -> Self { - UntaggedUnitVisitor { - type_name: type_name, - variant_name: variant_name, - } - } -} - -impl<'de, 'a> Visitor<'de> for UntaggedUnitVisitor<'a> { - type Value = (); - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - write!(formatter, "unit variant {}::{}", self.type_name, self.variant_name) - } - - fn visit_unit(self) -> Result<(), E> - where E: de::Error - { - Ok(()) - } -} diff --git a/serde/src/de/mod.rs b/serde/src/de/mod.rs index eac50313..0def4a6c 100644 --- a/serde/src/de/mod.rs +++ b/serde/src/de/mod.rs @@ -113,12 +113,6 @@ mod from_primitive; mod ignored_any; mod impls; -// Helpers used by generated code. Not public API. -#[doc(hidden)] -pub mod private; -#[cfg(any(feature = "std", feature = "collections"))] -mod content; - pub use self::ignored_any::IgnoredAny; /////////////////////////////////////////////////////////////////////////////// diff --git a/serde/src/de/private.rs b/serde/src/de/private.rs deleted file mode 100644 index 8121ee15..00000000 --- a/serde/src/de/private.rs +++ /dev/null @@ -1,176 +0,0 @@ -#[cfg(any(feature = "std", feature = "collections"))] -use core::{fmt, str}; - -use core::marker::PhantomData; - -#[cfg(feature = "collections")] -use collections::borrow::ToOwned; - -#[cfg(feature = "std")] -use std::borrow::Cow; -#[cfg(all(feature = "collections", not(feature = "std")))] -use collections::borrow::Cow; - -#[cfg(all(feature = "collections", not(feature = "std")))] -use collections::{String, Vec}; - -use de::{Deserialize, Deserializer, Error, Visitor}; - -#[cfg(any(feature = "std", feature = "collections"))] -use de::Unexpected; - -#[cfg(any(feature = "std", feature = "collections"))] -pub use de::content::{Content, ContentRefDeserializer, ContentDeserializer, TaggedContentVisitor, - TagOrContentField, TagOrContentFieldVisitor, InternallyTaggedUnitVisitor, - UntaggedUnitVisitor}; - -/// If the missing field is of type `Option` then treat is as `None`, -/// otherwise it is an error. -pub fn missing_field<'de, V, E>(field: &'static str) -> Result - where V: Deserialize<'de>, - E: Error -{ - struct MissingFieldDeserializer(&'static str, PhantomData); - - impl<'de, E> Deserializer<'de> for MissingFieldDeserializer - where E: Error - { - type Error = E; - - fn deserialize(self, _visitor: V) -> Result - where V: Visitor<'de> - { - Err(Error::missing_field(self.0)) - } - - fn deserialize_option(self, visitor: V) -> Result - where V: Visitor<'de> - { - visitor.visit_none() - } - - forward_to_deserialize! { - bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq - seq_fixed_size bytes byte_buf map unit_struct newtype_struct - tuple_struct struct struct_field tuple enum ignored_any - } - } - - let deserializer = MissingFieldDeserializer(field, PhantomData); - Deserialize::deserialize(deserializer) -} - -#[cfg(any(feature = "std", feature = "collections"))] -pub fn borrow_cow_str<'de: 'a, 'a, D>(deserializer: D) -> Result, D::Error> - where D: Deserializer<'de> -{ - struct CowStrVisitor; - - impl<'a> Visitor<'a> for CowStrVisitor { - type Value = Cow<'a, str>; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("a string") - } - - fn visit_str(self, v: &str) -> Result - where E: Error - { - Ok(Cow::Owned(v.to_owned())) - } - - fn visit_borrowed_str(self, v: &'a str) -> Result - where E: Error - { - Ok(Cow::Borrowed(v)) - } - - fn visit_string(self, v: String) -> Result - where E: Error - { - Ok(Cow::Owned(v)) - } - - fn visit_bytes(self, v: &[u8]) -> Result - where E: Error - { - match str::from_utf8(v) { - Ok(s) => Ok(Cow::Owned(s.to_owned())), - Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)), - } - } - - fn visit_borrowed_bytes(self, v: &'a [u8]) -> Result - where E: Error - { - match str::from_utf8(v) { - Ok(s) => Ok(Cow::Borrowed(s)), - Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)), - } - } - - fn visit_byte_buf(self, v: Vec) -> Result - where E: Error - { - match String::from_utf8(v) { - Ok(s) => Ok(Cow::Owned(s)), - Err(e) => Err(Error::invalid_value(Unexpected::Bytes(&e.into_bytes()), &self)), - } - } - } - - deserializer.deserialize_str(CowStrVisitor) -} - -#[cfg(any(feature = "std", feature = "collections"))] -pub fn borrow_cow_bytes<'de: 'a, 'a, D>(deserializer: D) -> Result, D::Error> - where D: Deserializer<'de> -{ - struct CowBytesVisitor; - - impl<'a> Visitor<'a> for CowBytesVisitor { - type Value = Cow<'a, [u8]>; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("a byte array") - } - - fn visit_str(self, v: &str) -> Result - where E: Error - { - Ok(Cow::Owned(v.as_bytes().to_vec())) - } - - fn visit_borrowed_str(self, v: &'a str) -> Result - where E: Error - { - Ok(Cow::Borrowed(v.as_bytes())) - } - - fn visit_string(self, v: String) -> Result - where E: Error - { - Ok(Cow::Owned(v.into_bytes())) - } - - fn visit_bytes(self, v: &[u8]) -> Result - where E: Error - { - Ok(Cow::Owned(v.to_vec())) - } - - fn visit_borrowed_bytes(self, v: &'a [u8]) -> Result - where E: Error - { - Ok(Cow::Borrowed(v)) - } - - fn visit_byte_buf(self, v: Vec) -> Result - where E: Error - { - Ok(Cow::Owned(v)) - } - } - - deserializer.deserialize_str(CowBytesVisitor) -} diff --git a/serde/src/lib.rs b/serde/src/lib.rs index 10cb570f..ada910ca 100644 --- a/serde/src/lib.rs +++ b/serde/src/lib.rs @@ -93,15 +93,19 @@ pub use de::{Deserialize, Deserializer}; #[macro_use] mod macros; +mod utils; pub mod de; pub mod ser; -mod utils; // Generated code uses these to support no_std. Not public API. #[doc(hidden)] pub mod export; +// Helpers used by generated code and doc tests. Not public API. +#[doc(hidden)] +pub mod private; + // Re-export #[derive(Serialize, Deserialize)]. // // This is a workaround for https://github.com/rust-lang/cargo/issues/1286. diff --git a/serde/src/macros.rs b/serde/src/macros.rs index dcd2433e..022e1214 100644 --- a/serde/src/macros.rs +++ b/serde/src/macros.rs @@ -177,162 +177,3 @@ macro_rules! forward_to_deserialize { $(forward_to_deserialize_helper!{$func})* }; } - -/// Seralize the `$value` that implements Display as a string, -/// when that string is statically known to never have more than -/// a constant `$MAX_LEN` bytes. -/// -/// Panics if the Display impl tries to write more than `$MAX_LEN` bytes. -#[cfg(feature = "std")] -// Not exported -macro_rules! serialize_display_bounded_length { - ($value: expr, $MAX_LEN: expr, $serializer: expr) => { - { - use std::io::Write; - let mut buffer: [u8; $MAX_LEN] = unsafe { ::std::mem::uninitialized() }; - let remaining_len; - { - let mut remaining = &mut buffer[..]; - write!(remaining, "{}", $value).unwrap(); - remaining_len = remaining.len() - } - let written_len = buffer.len() - remaining_len; - let written = &buffer[..written_len]; - - // write! only provides std::fmt::Formatter to Display implementations, - // which has methods write_str and write_char but no method to write arbitrary bytes. - // Therefore, `written` is well-formed in UTF-8. - let written_str = unsafe { - ::std::str::from_utf8_unchecked(written) - }; - $serializer.serialize_str(written_str) - } - } -} - -#[doc(hidden)] -#[macro_export] -macro_rules! __serialize_unimplemented_method { - ($func:ident $(<$t:ident>)* ($($arg:ty),*) -> $ret:ident) => { - fn $func $(<$t: ?Sized + $crate::Serialize>)* (self $(, _: $arg)*) -> $crate::export::Result { - unimplemented!() - } - }; -} - -#[doc(hidden)] -#[macro_export] -macro_rules! __serialize_unimplemented_helper { - (bool) => { - __serialize_unimplemented_method!(serialize_bool(bool) -> Ok); - }; - (i8) => { - __serialize_unimplemented_method!(serialize_i8(i8) -> Ok); - }; - (i16) => { - __serialize_unimplemented_method!(serialize_i16(i16) -> Ok); - }; - (i32) => { - __serialize_unimplemented_method!(serialize_i32(i32) -> Ok); - }; - (i64) => { - __serialize_unimplemented_method!(serialize_i64(i64) -> Ok); - }; - (u8) => { - __serialize_unimplemented_method!(serialize_u8(u8) -> Ok); - }; - (u16) => { - __serialize_unimplemented_method!(serialize_u16(u16) -> Ok); - }; - (u32) => { - __serialize_unimplemented_method!(serialize_u32(u32) -> Ok); - }; - (u64) => { - __serialize_unimplemented_method!(serialize_u64(u64) -> Ok); - }; - (f32) => { - __serialize_unimplemented_method!(serialize_f32(f32) -> Ok); - }; - (f64) => { - __serialize_unimplemented_method!(serialize_f64(f64) -> Ok); - }; - (char) => { - __serialize_unimplemented_method!(serialize_char(char) -> Ok); - }; - (str) => { - __serialize_unimplemented_method!(serialize_str(&str) -> Ok); - }; - (bytes) => { - __serialize_unimplemented_method!(serialize_bytes(&[u8]) -> Ok); - }; - (none) => { - __serialize_unimplemented_method!(serialize_none() -> Ok); - }; - (some) => { - __serialize_unimplemented_method!(serialize_some(&T) -> Ok); - }; - (unit) => { - __serialize_unimplemented_method!(serialize_unit() -> Ok); - }; - (unit_struct) => { - __serialize_unimplemented_method!(serialize_unit_struct(&str) -> Ok); - }; - (unit_variant) => { - __serialize_unimplemented_method!(serialize_unit_variant(&str, usize, &str) -> Ok); - }; - (newtype_struct) => { - __serialize_unimplemented_method!(serialize_newtype_struct(&str, &T) -> Ok); - }; - (newtype_variant) => { - __serialize_unimplemented_method!(serialize_newtype_variant(&str, usize, &str, &T) -> Ok); - }; - (seq) => { - type SerializeSeq = $crate::ser::Impossible; - __serialize_unimplemented_method!(serialize_seq(Option) -> SerializeSeq); - }; - (seq_fixed_size) => { - __serialize_unimplemented_method!(serialize_seq_fixed_size(usize) -> SerializeSeq); - }; - (tuple) => { - type SerializeTuple = $crate::ser::Impossible; - __serialize_unimplemented_method!(serialize_tuple(usize) -> SerializeTuple); - }; - (tuple_struct) => { - type SerializeTupleStruct = $crate::ser::Impossible; - __serialize_unimplemented_method!(serialize_tuple_struct(&str, usize) -> SerializeTupleStruct); - }; - (tuple_variant) => { - type SerializeTupleVariant = $crate::ser::Impossible; - __serialize_unimplemented_method!(serialize_tuple_variant(&str, usize, &str, usize) -> SerializeTupleVariant); - }; - (map) => { - type SerializeMap = $crate::ser::Impossible; - __serialize_unimplemented_method!(serialize_map(Option) -> SerializeMap); - }; - (struct) => { - type SerializeStruct = $crate::ser::Impossible; - __serialize_unimplemented_method!(serialize_struct(&str, usize) -> SerializeStruct); - }; - (struct_variant) => { - type SerializeStructVariant = $crate::ser::Impossible; - __serialize_unimplemented_method!(serialize_struct_variant(&str, usize, &str, usize) -> SerializeStructVariant); - }; -} - -/// Used only by Serde doc tests. Not public API. -#[doc(hidden)] -#[macro_export] -macro_rules! __serialize_unimplemented { - ($($func:ident)*) => { - $( - __serialize_unimplemented_helper!($func); - )* - }; -} - -/// Used only by Serde doc tests. Not public API. -#[doc(hidden)] -#[macro_export] -macro_rules! __serde_ignore_tokens { - ($($tt:tt)+) => {} -} diff --git a/serde/src/private/de.rs b/serde/src/private/de.rs new file mode 100644 index 00000000..f4e95dc6 --- /dev/null +++ b/serde/src/private/de.rs @@ -0,0 +1,1520 @@ +#[cfg(any(feature = "std", feature = "collections"))] +use core::{fmt, str}; + +use core::marker::PhantomData; + +#[cfg(feature = "collections")] +use collections::borrow::ToOwned; + +#[cfg(feature = "std")] +use std::borrow::Cow; +#[cfg(all(feature = "collections", not(feature = "std")))] +use collections::borrow::Cow; + +#[cfg(all(feature = "collections", not(feature = "std")))] +use collections::{String, Vec}; + +use de::{Deserialize, Deserializer, Error, Visitor}; + +#[cfg(any(feature = "std", feature = "collections"))] +use de::Unexpected; + +#[cfg(any(feature = "std", feature = "collections"))] +pub use self::content::{Content, ContentRefDeserializer, ContentDeserializer, TaggedContentVisitor, + TagOrContentField, TagOrContentFieldVisitor, InternallyTaggedUnitVisitor, + UntaggedUnitVisitor}; + +/// If the missing field is of type `Option` then treat is as `None`, +/// otherwise it is an error. +pub fn missing_field<'de, V, E>(field: &'static str) -> Result + where V: Deserialize<'de>, + E: Error +{ + struct MissingFieldDeserializer(&'static str, PhantomData); + + impl<'de, E> Deserializer<'de> for MissingFieldDeserializer + where E: Error + { + type Error = E; + + fn deserialize(self, _visitor: V) -> Result + where V: Visitor<'de> + { + Err(Error::missing_field(self.0)) + } + + fn deserialize_option(self, visitor: V) -> Result + where V: Visitor<'de> + { + visitor.visit_none() + } + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq + seq_fixed_size bytes byte_buf map unit_struct newtype_struct + tuple_struct struct struct_field tuple enum ignored_any + } + } + + let deserializer = MissingFieldDeserializer(field, PhantomData); + Deserialize::deserialize(deserializer) +} + +#[cfg(any(feature = "std", feature = "collections"))] +pub fn borrow_cow_str<'de: 'a, 'a, D>(deserializer: D) -> Result, D::Error> + where D: Deserializer<'de> +{ + struct CowStrVisitor; + + impl<'a> Visitor<'a> for CowStrVisitor { + type Value = Cow<'a, str>; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a string") + } + + fn visit_str(self, v: &str) -> Result + where E: Error + { + Ok(Cow::Owned(v.to_owned())) + } + + fn visit_borrowed_str(self, v: &'a str) -> Result + where E: Error + { + Ok(Cow::Borrowed(v)) + } + + fn visit_string(self, v: String) -> Result + where E: Error + { + Ok(Cow::Owned(v)) + } + + fn visit_bytes(self, v: &[u8]) -> Result + where E: Error + { + match str::from_utf8(v) { + Ok(s) => Ok(Cow::Owned(s.to_owned())), + Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)), + } + } + + fn visit_borrowed_bytes(self, v: &'a [u8]) -> Result + where E: Error + { + match str::from_utf8(v) { + Ok(s) => Ok(Cow::Borrowed(s)), + Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)), + } + } + + fn visit_byte_buf(self, v: Vec) -> Result + where E: Error + { + match String::from_utf8(v) { + Ok(s) => Ok(Cow::Owned(s)), + Err(e) => Err(Error::invalid_value(Unexpected::Bytes(&e.into_bytes()), &self)), + } + } + } + + deserializer.deserialize_str(CowStrVisitor) +} + +#[cfg(any(feature = "std", feature = "collections"))] +pub fn borrow_cow_bytes<'de: 'a, 'a, D>(deserializer: D) -> Result, D::Error> + where D: Deserializer<'de> +{ + struct CowBytesVisitor; + + impl<'a> Visitor<'a> for CowBytesVisitor { + type Value = Cow<'a, [u8]>; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a byte array") + } + + fn visit_str(self, v: &str) -> Result + where E: Error + { + Ok(Cow::Owned(v.as_bytes().to_vec())) + } + + fn visit_borrowed_str(self, v: &'a str) -> Result + where E: Error + { + Ok(Cow::Borrowed(v.as_bytes())) + } + + fn visit_string(self, v: String) -> Result + where E: Error + { + Ok(Cow::Owned(v.into_bytes())) + } + + fn visit_bytes(self, v: &[u8]) -> Result + where E: Error + { + Ok(Cow::Owned(v.to_vec())) + } + + fn visit_borrowed_bytes(self, v: &'a [u8]) -> Result + where E: Error + { + Ok(Cow::Borrowed(v)) + } + + fn visit_byte_buf(self, v: Vec) -> Result + where E: Error + { + Ok(Cow::Owned(v)) + } + } + + deserializer.deserialize_str(CowBytesVisitor) +} + +#[cfg(any(feature = "std", feature = "collections"))] +mod content { + // This module is private and nothing here should be used outside of + // generated code. + // + // We will iterate on the implementation for a few releases and only have to + // worry about backward compatibility for the `untagged` and `tag` attributes + // rather than for this entire mechanism. + // + // This issue is tracking making some of this stuff public: + // https://github.com/serde-rs/serde/issues/741 + + #![doc(hidden)] + + use core::cmp; + use core::fmt; + use core::marker::PhantomData; + + #[cfg(all(not(feature = "std"), feature = "collections"))] + use collections::{String, Vec}; + + #[cfg(all(feature = "alloc", not(feature = "std")))] + use alloc::boxed::Box; + + use de::{self, Deserialize, DeserializeSeed, Deserializer, Visitor, SeqVisitor, MapVisitor, + EnumVisitor, Unexpected}; + + /// Used from generated code to buffer the contents of the Deserializer when + /// deserializing untagged enums and internally tagged enums. + /// + /// Not public API. Use serde-value instead. + #[derive(Debug)] + pub enum Content { + Bool(bool), + + U8(u8), + U16(u16), + U32(u32), + U64(u64), + + I8(i8), + I16(i16), + I32(i32), + I64(i64), + + F32(f32), + F64(f64), + + Char(char), + String(String), + Bytes(Vec), + + None, + Some(Box), + + Unit, + Newtype(Box), + Seq(Vec), + Map(Vec<(Content, Content)>), + } + + impl Content { + fn unexpected(&self) -> Unexpected { + match *self { + Content::Bool(b) => Unexpected::Bool(b), + Content::U8(n) => Unexpected::Unsigned(n as u64), + Content::U16(n) => Unexpected::Unsigned(n as u64), + Content::U32(n) => Unexpected::Unsigned(n as u64), + Content::U64(n) => Unexpected::Unsigned(n), + Content::I8(n) => Unexpected::Signed(n as i64), + Content::I16(n) => Unexpected::Signed(n as i64), + Content::I32(n) => Unexpected::Signed(n as i64), + Content::I64(n) => Unexpected::Signed(n), + Content::F32(f) => Unexpected::Float(f as f64), + Content::F64(f) => Unexpected::Float(f), + Content::Char(c) => Unexpected::Char(c), + Content::String(ref s) => Unexpected::Str(s), + Content::Bytes(ref b) => Unexpected::Bytes(b), + Content::None | Content::Some(_) => Unexpected::Option, + Content::Unit => Unexpected::Unit, + Content::Newtype(_) => Unexpected::NewtypeStruct, + Content::Seq(_) => Unexpected::Seq, + Content::Map(_) => Unexpected::Map, + } + } + } + + impl<'de> Deserialize<'de> for Content { + fn deserialize(deserializer: D) -> Result + where D: Deserializer<'de> + { + // Untagged and internally tagged enums are only supported in + // self-describing formats. + deserializer.deserialize(ContentVisitor) + } + } + + struct ContentVisitor; + + impl<'de> Visitor<'de> for ContentVisitor { + type Value = Content; + + fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.write_str("any value") + } + + fn visit_bool(self, value: bool) -> Result + where F: de::Error + { + Ok(Content::Bool(value)) + } + + fn visit_i8(self, value: i8) -> Result + where F: de::Error + { + Ok(Content::I8(value)) + } + + fn visit_i16(self, value: i16) -> Result + where F: de::Error + { + Ok(Content::I16(value)) + } + + fn visit_i32(self, value: i32) -> Result + where F: de::Error + { + Ok(Content::I32(value)) + } + + fn visit_i64(self, value: i64) -> Result + where F: de::Error + { + Ok(Content::I64(value)) + } + + fn visit_u8(self, value: u8) -> Result + where F: de::Error + { + Ok(Content::U8(value)) + } + + fn visit_u16(self, value: u16) -> Result + where F: de::Error + { + Ok(Content::U16(value)) + } + + fn visit_u32(self, value: u32) -> Result + where F: de::Error + { + Ok(Content::U32(value)) + } + + fn visit_u64(self, value: u64) -> Result + where F: de::Error + { + Ok(Content::U64(value)) + } + + fn visit_f32(self, value: f32) -> Result + where F: de::Error + { + Ok(Content::F32(value)) + } + + fn visit_f64(self, value: f64) -> Result + where F: de::Error + { + Ok(Content::F64(value)) + } + + fn visit_char(self, value: char) -> Result + where F: de::Error + { + Ok(Content::Char(value)) + } + + fn visit_str(self, value: &str) -> Result + where F: de::Error + { + Ok(Content::String(value.into())) + } + + fn visit_string(self, value: String) -> Result + where F: de::Error + { + Ok(Content::String(value)) + } + + fn visit_bytes(self, value: &[u8]) -> Result + where F: de::Error + { + Ok(Content::Bytes(value.into())) + } + + fn visit_byte_buf(self, value: Vec) -> Result + where F: de::Error + { + Ok(Content::Bytes(value)) + } + + fn visit_unit(self) -> Result + where F: de::Error + { + Ok(Content::Unit) + } + + fn visit_none(self) -> Result + where F: de::Error + { + Ok(Content::None) + } + + fn visit_some(self, deserializer: D) -> Result + where D: Deserializer<'de> + { + Deserialize::deserialize(deserializer).map(|v| Content::Some(Box::new(v))) + } + + fn visit_newtype_struct(self, deserializer: D) -> Result + where D: Deserializer<'de> + { + Deserialize::deserialize(deserializer).map(|v| Content::Newtype(Box::new(v))) + } + + fn visit_seq(self, mut visitor: V) -> Result + where V: SeqVisitor<'de> + { + let mut vec = Vec::with_capacity(cmp::min(visitor.size_hint().0, 4096)); + while let Some(e) = try!(visitor.visit()) { + vec.push(e); + } + Ok(Content::Seq(vec)) + } + + fn visit_map(self, mut visitor: V) -> Result + where V: MapVisitor<'de> + { + let mut vec = Vec::with_capacity(cmp::min(visitor.size_hint().0, 4096)); + while let Some(kv) = try!(visitor.visit()) { + vec.push(kv); + } + Ok(Content::Map(vec)) + } + + fn visit_enum(self, _visitor: V) -> Result + where V: EnumVisitor<'de> + { + Err(de::Error::custom("untagged and internally tagged enums do not support enum input")) + } + } + + /// This is the type of the map keys in an internally tagged enum. + /// + /// Not public API. + pub enum TagOrContent { + Tag, + Content(Content), + } + + struct TagOrContentVisitor { + name: &'static str, + } + + impl TagOrContentVisitor { + fn new(name: &'static str) -> Self { + TagOrContentVisitor { name: name } + } + } + + impl<'de> DeserializeSeed<'de> for TagOrContentVisitor { + type Value = TagOrContent; + + fn deserialize(self, deserializer: D) -> Result + where D: Deserializer<'de> + { + // Internally tagged enums are only supported in self-describing + // formats. + deserializer.deserialize(self) + } + } + + impl<'de> Visitor<'de> for TagOrContentVisitor { + type Value = TagOrContent; + + fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "a type tag `{}` or any other value", self.name) + } + + fn visit_bool(self, value: bool) -> Result + where F: de::Error + { + ContentVisitor.visit_bool(value).map(TagOrContent::Content) + } + + fn visit_i8(self, value: i8) -> Result + where F: de::Error + { + ContentVisitor.visit_i8(value).map(TagOrContent::Content) + } + + fn visit_i16(self, value: i16) -> Result + where F: de::Error + { + ContentVisitor.visit_i16(value).map(TagOrContent::Content) + } + + fn visit_i32(self, value: i32) -> Result + where F: de::Error + { + ContentVisitor.visit_i32(value).map(TagOrContent::Content) + } + + fn visit_i64(self, value: i64) -> Result + where F: de::Error + { + ContentVisitor.visit_i64(value).map(TagOrContent::Content) + } + + fn visit_u8(self, value: u8) -> Result + where F: de::Error + { + ContentVisitor.visit_u8(value).map(TagOrContent::Content) + } + + fn visit_u16(self, value: u16) -> Result + where F: de::Error + { + ContentVisitor.visit_u16(value).map(TagOrContent::Content) + } + + fn visit_u32(self, value: u32) -> Result + where F: de::Error + { + ContentVisitor.visit_u32(value).map(TagOrContent::Content) + } + + fn visit_u64(self, value: u64) -> Result + where F: de::Error + { + ContentVisitor.visit_u64(value).map(TagOrContent::Content) + } + + fn visit_f32(self, value: f32) -> Result + where F: de::Error + { + ContentVisitor.visit_f32(value).map(TagOrContent::Content) + } + + fn visit_f64(self, value: f64) -> Result + where F: de::Error + { + ContentVisitor.visit_f64(value).map(TagOrContent::Content) + } + + fn visit_char(self, value: char) -> Result + where F: de::Error + { + ContentVisitor.visit_char(value).map(TagOrContent::Content) + } + + fn visit_str(self, value: &str) -> Result + where F: de::Error + { + if value == self.name { + Ok(TagOrContent::Tag) + } else { + ContentVisitor.visit_str(value).map(TagOrContent::Content) + } + } + + fn visit_string(self, value: String) -> Result + where F: de::Error + { + if value == self.name { + Ok(TagOrContent::Tag) + } else { + ContentVisitor.visit_string(value).map(TagOrContent::Content) + } + } + + fn visit_bytes(self, value: &[u8]) -> Result + where F: de::Error + { + if value == self.name.as_bytes() { + Ok(TagOrContent::Tag) + } else { + ContentVisitor.visit_bytes(value).map(TagOrContent::Content) + } + } + + fn visit_byte_buf(self, value: Vec) -> Result + where F: de::Error + { + if value == self.name.as_bytes() { + Ok(TagOrContent::Tag) + } else { + ContentVisitor.visit_byte_buf(value).map(TagOrContent::Content) + } + } + + fn visit_unit(self) -> Result + where F: de::Error + { + ContentVisitor.visit_unit().map(TagOrContent::Content) + } + + fn visit_none(self) -> Result + where F: de::Error + { + ContentVisitor.visit_none().map(TagOrContent::Content) + } + + fn visit_some(self, deserializer: D) -> Result + where D: Deserializer<'de> + { + ContentVisitor.visit_some(deserializer).map(TagOrContent::Content) + } + + fn visit_newtype_struct(self, deserializer: D) -> Result + where D: Deserializer<'de> + { + ContentVisitor.visit_newtype_struct(deserializer).map(TagOrContent::Content) + } + + fn visit_seq(self, visitor: V) -> Result + where V: SeqVisitor<'de> + { + ContentVisitor.visit_seq(visitor).map(TagOrContent::Content) + } + + fn visit_map(self, visitor: V) -> Result + where V: MapVisitor<'de> + { + ContentVisitor.visit_map(visitor).map(TagOrContent::Content) + } + + fn visit_enum(self, visitor: V) -> Result + where V: EnumVisitor<'de> + { + ContentVisitor.visit_enum(visitor).map(TagOrContent::Content) + } + } + + /// Used by generated code to deserialize an internally tagged enum. + /// + /// Not public API. + pub struct TaggedContent { + pub tag: T, + pub content: Content, + } + + /// Not public API. + pub struct TaggedContentVisitor { + tag_name: &'static str, + tag: PhantomData, + } + + impl TaggedContentVisitor { + /// Visitor for the content of an internally tagged enum with the given tag + /// name. + pub fn new(name: &'static str) -> Self { + TaggedContentVisitor { + tag_name: name, + tag: PhantomData, + } + } + } + + impl<'de, T> DeserializeSeed<'de> for TaggedContentVisitor + where T: Deserialize<'de> + { + type Value = TaggedContent; + + fn deserialize(self, deserializer: D) -> Result + where D: Deserializer<'de> + { + // Internally tagged enums are only supported in self-describing + // formats. + deserializer.deserialize(self) + } + } + + impl<'de, T> Visitor<'de> for TaggedContentVisitor + where T: Deserialize<'de> + { + type Value = TaggedContent; + + fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.write_str("any value") + } + + fn visit_map(self, mut visitor: V) -> Result + where V: MapVisitor<'de> + { + let mut tag = None; + let mut vec = Vec::with_capacity(cmp::min(visitor.size_hint().0, 4096)); + while let Some(k) = try!(visitor.visit_key_seed(TagOrContentVisitor::new(self.tag_name))) { + match k { + TagOrContent::Tag => { + if tag.is_some() { + return Err(de::Error::duplicate_field(self.tag_name)); + } + tag = Some(try!(visitor.visit_value())); + } + TagOrContent::Content(k) => { + let v = try!(visitor.visit_value()); + vec.push((k, v)); + } + } + } + match tag { + None => Err(de::Error::missing_field(self.tag_name)), + Some(tag) => { + Ok(TaggedContent { + tag: tag, + content: Content::Map(vec), + }) + } + } + } + } + + /// Used by generated code to deserialize an adjacently tagged enum. + /// + /// Not public API. + pub enum TagOrContentField { + Tag, + Content, + } + + /// Not public API. + pub struct TagOrContentFieldVisitor { + pub tag: &'static str, + pub content: &'static str, + } + + impl<'de> DeserializeSeed<'de> for TagOrContentFieldVisitor { + type Value = TagOrContentField; + + fn deserialize(self, deserializer: D) -> Result + where D: Deserializer<'de> + { + deserializer.deserialize_str(self) + } + } + + impl<'de> Visitor<'de> for TagOrContentFieldVisitor { + type Value = TagOrContentField; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "{:?} or {:?}", self.tag, self.content) + } + + fn visit_str(self, field: &str) -> Result + where E: de::Error + { + if field == self.tag { + Ok(TagOrContentField::Tag) + } else if field == self.content { + Ok(TagOrContentField::Content) + } else { + Err(de::Error::invalid_value(Unexpected::Str(field), &self)) + } + } + } + + /// Not public API + pub struct ContentDeserializer { + content: Content, + err: PhantomData, + } + + /// Used when deserializing an internally tagged enum because the content will + /// be used exactly once. + impl<'de, E> Deserializer<'de> for ContentDeserializer + where E: de::Error + { + type Error = E; + + fn deserialize(self, visitor: V) -> Result + where V: Visitor<'de> + { + match self.content { + Content::Bool(v) => visitor.visit_bool(v), + Content::U8(v) => visitor.visit_u8(v), + Content::U16(v) => visitor.visit_u16(v), + Content::U32(v) => visitor.visit_u32(v), + Content::U64(v) => visitor.visit_u64(v), + Content::I8(v) => visitor.visit_i8(v), + Content::I16(v) => visitor.visit_i16(v), + Content::I32(v) => visitor.visit_i32(v), + Content::I64(v) => visitor.visit_i64(v), + Content::F32(v) => visitor.visit_f32(v), + Content::F64(v) => visitor.visit_f64(v), + Content::Char(v) => visitor.visit_char(v), + Content::String(v) => visitor.visit_string(v), + Content::Unit => visitor.visit_unit(), + Content::None => visitor.visit_none(), + Content::Some(v) => visitor.visit_some(ContentDeserializer::new(*v)), + Content::Newtype(v) => visitor.visit_newtype_struct(ContentDeserializer::new(*v)), + Content::Seq(v) => { + let seq = v.into_iter().map(ContentDeserializer::new); + let mut seq_visitor = de::value::SeqDeserializer::new(seq); + let value = try!(visitor.visit_seq(&mut seq_visitor)); + try!(seq_visitor.end()); + Ok(value) + } + Content::Map(v) => { + let map = v.into_iter().map(|(k, v)| { + (ContentDeserializer::new(k), + ContentDeserializer::new(v)) + }); + let mut map_visitor = de::value::MapDeserializer::new(map); + let value = try!(visitor.visit_map(&mut map_visitor)); + try!(map_visitor.end()); + Ok(value) + } + Content::Bytes(v) => visitor.visit_byte_buf(v), + } + } + + fn deserialize_option(self, visitor: V) -> Result + where V: Visitor<'de> + { + match self.content { + Content::None => visitor.visit_none(), + Content::Some(v) => visitor.visit_some(ContentDeserializer::new(*v)), + Content::Unit => visitor.visit_unit(), + _ => visitor.visit_some(self), + } + } + + fn deserialize_newtype_struct(self, _name: &str, visitor: V) -> Result + where V: Visitor<'de> + { + visitor.visit_newtype_struct(self) + } + + fn deserialize_enum(self, + _name: &str, + _variants: &'static [&'static str], + visitor: V) + -> Result + where V: Visitor<'de> + { + let (variant, value) = match self.content { + Content::Map(value) => { + let mut iter = value.into_iter(); + let (variant, value) = match iter.next() { + Some(v) => v, + None => { + return Err(de::Error::invalid_value(de::Unexpected::Map, + &"map with a single key")); + } + }; + // enums are encoded in json as maps with a single key:value pair + if iter.next().is_some() { + return Err(de::Error::invalid_value(de::Unexpected::Map, + &"map with a single key")); + } + (variant, Some(value)) + } + Content::String(variant) => (Content::String(variant), None), + other => { + return Err(de::Error::invalid_type(other.unexpected(), &"string or map")); + } + }; + + visitor.visit_enum(EnumDeserializer { + variant: variant, + value: value, + err: PhantomData, + }) + } + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq + seq_fixed_size bytes byte_buf map unit_struct tuple_struct struct + struct_field tuple ignored_any + } + } + + impl ContentDeserializer { + /// private API, don't use + pub fn new(content: Content) -> Self { + ContentDeserializer { + content: content, + err: PhantomData, + } + } + } + + struct EnumDeserializer + where E: de::Error + { + variant: Content, + value: Option, + err: PhantomData, + } + + impl<'de, E> de::EnumVisitor<'de> for EnumDeserializer + where E: de::Error + { + type Error = E; + type Variant = VariantDeserializer; + + fn visit_variant_seed(self, + seed: V) + -> Result<(V::Value, VariantDeserializer), Self::Error> + where V: de::DeserializeSeed<'de> + { + let visitor = VariantDeserializer { + value: self.value, + err: PhantomData, + }; + seed.deserialize(ContentDeserializer::new(self.variant)).map(|v| (v, visitor)) + } + } + + struct VariantDeserializer + where E: de::Error + { + value: Option, + err: PhantomData, + } + + impl<'de, E> de::VariantVisitor<'de> for VariantDeserializer + where E: de::Error + { + type Error = E; + + fn visit_unit(self) -> Result<(), E> { + match self.value { + Some(value) => de::Deserialize::deserialize(ContentDeserializer::new(value)), + None => Ok(()), + } + } + + fn visit_newtype_seed(self, seed: T) -> Result + where T: de::DeserializeSeed<'de> + { + match self.value { + Some(value) => seed.deserialize(ContentDeserializer::new(value)), + None => Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"newtype variant")), + } + } + + fn visit_tuple(self, _len: usize, visitor: V) -> Result + where V: de::Visitor<'de> + { + match self.value { + Some(Content::Seq(v)) => { + de::Deserializer::deserialize(SeqDeserializer::new(v), visitor) + } + Some(other) => Err(de::Error::invalid_type(other.unexpected(), &"tuple variant")), + None => Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"tuple variant")), + } + } + + fn visit_struct(self, + _fields: &'static [&'static str], + visitor: V) + -> Result + where V: de::Visitor<'de> + { + match self.value { + Some(Content::Map(v)) => { + de::Deserializer::deserialize(MapDeserializer::new(v), visitor) + } + Some(other) => Err(de::Error::invalid_type(other.unexpected(), &"struct variant")), + _ => Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"struct variant")), + } + } + } + + struct SeqDeserializer + where E: de::Error + { + iter: as IntoIterator>::IntoIter, + err: PhantomData, + } + + impl SeqDeserializer + where E: de::Error + { + fn new(vec: Vec) -> Self { + SeqDeserializer { + iter: vec.into_iter(), + err: PhantomData, + } + } + } + + impl<'de, E> de::Deserializer<'de> for SeqDeserializer + where E: de::Error + { + type Error = E; + + #[inline] + fn deserialize(mut self, visitor: V) -> Result + where V: de::Visitor<'de> + { + let len = self.iter.len(); + if len == 0 { + visitor.visit_unit() + } else { + let ret = try!(visitor.visit_seq(&mut self)); + let remaining = self.iter.len(); + if remaining == 0 { + Ok(ret) + } else { + Err(de::Error::invalid_length(len, &"fewer elements in array")) + } + } + } + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option + seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct + tuple_struct struct struct_field tuple enum ignored_any + } + } + + impl<'de, E> de::SeqVisitor<'de> for SeqDeserializer + where E: de::Error + { + type Error = E; + + fn visit_seed(&mut self, seed: T) -> Result, Self::Error> + where T: de::DeserializeSeed<'de> + { + match self.iter.next() { + Some(value) => seed.deserialize(ContentDeserializer::new(value)).map(Some), + None => Ok(None), + } + } + + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } + } + + struct MapDeserializer + where E: de::Error + { + iter: as IntoIterator>::IntoIter, + value: Option, + err: PhantomData, + } + + impl MapDeserializer + where E: de::Error + { + fn new(map: Vec<(Content, Content)>) -> Self { + MapDeserializer { + iter: map.into_iter(), + value: None, + err: PhantomData, + } + } + } + + impl<'de, E> de::MapVisitor<'de> for MapDeserializer + where E: de::Error + { + type Error = E; + + fn visit_key_seed(&mut self, seed: T) -> Result, Self::Error> + where T: de::DeserializeSeed<'de> + { + match self.iter.next() { + Some((key, value)) => { + self.value = Some(value); + seed.deserialize(ContentDeserializer::new(key)).map(Some) + } + None => Ok(None), + } + } + + fn visit_value_seed(&mut self, seed: T) -> Result + where T: de::DeserializeSeed<'de> + { + match self.value.take() { + Some(value) => seed.deserialize(ContentDeserializer::new(value)), + None => Err(de::Error::custom("value is missing")), + } + } + + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } + } + + impl<'de, E> de::Deserializer<'de> for MapDeserializer + where E: de::Error + { + type Error = E; + + #[inline] + fn deserialize(self, visitor: V) -> Result + where V: de::Visitor<'de> + { + visitor.visit_map(self) + } + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option + seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct + tuple_struct struct struct_field tuple enum ignored_any + } + } + + + /// Not public API. + pub struct ContentRefDeserializer<'a, E> { + content: &'a Content, + err: PhantomData, + } + + /// Used when deserializing an untagged enum because the content may need to be + /// used more than once. + impl<'de, 'a, E> Deserializer<'de> for ContentRefDeserializer<'a, E> + where E: de::Error + { + type Error = E; + + fn deserialize(self, visitor: V) -> Result + where V: Visitor<'de> + { + match *self.content { + Content::Bool(v) => visitor.visit_bool(v), + Content::U8(v) => visitor.visit_u8(v), + Content::U16(v) => visitor.visit_u16(v), + Content::U32(v) => visitor.visit_u32(v), + Content::U64(v) => visitor.visit_u64(v), + Content::I8(v) => visitor.visit_i8(v), + Content::I16(v) => visitor.visit_i16(v), + Content::I32(v) => visitor.visit_i32(v), + Content::I64(v) => visitor.visit_i64(v), + Content::F32(v) => visitor.visit_f32(v), + Content::F64(v) => visitor.visit_f64(v), + Content::Char(v) => visitor.visit_char(v), + Content::String(ref v) => visitor.visit_str(v), + Content::Unit => visitor.visit_unit(), + Content::None => visitor.visit_none(), + Content::Some(ref v) => visitor.visit_some(ContentRefDeserializer::new(v)), + Content::Newtype(ref v) => visitor.visit_newtype_struct(ContentRefDeserializer::new(v)), + Content::Seq(ref v) => { + let seq = v.into_iter().map(ContentRefDeserializer::new); + let mut seq_visitor = de::value::SeqDeserializer::new(seq); + let value = try!(visitor.visit_seq(&mut seq_visitor)); + try!(seq_visitor.end()); + Ok(value) + } + Content::Map(ref v) => { + let map = v.into_iter().map(|&(ref k, ref v)| { + (ContentRefDeserializer::new(k), + ContentRefDeserializer::new(v)) + }); + let mut map_visitor = de::value::MapDeserializer::new(map); + let value = try!(visitor.visit_map(&mut map_visitor)); + try!(map_visitor.end()); + Ok(value) + } + Content::Bytes(ref v) => visitor.visit_bytes(v), + } + } + + fn deserialize_option(self, visitor: V) -> Result + where V: Visitor<'de> + { + match *self.content { + Content::None => visitor.visit_none(), + Content::Some(ref v) => visitor.visit_some(ContentRefDeserializer::new(v)), + Content::Unit => visitor.visit_unit(), + _ => visitor.visit_some(self), + } + } + + fn deserialize_newtype_struct(self, _name: &str, visitor: V) -> Result + where V: Visitor<'de> + { + visitor.visit_newtype_struct(self) + } + + fn deserialize_enum(self, + _name: &str, + _variants: &'static [&'static str], + visitor: V) + -> Result + where V: Visitor<'de> + { + let (variant, value) = match *self.content { + Content::Map(ref value) => { + let mut iter = value.into_iter(); + let &(ref variant, ref value) = match iter.next() { + Some(v) => v, + None => { + return Err(de::Error::invalid_value(de::Unexpected::Map, + &"map with a single key")); + } + }; + // enums are encoded in json as maps with a single key:value pair + if iter.next().is_some() { + return Err(de::Error::invalid_value(de::Unexpected::Map, + &"map with a single key")); + } + (variant, Some(value)) + } + ref s @ Content::String(_) => (s, None), + ref other => { + return Err(de::Error::invalid_type(other.unexpected(), &"string or map")); + } + }; + + visitor.visit_enum(EnumRefDeserializer { + variant: variant, + value: value, + err: PhantomData, + }) + } + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq + seq_fixed_size bytes byte_buf map unit_struct tuple_struct struct + struct_field tuple ignored_any + } + } + + impl<'a, E> ContentRefDeserializer<'a, E> { + /// private API, don't use + pub fn new(content: &'a Content) -> Self { + ContentRefDeserializer { + content: content, + err: PhantomData, + } + } + } + + struct EnumRefDeserializer<'a, E> + where E: de::Error + { + variant: &'a Content, + value: Option<&'a Content>, + err: PhantomData, + } + + impl<'de, 'a, E> de::EnumVisitor<'de> for EnumRefDeserializer<'a, E> + where E: de::Error + { + type Error = E; + type Variant = VariantRefDeserializer<'a, Self::Error>; + + fn visit_variant_seed(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> + where V: de::DeserializeSeed<'de> + { + let visitor = VariantRefDeserializer { + value: self.value, + err: PhantomData, + }; + seed.deserialize(ContentRefDeserializer::new(self.variant)).map(|v| (v, visitor)) + } + } + + struct VariantRefDeserializer<'a, E> + where E: de::Error + { + value: Option<&'a Content>, + err: PhantomData, + } + + impl<'de, 'a, E> de::VariantVisitor<'de> for VariantRefDeserializer<'a, E> + where E: de::Error + { + type Error = E; + + fn visit_unit(self) -> Result<(), E> { + match self.value { + Some(value) => de::Deserialize::deserialize(ContentRefDeserializer::new(value)), + None => Ok(()), + } + } + + fn visit_newtype_seed(self, seed: T) -> Result + where T: de::DeserializeSeed<'de> + { + match self.value { + Some(value) => seed.deserialize(ContentRefDeserializer::new(value)), + None => Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"newtype variant")), + } + } + + fn visit_tuple(self, _len: usize, visitor: V) -> Result + where V: de::Visitor<'de> + { + match self.value { + Some(&Content::Seq(ref v)) => { + de::Deserializer::deserialize(SeqRefDeserializer::new(v), visitor) + } + Some(other) => Err(de::Error::invalid_type(other.unexpected(), &"tuple variant")), + None => Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"tuple variant")), + } + } + + fn visit_struct(self, + _fields: &'static [&'static str], + visitor: V) + -> Result + where V: de::Visitor<'de> + { + match self.value { + Some(&Content::Map(ref v)) => { + de::Deserializer::deserialize(MapRefDeserializer::new(v), visitor) + } + Some(other) => Err(de::Error::invalid_type(other.unexpected(), &"struct variant")), + _ => Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"struct variant")), + } + } + } + + struct SeqRefDeserializer<'a, E> + where E: de::Error + { + iter: <&'a [Content] as IntoIterator>::IntoIter, + err: PhantomData, + } + + impl<'a, E> SeqRefDeserializer<'a, E> + where E: de::Error + { + fn new(vec: &'a [Content]) -> Self { + SeqRefDeserializer { + iter: vec.into_iter(), + err: PhantomData, + } + } + } + + impl<'de, 'a, E> de::Deserializer<'de> for SeqRefDeserializer<'a, E> + where E: de::Error + { + type Error = E; + + #[inline] + fn deserialize(mut self, visitor: V) -> Result + where V: de::Visitor<'de> + { + let len = self.iter.len(); + if len == 0 { + visitor.visit_unit() + } else { + let ret = try!(visitor.visit_seq(&mut self)); + let remaining = self.iter.len(); + if remaining == 0 { + Ok(ret) + } else { + Err(de::Error::invalid_length(len, &"fewer elements in array")) + } + } + } + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option + seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct + tuple_struct struct struct_field tuple enum ignored_any + } + } + + impl<'de, 'a, E> de::SeqVisitor<'de> for SeqRefDeserializer<'a, E> + where E: de::Error + { + type Error = E; + + fn visit_seed(&mut self, seed: T) -> Result, Self::Error> + where T: de::DeserializeSeed<'de> + { + match self.iter.next() { + Some(value) => seed.deserialize(ContentRefDeserializer::new(value)).map(Some), + None => Ok(None), + } + } + + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } + } + + struct MapRefDeserializer<'a, E> + where E: de::Error + { + iter: <&'a [(Content, Content)] as IntoIterator>::IntoIter, + value: Option<&'a Content>, + err: PhantomData, + } + + impl<'a, E> MapRefDeserializer<'a, E> + where E: de::Error + { + fn new(map: &'a [(Content, Content)]) -> Self { + MapRefDeserializer { + iter: map.into_iter(), + value: None, + err: PhantomData, + } + } + } + + impl<'de, 'a, E> de::MapVisitor<'de> for MapRefDeserializer<'a, E> + where E: de::Error + { + type Error = E; + + fn visit_key_seed(&mut self, seed: T) -> Result, Self::Error> + where T: de::DeserializeSeed<'de> + { + match self.iter.next() { + Some(&(ref key, ref value)) => { + self.value = Some(value); + seed.deserialize(ContentRefDeserializer::new(key)).map(Some) + } + None => Ok(None), + } + } + + fn visit_value_seed(&mut self, seed: T) -> Result + where T: de::DeserializeSeed<'de> + { + match self.value.take() { + Some(value) => seed.deserialize(ContentRefDeserializer::new(value)), + None => Err(de::Error::custom("value is missing")), + } + } + + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } + } + + impl<'de, 'a, E> de::Deserializer<'de> for MapRefDeserializer<'a, E> + where E: de::Error + { + type Error = E; + + #[inline] + fn deserialize(self, visitor: V) -> Result + where V: de::Visitor<'de> + { + visitor.visit_map(self) + } + + forward_to_deserialize! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option + seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct + tuple_struct struct struct_field tuple enum ignored_any + } + } + + impl<'de, E> de::value::ValueDeserializer<'de, E> for ContentDeserializer + where E: de::Error + { + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } + } + + impl<'de, 'a, E> de::value::ValueDeserializer<'de, E> for ContentRefDeserializer<'a, E> + where E: de::Error + { + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } + } + + /// Visitor for deserializing an internally tagged unit variant. + /// + /// Not public API. + pub struct InternallyTaggedUnitVisitor<'a> { + type_name: &'a str, + variant_name: &'a str, + } + + impl<'a> InternallyTaggedUnitVisitor<'a> { + /// Not public API. + pub fn new(type_name: &'a str, variant_name: &'a str) -> Self { + InternallyTaggedUnitVisitor { + type_name: type_name, + variant_name: variant_name, + } + } + } + + impl<'de, 'a> Visitor<'de> for InternallyTaggedUnitVisitor<'a> { + type Value = (); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "unit variant {}::{}", self.type_name, self.variant_name) + } + + fn visit_map(self, _: V) -> Result<(), V::Error> + where V: MapVisitor<'de> + { + Ok(()) + } + } + + /// Visitor for deserializing an untagged unit variant. + /// + /// Not public API. + pub struct UntaggedUnitVisitor<'a> { + type_name: &'a str, + variant_name: &'a str, + } + + impl<'a> UntaggedUnitVisitor<'a> { + /// Not public API. + pub fn new(type_name: &'a str, variant_name: &'a str) -> Self { + UntaggedUnitVisitor { + type_name: type_name, + variant_name: variant_name, + } + } + } + + impl<'de, 'a> Visitor<'de> for UntaggedUnitVisitor<'a> { + type Value = (); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "unit variant {}::{}", self.type_name, self.variant_name) + } + + fn visit_unit(self) -> Result<(), E> + where E: de::Error + { + Ok(()) + } + } +} diff --git a/serde/src/private/macros.rs b/serde/src/private/macros.rs new file mode 100644 index 00000000..f8298a29 --- /dev/null +++ b/serde/src/private/macros.rs @@ -0,0 +1,126 @@ +#[doc(hidden)] +#[macro_export] +macro_rules! __serialize_unimplemented_method { + ($func:ident $(<$t:ident>)* ($($arg:ty),*) -> $ret:ident) => { + fn $func $(<$t: ?Sized + $crate::Serialize>)* (self $(, _: $arg)*) -> $crate::export::Result { + unimplemented!() + } + }; +} + +#[doc(hidden)] +#[macro_export] +macro_rules! __serialize_unimplemented_helper { + (bool) => { + __serialize_unimplemented_method!(serialize_bool(bool) -> Ok); + }; + (i8) => { + __serialize_unimplemented_method!(serialize_i8(i8) -> Ok); + }; + (i16) => { + __serialize_unimplemented_method!(serialize_i16(i16) -> Ok); + }; + (i32) => { + __serialize_unimplemented_method!(serialize_i32(i32) -> Ok); + }; + (i64) => { + __serialize_unimplemented_method!(serialize_i64(i64) -> Ok); + }; + (u8) => { + __serialize_unimplemented_method!(serialize_u8(u8) -> Ok); + }; + (u16) => { + __serialize_unimplemented_method!(serialize_u16(u16) -> Ok); + }; + (u32) => { + __serialize_unimplemented_method!(serialize_u32(u32) -> Ok); + }; + (u64) => { + __serialize_unimplemented_method!(serialize_u64(u64) -> Ok); + }; + (f32) => { + __serialize_unimplemented_method!(serialize_f32(f32) -> Ok); + }; + (f64) => { + __serialize_unimplemented_method!(serialize_f64(f64) -> Ok); + }; + (char) => { + __serialize_unimplemented_method!(serialize_char(char) -> Ok); + }; + (str) => { + __serialize_unimplemented_method!(serialize_str(&str) -> Ok); + }; + (bytes) => { + __serialize_unimplemented_method!(serialize_bytes(&[u8]) -> Ok); + }; + (none) => { + __serialize_unimplemented_method!(serialize_none() -> Ok); + }; + (some) => { + __serialize_unimplemented_method!(serialize_some(&T) -> Ok); + }; + (unit) => { + __serialize_unimplemented_method!(serialize_unit() -> Ok); + }; + (unit_struct) => { + __serialize_unimplemented_method!(serialize_unit_struct(&str) -> Ok); + }; + (unit_variant) => { + __serialize_unimplemented_method!(serialize_unit_variant(&str, usize, &str) -> Ok); + }; + (newtype_struct) => { + __serialize_unimplemented_method!(serialize_newtype_struct(&str, &T) -> Ok); + }; + (newtype_variant) => { + __serialize_unimplemented_method!(serialize_newtype_variant(&str, usize, &str, &T) -> Ok); + }; + (seq) => { + type SerializeSeq = $crate::ser::Impossible; + __serialize_unimplemented_method!(serialize_seq(Option) -> SerializeSeq); + }; + (seq_fixed_size) => { + __serialize_unimplemented_method!(serialize_seq_fixed_size(usize) -> SerializeSeq); + }; + (tuple) => { + type SerializeTuple = $crate::ser::Impossible; + __serialize_unimplemented_method!(serialize_tuple(usize) -> SerializeTuple); + }; + (tuple_struct) => { + type SerializeTupleStruct = $crate::ser::Impossible; + __serialize_unimplemented_method!(serialize_tuple_struct(&str, usize) -> SerializeTupleStruct); + }; + (tuple_variant) => { + type SerializeTupleVariant = $crate::ser::Impossible; + __serialize_unimplemented_method!(serialize_tuple_variant(&str, usize, &str, usize) -> SerializeTupleVariant); + }; + (map) => { + type SerializeMap = $crate::ser::Impossible; + __serialize_unimplemented_method!(serialize_map(Option) -> SerializeMap); + }; + (struct) => { + type SerializeStruct = $crate::ser::Impossible; + __serialize_unimplemented_method!(serialize_struct(&str, usize) -> SerializeStruct); + }; + (struct_variant) => { + type SerializeStructVariant = $crate::ser::Impossible; + __serialize_unimplemented_method!(serialize_struct_variant(&str, usize, &str, usize) -> SerializeStructVariant); + }; +} + +/// Used only by Serde doc tests. Not public API. +#[doc(hidden)] +#[macro_export] +macro_rules! __serialize_unimplemented { + ($($func:ident)*) => { + $( + __serialize_unimplemented_helper!($func); + )* + }; +} + +/// Used only by Serde doc tests. Not public API. +#[doc(hidden)] +#[macro_export] +macro_rules! __serde_ignore_tokens { + ($($tt:tt)+) => {} +} diff --git a/serde/src/private/mod.rs b/serde/src/private/mod.rs new file mode 100644 index 00000000..0d46e9cc --- /dev/null +++ b/serde/src/private/mod.rs @@ -0,0 +1,4 @@ +pub mod ser; +pub mod de; + +mod macros; diff --git a/serde/src/private/ser.rs b/serde/src/private/ser.rs new file mode 100644 index 00000000..c8d09d0b --- /dev/null +++ b/serde/src/private/ser.rs @@ -0,0 +1,944 @@ +use core::fmt::{self, Display}; + +use ser::{self, Serialize, Serializer, SerializeMap, SerializeStruct, Impossible}; + +#[cfg(any(feature = "std", feature = "collections"))] +use self::content::{SerializeTupleVariantAsMapValue, SerializeStructVariantAsMapValue}; + +#[cfg(feature = "std")] +use std::error; + +/// Not public API. +pub fn serialize_tagged_newtype(serializer: S, + type_ident: &'static str, + variant_ident: &'static str, + tag: &'static str, + variant_name: &'static str, + value: &T) + -> Result + where S: Serializer, + T: Serialize +{ + value.serialize(TaggedSerializer { + type_ident: type_ident, + variant_ident: variant_ident, + tag: tag, + variant_name: variant_name, + delegate: serializer, + }) +} + +struct TaggedSerializer { + type_ident: &'static str, + variant_ident: &'static str, + tag: &'static str, + variant_name: &'static str, + delegate: S, +} + +enum Unsupported { + Boolean, + Integer, + Float, + Char, + String, + ByteArray, + Optional, + Unit, + UnitStruct, + Sequence, + Tuple, + TupleStruct, + #[cfg(not(any(feature = "std", feature = "collections")))] + Enum, +} + +impl Display for Unsupported { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match *self { + Unsupported::Boolean => formatter.write_str("a boolean"), + Unsupported::Integer => formatter.write_str("an integer"), + Unsupported::Float => formatter.write_str("a float"), + Unsupported::Char => formatter.write_str("a char"), + Unsupported::String => formatter.write_str("a string"), + Unsupported::ByteArray => formatter.write_str("a byte array"), + Unsupported::Optional => formatter.write_str("an optional"), + Unsupported::Unit => formatter.write_str("unit"), + Unsupported::UnitStruct => formatter.write_str("a unit struct"), + Unsupported::Sequence => formatter.write_str("a sequence"), + Unsupported::Tuple => formatter.write_str("a tuple"), + Unsupported::TupleStruct => formatter.write_str("a tuple struct"), + #[cfg(not(any(feature = "std", feature = "collections")))] + Unsupported::Enum => formatter.write_str("an enum"), + } + } +} + +impl TaggedSerializer + where S: Serializer +{ + fn bad_type(self, what: Unsupported) -> S::Error { + ser::Error::custom(format_args!( + "cannot serialize tagged newtype variant {}::{} containing {}", + self.type_ident, + self.variant_ident, + what)) + } +} + +impl Serializer for TaggedSerializer + where S: Serializer +{ + type Ok = S::Ok; + type Error = S::Error; + + type SerializeSeq = Impossible; + type SerializeTuple = Impossible; + type SerializeTupleStruct = Impossible; + type SerializeMap = S::SerializeMap; + type SerializeStruct = S::SerializeStruct; + + #[cfg(not(any(feature = "std", feature = "collections")))] + type SerializeTupleVariant = Impossible; + #[cfg(any(feature = "std", feature = "collections"))] + type SerializeTupleVariant = SerializeTupleVariantAsMapValue; + + #[cfg(not(any(feature = "std", feature = "collections")))] + type SerializeStructVariant = Impossible; + #[cfg(any(feature = "std", feature = "collections"))] + type SerializeStructVariant = SerializeStructVariantAsMapValue; + + fn serialize_bool(self, _: bool) -> Result { + Err(self.bad_type(Unsupported::Boolean)) + } + + fn serialize_i8(self, _: i8) -> Result { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_i16(self, _: i16) -> Result { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_i32(self, _: i32) -> Result { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_i64(self, _: i64) -> Result { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_u8(self, _: u8) -> Result { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_u16(self, _: u16) -> Result { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_u32(self, _: u32) -> Result { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_u64(self, _: u64) -> Result { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_f32(self, _: f32) -> Result { + Err(self.bad_type(Unsupported::Float)) + } + + fn serialize_f64(self, _: f64) -> Result { + Err(self.bad_type(Unsupported::Float)) + } + + fn serialize_char(self, _: char) -> Result { + Err(self.bad_type(Unsupported::Char)) + } + + fn serialize_str(self, _: &str) -> Result { + Err(self.bad_type(Unsupported::String)) + } + + fn serialize_bytes(self, _: &[u8]) -> Result { + Err(self.bad_type(Unsupported::ByteArray)) + } + + fn serialize_none(self) -> Result { + Err(self.bad_type(Unsupported::Optional)) + } + + fn serialize_some(self, _: &T) -> Result + where T: Serialize + { + Err(self.bad_type(Unsupported::Optional)) + } + + fn serialize_unit(self) -> Result { + Err(self.bad_type(Unsupported::Unit)) + } + + fn serialize_unit_struct(self, _: &'static str) -> Result { + Err(self.bad_type(Unsupported::UnitStruct)) + } + + fn serialize_unit_variant(self, + _: &'static str, + _: usize, + inner_variant: &'static str) + -> Result { + let mut map = try!(self.delegate.serialize_map(Some(2))); + try!(map.serialize_entry(self.tag, self.variant_name)); + try!(map.serialize_entry(inner_variant, &())); + map.end() + } + + fn serialize_newtype_struct(self, + _: &'static str, + value: &T) + -> Result + where T: Serialize + { + value.serialize(self) + } + + fn serialize_newtype_variant(self, + _: &'static str, + _: usize, + inner_variant: &'static str, + inner_value: &T) + -> Result + where T: Serialize + { + let mut map = try!(self.delegate.serialize_map(Some(2))); + try!(map.serialize_entry(self.tag, self.variant_name)); + try!(map.serialize_entry(inner_variant, inner_value)); + map.end() + } + + fn serialize_seq(self, _: Option) -> Result { + Err(self.bad_type(Unsupported::Sequence)) + } + + fn serialize_seq_fixed_size(self, _: usize) -> Result { + Err(self.bad_type(Unsupported::Sequence)) + } + + fn serialize_tuple(self, _: usize) -> Result { + Err(self.bad_type(Unsupported::Tuple)) + } + + fn serialize_tuple_struct(self, + _: &'static str, + _: usize) + -> Result { + Err(self.bad_type(Unsupported::TupleStruct)) + } + + #[cfg(not(any(feature = "std", feature = "collections")))] + fn serialize_tuple_variant(self, + _: &'static str, + _: usize, + _: &'static str, + _: usize) + -> Result { + // Lack of push-based serialization means we need to buffer the content + // of the tuple variant, so it requires std. + Err(self.bad_type(Unsupported::Enum)) + } + + #[cfg(any(feature = "std", feature = "collections"))] + fn serialize_tuple_variant(self, + _: &'static str, + _: usize, + inner_variant: &'static str, + len: usize) + -> Result { + let mut map = try!(self.delegate.serialize_map(Some(2))); + try!(map.serialize_entry(self.tag, self.variant_name)); + try!(map.serialize_key(inner_variant)); + Ok(SerializeTupleVariantAsMapValue::new(map, inner_variant, len)) + } + + fn serialize_map(self, len: Option) -> Result { + let mut map = try!(self.delegate.serialize_map(len.map(|len| len + 1))); + try!(map.serialize_entry(self.tag, self.variant_name)); + Ok(map) + } + + fn serialize_struct(self, + name: &'static str, + len: usize) + -> Result { + let mut state = try!(self.delegate.serialize_struct(name, len + 1)); + try!(state.serialize_field(self.tag, self.variant_name)); + Ok(state) + } + + #[cfg(not(any(feature = "std", feature = "collections")))] + fn serialize_struct_variant(self, + _: &'static str, + _: usize, + _: &'static str, + _: usize) + -> Result { + // Lack of push-based serialization means we need to buffer the content + // of the struct variant, so it requires std. + Err(self.bad_type(Unsupported::Enum)) + } + + #[cfg(any(feature = "std", feature = "collections"))] + fn serialize_struct_variant(self, + _: &'static str, + _: usize, + inner_variant: &'static str, + len: usize) + -> Result { + let mut map = try!(self.delegate.serialize_map(Some(2))); + try!(map.serialize_entry(self.tag, self.variant_name)); + try!(map.serialize_key(inner_variant)); + Ok(SerializeStructVariantAsMapValue::new(map, inner_variant, len)) + } + + #[cfg(not(any(feature = "std", feature = "collections")))] + fn collect_str(self, _: &T) -> Result + where T: Display + { + Err(self.bad_type(Unsupported::String)) + } +} + +/// Used only by Serde doc tests. Not public API. +#[doc(hidden)] +#[derive(Debug)] +pub struct Error; + +impl ser::Error for Error { + fn custom(_: T) -> Self { + unimplemented!() + } +} + +#[cfg(feature = "std")] +impl error::Error for Error { + fn description(&self) -> &str { + unimplemented!() + } +} + +impl Display for Error { + fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { + unimplemented!() + } +} + +#[cfg(any(feature = "std", feature = "collections"))] +mod content { + use core::marker::PhantomData; + + #[cfg(all(not(feature = "std"), feature = "collections"))] + use collections::{String, Vec}; + + #[cfg(all(feature = "alloc", not(feature = "std")))] + use alloc::boxed::Box; + + #[cfg(feature = "collections")] + use collections::borrow::ToOwned; + + use ser::{self, Serialize, Serializer}; + + pub struct SerializeTupleVariantAsMapValue { + map: M, + name: &'static str, + fields: Vec, + } + + impl SerializeTupleVariantAsMapValue { + pub fn new(map: M, name: &'static str, len: usize) -> Self { + SerializeTupleVariantAsMapValue { + map: map, + name: name, + fields: Vec::with_capacity(len), + } + } + } + + impl ser::SerializeTupleVariant for SerializeTupleVariantAsMapValue + where M: ser::SerializeMap + { + type Ok = M::Ok; + type Error = M::Error; + + fn serialize_field(&mut self, value: &T) -> Result<(), M::Error> { + let value = try!(value.serialize(ContentSerializer::::new())); + self.fields.push(value); + Ok(()) + } + + fn end(mut self) -> Result { + try!(self.map.serialize_value(&Content::TupleStruct(self.name, self.fields))); + self.map.end() + } + } + + pub struct SerializeStructVariantAsMapValue { + map: M, + name: &'static str, + fields: Vec<(&'static str, Content)>, + } + + impl SerializeStructVariantAsMapValue { + pub fn new(map: M, name: &'static str, len: usize) -> Self { + SerializeStructVariantAsMapValue { + map: map, + name: name, + fields: Vec::with_capacity(len), + } + } + } + + impl ser::SerializeStructVariant for SerializeStructVariantAsMapValue + where M: ser::SerializeMap + { + type Ok = M::Ok; + type Error = M::Error; + + fn serialize_field(&mut self, + key: &'static str, + value: &T) + -> Result<(), M::Error> { + let value = try!(value.serialize(ContentSerializer::::new())); + self.fields.push((key, value)); + Ok(()) + } + + fn end(mut self) -> Result { + try!(self.map.serialize_value(&Content::Struct(self.name, self.fields))); + self.map.end() + } + } + + #[derive(Debug)] + enum Content { + Bool(bool), + + U8(u8), + U16(u16), + U32(u32), + U64(u64), + + I8(i8), + I16(i16), + I32(i32), + I64(i64), + + F32(f32), + F64(f64), + + Char(char), + String(String), + Bytes(Vec), + + None, + Some(Box), + + Unit, + UnitStruct(&'static str), + UnitVariant(&'static str, usize, &'static str), + NewtypeStruct(&'static str, Box), + NewtypeVariant(&'static str, usize, &'static str, Box), + + Seq(Vec), + SeqFixedSize(Vec), + Tuple(Vec), + TupleStruct(&'static str, Vec), + TupleVariant(&'static str, usize, &'static str, Vec), + Map(Vec<(Content, Content)>), + Struct(&'static str, Vec<(&'static str, Content)>), + StructVariant(&'static str, usize, &'static str, Vec<(&'static str, Content)>), + } + + impl Serialize for Content { + fn serialize(&self, serializer: S) -> Result + where S: Serializer + { + match *self { + Content::Bool(b) => serializer.serialize_bool(b), + Content::U8(u) => serializer.serialize_u8(u), + Content::U16(u) => serializer.serialize_u16(u), + Content::U32(u) => serializer.serialize_u32(u), + Content::U64(u) => serializer.serialize_u64(u), + Content::I8(i) => serializer.serialize_i8(i), + Content::I16(i) => serializer.serialize_i16(i), + Content::I32(i) => serializer.serialize_i32(i), + Content::I64(i) => serializer.serialize_i64(i), + Content::F32(f) => serializer.serialize_f32(f), + Content::F64(f) => serializer.serialize_f64(f), + Content::Char(c) => serializer.serialize_char(c), + Content::String(ref s) => serializer.serialize_str(s), + Content::Bytes(ref b) => serializer.serialize_bytes(b), + Content::None => serializer.serialize_none(), + Content::Some(ref c) => serializer.serialize_some(&**c), + Content::Unit => serializer.serialize_unit(), + Content::UnitStruct(n) => serializer.serialize_unit_struct(n), + Content::UnitVariant(n, i, v) => serializer.serialize_unit_variant(n, i, v), + Content::NewtypeStruct(n, ref c) => serializer.serialize_newtype_struct(n, &**c), + Content::NewtypeVariant(n, i, v, ref c) => { + serializer.serialize_newtype_variant(n, i, v, &**c) + } + Content::Seq(ref elements) => elements.serialize(serializer), + Content::SeqFixedSize(ref elements) => { + use ser::SerializeSeq; + let mut seq = try!(serializer.serialize_seq_fixed_size(elements.len())); + for e in elements { + try!(seq.serialize_element(e)); + } + seq.end() + } + Content::Tuple(ref elements) => { + use ser::SerializeTuple; + let mut tuple = try!(serializer.serialize_tuple(elements.len())); + for e in elements { + try!(tuple.serialize_element(e)); + } + tuple.end() + } + Content::TupleStruct(n, ref fields) => { + use ser::SerializeTupleStruct; + let mut ts = try!(serializer.serialize_tuple_struct(n, fields.len())); + for f in fields { + try!(ts.serialize_field(f)); + } + ts.end() + } + Content::TupleVariant(n, i, v, ref fields) => { + use ser::SerializeTupleVariant; + let mut tv = try!(serializer.serialize_tuple_variant(n, i, v, fields.len())); + for f in fields { + try!(tv.serialize_field(f)); + } + tv.end() + } + Content::Map(ref entries) => { + use ser::SerializeMap; + let mut map = try!(serializer.serialize_map(Some(entries.len()))); + for &(ref k, ref v) in entries { + try!(map.serialize_entry(k, v)); + } + map.end() + } + Content::Struct(n, ref fields) => { + use ser::SerializeStruct; + let mut s = try!(serializer.serialize_struct(n, fields.len())); + for &(k, ref v) in fields { + try!(s.serialize_field(k, v)); + } + s.end() + } + Content::StructVariant(n, i, v, ref fields) => { + use ser::SerializeStructVariant; + let mut sv = try!(serializer.serialize_struct_variant(n, i, v, fields.len())); + for &(k, ref v) in fields { + try!(sv.serialize_field(k, v)); + } + sv.end() + } + } + } + } + + struct ContentSerializer { + error: PhantomData, + } + + impl ContentSerializer { + fn new() -> Self { + ContentSerializer { error: PhantomData } + } + } + + impl Serializer for ContentSerializer + where E: ser::Error + { + type Ok = Content; + type Error = E; + + type SerializeSeq = SerializeSeq; + type SerializeTuple = SerializeTuple; + type SerializeTupleStruct = SerializeTupleStruct; + type SerializeTupleVariant = SerializeTupleVariant; + type SerializeMap = SerializeMap; + type SerializeStruct = SerializeStruct; + type SerializeStructVariant = SerializeStructVariant; + + fn serialize_bool(self, v: bool) -> Result { + Ok(Content::Bool(v)) + } + + fn serialize_i8(self, v: i8) -> Result { + Ok(Content::I8(v)) + } + + fn serialize_i16(self, v: i16) -> Result { + Ok(Content::I16(v)) + } + + fn serialize_i32(self, v: i32) -> Result { + Ok(Content::I32(v)) + } + + fn serialize_i64(self, v: i64) -> Result { + Ok(Content::I64(v)) + } + + fn serialize_u8(self, v: u8) -> Result { + Ok(Content::U8(v)) + } + + fn serialize_u16(self, v: u16) -> Result { + Ok(Content::U16(v)) + } + + fn serialize_u32(self, v: u32) -> Result { + Ok(Content::U32(v)) + } + + fn serialize_u64(self, v: u64) -> Result { + Ok(Content::U64(v)) + } + + fn serialize_f32(self, v: f32) -> Result { + Ok(Content::F32(v)) + } + + fn serialize_f64(self, v: f64) -> Result { + Ok(Content::F64(v)) + } + + fn serialize_char(self, v: char) -> Result { + Ok(Content::Char(v)) + } + + fn serialize_str(self, value: &str) -> Result { + Ok(Content::String(value.to_owned())) + } + + fn serialize_bytes(self, value: &[u8]) -> Result { + Ok(Content::Bytes(value.to_owned())) + } + + fn serialize_none(self) -> Result { + Ok(Content::None) + } + + fn serialize_some(self, value: &T) -> Result { + Ok(Content::Some(Box::new(try!(value.serialize(self))))) + } + + fn serialize_unit(self) -> Result { + Ok(Content::Unit) + } + + fn serialize_unit_struct(self, name: &'static str) -> Result { + Ok(Content::UnitStruct(name)) + } + + fn serialize_unit_variant(self, + name: &'static str, + variant_index: usize, + variant: &'static str) + -> Result { + Ok(Content::UnitVariant(name, variant_index, variant)) + } + + fn serialize_newtype_struct(self, + name: &'static str, + value: &T) + -> Result { + Ok(Content::NewtypeStruct(name, Box::new(try!(value.serialize(self))))) + } + + fn serialize_newtype_variant(self, + name: &'static str, + variant_index: usize, + variant: &'static str, + value: &T) + -> Result { + Ok(Content::NewtypeVariant(name, + variant_index, + variant, + Box::new(try!(value.serialize(self))))) + } + + fn serialize_seq(self, len: Option) -> Result { + Ok(SerializeSeq { + fixed_size: false, + elements: Vec::with_capacity(len.unwrap_or(0)), + error: PhantomData, + }) + } + + fn serialize_seq_fixed_size(self, size: usize) -> Result { + Ok(SerializeSeq { + fixed_size: true, + elements: Vec::with_capacity(size), + error: PhantomData, + }) + } + + fn serialize_tuple(self, len: usize) -> Result { + Ok(SerializeTuple { + elements: Vec::with_capacity(len), + error: PhantomData, + }) + } + + fn serialize_tuple_struct(self, + name: &'static str, + len: usize) + -> Result { + Ok(SerializeTupleStruct { + name: name, + fields: Vec::with_capacity(len), + error: PhantomData, + }) + } + + fn serialize_tuple_variant(self, + name: &'static str, + variant_index: usize, + variant: &'static str, + len: usize) + -> Result { + Ok(SerializeTupleVariant { + name: name, + variant_index: variant_index, + variant: variant, + fields: Vec::with_capacity(len), + error: PhantomData, + }) + } + + fn serialize_map(self, len: Option) -> Result { + Ok(SerializeMap { + entries: Vec::with_capacity(len.unwrap_or(0)), + key: None, + error: PhantomData, + }) + } + + fn serialize_struct(self, name: &'static str, len: usize) -> Result { + Ok(SerializeStruct { + name: name, + fields: Vec::with_capacity(len), + error: PhantomData, + }) + } + + fn serialize_struct_variant(self, + name: &'static str, + variant_index: usize, + variant: &'static str, + len: usize) + -> Result { + Ok(SerializeStructVariant { + name: name, + variant_index: variant_index, + variant: variant, + fields: Vec::with_capacity(len), + error: PhantomData, + }) + } + } + + struct SerializeSeq { + fixed_size: bool, + elements: Vec, + error: PhantomData, + } + + impl ser::SerializeSeq for SerializeSeq + where E: ser::Error + { + type Ok = Content; + type Error = E; + + fn serialize_element(&mut self, value: &T) -> Result<(), E> { + let value = try!(value.serialize(ContentSerializer::::new())); + self.elements.push(value); + Ok(()) + } + + fn end(self) -> Result { + Ok(if self.fixed_size { + Content::SeqFixedSize(self.elements) + } else { + Content::Seq(self.elements) + }) + } + } + + struct SerializeTuple { + elements: Vec, + error: PhantomData, + } + + impl ser::SerializeTuple for SerializeTuple + where E: ser::Error + { + type Ok = Content; + type Error = E; + + fn serialize_element(&mut self, value: &T) -> Result<(), E> { + let value = try!(value.serialize(ContentSerializer::::new())); + self.elements.push(value); + Ok(()) + } + + fn end(self) -> Result { + Ok(Content::Tuple(self.elements)) + } + } + + struct SerializeTupleStruct { + name: &'static str, + fields: Vec, + error: PhantomData, + } + + impl ser::SerializeTupleStruct for SerializeTupleStruct + where E: ser::Error + { + type Ok = Content; + type Error = E; + + fn serialize_field(&mut self, value: &T) -> Result<(), E> { + let value = try!(value.serialize(ContentSerializer::::new())); + self.fields.push(value); + Ok(()) + } + + fn end(self) -> Result { + Ok(Content::TupleStruct(self.name, self.fields)) + } + } + + struct SerializeTupleVariant { + name: &'static str, + variant_index: usize, + variant: &'static str, + fields: Vec, + error: PhantomData, + } + + impl ser::SerializeTupleVariant for SerializeTupleVariant + where E: ser::Error + { + type Ok = Content; + type Error = E; + + fn serialize_field(&mut self, value: &T) -> Result<(), E> { + let value = try!(value.serialize(ContentSerializer::::new())); + self.fields.push(value); + Ok(()) + } + + fn end(self) -> Result { + Ok(Content::TupleVariant(self.name, self.variant_index, self.variant, self.fields)) + } + } + + struct SerializeMap { + entries: Vec<(Content, Content)>, + key: Option, + error: PhantomData, + } + + impl ser::SerializeMap for SerializeMap + where E: ser::Error + { + type Ok = Content; + type Error = E; + + fn serialize_key(&mut self, key: &T) -> Result<(), E> { + let key = try!(key.serialize(ContentSerializer::::new())); + self.key = Some(key); + Ok(()) + } + + fn serialize_value(&mut self, value: &T) -> Result<(), E> { + let key = self.key.take().expect("serialize_value called before serialize_key"); + let value = try!(value.serialize(ContentSerializer::::new())); + self.entries.push((key, value)); + Ok(()) + } + + fn end(self) -> Result { + Ok(Content::Map(self.entries)) + } + + fn serialize_entry(&mut self, + key: &K, + value: &V) + -> Result<(), E> { + let key = try!(key.serialize(ContentSerializer::::new())); + let value = try!(value.serialize(ContentSerializer::::new())); + self.entries.push((key, value)); + Ok(()) + } + } + + struct SerializeStruct { + name: &'static str, + fields: Vec<(&'static str, Content)>, + error: PhantomData, + } + + impl ser::SerializeStruct for SerializeStruct + where E: ser::Error + { + type Ok = Content; + type Error = E; + + fn serialize_field(&mut self, + key: &'static str, + value: &T) + -> Result<(), E> { + let value = try!(value.serialize(ContentSerializer::::new())); + self.fields.push((key, value)); + Ok(()) + } + + fn end(self) -> Result { + Ok(Content::Struct(self.name, self.fields)) + } + } + + struct SerializeStructVariant { + name: &'static str, + variant_index: usize, + variant: &'static str, + fields: Vec<(&'static str, Content)>, + error: PhantomData, + } + + impl ser::SerializeStructVariant for SerializeStructVariant + where E: ser::Error + { + type Ok = Content; + type Error = E; + + fn serialize_field(&mut self, + key: &'static str, + value: &T) + -> Result<(), E> { + let value = try!(value.serialize(ContentSerializer::::new())); + self.fields.push((key, value)); + Ok(()) + } + + fn end(self) -> Result { + Ok(Content::StructVariant(self.name, self.variant_index, self.variant, self.fields)) + } + } +} diff --git a/serde/src/ser/content.rs b/serde/src/ser/content.rs deleted file mode 100644 index 75482b02..00000000 --- a/serde/src/ser/content.rs +++ /dev/null @@ -1,607 +0,0 @@ -use core::marker::PhantomData; - -#[cfg(all(not(feature = "std"), feature = "collections"))] -use collections::{String, Vec}; - -#[cfg(all(feature = "alloc", not(feature = "std")))] -use alloc::boxed::Box; - -#[cfg(feature = "collections")] -use collections::borrow::ToOwned; - -use ser::{self, Serialize, Serializer}; - -pub struct SerializeTupleVariantAsMapValue { - map: M, - name: &'static str, - fields: Vec, -} - -impl SerializeTupleVariantAsMapValue { - pub fn new(map: M, name: &'static str, len: usize) -> Self { - SerializeTupleVariantAsMapValue { - map: map, - name: name, - fields: Vec::with_capacity(len), - } - } -} - -impl ser::SerializeTupleVariant for SerializeTupleVariantAsMapValue - where M: ser::SerializeMap -{ - type Ok = M::Ok; - type Error = M::Error; - - fn serialize_field(&mut self, value: &T) -> Result<(), M::Error> { - let value = try!(value.serialize(ContentSerializer::::new())); - self.fields.push(value); - Ok(()) - } - - fn end(mut self) -> Result { - try!(self.map.serialize_value(&Content::TupleStruct(self.name, self.fields))); - self.map.end() - } -} - -pub struct SerializeStructVariantAsMapValue { - map: M, - name: &'static str, - fields: Vec<(&'static str, Content)>, -} - -impl SerializeStructVariantAsMapValue { - pub fn new(map: M, name: &'static str, len: usize) -> Self { - SerializeStructVariantAsMapValue { - map: map, - name: name, - fields: Vec::with_capacity(len), - } - } -} - -impl ser::SerializeStructVariant for SerializeStructVariantAsMapValue - where M: ser::SerializeMap -{ - type Ok = M::Ok; - type Error = M::Error; - - fn serialize_field(&mut self, - key: &'static str, - value: &T) - -> Result<(), M::Error> { - let value = try!(value.serialize(ContentSerializer::::new())); - self.fields.push((key, value)); - Ok(()) - } - - fn end(mut self) -> Result { - try!(self.map.serialize_value(&Content::Struct(self.name, self.fields))); - self.map.end() - } -} - -#[derive(Debug)] -enum Content { - Bool(bool), - - U8(u8), - U16(u16), - U32(u32), - U64(u64), - - I8(i8), - I16(i16), - I32(i32), - I64(i64), - - F32(f32), - F64(f64), - - Char(char), - String(String), - Bytes(Vec), - - None, - Some(Box), - - Unit, - UnitStruct(&'static str), - UnitVariant(&'static str, usize, &'static str), - NewtypeStruct(&'static str, Box), - NewtypeVariant(&'static str, usize, &'static str, Box), - - Seq(Vec), - SeqFixedSize(Vec), - Tuple(Vec), - TupleStruct(&'static str, Vec), - TupleVariant(&'static str, usize, &'static str, Vec), - Map(Vec<(Content, Content)>), - Struct(&'static str, Vec<(&'static str, Content)>), - StructVariant(&'static str, usize, &'static str, Vec<(&'static str, Content)>), -} - -impl Serialize for Content { - fn serialize(&self, serializer: S) -> Result - where S: Serializer - { - match *self { - Content::Bool(b) => serializer.serialize_bool(b), - Content::U8(u) => serializer.serialize_u8(u), - Content::U16(u) => serializer.serialize_u16(u), - Content::U32(u) => serializer.serialize_u32(u), - Content::U64(u) => serializer.serialize_u64(u), - Content::I8(i) => serializer.serialize_i8(i), - Content::I16(i) => serializer.serialize_i16(i), - Content::I32(i) => serializer.serialize_i32(i), - Content::I64(i) => serializer.serialize_i64(i), - Content::F32(f) => serializer.serialize_f32(f), - Content::F64(f) => serializer.serialize_f64(f), - Content::Char(c) => serializer.serialize_char(c), - Content::String(ref s) => serializer.serialize_str(s), - Content::Bytes(ref b) => serializer.serialize_bytes(b), - Content::None => serializer.serialize_none(), - Content::Some(ref c) => serializer.serialize_some(&**c), - Content::Unit => serializer.serialize_unit(), - Content::UnitStruct(n) => serializer.serialize_unit_struct(n), - Content::UnitVariant(n, i, v) => serializer.serialize_unit_variant(n, i, v), - Content::NewtypeStruct(n, ref c) => serializer.serialize_newtype_struct(n, &**c), - Content::NewtypeVariant(n, i, v, ref c) => { - serializer.serialize_newtype_variant(n, i, v, &**c) - } - Content::Seq(ref elements) => elements.serialize(serializer), - Content::SeqFixedSize(ref elements) => { - use ser::SerializeSeq; - let mut seq = try!(serializer.serialize_seq_fixed_size(elements.len())); - for e in elements { - try!(seq.serialize_element(e)); - } - seq.end() - } - Content::Tuple(ref elements) => { - use ser::SerializeTuple; - let mut tuple = try!(serializer.serialize_tuple(elements.len())); - for e in elements { - try!(tuple.serialize_element(e)); - } - tuple.end() - } - Content::TupleStruct(n, ref fields) => { - use ser::SerializeTupleStruct; - let mut ts = try!(serializer.serialize_tuple_struct(n, fields.len())); - for f in fields { - try!(ts.serialize_field(f)); - } - ts.end() - } - Content::TupleVariant(n, i, v, ref fields) => { - use ser::SerializeTupleVariant; - let mut tv = try!(serializer.serialize_tuple_variant(n, i, v, fields.len())); - for f in fields { - try!(tv.serialize_field(f)); - } - tv.end() - } - Content::Map(ref entries) => { - use ser::SerializeMap; - let mut map = try!(serializer.serialize_map(Some(entries.len()))); - for &(ref k, ref v) in entries { - try!(map.serialize_entry(k, v)); - } - map.end() - } - Content::Struct(n, ref fields) => { - use ser::SerializeStruct; - let mut s = try!(serializer.serialize_struct(n, fields.len())); - for &(k, ref v) in fields { - try!(s.serialize_field(k, v)); - } - s.end() - } - Content::StructVariant(n, i, v, ref fields) => { - use ser::SerializeStructVariant; - let mut sv = try!(serializer.serialize_struct_variant(n, i, v, fields.len())); - for &(k, ref v) in fields { - try!(sv.serialize_field(k, v)); - } - sv.end() - } - } - } -} - -struct ContentSerializer { - error: PhantomData, -} - -impl ContentSerializer { - fn new() -> Self { - ContentSerializer { error: PhantomData } - } -} - -impl Serializer for ContentSerializer - where E: ser::Error -{ - type Ok = Content; - type Error = E; - - type SerializeSeq = SerializeSeq; - type SerializeTuple = SerializeTuple; - type SerializeTupleStruct = SerializeTupleStruct; - type SerializeTupleVariant = SerializeTupleVariant; - type SerializeMap = SerializeMap; - type SerializeStruct = SerializeStruct; - type SerializeStructVariant = SerializeStructVariant; - - fn serialize_bool(self, v: bool) -> Result { - Ok(Content::Bool(v)) - } - - fn serialize_i8(self, v: i8) -> Result { - Ok(Content::I8(v)) - } - - fn serialize_i16(self, v: i16) -> Result { - Ok(Content::I16(v)) - } - - fn serialize_i32(self, v: i32) -> Result { - Ok(Content::I32(v)) - } - - fn serialize_i64(self, v: i64) -> Result { - Ok(Content::I64(v)) - } - - fn serialize_u8(self, v: u8) -> Result { - Ok(Content::U8(v)) - } - - fn serialize_u16(self, v: u16) -> Result { - Ok(Content::U16(v)) - } - - fn serialize_u32(self, v: u32) -> Result { - Ok(Content::U32(v)) - } - - fn serialize_u64(self, v: u64) -> Result { - Ok(Content::U64(v)) - } - - fn serialize_f32(self, v: f32) -> Result { - Ok(Content::F32(v)) - } - - fn serialize_f64(self, v: f64) -> Result { - Ok(Content::F64(v)) - } - - fn serialize_char(self, v: char) -> Result { - Ok(Content::Char(v)) - } - - fn serialize_str(self, value: &str) -> Result { - Ok(Content::String(value.to_owned())) - } - - fn serialize_bytes(self, value: &[u8]) -> Result { - Ok(Content::Bytes(value.to_owned())) - } - - fn serialize_none(self) -> Result { - Ok(Content::None) - } - - fn serialize_some(self, value: &T) -> Result { - Ok(Content::Some(Box::new(try!(value.serialize(self))))) - } - - fn serialize_unit(self) -> Result { - Ok(Content::Unit) - } - - fn serialize_unit_struct(self, name: &'static str) -> Result { - Ok(Content::UnitStruct(name)) - } - - fn serialize_unit_variant(self, - name: &'static str, - variant_index: usize, - variant: &'static str) - -> Result { - Ok(Content::UnitVariant(name, variant_index, variant)) - } - - fn serialize_newtype_struct(self, - name: &'static str, - value: &T) - -> Result { - Ok(Content::NewtypeStruct(name, Box::new(try!(value.serialize(self))))) - } - - fn serialize_newtype_variant(self, - name: &'static str, - variant_index: usize, - variant: &'static str, - value: &T) - -> Result { - Ok(Content::NewtypeVariant(name, - variant_index, - variant, - Box::new(try!(value.serialize(self))))) - } - - fn serialize_seq(self, len: Option) -> Result { - Ok(SerializeSeq { - fixed_size: false, - elements: Vec::with_capacity(len.unwrap_or(0)), - error: PhantomData, - }) - } - - fn serialize_seq_fixed_size(self, size: usize) -> Result { - Ok(SerializeSeq { - fixed_size: true, - elements: Vec::with_capacity(size), - error: PhantomData, - }) - } - - fn serialize_tuple(self, len: usize) -> Result { - Ok(SerializeTuple { - elements: Vec::with_capacity(len), - error: PhantomData, - }) - } - - fn serialize_tuple_struct(self, - name: &'static str, - len: usize) - -> Result { - Ok(SerializeTupleStruct { - name: name, - fields: Vec::with_capacity(len), - error: PhantomData, - }) - } - - fn serialize_tuple_variant(self, - name: &'static str, - variant_index: usize, - variant: &'static str, - len: usize) - -> Result { - Ok(SerializeTupleVariant { - name: name, - variant_index: variant_index, - variant: variant, - fields: Vec::with_capacity(len), - error: PhantomData, - }) - } - - fn serialize_map(self, len: Option) -> Result { - Ok(SerializeMap { - entries: Vec::with_capacity(len.unwrap_or(0)), - key: None, - error: PhantomData, - }) - } - - fn serialize_struct(self, name: &'static str, len: usize) -> Result { - Ok(SerializeStruct { - name: name, - fields: Vec::with_capacity(len), - error: PhantomData, - }) - } - - fn serialize_struct_variant(self, - name: &'static str, - variant_index: usize, - variant: &'static str, - len: usize) - -> Result { - Ok(SerializeStructVariant { - name: name, - variant_index: variant_index, - variant: variant, - fields: Vec::with_capacity(len), - error: PhantomData, - }) - } -} - -struct SerializeSeq { - fixed_size: bool, - elements: Vec, - error: PhantomData, -} - -impl ser::SerializeSeq for SerializeSeq - where E: ser::Error -{ - type Ok = Content; - type Error = E; - - fn serialize_element(&mut self, value: &T) -> Result<(), E> { - let value = try!(value.serialize(ContentSerializer::::new())); - self.elements.push(value); - Ok(()) - } - - fn end(self) -> Result { - Ok(if self.fixed_size { - Content::SeqFixedSize(self.elements) - } else { - Content::Seq(self.elements) - }) - } -} - -struct SerializeTuple { - elements: Vec, - error: PhantomData, -} - -impl ser::SerializeTuple for SerializeTuple - where E: ser::Error -{ - type Ok = Content; - type Error = E; - - fn serialize_element(&mut self, value: &T) -> Result<(), E> { - let value = try!(value.serialize(ContentSerializer::::new())); - self.elements.push(value); - Ok(()) - } - - fn end(self) -> Result { - Ok(Content::Tuple(self.elements)) - } -} - -struct SerializeTupleStruct { - name: &'static str, - fields: Vec, - error: PhantomData, -} - -impl ser::SerializeTupleStruct for SerializeTupleStruct - where E: ser::Error -{ - type Ok = Content; - type Error = E; - - fn serialize_field(&mut self, value: &T) -> Result<(), E> { - let value = try!(value.serialize(ContentSerializer::::new())); - self.fields.push(value); - Ok(()) - } - - fn end(self) -> Result { - Ok(Content::TupleStruct(self.name, self.fields)) - } -} - -struct SerializeTupleVariant { - name: &'static str, - variant_index: usize, - variant: &'static str, - fields: Vec, - error: PhantomData, -} - -impl ser::SerializeTupleVariant for SerializeTupleVariant - where E: ser::Error -{ - type Ok = Content; - type Error = E; - - fn serialize_field(&mut self, value: &T) -> Result<(), E> { - let value = try!(value.serialize(ContentSerializer::::new())); - self.fields.push(value); - Ok(()) - } - - fn end(self) -> Result { - Ok(Content::TupleVariant(self.name, self.variant_index, self.variant, self.fields)) - } -} - -struct SerializeMap { - entries: Vec<(Content, Content)>, - key: Option, - error: PhantomData, -} - -impl ser::SerializeMap for SerializeMap - where E: ser::Error -{ - type Ok = Content; - type Error = E; - - fn serialize_key(&mut self, key: &T) -> Result<(), E> { - let key = try!(key.serialize(ContentSerializer::::new())); - self.key = Some(key); - Ok(()) - } - - fn serialize_value(&mut self, value: &T) -> Result<(), E> { - let key = self.key.take().expect("serialize_value called before serialize_key"); - let value = try!(value.serialize(ContentSerializer::::new())); - self.entries.push((key, value)); - Ok(()) - } - - fn end(self) -> Result { - Ok(Content::Map(self.entries)) - } - - fn serialize_entry(&mut self, - key: &K, - value: &V) - -> Result<(), E> { - let key = try!(key.serialize(ContentSerializer::::new())); - let value = try!(value.serialize(ContentSerializer::::new())); - self.entries.push((key, value)); - Ok(()) - } -} - -struct SerializeStruct { - name: &'static str, - fields: Vec<(&'static str, Content)>, - error: PhantomData, -} - -impl ser::SerializeStruct for SerializeStruct - where E: ser::Error -{ - type Ok = Content; - type Error = E; - - fn serialize_field(&mut self, - key: &'static str, - value: &T) - -> Result<(), E> { - let value = try!(value.serialize(ContentSerializer::::new())); - self.fields.push((key, value)); - Ok(()) - } - - fn end(self) -> Result { - Ok(Content::Struct(self.name, self.fields)) - } -} - -struct SerializeStructVariant { - name: &'static str, - variant_index: usize, - variant: &'static str, - fields: Vec<(&'static str, Content)>, - error: PhantomData, -} - -impl ser::SerializeStructVariant for SerializeStructVariant - where E: ser::Error -{ - type Ok = Content; - type Error = E; - - fn serialize_field(&mut self, - key: &'static str, - value: &T) - -> Result<(), E> { - let value = try!(value.serialize(ContentSerializer::::new())); - self.fields.push((key, value)); - Ok(()) - } - - fn end(self) -> Result { - Ok(Content::StructVariant(self.name, self.variant_index, self.variant, self.fields)) - } -} diff --git a/serde/src/ser/impls.rs b/serde/src/ser/impls.rs index 6cfa32a9..d0a74b97 100644 --- a/serde/src/ser/impls.rs +++ b/serde/src/ser/impls.rs @@ -626,6 +626,37 @@ impl Serialize for Duration { /////////////////////////////////////////////////////////////////////////////// +/// Seralize the `$value` that implements Display as a string, +/// when that string is statically known to never have more than +/// a constant `$MAX_LEN` bytes. +/// +/// Panics if the Display impl tries to write more than `$MAX_LEN` bytes. +#[cfg(feature = "std")] +macro_rules! serialize_display_bounded_length { + ($value: expr, $MAX_LEN: expr, $serializer: expr) => { + { + use std::io::Write; + let mut buffer: [u8; $MAX_LEN] = unsafe { ::std::mem::uninitialized() }; + let remaining_len; + { + let mut remaining = &mut buffer[..]; + write!(remaining, "{}", $value).unwrap(); + remaining_len = remaining.len() + } + let written_len = buffer.len() - remaining_len; + let written = &buffer[..written_len]; + + // write! only provides std::fmt::Formatter to Display implementations, + // which has methods write_str and write_char but no method to write arbitrary bytes. + // Therefore, `written` is well-formed in UTF-8. + let written_str = unsafe { + ::std::str::from_utf8_unchecked(written) + }; + $serializer.serialize_str(written_str) + } + } +} + #[cfg(feature = "std")] impl Serialize for net::IpAddr { fn serialize(&self, serializer: S) -> Result diff --git a/serde/src/ser/impossible.rs b/serde/src/ser/impossible.rs index 82755d72..7f08a0db 100644 --- a/serde/src/ser/impossible.rs +++ b/serde/src/ser/impossible.rs @@ -18,7 +18,7 @@ use ser::{self, Serialize, SerializeSeq, SerializeTuple, SerializeTupleStruct, /// # extern crate serde; /// # /// # use serde::ser::{Serializer, Impossible}; -/// # use serde::ser::private::Error; +/// # use serde::private::ser::Error; /// # /// # struct MySerializer; /// # diff --git a/serde/src/ser/mod.rs b/serde/src/ser/mod.rs index eeac1761..831fa1c6 100644 --- a/serde/src/ser/mod.rs +++ b/serde/src/ser/mod.rs @@ -107,12 +107,6 @@ use core::iter::IntoIterator; mod impls; mod impossible; -// Helpers used by generated code. Not public API. -#[doc(hidden)] -pub mod private; -#[cfg(any(feature = "std", feature = "collections"))] -mod content; - pub use self::impossible::Impossible; /////////////////////////////////////////////////////////////////////////////// @@ -379,7 +373,7 @@ pub trait Serializer: Sized { /// # extern crate serde; /// # /// # use serde::ser::{Serializer, SerializeSeq}; - /// # use serde::ser::private::Error; + /// # use serde::private::ser::Error; /// # /// # struct MySerializer; /// # diff --git a/serde/src/ser/private.rs b/serde/src/ser/private.rs deleted file mode 100644 index 5d1f723f..00000000 --- a/serde/src/ser/private.rs +++ /dev/null @@ -1,333 +0,0 @@ -use core::fmt::{self, Display}; - -use ser::{self, Serialize, Serializer, SerializeMap, SerializeStruct, Impossible}; - -#[cfg(any(feature = "std", feature = "collections"))] -use ser::content::{SerializeTupleVariantAsMapValue, SerializeStructVariantAsMapValue}; - -#[cfg(feature = "std")] -use std::error; - -/// Not public API. -pub fn serialize_tagged_newtype(serializer: S, - type_ident: &'static str, - variant_ident: &'static str, - tag: &'static str, - variant_name: &'static str, - value: &T) - -> Result - where S: Serializer, - T: Serialize -{ - value.serialize(TaggedSerializer { - type_ident: type_ident, - variant_ident: variant_ident, - tag: tag, - variant_name: variant_name, - delegate: serializer, - }) -} - -struct TaggedSerializer { - type_ident: &'static str, - variant_ident: &'static str, - tag: &'static str, - variant_name: &'static str, - delegate: S, -} - -enum Unsupported { - Boolean, - Integer, - Float, - Char, - String, - ByteArray, - Optional, - Unit, - UnitStruct, - Sequence, - Tuple, - TupleStruct, - #[cfg(not(any(feature = "std", feature = "collections")))] - Enum, -} - -impl Display for Unsupported { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - match *self { - Unsupported::Boolean => formatter.write_str("a boolean"), - Unsupported::Integer => formatter.write_str("an integer"), - Unsupported::Float => formatter.write_str("a float"), - Unsupported::Char => formatter.write_str("a char"), - Unsupported::String => formatter.write_str("a string"), - Unsupported::ByteArray => formatter.write_str("a byte array"), - Unsupported::Optional => formatter.write_str("an optional"), - Unsupported::Unit => formatter.write_str("unit"), - Unsupported::UnitStruct => formatter.write_str("a unit struct"), - Unsupported::Sequence => formatter.write_str("a sequence"), - Unsupported::Tuple => formatter.write_str("a tuple"), - Unsupported::TupleStruct => formatter.write_str("a tuple struct"), - #[cfg(not(any(feature = "std", feature = "collections")))] - Unsupported::Enum => formatter.write_str("an enum"), - } - } -} - -impl TaggedSerializer - where S: Serializer -{ - fn bad_type(self, what: Unsupported) -> S::Error { - ser::Error::custom(format_args!( - "cannot serialize tagged newtype variant {}::{} containing {}", - self.type_ident, - self.variant_ident, - what)) - } -} - -impl Serializer for TaggedSerializer - where S: Serializer -{ - type Ok = S::Ok; - type Error = S::Error; - - type SerializeSeq = Impossible; - type SerializeTuple = Impossible; - type SerializeTupleStruct = Impossible; - type SerializeMap = S::SerializeMap; - type SerializeStruct = S::SerializeStruct; - - #[cfg(not(any(feature = "std", feature = "collections")))] - type SerializeTupleVariant = Impossible; - #[cfg(any(feature = "std", feature = "collections"))] - type SerializeTupleVariant = SerializeTupleVariantAsMapValue; - - #[cfg(not(any(feature = "std", feature = "collections")))] - type SerializeStructVariant = Impossible; - #[cfg(any(feature = "std", feature = "collections"))] - type SerializeStructVariant = SerializeStructVariantAsMapValue; - - fn serialize_bool(self, _: bool) -> Result { - Err(self.bad_type(Unsupported::Boolean)) - } - - fn serialize_i8(self, _: i8) -> Result { - Err(self.bad_type(Unsupported::Integer)) - } - - fn serialize_i16(self, _: i16) -> Result { - Err(self.bad_type(Unsupported::Integer)) - } - - fn serialize_i32(self, _: i32) -> Result { - Err(self.bad_type(Unsupported::Integer)) - } - - fn serialize_i64(self, _: i64) -> Result { - Err(self.bad_type(Unsupported::Integer)) - } - - fn serialize_u8(self, _: u8) -> Result { - Err(self.bad_type(Unsupported::Integer)) - } - - fn serialize_u16(self, _: u16) -> Result { - Err(self.bad_type(Unsupported::Integer)) - } - - fn serialize_u32(self, _: u32) -> Result { - Err(self.bad_type(Unsupported::Integer)) - } - - fn serialize_u64(self, _: u64) -> Result { - Err(self.bad_type(Unsupported::Integer)) - } - - fn serialize_f32(self, _: f32) -> Result { - Err(self.bad_type(Unsupported::Float)) - } - - fn serialize_f64(self, _: f64) -> Result { - Err(self.bad_type(Unsupported::Float)) - } - - fn serialize_char(self, _: char) -> Result { - Err(self.bad_type(Unsupported::Char)) - } - - fn serialize_str(self, _: &str) -> Result { - Err(self.bad_type(Unsupported::String)) - } - - fn serialize_bytes(self, _: &[u8]) -> Result { - Err(self.bad_type(Unsupported::ByteArray)) - } - - fn serialize_none(self) -> Result { - Err(self.bad_type(Unsupported::Optional)) - } - - fn serialize_some(self, _: &T) -> Result - where T: Serialize - { - Err(self.bad_type(Unsupported::Optional)) - } - - fn serialize_unit(self) -> Result { - Err(self.bad_type(Unsupported::Unit)) - } - - fn serialize_unit_struct(self, _: &'static str) -> Result { - Err(self.bad_type(Unsupported::UnitStruct)) - } - - fn serialize_unit_variant(self, - _: &'static str, - _: usize, - inner_variant: &'static str) - -> Result { - let mut map = try!(self.delegate.serialize_map(Some(2))); - try!(map.serialize_entry(self.tag, self.variant_name)); - try!(map.serialize_entry(inner_variant, &())); - map.end() - } - - fn serialize_newtype_struct(self, - _: &'static str, - value: &T) - -> Result - where T: Serialize - { - value.serialize(self) - } - - fn serialize_newtype_variant(self, - _: &'static str, - _: usize, - inner_variant: &'static str, - inner_value: &T) - -> Result - where T: Serialize - { - let mut map = try!(self.delegate.serialize_map(Some(2))); - try!(map.serialize_entry(self.tag, self.variant_name)); - try!(map.serialize_entry(inner_variant, inner_value)); - map.end() - } - - fn serialize_seq(self, _: Option) -> Result { - Err(self.bad_type(Unsupported::Sequence)) - } - - fn serialize_seq_fixed_size(self, _: usize) -> Result { - Err(self.bad_type(Unsupported::Sequence)) - } - - fn serialize_tuple(self, _: usize) -> Result { - Err(self.bad_type(Unsupported::Tuple)) - } - - fn serialize_tuple_struct(self, - _: &'static str, - _: usize) - -> Result { - Err(self.bad_type(Unsupported::TupleStruct)) - } - - #[cfg(not(any(feature = "std", feature = "collections")))] - fn serialize_tuple_variant(self, - _: &'static str, - _: usize, - _: &'static str, - _: usize) - -> Result { - // Lack of push-based serialization means we need to buffer the content - // of the tuple variant, so it requires std. - Err(self.bad_type(Unsupported::Enum)) - } - - #[cfg(any(feature = "std", feature = "collections"))] - fn serialize_tuple_variant(self, - _: &'static str, - _: usize, - inner_variant: &'static str, - len: usize) - -> Result { - let mut map = try!(self.delegate.serialize_map(Some(2))); - try!(map.serialize_entry(self.tag, self.variant_name)); - try!(map.serialize_key(inner_variant)); - Ok(SerializeTupleVariantAsMapValue::new(map, inner_variant, len)) - } - - fn serialize_map(self, len: Option) -> Result { - let mut map = try!(self.delegate.serialize_map(len.map(|len| len + 1))); - try!(map.serialize_entry(self.tag, self.variant_name)); - Ok(map) - } - - fn serialize_struct(self, - name: &'static str, - len: usize) - -> Result { - let mut state = try!(self.delegate.serialize_struct(name, len + 1)); - try!(state.serialize_field(self.tag, self.variant_name)); - Ok(state) - } - - #[cfg(not(any(feature = "std", feature = "collections")))] - fn serialize_struct_variant(self, - _: &'static str, - _: usize, - _: &'static str, - _: usize) - -> Result { - // Lack of push-based serialization means we need to buffer the content - // of the struct variant, so it requires std. - Err(self.bad_type(Unsupported::Enum)) - } - - #[cfg(any(feature = "std", feature = "collections"))] - fn serialize_struct_variant(self, - _: &'static str, - _: usize, - inner_variant: &'static str, - len: usize) - -> Result { - let mut map = try!(self.delegate.serialize_map(Some(2))); - try!(map.serialize_entry(self.tag, self.variant_name)); - try!(map.serialize_key(inner_variant)); - Ok(SerializeStructVariantAsMapValue::new(map, inner_variant, len)) - } - - #[cfg(not(any(feature = "std", feature = "collections")))] - fn collect_str(self, _: &T) -> Result - where T: Display - { - Err(self.bad_type(Unsupported::String)) - } -} - -/// Used only by Serde doc tests. Not public API. -#[doc(hidden)] -#[derive(Debug)] -pub struct Error; - -impl ser::Error for Error { - fn custom(_: T) -> Self { - unimplemented!() - } -} - -#[cfg(feature = "std")] -impl error::Error for Error { - fn description(&self) -> &str { - unimplemented!() - } -} - -impl Display for Error { - fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { - unimplemented!() - } -} diff --git a/serde_codegen_internals/src/attr.rs b/serde_codegen_internals/src/attr.rs index 270a4823..9e957ad9 100644 --- a/serde_codegen_internals/src/attr.rs +++ b/serde_codegen_internals/src/attr.rs @@ -705,10 +705,10 @@ impl Field { // impl<'de: 'a, 'a> Deserialize<'de> for Cow<'a, str> // impl<'de: 'a, 'a> Deserialize<'de> for Cow<'a, [u8]> if is_cow(&field.ty, "str") { - let path = syn::parse_path("_serde::de::private::borrow_cow_str").unwrap(); + let path = syn::parse_path("_serde::private::de::borrow_cow_str").unwrap(); deserialize_with.set_if_none(path); } else if is_cow(&field.ty, "[u8]") { - let path = syn::parse_path("_serde::de::private::borrow_cow_bytes").unwrap(); + let path = syn::parse_path("_serde::private::de::borrow_cow_bytes").unwrap(); deserialize_with.set_if_none(path); } } else if is_rptr(&field.ty, "str") || is_rptr(&field.ty, "[u8]") { diff --git a/serde_derive/src/de.rs b/serde_derive/src/de.rs index 441d7dc5..5c84a649 100644 --- a/serde_derive/src/de.rs +++ b/serde_derive/src/de.rs @@ -622,7 +622,7 @@ fn deserialize_internally_tagged_enum(ident: &syn::Ident, params, variant, item_attrs, - quote!(_serde::de::private::ContentDeserializer::<__D::Error>::new(__tagged.content)), + quote!(_serde::private::de::ContentDeserializer::<__D::Error>::new(__tagged.content)), )); quote! { @@ -637,7 +637,7 @@ fn deserialize_internally_tagged_enum(ident: &syn::Ident, let __tagged = try!(_serde::Deserializer::deserialize( __deserializer, - _serde::de::private::TaggedContentVisitor::<__Field>::new(#tag))); + _serde::private::de::TaggedContentVisitor::<__Field>::new(#tag))); match __tagged.tag { #(#variant_arms)* @@ -693,7 +693,7 @@ fn deserialize_adjacently_tagged_enum(ident: &syn::Ident, let type_name = item_attrs.name().deserialize_name(); let tag_or_content = quote! { - _serde::de::private::TagOrContentFieldVisitor { + _serde::private::de::TagOrContentFieldVisitor { tag: #tag, content: #content, } @@ -738,10 +738,10 @@ fn deserialize_adjacently_tagged_enum(ident: &syn::Ident, let visit_third_key = quote! { // Visit the third key in the map, hopefully there isn't one. match try!(_serde::de::MapVisitor::visit_key_seed(&mut __visitor, #tag_or_content)) { - _serde::export::Some(_serde::de::private::TagOrContentField::Tag) => { + _serde::export::Some(_serde::private::de::TagOrContentField::Tag) => { _serde::export::Err(<__V::Error as _serde::de::Error>::duplicate_field(#tag)) } - _serde::export::Some(_serde::de::private::TagOrContentField::Content) => { + _serde::export::Some(_serde::private::de::TagOrContentField::Content) => { _serde::export::Err(<__V::Error as _serde::de::Error>::duplicate_field(#content)) } _serde::export::None => _serde::export::Ok(__ret), @@ -789,17 +789,17 @@ fn deserialize_adjacently_tagged_enum(ident: &syn::Ident, // Visit the first key. match try!(_serde::de::MapVisitor::visit_key_seed(&mut __visitor, #tag_or_content)) { // First key is the tag. - _serde::export::Some(_serde::de::private::TagOrContentField::Tag) => { + _serde::export::Some(_serde::private::de::TagOrContentField::Tag) => { // Parse the tag. let __field = try!(_serde::de::MapVisitor::visit_value(&mut __visitor)); // Visit the second key. match try!(_serde::de::MapVisitor::visit_key_seed(&mut __visitor, #tag_or_content)) { // Second key is a duplicate of the tag. - _serde::export::Some(_serde::de::private::TagOrContentField::Tag) => { + _serde::export::Some(_serde::private::de::TagOrContentField::Tag) => { _serde::export::Err(<__V::Error as _serde::de::Error>::duplicate_field(#tag)) } // Second key is the content. - _serde::export::Some(_serde::de::private::TagOrContentField::Content) => { + _serde::export::Some(_serde::private::de::TagOrContentField::Content) => { let __ret = try!(_serde::de::MapVisitor::visit_value_seed(&mut __visitor, __Seed { field: __field, @@ -814,14 +814,14 @@ fn deserialize_adjacently_tagged_enum(ident: &syn::Ident, } } // First key is the content. - _serde::export::Some(_serde::de::private::TagOrContentField::Content) => { + _serde::export::Some(_serde::private::de::TagOrContentField::Content) => { // Buffer up the content. - let __content = try!(_serde::de::MapVisitor::visit_value::<_serde::de::private::Content>(&mut __visitor)); + let __content = try!(_serde::de::MapVisitor::visit_value::<_serde::private::de::Content>(&mut __visitor)); // Visit the second key. match try!(_serde::de::MapVisitor::visit_key_seed(&mut __visitor, #tag_or_content)) { // Second key is the tag. - _serde::export::Some(_serde::de::private::TagOrContentField::Tag) => { - let __deserializer = _serde::de::private::ContentDeserializer::<__V::Error>::new(__content); + _serde::export::Some(_serde::private::de::TagOrContentField::Tag) => { + let __deserializer = _serde::private::de::ContentDeserializer::<__V::Error>::new(__content); // Parse the tag. let __ret = try!(match try!(_serde::de::MapVisitor::visit_value(&mut __visitor)) { // Deserialize the buffered content now that we know the variant. @@ -831,7 +831,7 @@ fn deserialize_adjacently_tagged_enum(ident: &syn::Ident, #visit_third_key } // Second key is a duplicate of the content. - _serde::export::Some(_serde::de::private::TagOrContentField::Content) => { + _serde::export::Some(_serde::private::de::TagOrContentField::Content) => { _serde::export::Err(<__V::Error as _serde::de::Error>::duplicate_field(#content)) } // There is no second key. @@ -897,7 +897,7 @@ fn deserialize_untagged_enum(ident: &syn::Ident, params, variant, item_attrs, - quote!(_serde::de::private::ContentRefDeserializer::<__D::Error>::new(&__content)), + quote!(_serde::private::de::ContentRefDeserializer::<__D::Error>::new(&__content)), )) }); @@ -910,7 +910,7 @@ fn deserialize_untagged_enum(ident: &syn::Ident, let fallthrough_msg = format!("data did not match any variant of untagged enum {}", ident); quote_block! { - let __content = try!(<_serde::de::private::Content as _serde::Deserialize>::deserialize(__deserializer)); + let __content = try!(<_serde::private::de::Content as _serde::Deserialize>::deserialize(__deserializer)); #( if let _serde::export::Ok(__ok) = #attempts { @@ -974,7 +974,7 @@ fn deserialize_internally_tagged_variant(ident: &syn::Ident, let type_name = ident.as_ref(); let variant_name = variant.ident.as_ref(); quote_block! { - try!(_serde::Deserializer::deserialize(#deserializer, _serde::de::private::InternallyTaggedUnitVisitor::new(#type_name, #variant_name))); + try!(_serde::Deserializer::deserialize(#deserializer, _serde::private::de::InternallyTaggedUnitVisitor::new(#type_name, #variant_name))); _serde::export::Ok(#ident::#variant_ident) } } @@ -1005,7 +1005,7 @@ fn deserialize_untagged_variant(ident: &syn::Ident, _serde::export::Result::map( _serde::Deserializer::deserialize( #deserializer, - _serde::de::private::UntaggedUnitVisitor::new(#type_name, #variant_name) + _serde::private::de::UntaggedUnitVisitor::new(#type_name, #variant_name) ), |()| #ident::#variant_ident) } @@ -1428,7 +1428,7 @@ fn expr_is_missing(field: &Field, item_attrs: &attr::Item) -> Fragment { match field.attrs.deserialize_with() { None => { quote_expr! { - try!(_serde::de::private::missing_field(#name)) + try!(_serde::private::de::missing_field(#name)) } } Some(_) => { diff --git a/serde_derive/src/ser.rs b/serde_derive/src/ser.rs index a16f7567..51826928 100644 --- a/serde_derive/src/ser.rs +++ b/serde_derive/src/ser.rs @@ -379,7 +379,7 @@ fn serialize_internally_tagged_variant(ident: &syn::Ident, } quote_expr! { - _serde::ser::private::serialize_tagged_newtype( + _serde::private::ser::serialize_tagged_newtype( __serializer, #enum_ident_str, #variant_ident_str,