Skip to content

Commit 075819b

Browse files
authored
Merge pull request #344 from AdExNetwork/issue-343-fromstr-for-channelid
closes #343 - FromStr implemented for ChannelId
2 parents 38ccf66 + c2f1b5f commit 075819b

File tree

1 file changed

+24
-6
lines changed

1 file changed

+24
-6
lines changed

primitives/src/channel.rs

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use std::error::Error;
22
use std::fmt;
33
use std::ops::Deref;
4+
use std::str::FromStr;
45

56
use chrono::serde::{ts_milliseconds, ts_milliseconds_option, ts_seconds};
67
use chrono::{DateTime, Utc};
@@ -14,7 +15,7 @@ use hex::{FromHex, FromHexError};
1415
#[serde(transparent)]
1516
pub struct ChannelId(
1617
#[serde(
17-
deserialize_with = "channel_id_from_str",
18+
deserialize_with = "deserialize_channel_id",
1819
serialize_with = "SerHex::<StrictPfx>::serialize"
1920
)]
2021
[u8; 32],
@@ -26,16 +27,25 @@ impl fmt::Debug for ChannelId {
2627
}
2728
}
2829

29-
fn channel_id_from_str<'de, D>(deserializer: D) -> Result<[u8; 32], D::Error>
30+
fn deserialize_channel_id<'de, D>(deserializer: D) -> Result<[u8; 32], D::Error>
3031
where
3132
D: Deserializer<'de>,
3233
{
3334
let channel_id = String::deserialize(deserializer)?;
34-
if channel_id.is_empty() || channel_id.len() != 66 {
35-
return Err(serde::de::Error::custom("invalid channel id".to_string()));
36-
}
35+
validate_channel_id(&channel_id).map_err(serde::de::Error::custom)
36+
}
3737

38-
<[u8; 32] as FromHex>::from_hex(&channel_id[2..]).map_err(serde::de::Error::custom)
38+
fn validate_channel_id(s: &str) -> Result<[u8; 32], FromHexError> {
39+
match (s.get(0..2), s.get(2..)) {
40+
(Some(prefix), Some(hex)) => {
41+
if hex.len() != 64 || prefix != "0x" {
42+
Err(FromHexError::InvalidStringLength)
43+
} else {
44+
Ok(<[u8; 32] as FromHex>::from_hex(s)?)
45+
}
46+
}
47+
_ => Err(FromHexError::InvalidStringLength),
48+
}
3949
}
4050

4151
impl Deref for ChannelId {
@@ -74,6 +84,14 @@ impl fmt::Display for ChannelId {
7484
}
7585
}
7686

87+
impl FromStr for ChannelId {
88+
type Err = FromHexError;
89+
90+
fn from_str(s: &str) -> Result<Self, Self::Err> {
91+
ChannelId::from_hex(validate_channel_id(s)?)
92+
}
93+
}
94+
7795
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
7896
#[serde(rename_all = "camelCase")]
7997
pub struct Channel {

0 commit comments

Comments
 (0)