Clean up some existing examples

This commit is contained in:
David Tolnay 2017-04-07 11:06:19 -07:00
parent 85d4dc3e20
commit fdaa8202b9
No known key found for this signature in database
GPG Key ID: F9BA143B95FF6D82
3 changed files with 119 additions and 63 deletions

View File

@ -139,20 +139,26 @@ macro_rules! declare_error_trait {
/// The message should not be capitalized and should not end with a period. /// The message should not be capitalized and should not end with a period.
/// ///
/// ```rust /// ```rust
/// # use serde::de::{Deserialize, Deserializer, Error};
/// # use std::str::FromStr; /// # use std::str::FromStr;
/// # #[allow(dead_code)] /// #
/// # struct IpAddr; /// # struct IpAddr;
/// #
/// # impl FromStr for IpAddr { /// # impl FromStr for IpAddr {
/// # type Err = String; /// # type Err = String;
/// # fn from_str(_: &str) -> Result<Self, String> { unimplemented!() } /// #
/// # fn from_str(_: &str) -> Result<Self, String> {
/// # unimplemented!()
/// # }
/// # } /// # }
/// #
/// use serde::de::{self, Deserialize, Deserializer};
///
/// impl<'de> Deserialize<'de> for IpAddr { /// impl<'de> Deserialize<'de> for IpAddr {
/// fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> /// fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
/// where D: Deserializer<'de> /// where D: Deserializer<'de>
/// { /// {
/// let s = try!(String::deserialize(deserializer)); /// let s = try!(String::deserialize(deserializer));
/// s.parse().map_err(Error::custom) /// s.parse().map_err(de::Error::custom)
/// } /// }
/// } /// }
/// ``` /// ```
@ -260,20 +266,24 @@ declare_error_trait!(Error: Sized + Debug + Display);
/// `invalid_length` methods of the `Error` trait to build error messages. /// `invalid_length` methods of the `Error` trait to build error messages.
/// ///
/// ```rust /// ```rust
/// # use serde::de::{Error, Unexpected, Visitor};
/// # use std::fmt; /// # use std::fmt;
/// # #[allow(dead_code)] /// #
/// # use serde::de::{self, Unexpected, Visitor};
/// #
/// # struct Example; /// # struct Example;
/// #
/// # impl<'de> Visitor<'de> for Example { /// # impl<'de> Visitor<'de> for Example {
/// # type Value = (); /// # type Value = ();
/// #
/// # fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
/// # write!(formatter, "definitely not a boolean")
/// # }
/// #
/// fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E> /// fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
/// where E: Error /// where E: de::Error
/// { /// {
/// Err(Error::invalid_type(Unexpected::Bool(v), &self)) /// Err(de::Error::invalid_type(Unexpected::Bool(v), &self))
/// } /// }
/// # fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
/// # write!(formatter, "definitely not a boolean")
/// # }
/// # } /// # }
/// ``` /// ```
#[derive(Clone, PartialEq, Debug)] #[derive(Clone, PartialEq, Debug)]
@ -380,31 +390,37 @@ impl<'a> fmt::Display for Unexpected<'a> {
/// (`&self`) is an implementation of this trait. /// (`&self`) is an implementation of this trait.
/// ///
/// ```rust /// ```rust
/// # use serde::de::{Error, Unexpected, Visitor};
/// # use std::fmt; /// # use std::fmt;
/// # #[allow(dead_code)] /// #
/// # use serde::de::{self, Unexpected, Visitor};
/// #
/// # struct Example; /// # struct Example;
/// #
/// # impl<'de> Visitor<'de> for Example { /// # impl<'de> Visitor<'de> for Example {
/// # type Value = (); /// # type Value = ();
/// #
/// # fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
/// # write!(formatter, "definitely not a boolean")
/// # }
/// #
/// fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E> /// fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
/// where E: Error /// where E: de::Error
/// { /// {
/// Err(Error::invalid_type(Unexpected::Bool(v), &self)) /// Err(de::Error::invalid_type(Unexpected::Bool(v), &self))
/// } /// }
/// # fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
/// # write!(formatter, "definitely not a boolean")
/// # }
/// # } /// # }
/// ``` /// ```
/// ///
/// Outside of a `Visitor`, `&"..."` can be used. /// Outside of a `Visitor`, `&"..."` can be used.
/// ///
/// ```rust /// ```rust
/// # use serde::de::{Error, Unexpected}; /// # use serde::de::{self, Unexpected};
/// # #[allow(dead_code)] /// #
/// # fn example<E: Error>() -> Result<(), E> { /// # fn example<E>() -> Result<(), E>
/// # let v = true; /// # where E: de::Error
/// return Err(Error::invalid_type(Unexpected::Bool(v), &"a negative integer")); /// # {
/// # let v = true;
/// return Err(de::Error::invalid_type(Unexpected::Bool(v), &"a negative integer"));
/// # } /// # }
/// ``` /// ```
pub trait Expected { pub trait Expected {
@ -509,11 +525,13 @@ impl<T> DeserializeOwned for T where T: for<'de> Deserialize<'de> {}
/// ///
/// ```rust /// ```rust
/// # use serde::Deserialize; /// # use serde::Deserialize;
/// # #[allow(dead_code)] /// #
/// # enum Error {} /// # enum Error {}
/// # #[allow(dead_code)] /// #
/// fn func<'de, T: Deserialize<'de>>() -> Result<T, Error> /// fn func<'de, T: Deserialize<'de>>() -> Result<T, Error>
/// # { unimplemented!() } /// # {
/// # unimplemented!()
/// # }
/// ``` /// ```
/// ///
/// Adjusting an API like this to support stateful deserialization is a matter /// Adjusting an API like this to support stateful deserialization is a matter
@ -521,9 +539,9 @@ impl<T> DeserializeOwned for T where T: for<'de> Deserialize<'de> {}
/// ///
/// ```rust /// ```rust
/// # use serde::de::DeserializeSeed; /// # use serde::de::DeserializeSeed;
/// # #[allow(dead_code)] /// #
/// # enum Error {} /// # enum Error {}
/// # #[allow(dead_code)] /// #
/// fn func_seed<'de, T: DeserializeSeed<'de>>(seed: T) -> Result<T::Value, Error> /// fn func_seed<'de, T: DeserializeSeed<'de>>(seed: T) -> Result<T::Value, Error>
/// # { /// # {
/// # let _ = seed; /// # let _ = seed;
@ -545,10 +563,11 @@ impl<T> DeserializeOwned for T where T: for<'de> Deserialize<'de> {}
/// trait. /// trait.
/// ///
/// ```rust /// ```rust
/// # use serde::de::{Deserialize, DeserializeSeed, Deserializer, Visitor, SeqVisitor}; /// use std::fmt;
/// # use std::fmt; /// use std::marker::PhantomData;
/// # use std::marker::PhantomData; ///
/// # /// use serde::de::{Deserialize, DeserializeSeed, Deserializer, Visitor, SeqVisitor};
///
/// // A DeserializeSeed implementation that uses stateful deserialization to /// // A DeserializeSeed implementation that uses stateful deserialization to
/// // append array elements onto the end of an existing vector. The preexisting /// // append array elements onto the end of an existing vector. The preexisting
/// // state ("seed") in this case is the Vec<T>. The `deserialize` method of /// // state ("seed") in this case is the Vec<T>. The `deserialize` method of
@ -576,6 +595,10 @@ impl<T> DeserializeOwned for T where T: for<'de> Deserialize<'de> {}
/// { /// {
/// type Value = (); /// type Value = ();
/// ///
/// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
/// write!(formatter, "an array of integers")
/// }
///
/// fn visit_seq<V>(self, mut visitor: V) -> Result<(), V::Error> /// fn visit_seq<V>(self, mut visitor: V) -> Result<(), V::Error>
/// where V: SeqVisitor<'de> /// where V: SeqVisitor<'de>
/// { /// {
@ -586,10 +609,6 @@ impl<T> DeserializeOwned for T where T: for<'de> Deserialize<'de> {}
/// } /// }
/// Ok(()) /// Ok(())
/// } /// }
/// #
/// # fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
/// # write!(formatter, "an array of integers")
/// # }
/// } /// }
/// ///
/// deserializer.deserialize_seq(ExtendVecVisitor(self.0)) /// deserializer.deserialize_seq(ExtendVecVisitor(self.0))
@ -606,6 +625,10 @@ impl<T> DeserializeOwned for T where T: for<'de> Deserialize<'de> {}
/// // contents of the inner arrays. /// // contents of the inner arrays.
/// type Value = Vec<T>; /// type Value = Vec<T>;
/// ///
/// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
/// write!(formatter, "an array of arrays")
/// }
///
/// fn visit_seq<V>(self, mut visitor: V) -> Result<Vec<T>, V::Error> /// fn visit_seq<V>(self, mut visitor: V) -> Result<Vec<T>, V::Error>
/// where V: SeqVisitor<'de> /// where V: SeqVisitor<'de>
/// { /// {
@ -620,18 +643,15 @@ impl<T> DeserializeOwned for T where T: for<'de> Deserialize<'de> {}
/// // Return the finished vec. /// // Return the finished vec.
/// Ok(vec) /// Ok(vec)
/// } /// }
/// #
/// # fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
/// # write!(formatter, "an array of arrays")
/// # }
/// } /// }
/// ///
/// # #[allow(dead_code)] /// # fn example<'de, D>(deserializer: D) -> Result<(), D::Error>
/// # fn example<'de, D: Deserializer<'de>>(deserializer: D) -> Result<(), D::Error> { /// # where D: Deserializer<'de>
/// # {
/// let visitor = FlattenedVecVisitor(PhantomData); /// let visitor = FlattenedVecVisitor(PhantomData);
/// let flattened: Vec<u64> = deserializer.deserialize_seq(visitor)?; /// let flattened: Vec<u64> = deserializer.deserialize_seq(visitor)?;
/// # let _ = flattened; /// # Ok(())
/// # Ok(()) } /// # }
/// ``` /// ```
pub trait DeserializeSeed<'de>: Sized { pub trait DeserializeSeed<'de>: Sized {
/// The type produced by using this seed. /// The type produced by using this seed.
@ -917,11 +937,12 @@ pub trait Deserializer<'de>: Sized {
/// This trait represents a visitor that walks through a deserializer. /// This trait represents a visitor that walks through a deserializer.
/// ///
/// ```rust /// ```rust
/// # use serde::de::{Error, Unexpected, Visitor};
/// # use std::fmt; /// # use std::fmt;
/// #
/// # use serde::de::{self, Unexpected, Visitor};
/// #
/// /// A visitor that deserializes a long string - a string containing at least /// /// A visitor that deserializes a long string - a string containing at least
/// /// some minimum number of bytes. /// /// some minimum number of bytes.
/// # #[allow(dead_code)]
/// struct LongString { /// struct LongString {
/// min: usize, /// min: usize,
/// } /// }
@ -934,12 +955,12 @@ pub trait Deserializer<'de>: Sized {
/// } /// }
/// ///
/// fn visit_str<E>(self, s: &str) -> Result<Self::Value, E> /// fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
/// where E: Error /// where E: de::Error
/// { /// {
/// if s.len() >= self.min { /// if s.len() >= self.min {
/// Ok(s.to_owned()) /// Ok(s.to_owned())
/// } else { /// } else {
/// Err(Error::invalid_value(Unexpected::Str(s), &self)) /// Err(de::Error::invalid_value(Unexpected::Str(s), &self))
/// } /// }
/// } /// }
/// } /// }
@ -957,10 +978,14 @@ pub trait Visitor<'de>: Sized {
/// ///
/// ```rust /// ```rust
/// # use std::fmt; /// # use std::fmt;
/// # #[allow(dead_code)] /// #
/// # struct S { max: usize } /// # struct S {
/// # max: usize,
/// # }
/// #
/// # impl<'de> serde::de::Visitor<'de> for S { /// # impl<'de> serde::de::Visitor<'de> for S {
/// # type Value = (); /// # type Value = ();
/// #
/// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { /// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
/// write!(formatter, "an integer between 0 and {}", self.max) /// write!(formatter, "an integer between 0 and {}", self.max)
/// } /// }

View File

@ -117,14 +117,21 @@ macro_rules! forward_to_deserialize_helper {
/// methods. /// methods.
/// ///
/// ```rust /// ```rust
/// # #[macro_use] extern crate serde; /// # #[macro_use]
/// # extern crate serde;
/// #
/// # use serde::de::{value, Deserializer, Visitor}; /// # use serde::de::{value, Deserializer, Visitor};
/// # pub struct MyDeserializer; /// #
/// # struct MyDeserializer;
/// #
/// # impl<'de> Deserializer<'de> for MyDeserializer { /// # impl<'de> Deserializer<'de> for MyDeserializer {
/// # type Error = value::Error; /// # type Error = value::Error;
/// #
/// # fn deserialize<V>(self, _: V) -> Result<V::Value, Self::Error> /// # fn deserialize<V>(self, _: V) -> Result<V::Value, Self::Error>
/// # where V: Visitor<'de> /// # where V: Visitor<'de>
/// # { unimplemented!() } /// # {
/// # unimplemented!()
/// # }
/// # /// #
/// #[inline] /// #[inline]
/// fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error> /// fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
@ -132,12 +139,14 @@ macro_rules! forward_to_deserialize_helper {
/// { /// {
/// self.deserialize(visitor) /// self.deserialize(visitor)
/// } /// }
/// #
/// # forward_to_deserialize! { /// # forward_to_deserialize! {
/// # u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option /// # 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 /// # seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct
/// # tuple_struct struct struct_field tuple enum ignored_any /// # tuple_struct struct struct_field tuple enum ignored_any
/// # } /// # }
/// # } /// # }
/// #
/// # fn main() {} /// # fn main() {}
/// ``` /// ```
/// ///
@ -146,11 +155,16 @@ macro_rules! forward_to_deserialize_helper {
/// can choose which methods to forward. /// can choose which methods to forward.
/// ///
/// ```rust /// ```rust
/// # #[macro_use] extern crate serde; /// # #[macro_use]
/// # extern crate serde;
/// #
/// # use serde::de::{value, Deserializer, Visitor}; /// # use serde::de::{value, Deserializer, Visitor};
/// # pub struct MyDeserializer; /// #
/// # struct MyDeserializer;
/// #
/// impl<'de> Deserializer<'de> for MyDeserializer { /// impl<'de> Deserializer<'de> for MyDeserializer {
/// # type Error = value::Error; /// # type Error = value::Error;
/// #
/// fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error> /// fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
/// where V: Visitor<'de> /// where V: Visitor<'de>
/// { /// {
@ -165,6 +179,7 @@ macro_rules! forward_to_deserialize_helper {
/// tuple_struct struct struct_field tuple enum ignored_any /// tuple_struct struct struct_field tuple enum ignored_any
/// } /// }
/// } /// }
/// #
/// # fn main() {} /// # fn main() {}
/// ``` /// ```
/// ///

View File

@ -127,16 +127,23 @@ macro_rules! declare_error_trait {
/// if it contains invalid UTF-8 data. /// if it contains invalid UTF-8 data.
/// ///
/// ```rust /// ```rust
/// # use serde::ser::{Serialize, Serializer, Error};
/// # struct Path; /// # struct Path;
/// # impl Path { fn to_str(&self) -> Option<&str> { unimplemented!() } } /// #
/// # impl Path {
/// # fn to_str(&self) -> Option<&str> {
/// # unimplemented!()
/// # }
/// # }
/// #
/// use serde::ser::{self, Serialize, Serializer};
///
/// impl Serialize for Path { /// impl Serialize for Path {
/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
/// where S: Serializer /// where S: Serializer
/// { /// {
/// match self.to_str() { /// match self.to_str() {
/// Some(s) => s.serialize(serializer), /// Some(s) => s.serialize(serializer),
/// None => Err(Error::custom("path contains invalid UTF-8 characters")), /// None => Err(ser::Error::custom("path contains invalid UTF-8 characters")),
/// } /// }
/// } /// }
/// } /// }
@ -524,6 +531,7 @@ pub trait Serializer: Sized {
/// # impl<'a, T> IntoIterator for &'a Vec<T> { /// # impl<'a, T> IntoIterator for &'a Vec<T> {
/// # type Item = &'a T; /// # type Item = &'a T;
/// # type IntoIter = Box<Iterator<Item = &'a T>>; /// # type IntoIter = Box<Iterator<Item = &'a T>>;
/// #
/// # fn into_iter(self) -> Self::IntoIter { /// # fn into_iter(self) -> Self::IntoIter {
/// # unimplemented!() /// # unimplemented!()
/// # } /// # }
@ -704,6 +712,7 @@ pub trait Serializer: Sized {
/// # impl<'a, K, V> IntoIterator for &'a HashMap<K, V> { /// # impl<'a, K, V> IntoIterator for &'a HashMap<K, V> {
/// # type Item = (&'a K, &'a V); /// # type Item = (&'a K, &'a V);
/// # type IntoIter = Box<Iterator<Item = (&'a K, &'a V)>>; /// # type IntoIter = Box<Iterator<Item = (&'a K, &'a V)>>;
/// #
/// # fn into_iter(self) -> Self::IntoIter { /// # fn into_iter(self) -> Self::IntoIter {
/// # unimplemented!() /// # unimplemented!()
/// # } /// # }
@ -844,12 +853,15 @@ pub trait Serializer: Sized {
/// more efficient implementation if possible. /// more efficient implementation if possible.
/// ///
/// ```rust /// ```rust
/// # use serde::{Serialize, Serializer};
/// # struct DateTime; /// # struct DateTime;
/// #
/// # impl DateTime { /// # impl DateTime {
/// # fn naive_local(&self) -> () { () } /// # fn naive_local(&self) -> () { () }
/// # fn offset(&self) -> () { () } /// # fn offset(&self) -> () { () }
/// # } /// # }
/// #
/// use serde::{Serialize, Serializer};
///
/// impl Serialize for DateTime { /// impl Serialize for DateTime {
/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
/// where S: Serializer /// where S: Serializer
@ -876,12 +888,15 @@ pub trait Serializer: Sized {
/// implementation is expected to return an error. /// implementation is expected to return an error.
/// ///
/// ```rust /// ```rust
/// # use serde::{Serialize, Serializer};
/// # struct DateTime; /// # struct DateTime;
/// #
/// # impl DateTime { /// # impl DateTime {
/// # fn naive_local(&self) -> () { () } /// # fn naive_local(&self) -> () { () }
/// # fn offset(&self) -> () { () } /// # fn offset(&self) -> () { () }
/// # } /// # }
/// #
/// use serde::{Serialize, Serializer};
///
/// impl Serialize for DateTime { /// impl Serialize for DateTime {
/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
/// where S: Serializer /// where S: Serializer
@ -1118,6 +1133,7 @@ pub trait SerializeTupleVariant {
/// # impl<'a, K, V> IntoIterator for &'a HashMap<K, V> { /// # impl<'a, K, V> IntoIterator for &'a HashMap<K, V> {
/// # type Item = (&'a K, &'a V); /// # type Item = (&'a K, &'a V);
/// # type IntoIter = Box<Iterator<Item = (&'a K, &'a V)>>; /// # type IntoIter = Box<Iterator<Item = (&'a K, &'a V)>>;
/// #
/// # fn into_iter(self) -> Self::IntoIter { /// # fn into_iter(self) -> Self::IntoIter {
/// # unimplemented!() /// # unimplemented!()
/// # } /// # }