#2 Added IpAddr from u32 function. Finally ready to integrate it into subnet calculation

This commit is contained in:
Luke Else 2023-05-15 19:51:26 +01:00
parent 6a4573450c
commit 8c88d7945a

View File

@ -58,6 +58,25 @@ impl IpAddr {
}
}
impl From<IpAddr> 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<u32> for IpAddr {
/// Function that converts an Unsigned 32-bit Ip address
/// into an IpAddr
///
@ -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<IpAddr> 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));
}
}