Repository: achanda/ipnetwork (language: rust)

Issue:
Parsing from ip/mask string
Currently the Ipv4Network can be parsed from `ip/prefix` representation (eg. `192.168.2.1/24`), but the older `ip/mask` (`192.168.2.1/255.255.255.0`) is rejected. Would it make sense to add such support too?


Discussion / hints:
Sure, sounds good. The only reason it was not added is no one requested it :)
OK, I'll put it into my queue to send it it. It might happen in a week or two, hopefully.
Thanks @vorner!

Fix patch:
diff --git a/src/ipv4.rs b/src/ipv4.rs
index f873d8e..eb81a5d 100644
--- a/src/ipv4.rs
+++ b/src/ipv4.rs
@@ -238,7 +238,13 @@ impl FromStr for Ipv4Network {
         let addr = Ipv4Addr::from_str(addr_str)
             .map_err(|_| IpNetworkError::InvalidAddr(addr_str.to_string()))?;
         let prefix = match prefix_str {
-            Some(v) => parse_prefix(v, IPV4_BITS)?,
+            Some(v) => {
+                if let Ok(netmask) = Ipv4Addr::from_str(v) {
+                    ipv4_mask_to_prefix(netmask)?
+                } else {
+                    parse_prefix(v, IPV4_BITS)?
+                }
+            },
             None => IPV4_BITS,
         };
         Ipv4Network::new(addr, prefix)
@@ -469,6 +475,19 @@ mod test {
         assert_eq!(prefix, 25);
     }
 
+    /// Parse netmask as well as prefix
+    #[test]
+    fn parse_netmask() {
+        let from_netmask: Ipv4Network = "192.168.1.0/255.255.255.0".parse().unwrap();
+        let from_prefix: Ipv4Network = "192.168.1.0/24".parse().unwrap();
+        assert_eq!(from_netmask, from_prefix);
+    }
+
+    #[test]
+    fn parse_netmask_broken() {
+        "192.168.1.0/255.0.255.0".parse::<Ipv4Network>().unwrap_err();
+    }
+
     #[test]
     fn invalid_v4_mask_to_prefix() {
         let mask = Ipv4Addr::new(255, 0, 255, 0);


Test patch: