dbsp/algebra/
checked_int.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
use crate::algebra::{AddAssignByRef, AddByRef, HasOne, HasZero, MulByRef, NegByRef};
use num::{traits::CheckedNeg, CheckedAdd, CheckedMul};
use size_of::SizeOf;
use std::{
    cmp::Ordering,
    fmt::{Debug, Display, Error, Formatter},
    ops::{Add, AddAssign, Neg},
};

/// Ring on numeric values that panics on overflow.
///
/// Computes exactly like any signed numeric value, but panics on overflow.
#[derive(
    Copy,
    Clone,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    SizeOf,
    Hash,
    Default,
    rkyv::Archive,
    rkyv::Serialize,
    rkyv::Deserialize,
)]
#[repr(transparent)]
pub struct CheckedInt<T> {
    value: T,
}

impl<T> CheckedInt<T> {
    #[inline]
    pub const fn new(value: T) -> Self {
        Self { value }
    }

    #[inline]
    pub fn into_inner(self) -> T {
        self.value
    }
}

impl<T> Add for CheckedInt<T>
where
    T: CheckedAdd,
{
    type Output = Self;

    #[inline]
    fn add(self, other: Self) -> Self {
        // intentional panic on overflow
        Self {
            value: self
                .value
                .checked_add(&other.value)
                .unwrap_or_else(|| checked_int_overflow()),
        }
    }
}

impl<T> AddByRef for CheckedInt<T>
where
    T: CheckedAdd,
{
    #[inline]
    fn add_by_ref(&self, other: &Self) -> Self {
        // intentional panic on overflow
        Self {
            value: self
                .value
                .checked_add(&other.value)
                .unwrap_or_else(|| checked_int_overflow()),
        }
    }
}

impl<T> AddAssign for CheckedInt<T>
where
    T: CheckedAdd,
{
    #[inline]
    fn add_assign(&mut self, other: Self) {
        self.value = self
            .value
            .checked_add(&other.value)
            .unwrap_or_else(|| checked_int_overflow())
    }
}

impl<T> AddAssignByRef for CheckedInt<T>
where
    T: CheckedAdd,
{
    #[inline]
    fn add_assign_by_ref(&mut self, other: &Self) {
        self.value = self
            .value
            .checked_add(&other.value)
            .unwrap_or_else(|| checked_int_overflow())
    }
}

impl<T> MulByRef for CheckedInt<T>
where
    T: CheckedMul,
{
    type Output = Self;

    #[inline]
    fn mul_by_ref(&self, rhs: &Self) -> Self::Output {
        // intentional panic on overflow
        Self {
            value: self
                .value
                .checked_mul(&rhs.value)
                .unwrap_or_else(|| checked_int_overflow()),
        }
    }
}

impl<T> NegByRef for CheckedInt<T>
where
    T: CheckedNeg,
{
    #[inline]
    fn neg_by_ref(&self) -> Self {
        Self {
            // intentional panic on overflow
            value: self
                .value
                .checked_neg()
                .unwrap_or_else(|| checked_int_overflow()),
        }
    }
}

impl<T> Neg for CheckedInt<T>
where
    T: CheckedNeg,
{
    type Output = Self;

    #[inline]
    fn neg(self) -> Self {
        Self {
            // intentional panic on overflow
            value: self
                .value
                .checked_neg()
                .unwrap_or_else(|| checked_int_overflow()),
        }
    }
}

impl<T> HasZero for CheckedInt<T>
where
    T: HasZero,
{
    #[inline]
    fn is_zero(&self) -> bool {
        T::is_zero(&self.value)
    }

    #[inline]
    fn zero() -> Self {
        Self::new(T::zero())
    }
}

impl<T> HasOne for CheckedInt<T>
where
    T: HasOne,
{
    #[inline]
    fn one() -> Self {
        Self::new(T::one())
    }
}

impl<T> PartialEq<T> for CheckedInt<T>
where
    T: PartialEq,
{
    #[inline]
    fn eq(&self, other: &T) -> bool {
        &self.value == other
    }
}

impl<T> PartialOrd<T> for CheckedInt<T>
where
    T: PartialOrd,
{
    #[inline]
    fn partial_cmp(&self, other: &T) -> Option<Ordering> {
        self.value.partial_cmp(other)
    }
}

impl<T> From<T> for CheckedInt<T> {
    #[inline]
    fn from(value: T) -> Self {
        Self { value }
    }
}

impl<T> Debug for CheckedInt<T>
where
    T: Debug,
{
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
        self.value.fmt(f)
    }
}

impl<T> Display for CheckedInt<T>
where
    T: Display,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
        self.value.fmt(f)
    }
}

#[cold]
#[inline(never)]
fn checked_int_overflow() -> ! {
    panic!("an operation on a CheckedInt overflowed or underflowed")
}

#[cfg(test)]
mod checked_integer_ring_tests {
    use super::{AddAssignByRef, AddByRef, CheckedInt, HasOne, HasZero, MulByRef, NegByRef};

    type CheckedI64 = CheckedInt<i64>;

    #[test]
    fn fixed_integer_tests() {
        assert_eq!(0i64, CheckedI64::zero().into_inner());
        assert_eq!(1i64, CheckedI64::one().into_inner());

        let two = CheckedI64::one().add_by_ref(&CheckedI64::one());
        assert_eq!(2i64, two.into_inner());
        assert_eq!(-2i64, two.neg_by_ref().into_inner());
        assert_eq!(-4i64, two.mul_by_ref(&two.neg_by_ref()).into_inner());

        let mut three = two;
        three.add_assign_by_ref(&CheckedI64::from(1i64));
        assert_eq!(3i64, three.into_inner());
        assert!(!three.is_zero());
    }

    #[test]
    #[should_panic]
    fn overflow_test() {
        let max = CheckedI64::from(i64::MAX);
        let _ = max.add_by_ref(&CheckedI64::one());
    }
}