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
macro_rules! nonmax {
( $nonmax: ident, $non_zero: ident, $primitive: ident ) => {
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct $nonmax(std::num::$non_zero);
impl $nonmax {
#[inline]
pub fn new(value: $primitive) -> Option<Self> {
if value == $primitive::max_value() {
None
} else {
let inner = unsafe {
std::num::$non_zero::new_unchecked(value ^ $primitive::max_value())
};
Some(Self(inner))
}
}
#[inline]
pub unsafe fn new_unchecked(value: $primitive) -> Self {
let inner = std::num::$non_zero::new_unchecked(value ^ $primitive::max_value());
Self(inner)
}
#[inline]
pub fn get(&self) -> $primitive {
self.0.get() ^ $primitive::max_value()
}
}
#[cfg(test)]
mod $primitive {
use super::*;
use std::mem::size_of;
#[test]
fn construct() {
let zero = $nonmax::new(0).unwrap();
assert_eq!(zero.get(), 0);
let some = $nonmax::new(19).unwrap();
assert_eq!(some.get(), 19);
let max = $nonmax::new($primitive::max_value());
assert_eq!(max, None);
}
#[test]
fn sizes_correct() {
assert_eq!(size_of::<$primitive>(), size_of::<$nonmax>());
assert_eq!(size_of::<$nonmax>(), size_of::<Option<$nonmax>>());
}
}
};
}
nonmax!(NonMaxI8, NonZeroI8, i8);
nonmax!(NonMaxI16, NonZeroI16, i16);
nonmax!(NonMaxI32, NonZeroI32, i32);
nonmax!(NonMaxI64, NonZeroI64, i64);
nonmax!(NonMaxIsize, NonZeroIsize, isize);
nonmax!(NonMaxU8, NonZeroU8, u8);
nonmax!(NonMaxU16, NonZeroU16, u16);
nonmax!(NonMaxU32, NonZeroU32, u32);
nonmax!(NonMaxU64, NonZeroU64, u64);
nonmax!(NonMaxUsize, NonZeroUsize, usize);