Implement serialization for NonZero values in nightly.

This commit is contained in:
Patrick Walton 2015-07-14 11:59:49 -07:00
parent bcc9e15b05
commit ea9ed22e3e
4 changed files with 38 additions and 0 deletions

View File

@ -11,3 +11,7 @@ keywords = ["serialization"]
[dependencies]
num = "*"
[features]
nightly = []

View File

@ -9,6 +9,11 @@ use std::sync::Arc;
use num::FromPrimitive;
#[cfg(feature = "nightly")]
use core::nonzero::{NonZero, Zeroable};
#[cfg(feature = "nightly")]
use std::num::Zero;
use de::{
Deserialize,
Deserializer,
@ -865,3 +870,18 @@ impl<'a, T: ?Sized> Deserialize for Cow<'a, T> where T: ToOwned, T::Owned: Deser
Ok(Cow::Owned(val))
}
}
///////////////////////////////////////////////////////////////////////////////
impl<T> Deserialize for NonZero<T> where T: Deserialize + PartialEq + Zeroable + Zero {
fn deserialize<D>(deserializer: &mut D) -> Result<NonZero<T>, D::Error> where D: Deserializer {
let value = try!(Deserialize::deserialize(deserializer));
if value == Zero::zero() {
return Err(Error::syntax_error())
}
unsafe {
Ok(NonZero::new(value))
}
}
}

View File

@ -6,9 +6,13 @@
//! leaving serde to perform roughly the same speed as a hand written serializer for a specific
//! type.
#![doc(html_root_url="http://erickt.github.io/rust-serde")]
#![cfg_attr(feature = "nightly", feature(core, nonzero, zero_one))]
extern crate num;
#[cfg(feature = "nightly")]
extern crate core;
pub use ser::{Serialize, Serializer};
pub use de::{Deserialize, Deserializer, Error};

View File

@ -5,6 +5,9 @@ use std::path;
use std::rc::Rc;
use std::sync::Arc;
#[cfg(feature = "nightly")]
use core::nonzero::{NonZero, Zeroable};
use super::{
Serialize,
Serializer,
@ -545,3 +548,10 @@ impl Serialize for path::PathBuf {
self.to_str().unwrap().serialize(serializer)
}
}
impl<T> Serialize for NonZero<T> where T: Serialize + Zeroable {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: Serializer {
(**self).serialize(serializer)
}
}