1// TODO: Use `adt_const_params` once stabilized to make a `Residue` generic around a modulus rather than having to implement a ZST + trait
2#[macro_export]
3/// Implements a modulus with the given name, type, and value, in that specific order. Please `use crypto_bigint::traits::Encoding` to make this work.
4/// For example, `impl_modulus!(MyModulus, U256, "73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001");` implements a 256-bit modulus named `MyModulus`.
5/// The modulus _must_ be odd, or this will panic.
6macro_rules! impl_modulus {
7 ($name:ident, $uint_type:ty, $value:expr) => {
8#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
9pub struct $name {}
10impl<const DLIMBS: usize>
11$crate::modular::constant_mod::ResidueParams<{ <$uint_type>::LIMBS }> for $name
12where
13$uint_type: $crate::ConcatMixed<MixedOutput = $crate::Uint<DLIMBS>>,
14 {
15const LIMBS: usize = <$uint_type>::LIMBS;
16const MODULUS: $uint_type = {
17let res = <$uint_type>::from_be_hex($value);
1819// Check that the modulus is odd
20if res.as_limbs()[0].0 & 1 == 0 {
21panic!("modulus must be odd");
22 }
2324 res
25 };
26const R: $uint_type = $crate::Uint::MAX
27.const_rem(&Self::MODULUS)
28 .0
29.wrapping_add(&$crate::Uint::ONE);
30const R2: $uint_type =
31$crate::Uint::const_rem_wide(Self::R.square_wide(), &Self::MODULUS).0;
32const MOD_NEG_INV: $crate::Limb = $crate::Limb(
33$crate::Word::MIN.wrapping_sub(
34Self::MODULUS
35 .inv_mod2k_vartime($crate::Word::BITS as usize)
36 .as_limbs()[0]
37 .0,
38 ),
39 );
40const R3: $uint_type = $crate::modular::montgomery_reduction(
41&Self::R2.square_wide(),
42&Self::MODULUS,
43Self::MOD_NEG_INV,
44 );
45 }
46 };
47}
4849#[macro_export]
50/// Creates a `Residue` with the given value for a specific modulus.
51/// For example, `residue!(U256::from(105u64), MyModulus);` creates a `Residue` for 105 mod `MyModulus`.
52/// The modulus _must_ be odd, or this will panic.
53macro_rules! const_residue {
54 ($variable:ident, $modulus:ident) => {
55$crate::modular::constant_mod::Residue::<$modulus, { $modulus::LIMBS }>::new(&$variable)
56 };
57}