Skip to content

Commit

Permalink
feat: impl Display for Prefix
Browse files Browse the repository at this point in the history
  • Loading branch information
b-zee committed Aug 5, 2022
1 parent 73123cb commit d42ba53
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions src/prefix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,14 @@ impl Debug for Prefix {
}
}

/// Format `Prefix` as bit string, e.g. `"010"` with a [`Prefix::bit_count`] of `3`.
impl Display for Prefix {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
// Use `Binary` impl from `XorName` with restricted width
write!(f, "{:width$b}", self.name, width = self.bit_count as usize)
}
}

#[derive(Debug)]
pub enum FromStrError {
InvalidChar(char),
Expand All @@ -296,11 +304,11 @@ impl Display for FromStrError {
write!(f, "expected `0` or `1`, but encountered `{}`", c)
}
FromStrError::TooLong(l) => {
write!(
write!(
f,
"max length exceeded {} with length of {l}",
XOR_NAME_LEN * 8
)
)
}
}
}
Expand Down Expand Up @@ -448,6 +456,16 @@ mod tests {
assert!(Prefix::from_str(&"1".repeat(XOR_NAME_LEN * 8 + 1)).is_err());
}

#[test]
fn format_parse_roundtrip() {
let format_parse_eq = |p| p == parse(&std::format!("{}", p));

assert!(format_parse_eq(Prefix::new(0, XorName([0xBB; 32]))));
assert!(format_parse_eq(Prefix::new(256, XorName([0x33; 32]))));
assert!(format_parse_eq(Prefix::new(5, XorName([0xAA; 32]))));
assert!(format_parse_eq(Prefix::new(76, XorName([0xAA; 32]))));
}

fn parse(input: &str) -> Prefix {
Prefix::from_str(input).unwrap()
}
Expand Down

0 comments on commit d42ba53

Please sign in to comment.