hopr_primitive_types/
bounded.rs

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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
use crate::prelude::GeneralError;
use std::fmt::{Display, Formatter};

/// Unsigned integer (`usize`) that has an explicit upper bound.
/// Trying to convert an integer that's above this bound will fail.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default, Hash, serde::Serialize, serde::Deserialize)]
pub struct BoundedSize<const B: usize>(usize);

impl<const B: usize> BoundedSize<B> {
    /// Minimum value - evaluates to 0.
    pub const MIN: Self = Self(0);
    /// Maximum value - evaluates to `B`.
    pub const MAX: Self = Self(B);
}

impl<const B: usize> TryFrom<u8> for BoundedSize<B> {
    type Error = GeneralError;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        (value as usize).try_into()
    }
}

impl<const B: usize> TryFrom<u16> for BoundedSize<B> {
    type Error = GeneralError;

    fn try_from(value: u16) -> Result<Self, Self::Error> {
        (value as usize).try_into()
    }
}

impl<const B: usize> TryFrom<u32> for BoundedSize<B> {
    type Error = GeneralError;

    fn try_from(value: u32) -> Result<Self, Self::Error> {
        (value as usize).try_into()
    }
}

impl<const B: usize> TryFrom<u64> for BoundedSize<B> {
    type Error = GeneralError;

    fn try_from(value: u64) -> Result<Self, Self::Error> {
        (value as usize).try_into()
    }
}

impl<const B: usize> TryFrom<usize> for BoundedSize<B> {
    type Error = GeneralError;

    fn try_from(value: usize) -> Result<Self, Self::Error> {
        if value <= B {
            Ok(Self(value))
        } else {
            Err(GeneralError::InvalidInput)
        }
    }
}

impl<const B: usize> TryFrom<i8> for BoundedSize<B> {
    type Error = GeneralError;

    fn try_from(value: i8) -> Result<Self, Self::Error> {
        Self::try_from(value as isize)
    }
}

impl<const B: usize> TryFrom<i16> for BoundedSize<B> {
    type Error = GeneralError;

    fn try_from(value: i16) -> Result<Self, Self::Error> {
        Self::try_from(value as isize)
    }
}

impl<const B: usize> TryFrom<i32> for BoundedSize<B> {
    type Error = GeneralError;

    fn try_from(value: i32) -> Result<Self, Self::Error> {
        Self::try_from(value as isize)
    }
}

impl<const B: usize> TryFrom<i64> for BoundedSize<B> {
    type Error = GeneralError;

    fn try_from(value: i64) -> Result<Self, Self::Error> {
        Self::try_from(value as isize)
    }
}

impl<const B: usize> TryFrom<isize> for BoundedSize<B> {
    type Error = GeneralError;

    fn try_from(value: isize) -> Result<Self, Self::Error> {
        if value >= 0 {
            Self::try_from(value as usize)
        } else {
            Err(GeneralError::InvalidInput)
        }
    }
}

impl<const B: usize> Display for BoundedSize<B> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl<const B: usize> From<BoundedSize<B>> for u8 {
    fn from(value: BoundedSize<B>) -> Self {
        value.0 as u8
    }
}

impl<const B: usize> From<BoundedSize<B>> for u16 {
    fn from(value: BoundedSize<B>) -> Self {
        value.0 as u16
    }
}

impl<const B: usize> From<BoundedSize<B>> for u32 {
    fn from(value: BoundedSize<B>) -> Self {
        value.0 as u32
    }
}

impl<const B: usize> From<BoundedSize<B>> for u64 {
    fn from(value: BoundedSize<B>) -> Self {
        value.0 as u64
    }
}

impl<const B: usize> From<BoundedSize<B>> for usize {
    fn from(value: BoundedSize<B>) -> Self {
        value.0
    }
}

/// Wrapper for [`Vec`] that has an explicit upper bound on the number of elements.
/// The Structure remains heap-allocated to avoid blowing up the size of types where it is used.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct BoundedVec<T, const N: usize>(Vec<T>);

impl<T, const N: usize> Default for BoundedVec<T, N> {
    fn default() -> Self {
        Self(vec![])
    }
}

impl<T, const N: usize> TryFrom<Vec<T>> for BoundedVec<T, N> {
    type Error = GeneralError;

    fn try_from(value: Vec<T>) -> Result<Self, Self::Error> {
        if value.len() <= N {
            Ok(Self(value))
        } else {
            Err(GeneralError::InvalidInput)
        }
    }
}

impl<T, const N: usize> IntoIterator for BoundedVec<T, N> {
    type Item = T;
    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl<T, const N: usize> FromIterator<T> for BoundedVec<T, N> {
    fn from_iter<V: IntoIterator<Item = T>>(iter: V) -> Self {
        Self(iter.into_iter().take(N).collect())
    }
}

impl<T, const N: usize> From<[T; N]> for BoundedVec<T, N> {
    fn from(value: [T; N]) -> Self {
        Self(Vec::from(value))
    }
}

impl<T, const N: usize> From<BoundedVec<T, N>> for Vec<T> {
    fn from(value: BoundedVec<T, N>) -> Self {
        value.0
    }
}

impl<T, const N: usize> AsRef<[T]> for BoundedVec<T, N> {
    fn as_ref(&self) -> &[T] {
        &self.0
    }
}

impl<T: Default + Copy, const N: usize> From<BoundedVec<T, N>> for [T; N] {
    fn from(value: BoundedVec<T, N>) -> Self {
        let mut out = [T::default(); N];
        value.0.into_iter().enumerate().for_each(|(i, e)| out[i] = e);
        out
    }
}

#[cfg(test)]
mod tests {
    use crate::bounded::{BoundedSize, BoundedVec};

    #[test]
    fn bounded_size_should_not_allow_bigger_numbers() {
        assert_eq!(0usize, BoundedSize::<10>::MIN.into());
        assert_eq!(10usize, BoundedSize::<10>::MAX.into());

        assert!(BoundedSize::<10>::try_from(5).is_ok_and(|b| u8::from(b) == 5));
        assert!(BoundedSize::<10>::try_from(11).is_err());
    }

    #[test]
    fn bounded_vec_should_not_fit_more_than_allowed() {
        assert!(BoundedVec::<i32, 3>::try_from(vec![]).is_ok_and(|b| Vec::from(b).is_empty()));
        assert!(BoundedVec::<i32, 3>::try_from(vec![1, 2]).is_ok_and(|b| Vec::from(b) == vec![1, 2]));
        assert!(BoundedVec::<i32, 3>::try_from(vec![1, 2, 3]).is_ok_and(|b| Vec::from(b) == vec![1, 2, 3]));
        assert!(BoundedVec::<i32, 3>::try_from(vec![1, 2, 3, 4]).is_err());

        assert_eq!(
            vec![1, 2, 3],
            Vec::from(BoundedVec::<i32, 3>::from_iter(vec![1, 2, 3, 4]))
        );
    }
}