ip/any/
mask.rs

1use core::fmt;
2
3use super::PrefixLength;
4use crate::{
5    concrete::{
6        self,
7        mask_types::{Bit, Host, Net, Type},
8        Ipv4, Ipv6,
9    },
10    traits,
11};
12
13/// Either an IPv4 or IPv6 address mask.
14///
15/// # Memory Use
16///
17/// Rust enums are sized to accomodate their largest variant, with smaller
18/// variants being padded to fill up any unused space.
19///
20/// As a result, users should avoid using this type in a context where only
21/// [`Mask::Ipv4`] variants are expected.
22#[allow(variant_size_differences)]
23#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
24pub enum Mask<T: Type> {
25    /// IPv4 address mask variant.
26    Ipv4(concrete::Mask<T, Ipv4>),
27    /// IPv6 address mask variant.
28    Ipv6(concrete::Mask<T, Ipv6>),
29}
30
31/// Either an IPv4 or IPv6 netmask.
32pub type Netmask = Mask<Net>;
33
34/// Either an IPv4 or IPv6 netmask.
35pub type Hostmask = Mask<Host>;
36
37/// Either an IPv4 or IPv6 bitmask.
38pub type Bitmask = Mask<Bit>;
39
40impl<T: Type> traits::Mask for Mask<T> {}
41impl traits::Netmask for Netmask {}
42impl traits::Hostmask for Hostmask {}
43impl traits::Bitmask for Bitmask {}
44
45impl<T: Type> From<concrete::Mask<T, Ipv4>> for Mask<T> {
46    fn from(mask: concrete::Mask<T, Ipv4>) -> Self {
47        Self::Ipv4(mask)
48    }
49}
50
51impl<T: Type> From<concrete::Mask<T, Ipv6>> for Mask<T> {
52    fn from(mask: concrete::Mask<T, Ipv6>) -> Self {
53        Self::Ipv6(mask)
54    }
55}
56
57impl From<PrefixLength> for Netmask {
58    fn from(len: PrefixLength) -> Self {
59        match len {
60            PrefixLength::Ipv4(len) => Self::Ipv4(len.into()),
61            PrefixLength::Ipv6(len) => Self::Ipv6(len.into()),
62        }
63    }
64}
65
66impl From<PrefixLength> for Hostmask {
67    fn from(len: PrefixLength) -> Self {
68        match len {
69            PrefixLength::Ipv4(len) => Self::Ipv4(len.into()),
70            PrefixLength::Ipv6(len) => Self::Ipv6(len.into()),
71        }
72    }
73}
74
75impl<T: Type> fmt::Display for Mask<T> {
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        match self {
78            Self::Ipv4(mask) => mask.fmt(f),
79            Self::Ipv6(mask) => mask.fmt(f),
80        }
81    }
82}
83
84// TODO: impl FromStr
85// TODO: impl Arbitrary