Implement Display trait for ChainId and DidPkh

This commit is contained in:
silverpill 2022-11-22 22:41:23 +00:00
parent 241351c2bf
commit 3f3518001d
2 changed files with 13 additions and 10 deletions

View file

@ -1,5 +1,6 @@
/// https://github.com/w3c-ccg/did-pkh/blob/main/did-pkh-method-draft.md /// https://github.com/w3c-ccg/did-pkh/blob/main/did-pkh-method-draft.md
use std::convert::TryInto; use std::convert::TryInto;
use std::fmt;
use std::str::FromStr; use std::str::FromStr;
use regex::Regex; use regex::Regex;
@ -8,6 +9,9 @@ use crate::utils::caip2::ChainId;
use crate::utils::currencies::Currency; use crate::utils::currencies::Currency;
use super::did::DidParseError; use super::did::DidParseError;
// https://github.com/ChainAgnostic/CAIPs/blob/master/CAIPs/caip-10.md#syntax
const DID_PKH_RE: &str = r"did:pkh:(?P<network>[-a-z0-9]{3,8}):(?P<chain>[-a-zA-Z0-9]{1,32}):(?P<address>[a-zA-Z0-9]{1,64})";
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
pub struct DidPkh { pub struct DidPkh {
pub chain_id: ChainId, pub chain_id: ChainId,
@ -29,20 +33,18 @@ impl DidPkh {
} }
} }
impl ToString for DidPkh { impl fmt::Display for DidPkh {
fn to_string(&self) -> String { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
format!( let did_str = format!(
"did:pkh:{}:{}:{}", "did:pkh:{}:{}:{}",
self.chain_id.namespace, self.chain_id.namespace,
self.chain_id.reference, self.chain_id.reference,
self.address, self.address,
) );
write!(formatter, "{}", did_str)
} }
} }
// https://github.com/ChainAgnostic/CAIPs/blob/master/CAIPs/caip-10.md#syntax
const DID_PKH_RE: &str = r"did:pkh:(?P<network>[-a-z0-9]{3,8}):(?P<chain>[-a-zA-Z0-9]{1,32}):(?P<address>[a-zA-Z0-9]{1,64})";
impl FromStr for DidPkh { impl FromStr for DidPkh {
type Err = DidParseError; type Err = DidParseError;

View file

@ -1,4 +1,5 @@
/// https://github.com/ChainAgnostic/CAIPs/blob/master/CAIPs/caip-2.md /// https://github.com/ChainAgnostic/CAIPs/blob/master/CAIPs/caip-2.md
use std::fmt;
use std::str::FromStr; use std::str::FromStr;
use regex::Regex; use regex::Regex;
@ -59,9 +60,9 @@ impl FromStr for ChainId {
} }
} }
impl ToString for ChainId { impl fmt::Display for ChainId {
fn to_string(&self) -> String { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
format!("{}:{}", self.namespace, self.reference) write!(formatter, "{}:{}", self.namespace, self.reference)
} }
} }