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
use crate::integer::int;
use crate::non_standard_integer::NonStandardIntegerCommon;
use core::ops::{Add, Div, Mul, Shl, Shr, Sub};
#[doc(hidden)]
pub macro impl_op($trait_name: ident, $trait_fn_name: ident ($rhs_ty: ty), $overflow_name: ident, $overflow_message: literal) {
impl<T: PartialOrd + Copy, const BITS: u32> $trait_name<$rhs_ty> for int<T, BITS>
where
Self: NonStandardIntegerCommon<T, BITS>,
{
type Output = Self;
fn $trait_fn_name(self, rhs: $rhs_ty) -> Self::Output {
let (val, overflowed) = self.$overflow_name(rhs);
debug_assert!(!overflowed, $overflow_message);
val
}
}
}
impl_op!(
Add,
add(Self),
overflowing_add,
"attempt to add with overflow"
);
impl_op!(
Sub,
sub(Self),
overflowing_sub,
"attempt to subtract with overflow"
);
impl_op!(
Mul,
mul(Self),
overflowing_mul,
"attempt to multiply with overflow"
);
impl_op!(
Div,
div(Self),
overflowing_div,
"attempt to divide with overflow"
);
impl_op!(
Shr,
shr(u32),
overflowing_shr,
"attempt to shift right with overflow"
);
impl_op!(
Shl,
shl(u32),
overflowing_shl,
"attempt to shift left with overflow"
);
#[cfg(test)]
mod test {
use super::*;
#[allow(non_camel_case_types)]
type u6 = int<u8, 6>;
#[test]
#[should_panic]
#[cfg(debug_assertions)]
fn add() {
let a = u6::new(32);
let b = u6::new(32);
assert_eq!(a + b, u6::new(0));
}
#[test]
#[cfg(not(debug_assertions))]
fn add() {
let a = u6::new(32);
let b = u6::new(32);
assert_eq!(a + b, u6::new(0));
}
#[test]
#[cfg(not(debug_assertions))]
fn sub() {
let a = u6::new(32);
let b = u6::new(32);
assert_eq!(a - b, u6::new(0));
}
#[test]
#[cfg(not(debug_assertions))]
fn mul() {
let a = u6::new(2);
let b = u6::new(32);
assert_eq!(a * b, u6::new(0));
}
#[test]
#[cfg(not(debug_assertions))]
fn div() {
let a = u6::new(9);
let b = u6::new(3);
assert_eq!(a / b, u6::new(3));
}
#[test]
#[should_panic]
#[cfg(debug_assertions)]
fn shl() {
let _ = u6::new(1) << 6;
}
#[test]
#[cfg(not(debug_assertions))]
fn shl() {
assert_eq!(u6::new(1) << 4, u6::new(16));
assert_eq!((u6::new(1) << 5), u6::new(32));
assert_eq!((u6::new(1) << 6), u6::new(0));
assert_eq!((u6::new(3) << 3), u6::new(24));
assert_eq!((u6::new(3) << 5), u6::new(32));
}
#[test]
#[should_panic]
#[cfg(debug_assertions)]
fn shr() {
let _ = u6::new(1) >> 6;
}
#[test]
#[cfg(not(debug_assertions))]
fn shr() {
assert_eq!(u6::new(4) >> 1, u6::new(2));
assert_eq!(u6::new(63) >> 7, u6::new(0));
}
}