Skip to content

Commit 0e142f0

Browse files
committed
reduced code repetition
1 parent c58e740 commit 0e142f0

File tree

1 file changed

+12
-11
lines changed

1 file changed

+12
-11
lines changed

primitives/src/channel.rs

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ use hex::{FromHex, FromHexError};
1515
#[serde(transparent)]
1616
pub struct ChannelId(
1717
#[serde(
18-
deserialize_with = "channel_id_from_str",
18+
deserialize_with = "deserialize_channel_id",
1919
serialize_with = "SerHex::<StrictPfx>::serialize"
2020
)]
2121
[u8; 32],
@@ -27,16 +27,21 @@ impl fmt::Debug for ChannelId {
2727
}
2828
}
2929

30-
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>
3131
where
3232
D: Deserializer<'de>,
3333
{
3434
let channel_id = String::deserialize(deserializer)?;
35-
if channel_id.is_empty() || channel_id.len() != 66 {
36-
return Err(serde::de::Error::custom("invalid channel id".to_string()));
37-
}
35+
let channel_id = validate_channel_id(channel_id).map_err(serde::de::Error::custom)?;
36+
<[u8; 32] as FromHex>::from_hex(channel_id).map_err(serde::de::Error::custom)
37+
}
3838

39-
<[u8; 32] as FromHex>::from_hex(&channel_id[2..]).map_err(serde::de::Error::custom)
39+
fn validate_channel_id(s: String) -> Result<String, FromHexError> {
40+
if s.is_empty() || s.len() != 66 || &s[0..2] != "0x" {
41+
Err(FromHexError::InvalidStringLength)
42+
} else {
43+
Ok(s[2..].into())
44+
}
4045
}
4146

4247
impl Deref for ChannelId {
@@ -79,11 +84,7 @@ impl FromStr for ChannelId {
7984
type Err = FromHexError;
8085

8186
fn from_str(s: &str) -> Result<Self, Self::Err> {
82-
if s.len() != 66 || &s[0..2] != "0x" {
83-
Err(FromHexError::InvalidStringLength)
84-
} else {
85-
Self::from_hex(&s[2..])
86-
}
87+
ChannelId::from_hex(validate_channel_id(s.into())?)
8788
}
8889
}
8990

0 commit comments

Comments
 (0)