modmath 0.2.0

Modular math implemented with traits.
Documentation
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
#[cfg(feature = "nightly")]
use fixed_bigint::const_numtraits::{ConstOverflowingAdd, ConstOverflowingSub};

#[cfg(feature = "nightly")]
c0nst::c0nst! {
    /// # Const Modular Addition
    /// Const-evaluable version of modular addition. Uses const traits from
    /// `fixed_bigint::const_numtraits` instead of `num_traits`.
    pub c0nst fn const_mod_add<T>(a: T, b: T, m: T) -> T
    where
        T: [c0nst] core::cmp::PartialOrd
            + Copy
            + [c0nst] ConstOverflowingAdd
            + [c0nst] ConstOverflowingSub
            + [c0nst] core::ops::Rem<Output = T>,
    {
        let a = a % m;
        let (sum, overflow) = a.overflowing_add(&(b % m));
        if sum >= m || overflow {
            sum.overflowing_sub(&m).0
        } else {
            sum
        }
    }
}

/// # Modular Addition (Basic)
/// Simple version that operates on values and copies them. Requires
/// `WrappingAdd` and `WrappingSub` traits to be implemented.
pub fn basic_mod_add<T>(a: T, b: T, m: T) -> T
where
    T: core::cmp::PartialOrd
        + Copy
        + num_traits::ops::wrapping::WrappingAdd
        + num_traits::ops::wrapping::WrappingSub
        + core::ops::Rem<Output = T>,
{
    basic_mod_add_pr(a % m, b % m, m)
}

/// # Modular Addition (Basic, pre-reduced)
/// Precondition: `a < m` and `b < m`. No `Rem` bound.
pub fn basic_mod_add_pr<T>(a: T, b: T, m: T) -> T
where
    T: core::cmp::PartialOrd
        + Copy
        + num_traits::ops::wrapping::WrappingAdd
        + num_traits::ops::wrapping::WrappingSub,
{
    let sum = a.wrapping_add(&b);
    if sum >= m || sum < a {
        sum.wrapping_sub(&m)
    } else {
        sum
    }
}

/// # Modular Addition (Constrained)
/// Version that works with references, requires `WrappingAdd` and
/// `WrappingSub` traits to be implemented.
pub fn constrained_mod_add<T>(a: T, b: &T, m: &T) -> T
where
    T: core::cmp::PartialOrd
        + num_traits::ops::wrapping::WrappingAdd
        + num_traits::ops::wrapping::WrappingSub,
    for<'a> &'a T: core::ops::Rem<&'a T, Output = T>,
{
    let a_mod = &a % m;
    let b_mod = b % m;
    constrained_mod_add_pr(a_mod, &b_mod, m)
}

/// # Modular Addition (Constrained, pre-reduced)
/// Precondition: `a < *m` and `*b < *m`. No `Rem` family bound.
pub fn constrained_mod_add_pr<T>(a: T, b: &T, m: &T) -> T
where
    T: core::cmp::PartialOrd
        + num_traits::ops::wrapping::WrappingAdd
        + num_traits::ops::wrapping::WrappingSub,
{
    let sum = a.wrapping_add(b);
    if &sum >= m || sum < a {
        sum.wrapping_sub(m)
    } else {
        sum
    }
}

/// # Modular Addition (Strict)
/// Most constrained version that works with references. Requires
/// `OverflowingAdd` and `OverflowingSub` traits to be implemented.
pub fn strict_mod_add<T>(mut a: T, b: &T, m: &T) -> T
where
    T: core::cmp::PartialOrd
        + num_traits::ops::overflowing::OverflowingAdd
        + num_traits::ops::overflowing::OverflowingSub,
    for<'b> T: core::ops::RemAssign<&'b T>,
    for<'a> &'a T: core::ops::Rem<&'a T, Output = T>,
{
    a.rem_assign(m);
    let b_mod = b % m;
    strict_mod_add_pr(a, &b_mod, m)
}

/// # Modular Addition (Strict, pre-reduced)
/// Precondition: `a < *m` and `*b < *m`. No `Rem` family bound.
pub fn strict_mod_add_pr<T>(a: T, b: &T, m: &T) -> T
where
    T: core::cmp::PartialOrd
        + num_traits::ops::overflowing::OverflowingAdd
        + num_traits::ops::overflowing::OverflowingSub,
{
    let (sum, overflow) = a.overflowing_add(b);
    if &sum >= m || overflow {
        sum.overflowing_sub(m).0
    } else {
        sum
    }
}

#[cfg(test)]
macro_rules! select_mod_add {
    ($mod_add:path, $t:ty, by_ref) => {
        fn mod_add(a: $t, b: &$t, m: &$t) -> $t {
            $mod_add(a, b, m)
        }
    };
    ($mod_add:path, $t:ty, by_val) => {
        fn mod_add(a: $t, b: &$t, m: &$t) -> $t {
            $mod_add(a, *b, *m)
        }
    };
}

#[cfg(test)]
macro_rules! generate_mod_add_tests {
    ($mod_add:path, $t:ty, $by_ref:tt) => {
        select_mod_add!($mod_add, $t, $by_ref);

        #[test]
        fn test_mod_add_basic() {
            assert_eq!(mod_add(5u8, &10u8, &20u8), 15u8);
            assert_eq!(mod_add(7u8, &6u8, &14u8), 13u8);
            assert_eq!(mod_add(0u8, &0u8, &10u8), 0u8);
        }

        #[test]
        fn test_mod_add_sum_equals_modulus() {
            assert_eq!(mod_add(10u8, &10u8, &20u8), 0u8);
            assert_eq!(mod_add(15u8, &5u8, &20u8), 0u8);
        }

        #[test]
        fn test_mod_add_sum_exceeds_modulus() {
            assert_eq!(mod_add(15u8, &10u8, &20u8), 5u8);
            assert_eq!(mod_add(25u8, &10u8, &30u8), 5u8);
        }

        #[test]
        fn test_mod_add_overflow() {
            assert_eq!(mod_add(200u8, &100u8, &50u8), 0u8);
            assert_eq!(mod_add(255u8, &255u8, &100u8), 10u8);
        }

        #[test]
        fn test_mod_add_with_zero() {
            assert_eq!(mod_add(0u8, &25u8, &30u8), 25u8);
            assert_eq!(mod_add(25u8, &0u8, &30u8), 25u8);
            assert_eq!(mod_add(0u8, &0u8, &30u8), 0u8);
        }

        #[test]
        fn test_mod_add_with_max_values() {
            assert_eq!(mod_add(255u8, &1u8, &100u8), 56u8);
            assert_eq!(mod_add(254u8, &1u8, &255u8), 0u8);
            assert_eq!(mod_add(255u8, &255u8, &255u8), 0u8);
        }

        #[test]
        fn test_mod_add_modulus_is_one() {
            assert_eq!(mod_add(10u8, &20u8, &1u8), 0u8);
            assert_eq!(mod_add(255u8, &255u8, &1u8), 0u8);
        }

        #[test]
        #[should_panic]
        fn test_mod_add_modulus_is_zero() {
            mod_add(10u8, &20u8, &0u8);
        }

        #[test]
        fn test_mod_add_operands_equal_modulus_minus_one() {
            assert_eq!(mod_add(19u8, &19u8, &20u8), 18u8);
            assert_eq!(mod_add(254u8, &254u8, &255u8), 253u8);
        }

        #[test]
        fn test_mod_add_large_modulus() {
            let large_modulus = 300u16;
            let result = mod_add(200u8, &100u8, &(large_modulus as u8));
            assert_eq!(result, 36u8);
        }

        #[test]
        fn test_mod_add_modulus_equals_u8_max() {
            assert_eq!(mod_add(100u8, &155u8, &255u8), 0u8);
            assert_eq!(mod_add(200u8, &100u8, &255u8), 45u8);
        }

        #[test]
        fn test_mod_add_overflow_edge_case() {
            assert_eq!(mod_add(255u8, &1u8, &255u8), 1u8);
        }

        #[test]
        fn test_mod_add_with_operands_exceeding_modulus() {
            assert_eq!(mod_add(200u8, &100u8, &50u8), 0u8);
            assert_eq!(mod_add(75u8, &80u8, &60u8), 35u8);
        }

        #[test]
        fn test_mod_add_with_modulus_exceeding_u8_max() {
            let modulus = 300u16;
            let result = mod_add(250u8, &10u8, &(modulus as u8));
            assert_eq!(result, 40u8);
        }
    };
}

#[cfg(test)]
mod strict_mod_add_tests {
    use super::strict_mod_add;
    generate_mod_add_tests!(strict_mod_add, u8, by_ref);
}

#[cfg(test)]
mod constrained_mod_add_tests {
    use super::constrained_mod_add;
    generate_mod_add_tests!(constrained_mod_add, u8, by_ref);
}

#[cfg(test)]
mod basic_mod_add_tests {
    use super::basic_mod_add;
    generate_mod_add_tests!(basic_mod_add, u8, by_val);
}

#[cfg(test)]
#[cfg(feature = "nightly")]
const _: () = {
    let result = const_mod_add(5u8, 10u8, 20u8);
    assert!(result == 15u8);
};

#[cfg(test)]
#[cfg(feature = "nightly")]
mod const_mod_add_tests {
    use super::const_mod_add;
    generate_mod_add_tests!(const_mod_add, u8, by_val);
}

#[cfg(test)]
macro_rules! add_test_module {
    (
        $stem:ident,           // Base name (e.g., "bnum")
        $type_path:path,       // Full path to the type
        $(type $type_def:ty = $type_expr:ty;)? // Optional type definition
        strict: $strict:expr,
        constrained: $constrained:expr,
        basic: $basic:expr,
    ) => {
        paste::paste! {
            mod [<$stem _tests>] {     // This creates e.g., mod bnum_tests
                #[allow(unused_imports)]
                use $type_path;
                $( type $type_def = $type_expr; )?

                #[test]
                #[allow(unused_variables)]
                fn test_mod_add_basic() {
                    let a = U256::from(5u8);
                    let b = U256::from(10u8);
                    let m = U256::from(20u8);
                    let result = U256::from(15u8);

                    crate::maybe_test!($strict, assert_eq!(super::strict_mod_add(a, &b, &m), result));
                    let a = U256::from(5u8);
                    crate::maybe_test!($constrained, assert_eq!(super::constrained_mod_add(a, &b, &m), result));
                    let a = U256::from(5u8);
                    crate::maybe_test!($basic, assert_eq!(super::basic_mod_add(a, b, m), result));
                }
            }
        }
    };
}

#[cfg(test)]
mod bnum_add_tests {
    use super::basic_mod_add;
    use super::constrained_mod_add;
    use super::strict_mod_add;

    add_test_module!(
        bnum,
        bnum::types::U256,
        strict: off, // OverflowingAdd + OverflowingSub is not implemented
        constrained: on,
        basic: on,
    );

    add_test_module!(
        bnum_patched,
        bnum_patched::types::U256,
        strict: on,
        constrained: on,
        basic: on,
    );

    add_test_module!(
        crypto_bigint,
        crypto_bigint::U256,
        strict: off,  // "Missing OverflowingAdd + OverflowingSub" },
        constrained: off, // "Rem<'a> is not implemented for U256" },
        basic: on,
    );

    add_test_module!(
        crypto_bigint_patched,
        crypto_bigint_patched::U256,
        strict: on,
        constrained: on,
        basic: on,
    );

    add_test_module!(
        num_bigint,
        num_bigint::BigUint,
        type U256 = num_bigint::BigUint;
        strict: off, // OverflowingAdd + OverflowingSub is not implemented
        constrained: off, // WrappingAdd + WrappingSub is not implemented
        basic: off, // Copy cannot be implemented, heap allocation
    );

    add_test_module!(
        num_bigint_patched,
        num_bigint_patched::BigUint,
        type U256 = num_bigint_patched::BigUint;
        strict: on,
        constrained: on,
        basic: off, // Copy cannot be implemented, heap allocation
    );

    add_test_module!(
        ibig,
        ibig::UBig,
        type U256 = ibig::UBig;
        strict: off, // OverflowingAdd + OverflowingSub is not implemented
        constrained: off, // WrappingAdd + WrappingSub is not implemented
        basic: off, // Copy cannot be implemented, heap allocation
    );

    add_test_module!(
        ibig_patched,
        ibig_patched::UBig,
        type U256 = ibig_patched::UBig;
        strict: on,
        constrained: on,
        basic: off, // Copy cannot be implemented, heap allocation
    );

    // Default (Nct-personality) FixedUInt provides Rem; the wrapper
    // functions are usable here. See fixed_bigint_pr_tests below for
    // additional _pr API coverage. (Ct-typed FixedUInt intentionally
    // omits Rem — the schoolbook reduce-then-add is variable-time, so a
    // Ct value passed to these wrappers would be a compile error.)
    add_test_module!(
        fixed_bigint,
        fixed_bigint::FixedUInt,
        type U256 = fixed_bigint::FixedUInt<u32, 4>;
        strict: on,
        constrained: on,
        basic: on,
    );
}

#[cfg(test)]
mod fixed_bigint_pr_tests {
    use super::{basic_mod_add_pr, constrained_mod_add_pr, strict_mod_add_pr};
    type U256 = fixed_bigint::FixedUInt<u32, 4>;

    #[test]
    fn test_mod_add_basic_pr() {
        let m = U256::from(20u8);
        let a = U256::from(7u8);
        let b = U256::from(8u8);
        let expected = U256::from(15u8); // 7 + 8 = 15, < 20

        assert_eq!(strict_mod_add_pr(a, &b, &m), expected);
        let a = U256::from(7u8);
        assert_eq!(constrained_mod_add_pr(a, &b, &m), expected);
        let a = U256::from(7u8);
        assert_eq!(basic_mod_add_pr(a, b, m), expected);
    }

    #[test]
    fn test_mod_add_wraps_pr() {
        // a + b >= m: subtract m
        let m = U256::from(20u8);
        let a = U256::from(15u8);
        let b = U256::from(13u8);
        let expected = U256::from(8u8); // 15 + 13 = 28 ≡ 8 (mod 20)

        assert_eq!(strict_mod_add_pr(a, &b, &m), expected);
        let a = U256::from(15u8);
        assert_eq!(constrained_mod_add_pr(a, &b, &m), expected);
        let a = U256::from(15u8);
        assert_eq!(basic_mod_add_pr(a, b, m), expected);
    }
}