Skip to content

Commit

Permalink
Add Ipv6Network::nth to get the nth address (take two) (#176)
Browse files Browse the repository at this point in the history
* Add `Ipv6Network::nth` to get the nth address

Works the same as `Ipv4Network::nth`, but using a `u128` index instead
of `u32`.

* add IpNetwork v6 nth test

---------

Co-authored-by: Josh Triplett <josh@joshtriplett.org>
  • Loading branch information
ctrlcctrlv and joshtriplett committed Jun 14, 2023
1 parent d19ac33 commit 1bd937e
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions src/ipv6.rs
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,30 @@ impl Ipv6Network {
let host_bits = u32::from(IPV6_BITS - self.prefix);
2u128.pow(host_bits)
}

/// Returns the `n`:th address within this network.
/// The adresses are indexed from 0 and `n` must be smaller than the size of the network.
///
/// # Examples
///
/// ```
/// use std::net::Ipv6Addr;
/// use ipnetwork::Ipv6Network;
///
/// let net: Ipv6Network = "ff01::0/32".parse().unwrap();
/// assert_eq!(net.nth(0).unwrap(), "ff01::0".parse::<Ipv6Addr>().unwrap());
/// assert_eq!(net.nth(255).unwrap(), "ff01::ff".parse::<Ipv6Addr>().unwrap());
/// assert_eq!(net.nth(65538).unwrap(), "ff01::1:2".parse::<Ipv6Addr>().unwrap());
/// assert!(net.nth(net.size()).is_none());
/// ```
pub fn nth(self, n: u128) -> Option<Ipv6Addr> {
if n < self.size() {
let net = u128::from(self.network());
Some(Ipv6Addr::from(net + n))
} else {
None
}
}
}

/// Creates an `Ipv6Network` from parsing a string in CIDR notation.
Expand Down Expand Up @@ -670,4 +694,26 @@ mod test {
let high_addrs: Vec<Ipv6Addr> = high.iter().collect();
assert_eq!(256, high_addrs.len());
}

#[test]
fn test_nth_ipv6() {
let net = Ipv6Network::from_str("ff01::/32").unwrap();

assert_eq!(
net.nth(0).unwrap(),
Ipv6Addr::from_str("ff01:0:0:0:0:0:0:0").unwrap()
);
assert_eq!(
net.nth(255).unwrap(),
Ipv6Addr::from_str("ff01::ff").unwrap()
);
assert_eq!(
net.nth(65538).unwrap(),
Ipv6Addr::from_str("ff01::1:2").unwrap()
);
assert_eq!(
net.nth(net.size()),
None
);
}
}

0 comments on commit 1bd937e

Please sign in to comment.