Skip to content

Commit

Permalink
wire: move prefix_len impl down to v4 and v6 addrs.
Browse files Browse the repository at this point in the history
  • Loading branch information
Dirbaio committed Sep 20, 2024
1 parent 34d1dd4 commit 0341cc9
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 20 deletions.
25 changes: 5 additions & 20 deletions src/wire/ip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,27 +180,12 @@ impl Address {
/// If `self` is a CIDR-compatible subnet mask, return `Some(prefix_len)`,
/// where `prefix_len` is the number of leading zeroes. Return `None` otherwise.
pub fn prefix_len(&self) -> Option<u8> {
let mut ones = true;
let mut prefix_len = 0;
for byte in self.as_bytes() {
let mut mask = 0x80;
for _ in 0..8 {
let one = *byte & mask != 0;
if ones {
// Expect 1s until first 0
if one {
prefix_len += 1;
} else {
ones = false;
}
} else if one {
// 1 where 0 was expected
return None;
}
mask >>= 1;
}
match self {
#[cfg(feature = "proto-ipv4")]
Address::Ipv4(addr) => addr.prefix_len(),
#[cfg(feature = "proto-ipv6")]
Address::Ipv6(addr) => addr.prefix_len(),
}
Some(prefix_len)
}
}

Expand Down
26 changes: 26 additions & 0 deletions src/wire/ipv4.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,32 @@ impl Address {
pub const fn into_address(self) -> super::IpAddress {
super::IpAddress::Ipv4(self)
}

/// If `self` is a CIDR-compatible subnet mask, return `Some(prefix_len)`,
/// where `prefix_len` is the number of leading zeroes. Return `None` otherwise.
pub fn prefix_len(&self) -> Option<u8> {
let mut ones = true;
let mut prefix_len = 0;
for byte in self.as_bytes() {
let mut mask = 0x80;
for _ in 0..8 {
let one = *byte & mask != 0;
if ones {
// Expect 1s until first 0
if one {
prefix_len += 1;
} else {
ones = false;
}
} else if one {
// 1 where 0 was expected
return None;
}
mask >>= 1;
}
}
Some(prefix_len)
}
}

impl From<::core::net::Ipv4Addr> for Address {
Expand Down
26 changes: 26 additions & 0 deletions src/wire/ipv6.rs
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,32 @@ impl Address {
pub const fn into_address(self) -> super::IpAddress {
super::IpAddress::Ipv6(self)
}

/// If `self` is a CIDR-compatible subnet mask, return `Some(prefix_len)`,
/// where `prefix_len` is the number of leading zeroes. Return `None` otherwise.
pub fn prefix_len(&self) -> Option<u8> {
let mut ones = true;
let mut prefix_len = 0;
for byte in self.as_bytes() {
let mut mask = 0x80;
for _ in 0..8 {
let one = *byte & mask != 0;
if ones {
// Expect 1s until first 0
if one {
prefix_len += 1;
} else {
ones = false;
}
} else if one {
// 1 where 0 was expected
return None;
}
mask >>= 1;
}
}
Some(prefix_len)
}
}

impl From<::core::net::Ipv6Addr> for Address {
Expand Down

0 comments on commit 0341cc9

Please sign in to comment.