Completed implementation of FromString for IpAddr

This commit is contained in:
Luke Else 2023-02-11 16:15:28 +00:00
parent 2033d9b2b8
commit 247587d99b
5 changed files with 110 additions and 72 deletions

View File

@ -1,57 +0,0 @@
//use std::str::FromStr;
/// Ip address enum that includes associated type
///
/// # Example
/// ```
/// //Loopback Addresses:
/// IpAddr::V4(127, 0, 0, 1)
/// IpAddr::V6(String::from("::1"))
/// ```
#[allow(unused)]
pub enum IpAddr {
V4(u8, u8, u8, u8),
V6(String)
}
impl ToString for IpAddr {
/// Function that returns an IP address in string form
fn to_string(&self) -> String {
match self {
IpAddr::V4(oct1, oct2, oct3, oct4) => format!("{}.{}.{}.{}", oct1, oct2, oct3, oct4),
IpAddr::V6(addr) => format!("{}", addr)
}
}
}
// impl FromStr for IpAddr {
// /// Function that generates a IpAddr / Err from a string
// fn from_str(s: &str) -> Result<Self, Self::Err> {
// //Awating implementation
// }
// }
/// Function that takes in an IP address and then prints a formatted string to the CLI
///
/// # Example
/// ```
/// let ip = IpAddr::V4(127, 0, 0, 1);
///
/// print_ip(ip);
/// //Output: IP Address: 127.0.0.1
/// ```
pub fn print_ip(ip_address: IpAddr) {
println!("IP Address: {}", ip_address.to_string())
}
mod tests {
#[test]
/// Tests if an IP is converted to a string
/// correctly using the to_string trait
fn ip_to_string() {
use super::*;
let ip = IpAddr::V4(192, 168, 0, 1);
assert_eq!(ip.to_string(), "192.168.0.1")
}
}

View File

@ -1,6 +1,5 @@
mod network; mod networking;
mod ip;
fn main() { fn main() {
println!("Hello, world!"); println!("Hello, World!")
} }

View File

@ -1,12 +0,0 @@
use crate::ip::IpAddr;
pub struct Network {
network_address: IpAddr,
broadcast_addr: IpAddr,
subnet_mask: Option<IpAddr>
}
impl Network {
// pub fn generate_subnets(self) -> Vec<Network> {}
// fn get_net_id(self) -> u8 {}
}

94
src/networking/ip.rs Normal file
View File

@ -0,0 +1,94 @@
use std::str::FromStr;
/// Ip address enum that includes associated type
///
/// # Example
/// ```
/// //Loopback Addresses:
/// IpAddr::V4(127, 0, 0, 1)
/// IpAddr::V6(String::from("::1"))
/// ```
#[allow(unused)]
#[derive(Debug, PartialEq, Eq)]
pub enum IpAddr {
V4(u8, u8, u8, u8),
V6(String)
}
#[derive(Debug)]
pub struct InvalidIPErr;
impl ToString for IpAddr {
/// Function that returns an IP address in string form
fn to_string(&self) -> String {
match self {
IpAddr::V4(oct1, oct2, oct3, oct4) => format!("{}.{}.{}.{}", oct1, oct2, oct3, oct4),
IpAddr::V6(addr) => format!("{}", addr)
}
}
}
impl FromStr for IpAddr {
type Err = InvalidIPErr;
/// Function that generates a IpAddr / Err from a string
fn from_str(s: &str) -> Result<Self, Self::Err> {
let split_ip = s.split('.');
if split_ip.clone().count() != 4 {
//Invalid IP address entered
return Err(InvalidIPErr)
}
let mut ip: [u8; 4] = Default::default();
//Go through each octet and ensure it can be parsed;
for (i, oct) in split_ip.into_iter().enumerate() {
match oct.parse::<u8>() {
Ok(parsed_oct) => ip[i] = parsed_oct,
Err(_) => return Err(InvalidIPErr)
}
}
Ok(IpAddr::V4(ip[0],ip[1],ip[2],ip[3]))
}
}
/// Function that takes in an IP address and then prints a formatted string to the CLI
///
/// # Example
/// ```
/// let ip = IpAddr::V4(127, 0, 0, 1);
///
/// print_ip(ip);
/// //Output: IP Address: 127.0.0.1
/// ```
#[allow(unused)]
pub fn print_ip(ip_address: IpAddr) {
println!("IP Address: {}", ip_address.to_string())
}
mod tests {
#[test]
/// Tests if an IP is converted to a string
/// 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")
}
#[test]
/// Tests if an IP is converted from a string
/// correctly using the FromString trait
fn string_to_ip() {
use super::*;
let ip = "127.0.0.1";
assert_eq!(IpAddr::from_str(ip).unwrap(), IpAddr::V4(127, 0, 0, 1))
}
#[test]
#[should_panic]
fn invalid_string_to_ip() {
use super::*;
let ip = "Hello, world";
IpAddr::from_str(ip).unwrap();
}
}

14
src/networking/mod.rs Normal file
View File

@ -0,0 +1,14 @@
mod ip;
use ip::IpAddr;
#[allow(unused)]
pub struct Network {
network_address: IpAddr,
broadcast_addr: IpAddr,
subnet_mask: Option<IpAddr>
}
impl Network {
// pub fn generate_subnets(self) -> Vec<Network> {}
// fn get_net_id(self) -> u8 {}
}