//! JSON codec marker and optional [`serde_json`] integration. //! //! The [`Json`] marker type is always available and can be used in type //! signatures without any feature flags. Enable the `serde_json` feature to //! get [`Encode`](super::Encode)/[`Decode`](super::Decode) implementations //! via [`serde_json`]. //! //! > **Note:** The `serde_json` feature requires `std`. /// JSON codec marker type. /// /// This type is always available regardless of feature flags, so you can /// reference it in type signatures from `no_std` crates. Enable the /// `serde_json` feature for [`Encode`](super::Encode)/[`Decode`](super::Decode) /// implementations. /// /// This codec does **not** implement [`Canonical`](super::Canonical) because /// JSON object key ordering is not guaranteed by `serde_json`. /// /// # Example /// /// ``` /// # #[cfg(all(feature = "serde_json", feature = "sha2"))] /// # { /// use evidence::digest::{Digest, sha2::Sha256}; /// use evidence::codec::json::Json; /// use serde::{Serialize, Deserialize}; /// /// #[derive(Serialize, Deserialize)] /// struct MyData { /// id: u32, /// name: String, /// } /// /// let data = MyData { id: 42, name: "test".into() }; /// let digest: Digest = Digest::hash(&data); /// # } /// ``` #[derive(Debug, Clone, Copy)] pub enum Json {} /// Error returned when JSON encoding fails. #[cfg(feature = "serde_json")] #[derive(Debug, Clone)] pub struct JsonEncodeError(alloc::string::String); #[cfg(feature = "serde_json")] impl core::fmt::Display for JsonEncodeError { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "JSON encode error: {}", self.0) } } #[cfg(feature = "serde_json")] impl super::Encode for Json { type Error = JsonEncodeError; fn encode(value: &T) -> Result, Self::Error> { serde_json::to_vec(value) .map_err(|e| JsonEncodeError(alloc::string::ToString::to_string(&e))) } } /// Error returned when JSON decoding fails. #[cfg(feature = "serde_json")] #[derive(Debug, Clone)] pub struct JsonDecodeError(alloc::string::String); #[cfg(feature = "serde_json")] impl core::fmt::Display for JsonDecodeError { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "JSON decode error: {}", self.0) } } #[cfg(feature = "serde_json")] impl super::Decode for Json { type Error = JsonDecodeError; fn decode(bytes: &[u8]) -> Result { serde_json::from_slice(bytes) .map_err(|e| JsonDecodeError(alloc::string::ToString::to_string(&e))) } }