p3_monty_31/
utils.rs

1use crate::{FieldParameters, MontyParameters};
2
3/// Convert a u32 into MONTY form.
4/// There are no constraints on the input.
5/// The output will be a u32 in range [0, P).
6#[inline]
7pub(crate) const fn to_monty<MP: MontyParameters>(x: u32) -> u32 {
8    (((x as u64) << MP::MONTY_BITS) % MP::PRIME as u64) as u32
9}
10
11/// Convert a u64 into MONTY form.
12/// There are no constraints on the input.
13/// The output will be a u32 in range [0, P).
14#[inline]
15pub(crate) const fn to_monty_64<MP: MontyParameters>(x: u64) -> u32 {
16    (((x as u128) << MP::MONTY_BITS) % MP::PRIME as u128) as u32
17}
18
19/// Convert a u32 out of MONTY form.
20/// There are no constraints on the input.
21/// The output will be a u32 in range [0, P).
22#[inline]
23#[must_use]
24pub(crate) const fn from_monty<MP: MontyParameters>(x: u32) -> u32 {
25    monty_reduce::<MP>(x as u64)
26}
27
28/// Given an element x from a 31 bit field F_P compute x/2.
29/// The input must be in [0, P).
30/// The output will also be in [0, P).
31#[inline]
32pub(crate) const fn halve_u32<FP: FieldParameters>(input: u32) -> u32 {
33    let shr = input >> 1;
34    let lo_bit = input & 1;
35    let shr_corr = shr + FP::HALF_P_PLUS_1;
36    if lo_bit == 0 {
37        shr
38    } else {
39        shr_corr
40    }
41}
42
43/// Montgomery reduction of a value in `0..P << MONTY_BITS`.
44/// the input must be in [0, MONTY * P).
45/// the output will be in [0, P).
46#[inline]
47#[must_use]
48pub(crate) const fn monty_reduce<MP: MontyParameters>(x: u64) -> u32 {
49    let t = x.wrapping_mul(MP::MONTY_MU as u64) & (MP::MONTY_MASK as u64);
50    let u = t * (MP::PRIME as u64);
51
52    let (x_sub_u, over) = x.overflowing_sub(u);
53    let x_sub_u_hi = (x_sub_u >> MP::MONTY_BITS) as u32;
54    let corr = if over { MP::PRIME } else { 0 };
55    x_sub_u_hi.wrapping_add(corr)
56}