#2 Made IpAddr to u32 function more efficient by using big endian functions built into rust

This commit is contained in:
Luke Else 2023-05-15 19:35:07 +01:00
parent 4ace257932
commit 6a4573450c

View File

@ -30,7 +30,7 @@ impl IpAddr {
/// let ip: IpAddr = IpAddr::V4(127, 0, 0, 1);
///
/// let ip_add: [u8; 4] = ip.to_arr();
/// /// ip_add = [127, 0, 0, 1]
/// >>> ip_add = [127, 0, 0, 1]
/// ```
pub fn to_arr(&self) -> Result<[u8; 4], NetworkingErr> {
match self {
@ -51,31 +51,28 @@ impl IpAddr {
/// let ip_add: [u8; 4] = [127, 0, 0, 1];
///
/// let ip: IpAddr = IpAddr::V4(127, 0, 0, 1);
/// /// ip_add = [127, 0, 0, 1]
/// >>> ip_add = [127, 0, 0, 1]
/// ```
pub fn from_arr(arr: &[u8; 4]) -> Result<IpAddr, NetworkingErr> {
Ok(IpAddr::V4(arr[0], arr[1], arr[2], arr[3]))
}
}
/// Function that converts an IPv4 Address into an unsigned
/// 32-bit integer.
/// Function that converts an Unsigned 32-bit Ip address
/// into an IpAddr
///
/// # Limitation
/// Currently only works for IPs of type IPv4
/// # Example
/// ```
/// let ip: IpAddr = IpAddr::V4(127, 0, 0, 1);
/// let ip: u32 = 2_130_706_433;
///
/// let ip_u32: u32 = ip.to_u32();
/// let ip_u32: u32 = u32::from(ip);
/// ip_u32 = 2130706433;
/// ```
pub fn to_u32(&self) -> Result<u32, NetworkingErr> {
let mut ip: u32 = 0;
let ip_addr = self.to_arr()?;
for (i, oct) in ip_addr.iter().enumerate() {
ip += (*oct as u32) * u32::pow(2, (ip_addr.len() as u32 - (i as u32 + 1)) * 8);
}
Ok(ip)
impl From<IpAddr> for u32 {
fn from(ip: IpAddr) -> Self {
u32::from_be_bytes(ip.to_arr().unwrap())
}
}
@ -194,15 +191,15 @@ mod tests {
fn ipaddr_to_u32() {
use super::*;
let ip = IpAddr::V4(0, 0, 0, 0);
assert_eq!(0, ip.to_u32().unwrap());
assert_eq!(0, u32::from(ip));
let ip = IpAddr::V4(127, 0, 0, 1);
assert_eq!(2_130_706_433, ip.to_u32().unwrap());
assert_eq!(2_130_706_433, u32::from(ip));
let ip = IpAddr::V4(10, 10, 10, 0);
assert_eq!(168_430_080, ip.to_u32().unwrap());
assert_eq!(168_430_080, u32::from(ip));
let ip = IpAddr::V4(255, 255, 255, 255);
assert_eq!(u32::MAX, ip.to_u32().unwrap());
assert_eq!(u32::MAX, u32::from(ip));
}
}