Skip to content

Commit 8c6b696

Browse files
authored
Implement human-readable serialization of Owner (#2722)
Use its `Display` implementation when serializing to human-readable formats.
1 parent b9b94c5 commit 8c6b696

File tree

1 file changed

+46
-16
lines changed

1 file changed

+46
-16
lines changed

linera-base/src/identifiers.rs

+46-16
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
//! Core identifiers used by the Linera protocol.
55
66
use std::{
7-
fmt::{self, Debug, Display},
7+
fmt::{self, Debug, Display, Formatter},
88
hash::{Hash, Hasher},
99
marker::PhantomData,
1010
str::FromStr,
@@ -24,21 +24,7 @@ use crate::{
2424

2525
/// The owner of a chain. This is currently the hash of the owner's public key used to
2626
/// verify signatures.
27-
#[derive(
28-
Eq,
29-
PartialEq,
30-
Ord,
31-
PartialOrd,
32-
Copy,
33-
Clone,
34-
Hash,
35-
Debug,
36-
Serialize,
37-
Deserialize,
38-
WitLoad,
39-
WitStore,
40-
WitType,
41-
)]
27+
#[derive(Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Hash, Debug, WitLoad, WitStore, WitType)]
4228
#[cfg_attr(with_testing, derive(Default, test_strategy::Arbitrary))]
4329
pub struct Owner(pub CryptoHash);
4430

@@ -859,6 +845,50 @@ impl std::str::FromStr for Owner {
859845
}
860846
}
861847

848+
impl Serialize for Owner {
849+
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
850+
where
851+
S: Serializer,
852+
{
853+
if serializer.is_human_readable() {
854+
serializer.serialize_str(&self.to_string())
855+
} else {
856+
serializer.serialize_newtype_struct("Owner", &self.0)
857+
}
858+
}
859+
}
860+
861+
impl<'de> Deserialize<'de> for Owner {
862+
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
863+
where
864+
D: Deserializer<'de>,
865+
{
866+
if deserializer.is_human_readable() {
867+
let string = String::deserialize(deserializer)?;
868+
Self::from_str(&string).map_err(serde::de::Error::custom)
869+
} else {
870+
deserializer.deserialize_newtype_struct("Owner", OwnerVisitor)
871+
}
872+
}
873+
}
874+
875+
struct OwnerVisitor;
876+
877+
impl<'de> serde::de::Visitor<'de> for OwnerVisitor {
878+
type Value = Owner;
879+
880+
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
881+
write!(formatter, "an owner represented as a `CryptoHash`")
882+
}
883+
884+
fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
885+
where
886+
D: Deserializer<'de>,
887+
{
888+
Ok(Owner(CryptoHash::deserialize(deserializer)?))
889+
}
890+
}
891+
862892
#[derive(Serialize, Deserialize)]
863893
#[serde(rename = "AccountOwner")]
864894
enum SerializableAccountOwner {

0 commit comments

Comments
 (0)