Skip to content

Commit

Permalink
Implement human-readable serialization of Owner
Browse files Browse the repository at this point in the history
Use its `Display` implementation when serializing to human-readable
formats.
  • Loading branch information
jvff committed Oct 26, 2024
1 parent a0003ce commit 4b7fb68
Showing 1 changed file with 46 additions and 16 deletions.
62 changes: 46 additions & 16 deletions linera-base/src/identifiers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
//! Core identifiers used by the Linera protocol.

use std::{
fmt::{self, Debug, Display},
fmt::{self, Debug, Display, Formatter},
hash::{Hash, Hasher},
marker::PhantomData,
str::FromStr,
Expand All @@ -24,21 +24,7 @@ use crate::{

/// The owner of a chain. This is currently the hash of the owner's public key used to
/// verify signatures.
#[derive(
Eq,
PartialEq,
Ord,
PartialOrd,
Copy,
Clone,
Hash,
Debug,
Serialize,
Deserialize,
WitLoad,
WitStore,
WitType,
)]
#[derive(Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Hash, Debug, WitLoad, WitStore, WitType)]
#[cfg_attr(with_testing, derive(Default, test_strategy::Arbitrary))]
pub struct Owner(pub CryptoHash);

Expand Down Expand Up @@ -859,6 +845,50 @@ impl std::str::FromStr for Owner {
}
}

impl Serialize for Owner {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if serializer.is_human_readable() {
serializer.serialize_str(&self.to_string())
} else {
serializer.serialize_newtype_struct("Owner", &self.0)
}
}
}

impl<'de> Deserialize<'de> for Owner {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
if deserializer.is_human_readable() {
let string = String::deserialize(deserializer)?;
Self::from_str(&string).map_err(serde::de::Error::custom)
} else {
deserializer.deserialize_newtype_struct("Owner", OwnerVisitor)
}
}
}

struct OwnerVisitor;

impl<'de> serde::de::Visitor<'de> for OwnerVisitor {
type Value = Owner;

fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
write!(formatter, "an owner represented as a `CryptoHash`")
}

fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
Ok(Owner(CryptoHash::deserialize(deserializer)?))
}
}

#[derive(Serialize, Deserialize)]
#[serde(rename = "AccountOwner")]
enum SerializableAccountOwner {
Expand Down

0 comments on commit 4b7fb68

Please sign in to comment.