binius_field/arch/portable/
pairwise_recursive_arithmetic.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
// Copyright 2024 Irreducible Inc.

use crate::{
	arch::PairwiseRecursiveStrategy,
	arithmetic_traits::{
		InvertOrZero, MulAlpha, Square, TaggedInvertOrZero, TaggedMul, TaggedMulAlpha, TaggedSquare,
	},
	packed::PackedField,
	TowerExtensionField,
};

impl<P> TaggedMul<PairwiseRecursiveStrategy> for P
where
	P: PackedField,
	P::Scalar: TowerExtensionField<DirectSubfield: MulAlpha>,
{
	#[inline]
	fn mul(self, rhs: Self) -> Self {
		P::from_fn(|i| {
			let (a0, a1) = self.get(i).into();
			let (b0, b1) = rhs.get(i).into();
			let (z0, z2) = (a0 * b0, a1 * b1);
			let z0z2 = z0 + z2;
			let z1 = (a0 + a1) * (b0 + b1) - z0z2;
			let z2a = MulAlpha::mul_alpha(z2);

			(z0z2, z1 + z2a).into()
		})
	}
}

impl<P> TaggedSquare<PairwiseRecursiveStrategy> for P
where
	P: PackedField,
	P::Scalar: TowerExtensionField<DirectSubfield: MulAlpha>,
{
	#[inline]
	fn square(self) -> Self {
		P::from_fn(|i| {
			let (a0, a1) = self.get(i).into();
			let (z0, z2) = (Square::square(a0), Square::square(a1));
			let z2a = MulAlpha::mul_alpha(z2);
			(z0 + z2, z2a).into()
		})
	}
}

impl<P> TaggedMulAlpha<PairwiseRecursiveStrategy> for P
where
	P: PackedField,
	P::Scalar: TowerExtensionField<DirectSubfield: MulAlpha>,
{
	#[inline]
	fn mul_alpha(self) -> Self {
		P::from_fn(|i| {
			let (a0, a1) = self.get(i).into();
			let z1 = MulAlpha::mul_alpha(a1);

			(a1, a0 + z1).into()
		})
	}
}

impl<P> TaggedInvertOrZero<PairwiseRecursiveStrategy> for P
where
	P: PackedField,
	P::Scalar: TowerExtensionField<DirectSubfield: MulAlpha + InvertOrZero>,
{
	#[inline]
	fn invert_or_zero(self) -> Self {
		P::from_fn(|i| {
			let (a0, a1) = self.get(i).into();
			let a0z1 = a0 + MulAlpha::mul_alpha(a1);
			let delta = a0 * a0z1 + Square::square(a1);
			let delta_inv = InvertOrZero::invert_or_zero(delta);
			let inv0 = delta_inv * a0z1;
			let inv1 = delta_inv * a1;
			(inv0, inv1).into()
		})
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	use crate::test_utils::{
		define_invert_tests, define_mul_alpha_tests, define_multiply_tests, define_square_tests,
	};

	define_multiply_tests!(
		TaggedMul<PairwiseRecursiveStrategy>::mul,
		TaggedMul<PairwiseRecursiveStrategy>
	);

	define_square_tests!(
		TaggedSquare<PairwiseRecursiveStrategy>::square,
		TaggedSquare<PairwiseRecursiveStrategy>
	);

	define_invert_tests!(
		TaggedInvertOrZero<PairwiseRecursiveStrategy>::invert_or_zero,
		TaggedInvertOrZero<PairwiseRecursiveStrategy>
	);

	define_mul_alpha_tests!(
		TaggedMulAlpha<PairwiseRecursiveStrategy>::mul_alpha,
		TaggedMulAlpha<PairwiseRecursiveStrategy>
	);
}