ip/concrete/
af.rs

1use core::fmt;
2
3#[cfg(feature = "std")]
4use super::PrefixSet;
5use super::{Address, Bitmask, Hostmask, Interface, Netmask, Prefix, PrefixLength, PrefixRange};
6use crate::{any, error::Error, traits};
7
8/// The IPv4 address family.
9#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
10pub enum Ipv4 {}
11
12/// The IPv6 address family.
13#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
14pub enum Ipv6 {}
15
16impl traits::Afi for Ipv4 {
17    type Octets = [u8; 4];
18    type Primitive = u32;
19    fn as_afi() -> Afi {
20        Afi::Ipv4
21    }
22}
23impl traits::Afi for Ipv6 {
24    type Octets = [u8; 16];
25    type Primitive = u128;
26    fn as_afi() -> Afi {
27        Afi::Ipv6
28    }
29}
30
31impl<A: traits::Afi> traits::AfiClass for A {
32    type Address = Address<A>;
33    type Interface = Interface<A>;
34    type PrefixLength = PrefixLength<A>;
35    type Prefix = Prefix<A>;
36    type Netmask = Netmask<A>;
37    type Hostmask = Hostmask<A>;
38    type Bitmask = Bitmask<A>;
39    type PrefixRange = PrefixRange<A>;
40
41    #[cfg(feature = "std")]
42    type PrefixSet = PrefixSet<A>;
43
44    fn as_afi_class() -> any::AfiClass {
45        A::as_afi().into()
46    }
47}
48
49/// Enumeration of concrete address families.
50///
51/// # Examples
52///
53/// ``` rust
54/// use ip::{Afi, Ipv4, Ipv6};
55///
56/// assert_eq!(Ipv4::as_afi().to_string(), "ipv4");
57/// assert_eq!(Ipv6::as_afi().to_string(), "ipv6");
58/// ```
59#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
60pub enum Afi {
61    /// Variant representing the IPv4 address family.
62    Ipv4,
63    /// Variant representing the IPv6 address family.
64    Ipv6,
65}
66
67impl Afi {
68    pub(crate) fn new_prefix_length(self, len: u8) -> Result<any::PrefixLength, Error> {
69        match self {
70            Self::Ipv4 => PrefixLength::<Ipv4>::from_primitive(len).map(any::PrefixLength::Ipv4),
71            Self::Ipv6 => PrefixLength::<Ipv6>::from_primitive(len).map(any::PrefixLength::Ipv6),
72        }
73    }
74}
75
76impl fmt::Display for Afi {
77    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78        match self {
79            Self::Ipv4 => f.write_str("ipv4"),
80            Self::Ipv6 => f.write_str("ipv6"),
81        }
82    }
83}