1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
use super::NetAddr; use crate::traits::Contains; impl Contains for NetAddr { fn contains<T: Copy>(&self, other: &T) -> bool where Self: From<T>, { let other: Self = Self::from(*other); match (self, other) { (Self::V4(netaddr), Self::V4(other)) => netaddr.contains(&other), (Self::V6(netaddr), Self::V6(other)) => netaddr.contains(&other), (_, _) => false, } } } #[cfg(test)] mod tests { use super::*; use crate::NetAddr; use std::net::IpAddr; mod v4 { use super::*; use std::net::Ipv4Addr; #[test] fn ip() { let net: NetAddr = "127.0.0.1/8".parse().unwrap(); assert!(net.contains(&IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)))); assert!(net.contains(&IpAddr::V4(Ipv4Addr::new(127, 127, 255, 1)))); assert!(!net.contains(&IpAddr::V4(Ipv4Addr::new(64, 0, 0, 0)))); } #[test] fn net() { let net: NetAddr = "127.0.0.1/8".parse().unwrap(); let net_inner: NetAddr = "127.128.0.1/24".parse().unwrap(); assert!(net.contains(&net_inner)); } #[test] fn v6_ip() { let net: NetAddr = "127.0.0.1/8".parse().unwrap(); let ip: IpAddr = "2001:db8:d00b::1".parse().unwrap(); assert!(!net.contains(&ip)); } #[test] fn v6_net() { let a: NetAddr = "127.0.0.1/8".parse().unwrap(); let b: NetAddr = "2001:db8:d0::/48".parse().unwrap(); assert!(!a.contains(&b)); } } mod v6 { use super::*; use std::net::Ipv6Addr; #[test] fn ip() { let net: NetAddr = "2001:db8:d00b::/48".parse().unwrap(); assert!(net.contains(&IpAddr::V6(Ipv6Addr::new( 0x2001, 0x0db8, 0xd00b, 0, 0, 0, 0, 0x0001 )))); assert!(net.contains(&IpAddr::V6(Ipv6Addr::new( 0x2001, 0x0db8, 0xd00b, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff )))); assert!(!net.contains(&IpAddr::V6(Ipv6Addr::new( 0x2001, 0x0db8, 0xd00c, 0, 0, 0, 0, 1 )))); } #[test] fn net() { let net: NetAddr = "2001:db8:d000::/40".parse().unwrap(); let net_inner: NetAddr = "2001:db8:d00b::/48".parse().unwrap(); assert!(net.contains(&net_inner)); } #[test] fn v4_ip() { let net: NetAddr = "2001:db8:d000::/40".parse().unwrap(); let ip: IpAddr = "127.0.0.1".parse().unwrap(); assert!(!net.contains(&ip)); } #[test] fn v4_net() { let a: NetAddr = "2001:db8:d0::/48".parse().unwrap(); let b: NetAddr = "127.0.0.1/8".parse().unwrap(); assert!(!a.contains(&b)); } } }