use crate::U256;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C, align(64))]
pub struct U256x2 {
pub low: U256,
pub high: U256,
}
impl U256x2 {
#[inline(always)]
pub const fn new(low: U256, high: U256) -> Self {
Self { low, high }
}
#[inline(always)]
pub fn add_pair(&self, rhs: &Self) -> Self {
Self {
low: self.low.wrapping_add(&rhs.low),
high: self.high.wrapping_add(&rhs.high),
}
}
#[inline(always)]
pub fn mul_pair(&self, rhs: &Self) -> Self {
Self {
low: self.low.wrapping_mul(&rhs.low),
high: self.high.wrapping_mul(&rhs.high),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_new_and_fields() {
let a = U256::from_limbs([1, 2, 3, 4]);
let b = U256::from_limbs([5, 6, 7, 8]);
let pair = U256x2::new(a, b);
assert_eq!(pair.low, a);
assert_eq!(pair.high, b);
}
#[test]
fn test_add_pair_is_elementwise() {
let pair_a = U256x2::new(U256::from_limbs([1, 0, 0, 0]), U256::from_limbs([10, 0, 0, 0]));
let pair_b = U256x2::new(U256::from_limbs([2, 0, 0, 0]), U256::from_limbs([20, 0, 0, 0]));
let res = pair_a.add_pair(&pair_b);
assert_eq!(res.low, U256::from_limbs([3, 0, 0, 0]));
assert_eq!(res.high, U256::from_limbs([30, 0, 0, 0]));
}
#[test]
fn test_add_pair_carry_is_independent_per_lane() {
let pair_a = U256x2::new(U256::from_limbs([u64::MAX, 0, 0, 0]), U256::from_limbs([1, 0, 0, 0]));
let pair_b = U256x2::new(U256::from_limbs([1, 0, 0, 0]), U256::from_limbs([1, 0, 0, 0]));
let res = pair_a.add_pair(&pair_b);
assert_eq!(res.low, U256::from_limbs([0, 1, 0, 0]));
assert_eq!(res.high, U256::from_limbs([2, 0, 0, 0]));
}
#[test]
fn test_mul_pair_is_elementwise() {
let pair_a = U256x2::new(U256::from_limbs([10, 0, 0, 0]), U256::from_limbs([3, 0, 0, 0]));
let pair_b = U256x2::new(U256::from_limbs([5, 0, 0, 0]), U256::from_limbs([4, 0, 0, 0]));
let res = pair_a.mul_pair(&pair_b);
assert_eq!(res.low, U256::from_limbs([50, 0, 0, 0]));
assert_eq!(res.high, U256::from_limbs([12, 0, 0, 0]));
}
#[test]
fn test_equality_derive() {
let a = U256x2::new(U256::ZERO, U256::ONE);
let b = U256x2::new(U256::ZERO, U256::ONE);
let c = U256x2::new(U256::ONE, U256::ZERO);
assert_eq!(a, b);
assert_ne!(a, c);
}
}