1 use super::{BigInt, Sign}; 2 3 use serde::de::{Error, Unexpected}; 4 use serde::{Deserialize, Deserializer, Serialize, Serializer}; 5 6 impl Serialize for Sign { serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer,7 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> 8 where 9 S: Serializer, 10 { 11 // Note: do not change the serialization format, or it may break 12 // forward and backward compatibility of serialized data! 13 match *self { 14 Sign::Minus => (-1i8).serialize(serializer), 15 Sign::NoSign => 0i8.serialize(serializer), 16 Sign::Plus => 1i8.serialize(serializer), 17 } 18 } 19 } 20 21 impl<'de> Deserialize<'de> for Sign { deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,22 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> 23 where 24 D: Deserializer<'de>, 25 { 26 let sign = i8::deserialize(deserializer)?; 27 match sign { 28 -1 => Ok(Sign::Minus), 29 0 => Ok(Sign::NoSign), 30 1 => Ok(Sign::Plus), 31 _ => Err(D::Error::invalid_value( 32 Unexpected::Signed(sign.into()), 33 &"a sign of -1, 0, or 1", 34 )), 35 } 36 } 37 } 38 39 impl Serialize for BigInt { serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer,40 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> 41 where 42 S: Serializer, 43 { 44 // Note: do not change the serialization format, or it may break 45 // forward and backward compatibility of serialized data! 46 (self.sign, &self.data).serialize(serializer) 47 } 48 } 49 50 impl<'de> Deserialize<'de> for BigInt { deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,51 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> 52 where 53 D: Deserializer<'de>, 54 { 55 let (sign, data) = Deserialize::deserialize(deserializer)?; 56 Ok(BigInt::from_biguint(sign, data)) 57 } 58 } 59