1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
use std::{convert::TryFrom, net::IpAddr};

#[derive(Debug)]
pub enum SubnetType {
    A, // a.xxx.xxx.xxx/8
    B, // a.b.xxx.xxx/16
    C, // a.b.c.xxx/24
}

impl SubnetType {
    pub fn subnet(&self, ip: &IpAddr) -> u32 {
        match *self {
            SubnetType::A => SubnetType::calc_subnet(ip, 8),
            SubnetType::B => SubnetType::calc_subnet(ip, 16),
            SubnetType::C => SubnetType::calc_subnet(ip, 24),
        }
    }

    fn calc_subnet(ip: &IpAddr, prefix_bits: usize) -> u32 {
        match ip {
            IpAddr::V4(ipv4) => {
                let num: u32 = ipv4.clone().into();
                num >> (32 - prefix_bits)
            }
            IpAddr::V6(ipv6) => {
                let num: u128 = ipv6.clone().into();
                (num >> (128 - prefix_bits)) as u32
            }
        }
    }
}

impl TryFrom<usize> for SubnetType {
    type Error = String;

    fn try_from(value: usize) -> Result<Self, String> {
        match value {
            8 => Ok(SubnetType::A),
            16 => Ok(SubnetType::B),
            24 => Ok(SubnetType::C),
            _ => Err("Valid subnet prefix bits are 8, 16 and 24".into()),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::SubnetType;
    use std::{net::IpAddr, str::FromStr};

    fn new_ip(ip: &'static str) -> IpAddr { IpAddr::from_str(ip).unwrap() }

    #[test]
    fn test_subnet() {
        assert_eq!(
            SubnetType::C.subnet(&new_ip("127.0.0.1")),
            SubnetType::C.subnet(&new_ip("127.0.0.2"))
        );
        assert_ne!(
            SubnetType::C.subnet(&new_ip("127.0.0.1")),
            SubnetType::C.subnet(&new_ip("127.0.1.1"))
        );

        assert_eq!(
            SubnetType::B.subnet(&new_ip("127.0.0.1")),
            SubnetType::B.subnet(&new_ip("127.0.0.2"))
        );
        assert_eq!(
            SubnetType::B.subnet(&new_ip("127.0.0.1")),
            SubnetType::B.subnet(&new_ip("127.0.1.1"))
        );
        assert_ne!(
            SubnetType::B.subnet(&new_ip("127.0.0.1")),
            SubnetType::B.subnet(&new_ip("127.1.0.1"))
        );

        assert_eq!(
            SubnetType::A.subnet(&new_ip("127.0.0.1")),
            SubnetType::A.subnet(&new_ip("127.0.0.2"))
        );
        assert_eq!(
            SubnetType::A.subnet(&new_ip("127.0.0.1")),
            SubnetType::A.subnet(&new_ip("127.0.1.1"))
        );
        assert_eq!(
            SubnetType::A.subnet(&new_ip("127.0.0.1")),
            SubnetType::A.subnet(&new_ip("127.1.0.1"))
        );
        assert_ne!(
            SubnetType::A.subnet(&new_ip("127.0.0.1")),
            SubnetType::A.subnet(&new_ip("192.0.0.1"))
        );
    }
}