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
use std::num::ParseIntError;
use thiserror::Error;
use crate::macros::assert_unchecked;
#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct BoundedU8<const MIN: u8, const MAX: u8>(u8);
impl<const MIN: u8, const MAX: u8> BoundedU8<MIN, MAX> {
pub const MIN_VALUE: u8 = {
assert!(MIN <= MAX);
MIN
};
pub const MAX_VALUE: u8 = MAX;
pub const MIN: Self = unsafe { Self::new_unchecked(Self::MIN_VALUE) };
pub const MAX: Self = unsafe { Self::new_unchecked(Self::MAX_VALUE) };
pub const fn in_range(x: u8) -> bool {
Self::MIN_VALUE <= x && x <= Self::MAX_VALUE
}
pub const fn new(inner: u8) -> Option<Self> {
if Self::in_range(inner) {
Some(unsafe { Self::new_unchecked(inner) })
} else {
None
}
}
pub const unsafe fn new_unchecked(inner: u8) -> Self {
assert_unchecked!(Self::in_range(inner));
Self(inner)
}
pub const fn get(self) -> u8 {
self.0
}
pub fn all(
) -> impl Iterator<Item = Self> + DoubleEndedIterator + ExactSizeIterator + std::iter::FusedIterator
{
(Self::MIN_VALUE..=Self::MAX_VALUE).map(|i| unsafe { Self::new_unchecked(i) })
}
pub fn from_str_radix(s: &str, radix: u32) -> Result<Self, BoundedIntegerParseError> {
let value = u8::from_str_radix(s, radix)?;
if value < Self::MIN_VALUE {
return Err(BoundedIntegerParseError::BelowMin);
} else if value > Self::MAX_VALUE {
return Err(BoundedIntegerParseError::AboveMax);
}
Ok(unsafe { Self::new_unchecked(value) })
}
}
impl<const MAX: u8> Default for BoundedU8<0, MAX> {
fn default() -> Self {
unsafe { Self::new_unchecked(0) }
}
}
macro_rules! impl_primitive_from_bounded_u8 {
($($ty:ty)*) => {
$(
impl<const MIN: u8, const MAX: u8> From<BoundedU8<MIN, MAX>> for $ty {
fn from(x: BoundedU8<MIN, MAX>) -> Self {
Self::from(x.get())
}
}
)*
};
}
impl_primitive_from_bounded_u8!(i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize);
impl<const MIN: u8, const MAX: u8> std::str::FromStr for BoundedU8<MIN, MAX> {
type Err = BoundedIntegerParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::from_str_radix(s, 10)
}
}
macro_rules! impl_fmt_traits {
($($trait:ident),*) => {
$(
impl<const MIN: u8, const MAX: u8> std::fmt::$trait for BoundedU8<MIN, MAX> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::$trait::fmt(&self.0, f)
}
}
)*
};
}
impl_fmt_traits!(Binary, Debug, Display, LowerExp, LowerHex, Octal, UpperExp, UpperHex);
#[derive(Clone, Debug, Eq, PartialEq, Error)]
pub enum BoundedIntegerParseError {
#[error("number is below MIN")]
BelowMin,
#[error("number is above MAX")]
AboveMax,
#[error(transparent)]
Parse(#[from] ParseIntError),
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_from_str_radix() {
type Num = BoundedU8<3, 44>;
assert_eq!(Num::from_str_radix("3", 10).unwrap().get(), 3);
assert_eq!(Num::from_str_radix("2C", 16).unwrap().get(), 44);
assert!(matches!(
Num::from_str_radix("A", 10),
Err(BoundedIntegerParseError::Parse(_))
));
assert!(matches!(
Num::from_str_radix("2", 10),
Err(BoundedIntegerParseError::BelowMin)
));
assert!(matches!(
Num::from_str_radix("45", 10),
Err(BoundedIntegerParseError::AboveMax)
));
}
}