Skip to content

Commit

Permalink
Make IpNetwork::mask const (#207)
Browse files Browse the repository at this point in the history
* Make `Ipv4Network::mask` const

* Make `Ipv6Network::mask` const

* Make `IpNetwork::mask` const
  • Loading branch information
MarkusPettersson98 authored Jan 8, 2025
1 parent c2812a9 commit 9ae7196
Show file tree
Hide file tree
Showing 3 changed files with 5 additions and 5 deletions.
4 changes: 2 additions & 2 deletions src/ipv4.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,13 +180,13 @@ impl Ipv4Network {
/// let net: Ipv4Network = "127.0.0.0/16".parse().unwrap();
/// assert_eq!(net.mask(), Ipv4Addr::new(255, 255, 0, 0));
/// ```
pub fn mask(&self) -> Ipv4Addr {
pub const fn mask(&self) -> Ipv4Addr {
debug_assert!(self.prefix <= 32);
if self.prefix == 0 {
return Ipv4Addr::new(0, 0, 0, 0);
}
let mask = u32::MAX << (IPV4_BITS - self.prefix);
Ipv4Addr::from(mask)
Ipv4Addr::from_bits(mask)
}

/// Returns the address of the network denoted by this `Ipv4Network`.
Expand Down
4 changes: 2 additions & 2 deletions src/ipv6.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,14 +200,14 @@ impl Ipv6Network {
/// let net: Ipv6Network = "ff01::0/32".parse().unwrap();
/// assert_eq!(net.mask(), Ipv6Addr::new(0xffff, 0xffff, 0, 0, 0, 0, 0, 0));
/// ```
pub fn mask(&self) -> Ipv6Addr {
pub const fn mask(&self) -> Ipv6Addr {
debug_assert!(self.prefix <= IPV6_BITS);

if self.prefix == 0 {
return Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0);
}
let mask = u128::MAX << (IPV6_BITS - self.prefix);
Ipv6Addr::from(mask)
Ipv6Addr::from_bits(mask)
}

/// Returns the address of the network denoted by this `Ipv6Network`.
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ impl IpNetwork {
/// let v6_net: IpNetwork = "ff01::0/32".parse().unwrap();
/// assert_eq!(v6_net.mask(), Ipv6Addr::new(0xffff, 0xffff, 0, 0, 0, 0, 0, 0));
/// ```
pub fn mask(&self) -> IpAddr {
pub const fn mask(&self) -> IpAddr {
match *self {
IpNetwork::V4(ref a) => IpAddr::V4(a.mask()),
IpNetwork::V6(ref a) => IpAddr::V6(a.mask()),
Expand Down

0 comments on commit 9ae7196

Please sign in to comment.