use crate::{
arithmetic::{
limbs_from_hex,
montgomery::{Encoding, ProductEncoding},
},
limb::{Limb, LIMB_BITS},
};
use core::marker::PhantomData;
#[derive(Clone, Copy)]
pub struct Elem<M, E: Encoding> {
pub(super) limbs: [Limb; MAX_LIMBS],
pub(super) m: PhantomData<M>,
pub(super) encoding: PhantomData<E>,
}
impl<M, E: Encoding> Elem<M, E> {
pub fn zero() -> Self {
Self {
limbs: [0; MAX_LIMBS],
m: PhantomData,
encoding: PhantomData,
}
}
pub const fn from_hex(hex: &str) -> Self {
Elem {
limbs: limbs_from_hex(hex),
m: PhantomData,
encoding: PhantomData,
}
}
}
#[inline]
pub fn mul_mont<M, EA: Encoding, EB: Encoding>(
f: unsafe extern "C" fn(r: *mut Limb, a: *const Limb, b: *const Limb),
a: &Elem<M, EA>,
b: &Elem<M, EB>,
) -> Elem<M, <(EA, EB) as ProductEncoding>::Output>
where
(EA, EB): ProductEncoding,
{
binary_op(f, a, b)
}
#[inline]
pub fn binary_op<M, EA: Encoding, EB: Encoding, ER: Encoding>(
f: unsafe extern "C" fn(r: *mut Limb, a: *const Limb, b: *const Limb),
a: &Elem<M, EA>,
b: &Elem<M, EB>,
) -> Elem<M, ER> {
let mut r = Elem {
limbs: [0; MAX_LIMBS],
m: PhantomData,
encoding: PhantomData,
};
unsafe { f(r.limbs.as_mut_ptr(), a.limbs.as_ptr(), b.limbs.as_ptr()) }
r
}
#[inline]
pub fn binary_op_assign<M, EA: Encoding, EB: Encoding>(
f: unsafe extern "C" fn(r: *mut Limb, a: *const Limb, b: *const Limb),
a: &mut Elem<M, EA>,
b: &Elem<M, EB>,
) {
unsafe { f(a.limbs.as_mut_ptr(), a.limbs.as_ptr(), b.limbs.as_ptr()) }
}
#[inline]
pub fn unary_op<M, E: Encoding>(
f: unsafe extern "C" fn(r: *mut Limb, a: *const Limb),
a: &Elem<M, E>,
) -> Elem<M, E> {
let mut r = Elem {
limbs: [0; MAX_LIMBS],
m: PhantomData,
encoding: PhantomData,
};
unsafe { f(r.limbs.as_mut_ptr(), a.limbs.as_ptr()) }
r
}
#[inline]
pub fn unary_op_assign<M, E: Encoding>(
f: unsafe extern "C" fn(r: *mut Limb, a: *const Limb),
a: &mut Elem<M, E>,
) {
unsafe { f(a.limbs.as_mut_ptr(), a.limbs.as_ptr()) }
}
#[inline]
pub fn unary_op_from_binary_op_assign<M, E: Encoding>(
f: unsafe extern "C" fn(r: *mut Limb, a: *const Limb, b: *const Limb),
a: &mut Elem<M, E>,
) {
unsafe { f(a.limbs.as_mut_ptr(), a.limbs.as_ptr(), a.limbs.as_ptr()) }
}
pub const MAX_LIMBS: usize = (384 + (LIMB_BITS - 1)) / LIMB_BITS;