Skip to main content

crypto_bigint/
primitives.rs

1//! Integer primitives for cryptographic arithmetic.
2
3use crate::{Choice, WideWord, Word};
4use core::hint::black_box;
5
6/// Computes `lhs + rhs + carry`, returning the result along with the new carry (0, 1, or 2).
7#[inline(always)]
8#[allow(clippy::cast_possible_truncation)]
9pub(crate) const fn carrying_add(lhs: Word, rhs: Word, carry: Word) -> (Word, Word) {
10    if cfg!(all(target_arch = "arm", not(target_feature = "thumb2"))) {
11        // Widened addition can introduce secret-dependent branches when extracting carries
12        // on Thumb-1. Use the hardened word-sized primitive for both additions instead.
13        let (sum, carry1) = overflowing_add(lhs, rhs);
14        let (sum, carry2) = overflowing_add(sum, carry);
15
16        // The incoming carry is a full Word, so both additions can overflow.
17        (sum, carry1.wrapping_add(carry2))
18    } else {
19        // We could use `Word::overflowing_add()` here analogous to `overflowing_add()`,
20        // but this version seems to produce a slightly better assembly.
21        let a = lhs as WideWord;
22        let b = rhs as WideWord;
23        let carry = carry as WideWord;
24        let ret = a + b + carry;
25        (ret as Word, (ret >> Word::BITS) as Word)
26    }
27}
28
29/// Computes `lhs + rhs`, returning the result along with the carry (0 or 1).
30#[inline(always)]
31pub(crate) const fn overflowing_add(lhs: Word, rhs: Word) -> (Word, Word) {
32    if cfg!(all(target_arch = "arm", not(target_feature = "thumb2"))) {
33        let sum = lhs.wrapping_add(rhs);
34
35        // See "Hacker's Delight", 2nd edition, section 2-13 (Overflow detection).
36        // Avoid a boolean overflow result, which can become a branch on Thumb-1.
37        // TODO(tarcieri): export `ctutils::bitborrow!` macro and use that
38        let carry = ((lhs & rhs) | ((lhs | rhs) & !sum)) >> (Word::BITS - 1);
39        (sum, black_box(carry))
40    } else {
41        let (res, carry) = lhs.overflowing_add(rhs);
42        (res, carry as Word)
43    }
44}
45
46/// Computes `lhs - rhs - borrow`, using word-sized borrow masks.
47///
48/// The incoming borrow is the most significant bit of `borrow`; all other bits are ignored.
49/// The outgoing borrow is `Word::MAX` if the subtraction underflows, or zero otherwise.
50#[inline]
51pub(crate) const fn borrowing_sub(lhs: Word, rhs: Word, borrow: Word) -> (Word, Word) {
52    // Keep all arithmetic in Word: widening can trigger incorrect optimization on older compilers:
53    // https://github.com/rust-lang/rust/issues/149522
54    let difference = lhs
55        .wrapping_sub(rhs)
56        .wrapping_sub(borrow >> (Word::BITS - 1));
57
58    // See "Hacker's Delight", 2nd edition, section 2-13 (Overflow detection).
59    let borrow = ((!lhs & rhs) | ((!lhs | rhs) & difference)) >> (Word::BITS - 1);
60
61    // Keep the full-width bit opaque before forming a mask, so a caller's masked addend can't be
62    // folded into a secret-dependent branch.
63    (difference, black_box(borrow).wrapping_neg())
64}
65
66/// Computes `lhs * rhs`, returning the low and the high words of the result.
67#[inline(always)]
68#[allow(clippy::cast_possible_truncation)]
69pub(crate) const fn widening_mul(lhs: Word, rhs: Word) -> (Word, Word) {
70    let a = lhs as WideWord;
71    let b = rhs as WideWord;
72    let ret = a * b;
73    (ret as Word, (ret >> Word::BITS) as Word)
74}
75
76/// Computes `(lhs * rhs) + addend + carry`, returning the result along with the new carry.
77#[inline(always)]
78#[allow(clippy::cast_possible_truncation)]
79pub(crate) const fn carrying_mul_add(
80    lhs: Word,
81    rhs: Word,
82    addend: Word,
83    carry: Word,
84) -> (Word, Word) {
85    let lhs = lhs as WideWord;
86    let rhs = rhs as WideWord;
87    let addend = addend as WideWord;
88    let carry = carry as WideWord;
89
90    // Cannot overflow:
91    // lhs      * rhs      + addend   + carry
92    // (2^64-1) * (2^64-1) + (2^64-1) + (2^64-1) =
93    // 2^128 - 2^65 + 1 + 2^64 - 1 + 2^64 - 1 =
94    // 2^128 - 2^65 + 2*2^64 - 1 =
95    // 2^128 - 1 = u128::MAX
96    let ret = ((lhs * rhs) + addend) + carry;
97    (ret as Word, (ret >> Word::BITS) as Word)
98}
99
100/// Count leading zero bits, returning `Word::BITS` if `value` is zero.
101#[inline]
102#[allow(clippy::cast_possible_truncation)]
103pub(crate) const fn leading_zeros(value: Word) -> u32 {
104    if cfg!(any(target_arch = "aarch64", target_arch = "x86_64")) {
105        value.leading_zeros()
106    } else {
107        cpubits::cpubits! {
108            32 => { leading_zeros_u32(value) }
109            64 => {
110                let hi = (value >> 32) as u32;
111                let lo = value as u32;
112                let mask = Choice::from_u32_nz(hi).not().to_u32_mask();
113                leading_zeros_u32(hi).wrapping_add(mask & leading_zeros_u32(lo))
114            }
115        }
116    }
117}
118
119/// Count leading zero bits, using native instructions where supported.
120#[inline]
121const fn leading_zeros_u32(value: u32) -> u32 {
122    if cfg!(any(
123        target_arch = "aarch64",
124        target_arch = "x86",
125        target_arch = "x86_64",
126        target_feature = "thumb2",
127        target_feature = "zbb"
128    )) {
129        value.leading_zeros()
130    } else {
131        leading_zeros_u32_soft(value)
132    }
133}
134
135/// Fixed-stage binary search for the highest set bit, including the zero case.
136#[inline]
137const fn leading_zeros_u32_soft(mut value: u32) -> u32 {
138    let mut count = 0u32;
139    let mut shift = 16;
140
141    while shift != 0 {
142        let mask = Choice::from_u32_nz(value >> (u32::BITS - shift))
143            .not()
144            .to_u32_mask();
145        value ^= mask & (value ^ (value << shift));
146        count = count.wrapping_add(mask & shift);
147        shift >>= 1;
148    }
149
150    count.wrapping_add(Choice::from_u32_nz(value).not().to_u32_mask() & 1)
151}
152
153/// Count trailing zero bits, returning `Word::BITS` if `value` is zero.
154#[inline]
155#[allow(clippy::cast_possible_truncation)]
156pub(crate) const fn trailing_zeros(value: Word) -> u32 {
157    if cfg!(any(target_arch = "aarch64", target_arch = "x86_64")) {
158        value.trailing_zeros()
159    } else {
160        cpubits::cpubits! {
161            32 => { trailing_zeros_u32(value) }
162            64 => {
163                let hi = (value >> 32) as u32;
164                let lo = value as u32;
165                let mask = Choice::from_u32_nz(lo).not().to_u32_mask();
166                trailing_zeros_u32(lo).wrapping_add(mask & trailing_zeros_u32(hi))
167            }
168        }
169    }
170}
171
172/// Count trailing zero bits, using native instructions where supported.
173#[inline]
174const fn trailing_zeros_u32(value: u32) -> u32 {
175    if cfg!(any(
176        target_arch = "aarch64",
177        target_arch = "x86",
178        target_arch = "x86_64",
179        target_feature = "thumb2",
180        target_feature = "zbb"
181    )) {
182        value.trailing_zeros()
183    } else {
184        // Reversing bits uses fixed shifts and masks when RBIT is unavailable.
185        leading_zeros_u32_soft(value.reverse_bits())
186    }
187}
188
189/// `const fn` equivalent of `u32::max(a, b)`.
190#[inline]
191pub(crate) const fn u32_max(a: u32, b: u32) -> u32 {
192    Choice::from_u32_lt(a, b).select_u32(a, b)
193}
194
195/// `const` equivalent of `u32::min(a, b)`.
196#[inline]
197pub(crate) const fn u32_min(a: u32, b: u32) -> u32 {
198    Choice::from_u32_lt(a, b).select_u32(b, a)
199}
200
201/// Remainder calculation, constant time for a given divisor `d`.
202/// Based on "Faster Remainder by Direct Computation: Applications to Compilers and Software Libraries"
203/// by Daniel Lemire, Owen Kaser, and Nathan Kurz., Fig. 1.
204#[inline(never)]
205#[allow(clippy::cast_possible_truncation, reason = "needs triage")]
206#[allow(clippy::integer_division_remainder_used, reason = "needs triage")]
207pub(crate) const fn u32_rem(n: u32, d: u32) -> u32 {
208    assert!(d > 0, "divisor must be nonzero");
209    let c = u64::MAX / (d as u64) + 1;
210    (((c.wrapping_mul(n as u64) as u128) * d as u128) >> 64) as u32
211}
212
213/// Compute the number of bits needed to represent `n`.
214#[inline(always)]
215pub(crate) const fn u32_bits(n: u32) -> u32 {
216    u32::BITS - n.leading_zeros()
217}
218
219/// Return a `Choice` representing whether `a < b`.
220#[allow(clippy::cast_possible_truncation)]
221#[cfg(target_pointer_width = "32")]
222#[inline]
223pub(crate) const fn usize_lt(a: usize, b: usize) -> Choice {
224    Choice::from_u32_lt(a as u32, b as u32)
225}
226
227/// Return a `Choice` representing whether `a < b`.
228#[allow(clippy::cast_possible_truncation)]
229#[cfg(target_pointer_width = "64")]
230#[inline]
231pub(crate) const fn usize_lt(a: usize, b: usize) -> Choice {
232    Choice::from_u64_lt(a as u64, b as u64)
233}
234
235cpubits::cpubits! {
236    32 => {
237        /// Returns the multiplicative inverse of the argument modulo 2^32.
238        ///
239        /// For correct results, the input `value` must be odd.
240        #[must_use]
241        pub(crate) const fn u32_invert_odd(value: u32) -> u32 {
242            debug_assert!(value & 1 == 1, "value must be odd");
243            let x = value.wrapping_mul(3) ^ 2;
244            let y = 1u32.wrapping_sub(x.wrapping_mul(value));
245            let (x, y) = (x.wrapping_mul(y.wrapping_add(1)), y.wrapping_mul(y));
246            let (x, y) = (x.wrapping_mul(y.wrapping_add(1)), y.wrapping_mul(y));
247            x.wrapping_mul(y.wrapping_add(1))
248        }
249    }
250}
251
252/// Returns the multiplicative inverse of the argument modulo 2^64. The implementation is based
253/// on Hurchalla's method for computing the multiplicative inverse modulo a power of two, and
254/// is essentially an optimized Newton iteration.
255///
256/// For correct results, the input `value` must be odd.
257///
258/// For better understanding the implementation, the following paper is recommended:
259/// J. Hurchalla, "An Improved Integer Multiplicative Inverse (modulo 2^w)",
260/// <https://arxiv.org/abs/2204.04342>
261#[must_use]
262pub(crate) const fn u64_invert_odd(value: u64) -> u64 {
263    debug_assert!(value & 1 == 1, "value must be odd");
264    let x = value.wrapping_mul(3) ^ 2;
265    let y = 1u64.wrapping_sub(x.wrapping_mul(value));
266    let (x, y) = (x.wrapping_mul(y.wrapping_add(1)), y.wrapping_mul(y));
267    let (x, y) = (x.wrapping_mul(y.wrapping_add(1)), y.wrapping_mul(y));
268    let (x, y) = (x.wrapping_mul(y.wrapping_add(1)), y.wrapping_mul(y));
269    x.wrapping_mul(y.wrapping_add(1))
270}
271
272#[cfg(test)]
273mod tests {
274    use super::{u32_max, u32_min, u32_rem, usize_lt};
275    use crate::{WideWord, Word};
276
277    // These primitives must remain usable by const callers.
278    const _: () = {
279        assert!(super::carrying_add(Word::MAX, Word::MAX, Word::MAX).0 == Word::MAX - 2);
280        assert!(super::carrying_add(Word::MAX, Word::MAX, Word::MAX).1 == 2);
281        assert!(super::overflowing_add(Word::MAX, 1).0 == 0);
282        assert!(super::overflowing_add(Word::MAX, 1).1 == 1);
283        assert!(super::borrowing_sub(0, 0, Word::MAX).0 == Word::MAX);
284        assert!(super::borrowing_sub(0, 0, Word::MAX).1 == Word::MAX);
285        assert!(super::borrowing_sub(1, 0, Word::MAX).1 == 0);
286        assert!(super::leading_zeros(0) == Word::BITS);
287        assert!(super::trailing_zeros(0) == Word::BITS);
288        assert!(super::leading_zeros_u32_soft(0) == u32::BITS);
289    };
290
291    #[test]
292    #[allow(clippy::cast_possible_truncation, reason = "tests")]
293    fn addition_boundary_values() {
294        let high_bit = 1 << (Word::BITS - 1);
295        let values = [
296            0,
297            1,
298            2,
299            high_bit - 1,
300            high_bit,
301            high_bit + 1,
302            Word::MAX - 1,
303            Word::MAX,
304        ];
305
306        for lhs in values {
307            for rhs in values {
308                let expected = WideWord::from(lhs) + WideWord::from(rhs);
309                assert_eq!(
310                    super::overflowing_add(lhs, rhs),
311                    (expected as Word, (expected >> Word::BITS) as Word)
312                );
313
314                // The incoming carry is not restricted to a bit, and the outgoing carry can be 2.
315                // In particular, combining the two overflows with OR is wrong.
316                for carry in values {
317                    let expected = expected + WideWord::from(carry);
318                    assert_eq!(
319                        super::carrying_add(lhs, rhs, carry),
320                        (expected as Word, (expected >> Word::BITS) as Word)
321                    );
322                }
323            }
324        }
325    }
326
327    #[test]
328    fn zero_counts() {
329        for bit in 0..Word::BITS {
330            for value in [0, 1 << bit, !(1 << bit), Word::MAX >> bit] {
331                assert_eq!(super::leading_zeros(value), value.leading_zeros());
332                assert_eq!(super::trailing_zeros(value), value.trailing_zeros());
333            }
334        }
335    }
336
337    #[test]
338    fn zero_counts_u32() {
339        for bit in 0..u32::BITS {
340            for value in [0, 1 << bit, !(1 << bit), u32::MAX >> bit] {
341                assert_eq!(super::leading_zeros_u32(value), value.leading_zeros());
342                assert_eq!(super::trailing_zeros_u32(value), value.trailing_zeros());
343                // Exercise the software fallback even on hosts with native instructions.
344                assert_eq!(super::leading_zeros_u32_soft(value), value.leading_zeros());
345                assert_eq!(
346                    super::leading_zeros_u32_soft(value.reverse_bits()),
347                    value.trailing_zeros()
348                );
349            }
350        }
351    }
352
353    #[test]
354    fn carrying_mul_add_cannot_overflow() {
355        let lhs = Word::MAX;
356        let rhs = Word::MAX;
357        let addend = Word::MAX;
358        let carry_in = Word::MAX;
359        let (result, carry_out) = super::carrying_mul_add(lhs, rhs, addend, carry_in);
360        assert_eq!(result, Word::MAX);
361        assert_eq!(carry_out, Word::MAX);
362    }
363
364    #[test]
365    fn test_u32_const_min() {
366        assert_eq!(u32_min(0, 5), 0);
367        assert_eq!(u32_min(7, 0), 0);
368        assert_eq!(u32_min(7, 5), 5);
369        assert_eq!(u32_min(7, 7), 7);
370    }
371
372    #[test]
373    fn test_u32_const_max() {
374        assert_eq!(u32_max(0, 5), 5);
375        assert_eq!(u32_max(7, 0), 7);
376        assert_eq!(u32_max(7, 5), 7);
377        assert_eq!(u32_max(7, 7), 7);
378    }
379
380    #[test]
381    fn test_u32_const_rem() {
382        assert_eq!(u32_rem(0, 5), 0);
383        assert_eq!(u32_rem(4, 5), 4);
384        assert_eq!(u32_rem(7, 5), 2);
385        assert_eq!(u32_rem(101, 5), 1);
386    }
387
388    #[test]
389    fn test_usize_const_lt() {
390        assert!(usize_lt(0, 5).to_bool());
391        assert!(!usize_lt(7, 0).to_bool());
392        assert!(!usize_lt(7, 5).to_bool());
393        assert!(!usize_lt(7, 7).to_bool());
394    }
395
396    cpubits::cpubits! {
397        32 => {
398            #[test]
399            fn test_u32_invert_odd() {
400                use super::u32_invert_odd;
401
402                assert_eq!(u32_invert_odd(1), 1);
403                assert_eq!(u32_invert_odd(5).wrapping_mul(5), 1);
404                assert_eq!(u32_invert_odd(u32::MAX).wrapping_mul(u32::MAX), 1);
405            }
406        }
407    }
408}