mirror of
https://github.com/achanda/ipnetwork.git
synced 2025-06-19 02:04:58 +00:00
ipnetwork: add netmask constructors
This adds constructors to build all network types from a network address and network mask pair.
This commit is contained in:
32
src/ipv6.rs
32
src/ipv6.rs
@ -33,6 +33,7 @@ impl Serialize for Ipv6Network {
|
||||
|
||||
impl Ipv6Network {
|
||||
/// Constructs a new `Ipv6Network` from any `Ipv6Addr` and a prefix denoting the network size.
|
||||
///
|
||||
/// If the prefix is larger than 128 this will return an `IpNetworkError::InvalidPrefix`.
|
||||
pub fn new(addr: Ipv6Addr, prefix: u8) -> Result<Ipv6Network, IpNetworkError> {
|
||||
if prefix > IPV6_BITS {
|
||||
@ -42,6 +43,18 @@ impl Ipv6Network {
|
||||
}
|
||||
}
|
||||
|
||||
/// Constructs a new `Ipv6Network` from a network address and a network mask.
|
||||
///
|
||||
/// If the netmask is not valid this will return an `IpNetworkError::InvalidPrefix`.
|
||||
pub fn with_netmask(netaddr: Ipv6Addr, netmask: Ipv6Addr) -> Result<Self, IpNetworkError> {
|
||||
let prefix = ipv6_mask_to_prefix(netmask)?;
|
||||
let net = Self {
|
||||
addr: netaddr,
|
||||
prefix,
|
||||
};
|
||||
Ok(net)
|
||||
}
|
||||
|
||||
/// Returns an iterator over `Ipv6Network`. Each call to `next` will return the next
|
||||
/// `Ipv6Addr` in the given network. `None` will be returned when there are no more
|
||||
/// addresses.
|
||||
@ -366,6 +379,25 @@ mod test {
|
||||
assert!(prefix.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ipv6network_with_netmask() {
|
||||
{
|
||||
// Positive test-case.
|
||||
let addr = Ipv6Addr::new(0xff01, 0, 0, 0x17, 0, 0, 0, 0x2);
|
||||
let mask = Ipv6Addr::new(0xffff, 0xffff, 0xffff, 0, 0, 0, 0, 0);
|
||||
let net = Ipv6Network::with_netmask(addr, mask).unwrap();
|
||||
let expected =
|
||||
Ipv6Network::new(Ipv6Addr::new(0xff01, 0, 0, 0x17, 0, 0, 0, 0x2), 48).unwrap();
|
||||
assert_eq!(net, expected);
|
||||
}
|
||||
{
|
||||
// Negative test-case.
|
||||
let addr = Ipv6Addr::new(0xff01, 0, 0, 0x17, 0, 0, 0, 0x2);
|
||||
let mask = Ipv6Addr::new(0, 0, 0xffff, 0xffff, 0, 0, 0, 0);
|
||||
Ipv6Network::with_netmask(addr, mask).unwrap_err();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iterator_v6() {
|
||||
let cidr: Ipv6Network = "2001:db8::/126".parse().unwrap();
|
||||
|
Reference in New Issue
Block a user