From 1171e5ae94a84c0c174b1ddae903c86fd371c90f Mon Sep 17 00:00:00 2001 From: Abhishek Chanda Date: Tue, 11 Jul 2017 21:01:41 +0100 Subject: [PATCH] Add a network method for Ipv6Network --- Cargo.toml | 1 + src/ipv6.rs | 27 +++++++++++++++++++++++++++ src/lib.rs | 1 + 3 files changed, 29 insertions(+) diff --git a/Cargo.toml b/Cargo.toml index 6860ab7..5807c7e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,3 +17,4 @@ clippy = {version = "0.0.104", optional = true} default = [] dev = ["clippy"] ipv6-iterator = [] +ipv6-methods = [] diff --git a/src/ipv6.rs b/src/ipv6.rs index 5b08519..f421f5e 100644 --- a/src/ipv6.rs +++ b/src/ipv6.rs @@ -52,6 +52,25 @@ impl Ipv6Network { } + /// Returns the address of the network denoted by this `Ipv6Network`. + /// This means the lowest possible IPv6 address inside of the network. + /// + /// # Examples + /// + /// ``` + /// use std::net::Ipv6Addr; + /// use ipnetwork::Ipv6Network; + /// + /// let net: Ipv6Network = "2001:db8::/96".parse().unwrap(); + /// assert_eq!(net.network(), Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)); + /// ``` + #[cfg(feature = "ipv6-methods")] + pub fn network(&self) -> Ipv6Addr { + let mask = u128::from(self.mask()); + let ip = u128::from(self.addr) & mask; + Ipv6Addr::from(ip) + } + pub fn ip(&self) -> Ipv6Addr { self.addr } @@ -290,4 +309,12 @@ mod test { assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 2), iter.next().unwrap()); } + #[test] + #[cfg(feature = "ipv6-methods")] + fn network_v6() { + let cidr: Ipv6Network = "2001:db8::0/96".parse().unwrap(); + let net = cidr.network(); + let expected: Ipv6Addr = "2001:db8::".parse().unwrap(); + assert_eq!(net, expected); + } } diff --git a/src/lib.rs b/src/lib.rs index 5758984..6cd0ef0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,6 +4,7 @@ #![cfg_attr(feature = "dev", feature(plugin))] #![cfg_attr(feature = "dev", plugin(clippy))] #![cfg_attr(feature = "ipv6-iterator", feature(i128_type))] +#![cfg_attr(feature = "ipv6-methods", feature(i128_type))] #![crate_type = "lib"] use std::fmt;