diff --git a/src/networking/ip.rs b/src/networking/ip.rs index 65da01d..207e8cb 100644 --- a/src/networking/ip.rs +++ b/src/networking/ip.rs @@ -58,7 +58,26 @@ impl IpAddr { } } -/// Function that converts an Unsigned 32-bit Ip address +impl From for u32 { + /// Function that converts an Ip address + /// into an Unsigned 32 bit integer. + /// + /// # Limitation + /// Currently only works for IPs of type IPv4 + /// # Example + /// ``` + /// let ip: IpAddr = IpAddr::V4(127, 0, 0, 1); + /// + /// let ip_u32: u32 = u32::from(ip); + /// >>> ip_u32 = 2130706433; + /// ``` + fn from(ip: IpAddr) -> Self { + u32::from_be_bytes(ip.to_arr().unwrap()) + } +} + +impl From for IpAddr { + /// Function that converts an Unsigned 32-bit Ip address /// into an IpAddr /// /// # Limitation @@ -67,12 +86,11 @@ impl IpAddr { /// ``` /// let ip: u32 = 2_130_706_433; /// - /// let ip_u32: u32 = u32::from(ip); - /// ip_u32 = 2130706433; + /// let ip_addr: u32 = IpAddr::from(ip); + /// >>> ip_addr = IpAddr::V4(127, 0, 0, 1); /// ``` -impl From for u32 { - fn from(ip: IpAddr) -> Self { - u32::from_be_bytes(ip.to_arr().unwrap()) + fn from(ip: u32) -> Self { + IpAddr::from_arr(&(ip.to_be_bytes() as [u8; 4])).unwrap() } } @@ -202,4 +220,23 @@ mod tests { let ip = IpAddr::V4(255, 255, 255, 255); assert_eq!(u32::MAX, u32::from(ip)); } + + #[test] + /// Tests the conversion of an u32 IPv4 Address to + /// an IpAddr + fn u32_to_ipaddr() + { + use super::*; + let ip = u32::from(IpAddr::V4(0, 0, 0, 0)); + assert_eq!(IpAddr::V4(0, 0, 0, 0), IpAddr::from(ip)); + + let ip = u32::from(IpAddr::V4(127, 0, 0, 1)); + assert_eq!(IpAddr::V4(127, 0, 0, 1), IpAddr::from(ip)); + + let ip = u32::from(IpAddr::V4(10, 10, 10, 0)); + assert_eq!(IpAddr::V4(10, 10, 10, 0), IpAddr::from(ip)); + + let ip = u32::from(IpAddr::V4(255, 255, 255, 255)); + assert_eq!(IpAddr::V4(255, 255, 255, 255), IpAddr::from(ip)); + } } \ No newline at end of file