#2 Added new function to convert an IPv4 Address to an Unsigned 32-bit interger. Also did some small bits of code cleanup
This commit is contained in:
@ -56,6 +56,27 @@ impl IpAddr {
|
||||
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.
|
||||
///
|
||||
/// # Limitation
|
||||
/// Currently only works for IPs of type IPv4
|
||||
/// # Example
|
||||
/// ```
|
||||
/// let ip: IpAddr = IpAddr::V4(127, 0, 0, 1);
|
||||
///
|
||||
/// let ip_u32: u32 = ip.to_u32();
|
||||
/// 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 ToString for IpAddr {
|
||||
@ -166,4 +187,22 @@ mod tests {
|
||||
let ip_addr: [u8; 4] = [127, 0, 0, 1];
|
||||
assert_eq!(IpAddr::from_arr(&ip_addr).unwrap(), IpAddr::V4(127, 0, 0, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Tests the conversion of an IPv4 Address to
|
||||
/// an unsigned 32-bit integer
|
||||
fn ipaddr_to_u32() {
|
||||
use super::*;
|
||||
let ip = IpAddr::V4(0, 0, 0, 0);
|
||||
assert_eq!(0, ip.to_u32().unwrap());
|
||||
|
||||
let ip = IpAddr::V4(127, 0, 0, 1);
|
||||
assert_eq!(2_130_706_433, ip.to_u32().unwrap());
|
||||
|
||||
let ip = IpAddr::V4(10, 10, 10, 0);
|
||||
assert_eq!(168_430_080, ip.to_u32().unwrap());
|
||||
|
||||
let ip = IpAddr::V4(255, 255, 255, 255);
|
||||
assert_eq!(u32::MAX, ip.to_u32().unwrap());
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user