diff --git a/src/lib.rs b/src/lib.rs index b5ad1129..defc7df6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -63,15 +63,24 @@ pub use prelude::*; pub const LIB_NAME_RGB: &str = "RGB"; -/// Reserved byte. +// TODO: Move to amplify crate + +/// Reserved bytes. #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug, Display)] #[display("reserved")] #[derive(StrictType, StrictEncode)] #[strict_type(lib = LIB_NAME_RGB)] -pub struct ReservedBytes([u8; LEN]); +pub struct ReservedBytes([u8; LEN]); -impl Default for ReservedBytes { - fn default() -> Self { Self([0; LEN]) } +impl Default for ReservedBytes { + fn default() -> Self { Self([VAL; LEN]) } +} + +impl From<[u8; LEN]> for ReservedBytes { + fn from(value: [u8; LEN]) -> Self { + assert_eq!(value, [VAL; LEN]); + Self(value) + } } mod _reserved { @@ -79,10 +88,10 @@ mod _reserved { use crate::ReservedBytes; - impl StrictDecode for ReservedBytes { + impl StrictDecode for ReservedBytes { fn strict_decode(reader: &mut impl TypedRead) -> Result { let reserved = reader.read_tuple(|r| r.read_field().map(Self))?; - if reserved != ReservedBytes::::default() { + if reserved != ReservedBytes::::default() { Err(DecodeError::DataIntegrityError(format!( "unsupported reserved byte value indicating a future RGB version. Please \ update your software, or, if the problem persists, contact your vendor \ @@ -93,6 +102,53 @@ mod _reserved { } } } + + #[cfg(feature = "serde")] + mod _serde { + use std::fmt; + + use serde_crate::de::Visitor; + use serde_crate::{de, Deserialize, Deserializer, Serialize, Serializer}; + + use super::*; + + impl Serialize for ReservedBytes { + fn serialize(&self, serializer: S) -> Result + where S: Serializer { + // Doing nothing + serializer.serialize_unit() + } + } + + impl<'de, const LEN: usize, const VAL: u8> Deserialize<'de> for ReservedBytes { + fn deserialize(deserializer: D) -> Result + where D: Deserializer<'de> { + #[derive(Default)] + pub struct UntaggedUnitVisitor; + + impl<'de> Visitor<'de> for UntaggedUnitVisitor { + type Value = (); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "reserved unit") + } + + fn visit_none(self) -> Result<(), E> + where E: de::Error { + Ok(()) + } + + fn visit_unit(self) -> Result<(), E> + where E: de::Error { + Ok(()) + } + } + + deserializer.deserialize_unit(UntaggedUnitVisitor)?; + Ok(default!()) + } + } + } } /// Fast-forward version code