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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
use core::fmt;
use core::ops::Neg;

use super::impl_try_from_any;
use crate::{
    any,
    error::{err, Error, Kind},
    traits::{
        self,
        primitive::{self, Address as _, Length as _},
        Afi,
    },
    Ipv4, Ipv6,
};

#[allow(clippy::wildcard_imports)]
mod private {
    use super::*;

    /// An IP prefix length guaranteed to be within appropriate bounds for
    /// address family `A`.
    #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
    pub struct PrefixLength<A: Afi>(<A::Primitive as primitive::Address<A>>::Length);

    impl<A: Afi> PrefixLength<A> {
        /// Minimum valid value of [`PrefixLength<A>`].
        pub const MIN: Self = Self(A::Primitive::MIN_LENGTH);

        /// Maximum valid value of [`PrefixLength<A>`].
        pub const MAX: Self = Self(A::Primitive::MAX_LENGTH);

        /// Construct a new [`PrefixLength<A>`] from an integer primitive
        /// appropriate to `A`.
        ///
        /// # Errors
        ///
        /// Fails if `n` is outside of the range [`Self::MIN`] to [`Self::MAX`]
        /// inclusive.
        pub fn from_primitive(
            n: <A::Primitive as primitive::Address<A>>::Length,
        ) -> Result<Self, Error> {
            if A::Primitive::MIN_LENGTH <= n && n <= A::Primitive::MAX_LENGTH {
                Ok(Self(n))
            } else {
                Err(err!(Kind::PrefixLength))
            }
        }

        /// Get the inner integer val, consuming `self`.
        pub const fn into_primitive(self) -> <A::Primitive as primitive::Address<A>>::Length {
            self.0
        }
    }

    impl<A> PrefixLength<A>
    where
        A: Afi,
        A::Primitive: primitive::Address<A, Length = u8>,
    {
        pub(super) const fn as_u8(&self) -> &u8 {
            &self.0
        }
    }
}

pub use self::private::PrefixLength;

impl<A: Afi> TryFrom<usize> for PrefixLength<A> {
    type Error = Error;

    fn try_from(value: usize) -> Result<Self, Self::Error> {
        value
            .try_into()
            .map_err(|_| err!(Kind::PrefixLength))
            .and_then(Self::from_primitive)
    }
}

impl<A: Afi> traits::PrefixLength for PrefixLength<A> {
    fn increment(self) -> Result<Self, Error> {
        let l = self.into_primitive();
        if l < <A::Primitive as primitive::Address<A>>::MAX_LENGTH {
            Self::from_primitive(l + <A::Primitive as primitive::Address<A>>::Length::ONE)
        } else {
            Err(err!(Kind::PrefixLength))
        }
    }
    fn decrement(self) -> Result<Self, Error> {
        let l = self.into_primitive();
        if l > <A::Primitive as primitive::Address<A>>::Length::ZERO {
            Self::from_primitive(l - <A::Primitive as primitive::Address<A>>::Length::ONE)
        } else {
            Err(err!(Kind::PrefixLength))
        }
    }
}

impl<A: Afi> AsRef<u8> for PrefixLength<A>
where
    A::Primitive: primitive::Address<A, Length = u8>,
{
    fn as_ref(&self) -> &u8 {
        self.as_u8()
    }
}

impl_try_from_any! {
    any::PrefixLength {
        any::PrefixLength::Ipv4 => PrefixLength<Ipv4>,
        any::PrefixLength::Ipv6 => PrefixLength<Ipv6>,
    }
}

impl<A: Afi> fmt::Display for PrefixLength<A> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.into_primitive().fmt(f)
    }
}

impl<A: Afi> Neg for PrefixLength<A> {
    type Output = Self;

    fn neg(self) -> Self::Output {
        // ok to unwrap since 0 <= self.0 <= A::MAX_LENGTH
        Self::from_primitive(A::Primitive::MAX_LENGTH - self.into_primitive()).unwrap()
    }
}

#[cfg(any(test, feature = "arbitrary"))]
use proptest::{
    arbitrary::Arbitrary,
    strategy::{BoxedStrategy, Strategy},
};

#[cfg(any(test, feature = "arbitrary"))]
impl<A: Afi> Arbitrary for PrefixLength<A>
where
    <A::Primitive as primitive::Address<A>>::Length: 'static,
    core::ops::RangeInclusive<<A::Primitive as primitive::Address<A>>::Length>:
        Strategy<Value = <A::Primitive as primitive::Address<A>>::Length>,
{
    type Parameters = ();
    type Strategy = BoxedStrategy<Self>;
    fn arbitrary_with(_: Self::Parameters) -> Self::Strategy {
        (A::Primitive::MIN_LENGTH..=A::Primitive::MAX_LENGTH)
            .prop_map(|l| Self::from_primitive(l).unwrap())
            .boxed()
    }
}