diff --git a/src/common.rs b/src/common.rs index 1180073..c34a977 100644 --- a/src/common.rs +++ b/src/common.rs @@ -1,6 +1,5 @@ use std::error::Error; use std::fmt; -use std::net::Ipv4Addr; /// Represents a bunch of errors that can occur while working with a `IpNetwork` #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/src/ipv4.rs b/src/ipv4.rs index 79c5218..67f49d7 100644 --- a/src/ipv4.rs +++ b/src/ipv4.rs @@ -49,7 +49,7 @@ impl Ipv4Network { /// `Ipv4Addr` in the given network. `None` will be returned when there are no more /// addresses. pub fn iter(&self) -> Ipv4NetworkIterator { - let start = u64::from(u32::from(self.network())); + let start = u32::from(self.network()); let end = start + self.size(); Ipv4NetworkIterator { next: start, end } } @@ -150,9 +150,9 @@ impl Ipv4Network { /// let tinynet: Ipv4Network = "0.0.0.0/32".parse().unwrap(); /// assert_eq!(tinynet.size(), 1); /// ``` - pub fn size(&self) -> u64 { + pub fn size(&self) -> u32 { let host_bits = u32::from(IPV4_BITS - self.prefix); - (2 as u64).pow(host_bits) + (2 as u32).pow(host_bits) } /// Returns the `n`:th address within this network. @@ -173,7 +173,7 @@ impl Ipv4Network { /// assert_eq!(net2.nth(256).unwrap(), Ipv4Addr::new(10, 0, 1, 0)); /// ``` pub fn nth(&self, n: u32) -> Option { - if u64::from(n) < self.size() { + if n < self.size() { let net = u32::from(self.network()); Some(Ipv4Addr::from(net + n)) } else { @@ -225,8 +225,8 @@ impl From for Ipv4Network { } pub struct Ipv4NetworkIterator { - next: u64, - end: u64, + next: u32, + end: u32, } impl Iterator for Ipv4NetworkIterator { diff --git a/src/lib.rs b/src/lib.rs index b83e63b..3d1a348 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -32,6 +32,14 @@ pub enum IpNetwork { V6(Ipv6Network), } + +/// Represents a generic network size. For IPv4, the max size is a u32 and for IPv6, it is a u128 +#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)] +pub enum NetworkSize { + V4(u32), + V6(u128), +} + impl IpNetwork { /// Constructs a new `IpNetwork` from a given `IpAddr` and a prefix denoting the /// network size. If the prefix is larger than 32 (for IPv4) or 128 (for IPv6), this @@ -198,6 +206,25 @@ impl IpNetwork { _ => false, } } + + + /// Returns the number of possible host addresses in this `IpAddr` + /// + /// # Examples + /// + /// ``` + /// use ipnetwork::{IpNetwork, NetworkSize}; + /// + /// + /// let net: IpNetwork = "127.0.0.0/24".parse().unwrap(); + /// assert_eq!(net.size(), NetworkSize::V4(256)) + /// ``` + pub fn size(&self) -> NetworkSize { + match *self { + IpNetwork::V4(ref ip) => NetworkSize::V4(ip.size()), + IpNetwork::V6(ref ip) => NetworkSize::V6(ip.size()), + } + } } /// Tries to parse the given string into a `IpNetwork`. Will first try to parse