Added to_arr and from_arr methods to IpAddr
This commit is contained in:
@ -19,6 +19,45 @@ pub enum IpAddr {
|
||||
V6(String)
|
||||
}
|
||||
|
||||
impl IpAddr {
|
||||
/// Function that generates ar array of 4 octets / error
|
||||
/// from an IpAddr
|
||||
///
|
||||
/// # Limitation
|
||||
/// Currently only works for IPs of type IPv4
|
||||
/// # Example
|
||||
/// ```
|
||||
/// let ip: IpAddr = IpAddr::V4(127, 0, 0, 1);
|
||||
///
|
||||
/// let ip_add: [u8; 4] = ip.to_arr();
|
||||
/// /// ip_add = [127, 0, 0, 1]
|
||||
/// ```
|
||||
pub fn to_arr(&self) -> Result<[u8; 4], NetworkingErr> {
|
||||
match self {
|
||||
IpAddr::V4(o1, o2, o3, o4) => {
|
||||
Ok([*o1, *o2, *o3, *o4])
|
||||
}
|
||||
_ => Err(NetworkingErr::InvalidIPErr)
|
||||
}
|
||||
}
|
||||
|
||||
/// Function that generates a IpAddr / Err from an array of
|
||||
/// a octests
|
||||
///
|
||||
/// # Limitation
|
||||
/// Currently only works for IPs of type IPv4
|
||||
/// # Example
|
||||
/// ```
|
||||
/// let ip_add: [u8; 4] = [127, 0, 0, 1];
|
||||
///
|
||||
/// let ip: IpAddr = IpAddr::V4(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]))
|
||||
}
|
||||
}
|
||||
|
||||
impl ToString for IpAddr {
|
||||
/// Function that returns an IP address in string form
|
||||
fn to_string(&self) -> String {
|
||||
@ -29,7 +68,6 @@ impl ToString for IpAddr {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
impl FromStr for IpAddr {
|
||||
type Err = NetworkingErr;
|
||||
/// Function that generates a IpAddr / Err from a string
|
||||
@ -85,7 +123,6 @@ mod tests {
|
||||
/// correctly using the ToString trait
|
||||
fn ip_to_string() {
|
||||
use super::*;
|
||||
|
||||
let ip = IpAddr::V4(192, 168, 0, 1);
|
||||
assert_eq!(ip.to_string(), "192.168.0.1")
|
||||
}
|
||||
@ -109,4 +146,24 @@ mod tests {
|
||||
IpAddr::from_str(ip).unwrap();
|
||||
assert_eq!(IpAddr::from_str(ip), Err(NetworkingErr::InvalidIPErr))
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Tests the conversion of an IPv4 Address to
|
||||
/// an array
|
||||
fn ipaddr_to_arr() {
|
||||
use super::*;
|
||||
let mut ip_addr = IpAddr::V4(127, 0, 0, 1);
|
||||
assert_eq!(ip_addr.to_arr().unwrap(), [127, 0, 0, 1]);
|
||||
ip_addr = IpAddr::V6("::".to_string());
|
||||
assert_eq!(ip_addr.to_arr().unwrap_err(), NetworkingErr::InvalidIPErr);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Tests the conversion of an array to
|
||||
// an IPv4 Address
|
||||
fn arr_to_ipaddr() {
|
||||
use super::*;
|
||||
let mut ip_addr: [u8; 4] = [127, 0, 0, 1];
|
||||
assert_eq!(IpAddr::from_arr(&ip_addr).unwrap(), IpAddr::V4(127, 0, 0, 1));
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user