Skip to main content

p3_field/extension/
binomial_extension.rs

1use alloc::format;
2use alloc::string::ToString;
3use alloc::vec::Vec;
4use core::array;
5use core::fmt::{self, Display, Formatter};
6use core::iter::{Product, Sum};
7use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
8
9use itertools::Itertools;
10use num_bigint::BigUint;
11use p3_util::{as_base_slice, as_base_slice_mut, reconstitute_from_base};
12
13use super::{ExtField, HasFrobenius, HasTwoAdicBinomialExtension, PackedBinomialExtensionField};
14use crate::extension::{Binomial, BinomiallyExtendable, ExtensionAlgebra};
15use crate::field::Field;
16use crate::{
17    Algebra, Dup, ExtensionField, PrimeCharacteristicRing, RawDataSerializable, TwoAdicField,
18    field_to_array,
19};
20
21/// Binomial extension field `F[X] / (X^D - W)`.
22///
23/// Type alias for the unified [`ExtField`] with `Shape = Binomial<F>`.
24pub type BinomialExtensionField<F, const D: usize, A = F> = ExtField<F, D, Binomial<F>, A>;
25
26impl<F: Copy, const D: usize> BinomialExtensionField<F, D, F> {
27    /// Convert a `[[F; D]; N]` array to an array of extension field elements.
28    ///
29    /// Const version of `input.map(BinomialExtensionField::new)`.
30    ///
31    /// # Panics
32    /// Panics if `N == 0`.
33    #[inline]
34    pub const fn new_array<const N: usize>(input: [[F; D]; N]) -> [Self; N] {
35        const { assert!(N > 0) }
36        let mut output = [Self::new(input[0]); N];
37        let mut i = 1;
38        while i < N {
39            output[i] = Self::new(input[i]);
40            i += 1;
41        }
42        output
43    }
44}
45
46impl<F: BinomiallyExtendable<D>, const D: usize> ExtensionField<F>
47    for BinomialExtensionField<F, D>
48{
49    type ExtensionPacking = PackedBinomialExtensionField<F, F::Packing, D>;
50
51    #[inline]
52    fn is_in_basefield(&self) -> bool {
53        self.value[1..].iter().all(F::is_zero)
54    }
55
56    #[inline]
57    fn as_base(&self) -> Option<F> {
58        <Self as ExtensionField<F>>::is_in_basefield(self).then(|| self.value[0])
59    }
60}
61
62impl<F: BinomiallyExtendable<D>, const D: usize> HasFrobenius<F> for BinomialExtensionField<F, D> {
63    /// FrobeniusField automorphisms: x -> x^n, where n is the order of BaseField.
64    #[inline]
65    fn frobenius(&self) -> Self {
66        // Slightly faster than self.repeated_frobenius(1)
67        let mut res = Self::ZERO;
68        for (i, z) in F::DTH_ROOT.powers().take(D).enumerate() {
69            res.value[i] = self.value[i] * z;
70        }
71
72        res
73    }
74
75    /// Repeated Frobenius automorphisms: x -> x^(n^count).
76    ///
77    /// Follows precomputation suggestion in Section 11.3.3 of the
78    /// Handbook of Elliptic and Hyperelliptic Curve Cryptography.
79    #[inline]
80    fn repeated_frobenius(&self, count: usize) -> Self {
81        if count == 0 {
82            return *self;
83        } else if count >= D {
84            // x |-> x^(n^D) is the identity, so x^(n^count) ==
85            // x^(n^(count % D))
86            return self.repeated_frobenius(count % D);
87        }
88
89        // z0 = DTH_ROOT^count = W^(k * count) where k = floor((n-1)/D)
90        let z0 = F::DTH_ROOT.exp_u64(count as u64);
91
92        let mut res = Self::ZERO;
93        for (i, z) in z0.powers().take(D).enumerate() {
94            res.value[i] = self.value[i] * z;
95        }
96
97        res
98    }
99
100    /// Compute the pseudo inverse of a given element making use of the Frobenius automorphism.
101    ///
102    /// Returns `0` if `self == 0`, and `1/self` otherwise.
103    ///
104    /// Algorithm 11.3.4 in Handbook of Elliptic and Hyperelliptic Curve Cryptography.
105    #[inline]
106    fn pseudo_inv(&self) -> Self {
107        // Writing 'a' for self and `q` for the order of the base field, our goal is to compute `a^{-1}`.
108        //
109        // Note that we can write `-1 = (q^{D - 1} + ... + q) - (q^{D - 1} + ... + q + 1)`.
110        // This is a useful decomposition as powers of q can be efficiently computed using the frobenius
111        // automorphism and `Norm(a) = a^{(q^{D - 1} + ... + q + 1)}` is guaranteed to lie in the base field.
112        // This means that `Norm(a)^{-1}` can be computed using base field operations.
113        //
114        // Hence this implementation first computes `ProdConj(a) = a^{q^{D - 1} + ... + q}` using frobenius automorphisms.
115        // From this, it computes `Norm(a) = a * ProdConj(a)` and returns `ProdConj(a) * Norm(a)^{-1} = a^{-1}`.
116
117        // This loop requires a linear number of multiplications and Frobenius automorphisms.
118        // If D is known, it is possible to do this in a logarithmic number. See quintic_inv
119        // for an example of this.
120        let mut prod_conj = self.frobenius();
121        for _ in 2..D {
122            prod_conj = (prod_conj * *self).frobenius();
123        }
124
125        // norm = a * prod_conj is in the base field, so only compute that
126        // coefficient rather than the full product.
127        let a = self.value;
128        let b = prod_conj.value;
129        let mut w_coeff = F::ZERO;
130        // This should really be a dot product but
131        // const generics doesn't let this happen:
132        // b.reverse();
133        // let mut g = F::dot_product::<{D - 1}>(a[1..].try_into().unwrap(), b[..D - 1].try_into().unwrap());
134        for i in 1..D {
135            w_coeff += a[i] * b[D - i];
136        }
137        let norm = F::dot_product(&[a[0], F::W], &[b[0], w_coeff]);
138        debug_assert_eq!(Self::from(norm), *self * prod_conj);
139
140        prod_conj * norm.inverse()
141    }
142}
143
144impl<F, A, const D: usize> PrimeCharacteristicRing for BinomialExtensionField<F, D, A>
145where
146    F: BinomiallyExtendable<D>,
147    A: ExtensionAlgebra<F, D, Binomial<F>> + Copy,
148{
149    type PrimeSubfield = <A as PrimeCharacteristicRing>::PrimeSubfield;
150
151    const ZERO: Self = Self::new([A::ZERO; D]);
152
153    const ONE: Self = Self::new(field_to_array(A::ONE));
154
155    const TWO: Self = Self::new(field_to_array(A::TWO));
156
157    const NEG_ONE: Self = Self::new(field_to_array(A::NEG_ONE));
158
159    #[inline]
160    fn from_prime_subfield(f: Self::PrimeSubfield) -> Self {
161        <A as PrimeCharacteristicRing>::from_prime_subfield(f).into()
162    }
163
164    #[inline]
165    fn halve(&self) -> Self {
166        Self::new(array::from_fn(|i| self.value[i].halve()))
167    }
168
169    #[inline(always)]
170    fn square(&self) -> Self {
171        let mut res = Self::default();
172        <A as ExtensionAlgebra<F, D, Binomial<F>>>::ext_square(&self.value, &mut res.value);
173        res
174    }
175
176    #[inline]
177    fn mul_2exp_u64(&self, exp: u64) -> Self {
178        // Depending on the field, this might be a little slower than
179        // the default implementation if the compiler doesn't realize `F::TWO.exp_u64(exp)` is a constant.
180        Self::new(array::from_fn(|i| self.value[i].mul_2exp_u64(exp)))
181    }
182
183    #[inline]
184    fn div_2exp_u64(&self, exp: u64) -> Self {
185        // Depending on the field, this might be a little slower than
186        // the default implementation if the compiler doesn't realize `F::ONE.halve().exp_u64(exp)` is a constant.
187        Self::new(array::from_fn(|i| self.value[i].div_2exp_u64(exp)))
188    }
189
190    #[inline]
191    fn zero_vec(len: usize) -> Vec<Self> {
192        // SAFETY: this is a repr(transparent) wrapper around an array.
193        unsafe { reconstitute_from_base(F::zero_vec(len * D)) }
194    }
195}
196
197impl<F: BinomiallyExtendable<D>, const D: usize> Algebra<F> for BinomialExtensionField<F, D> {}
198
199impl<F: BinomiallyExtendable<D>, const D: usize> RawDataSerializable
200    for BinomialExtensionField<F, D>
201{
202    const NUM_BYTES: usize = F::NUM_BYTES * D;
203
204    #[inline]
205    fn into_bytes(self) -> impl IntoIterator<Item = u8> {
206        self.value.into_iter().flat_map(|x| x.into_bytes())
207    }
208
209    #[inline]
210    fn into_byte_stream(input: impl IntoIterator<Item = Self>) -> impl IntoIterator<Item = u8> {
211        F::into_byte_stream(input.into_iter().flat_map(|x| x.value))
212    }
213
214    #[inline]
215    fn into_u32_stream(input: impl IntoIterator<Item = Self>) -> impl IntoIterator<Item = u32> {
216        F::into_u32_stream(input.into_iter().flat_map(|x| x.value))
217    }
218
219    #[inline]
220    fn into_u64_stream(input: impl IntoIterator<Item = Self>) -> impl IntoIterator<Item = u64> {
221        F::into_u64_stream(input.into_iter().flat_map(|x| x.value))
222    }
223
224    #[inline]
225    fn into_parallel_byte_streams<const N: usize>(
226        input: impl IntoIterator<Item = [Self; N]>,
227    ) -> impl IntoIterator<Item = [u8; N]> {
228        F::into_parallel_byte_streams(
229            input
230                .into_iter()
231                .flat_map(|x| (0..D).map(move |i| array::from_fn(|j| x[j].value[i]))),
232        )
233    }
234
235    #[inline]
236    fn into_parallel_u32_streams<const N: usize>(
237        input: impl IntoIterator<Item = [Self; N]>,
238    ) -> impl IntoIterator<Item = [u32; N]> {
239        F::into_parallel_u32_streams(
240            input
241                .into_iter()
242                .flat_map(|x| (0..D).map(move |i| array::from_fn(|j| x[j].value[i]))),
243        )
244    }
245
246    #[inline]
247    fn into_parallel_u64_streams<const N: usize>(
248        input: impl IntoIterator<Item = [Self; N]>,
249    ) -> impl IntoIterator<Item = [u64; N]> {
250        F::into_parallel_u64_streams(
251            input
252                .into_iter()
253                .flat_map(|x| (0..D).map(move |i| array::from_fn(|j| x[j].value[i]))),
254        )
255    }
256}
257
258impl<F: BinomiallyExtendable<D>, const D: usize> Field for BinomialExtensionField<F, D> {
259    type Packing = Self;
260
261    const GENERATOR: Self = Self::new(F::EXT_GENERATOR);
262
263    fn try_inverse(&self) -> Option<Self> {
264        if self.is_zero() {
265            return None;
266        }
267
268        let mut res = Self::default();
269
270        match D {
271            2 => quadratic_inv(&self.value, &mut res.value, F::W),
272            3 => cubic_inv(&self.value, &mut res.value, F::W),
273            4 => quartic_inv(&self.value, &mut res.value, F::W),
274            5 => res = quintic_inv(self),
275            8 => octic_inv(&self.value, &mut res.value, F::W),
276            _ => res = self.pseudo_inv(),
277        }
278
279        Some(res)
280    }
281
282    #[inline]
283    fn add_slices(slice_1: &mut [Self], slice_2: &[Self]) {
284        // By construction, Self is repr(transparent) over [F; D].
285        // Additionally, addition is F-linear. Hence we can cast
286        // everything to F and use F's add_slices.
287        unsafe {
288            let base_slice_1 = as_base_slice_mut(slice_1);
289            let base_slice_2 = as_base_slice(slice_2);
290
291            F::add_slices(base_slice_1, base_slice_2);
292        }
293    }
294
295    #[inline]
296    fn order() -> BigUint {
297        F::order().pow(D as u32)
298    }
299}
300
301impl<F, const D: usize> Display for BinomialExtensionField<F, D>
302where
303    F: BinomiallyExtendable<D>,
304{
305    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
306        if self.is_zero() {
307            write!(f, "0")
308        } else {
309            let str = self
310                .value
311                .iter()
312                .enumerate()
313                .filter(|(_, x)| !x.is_zero())
314                .map(|(i, x)| match (i, x.is_one()) {
315                    (0, _) => format!("{x}"),
316                    (1, true) => "X".to_string(),
317                    (1, false) => format!("{x} X"),
318                    (_, true) => format!("X^{i}"),
319                    (_, false) => format!("{x} X^{i}"),
320                })
321                .join(" + ");
322            write!(f, "{str}")
323        }
324    }
325}
326
327impl<F, A, const D: usize> Neg for BinomialExtensionField<F, D, A>
328where
329    F: BinomiallyExtendable<D>,
330    A: Algebra<F>,
331{
332    type Output = Self;
333
334    #[inline]
335    fn neg(self) -> Self {
336        Self::new(self.value.map(A::neg))
337    }
338}
339
340impl<F, A, const D: usize> Add for BinomialExtensionField<F, D, A>
341where
342    F: BinomiallyExtendable<D>,
343    A: ExtensionAlgebra<F, D, Binomial<F>>,
344{
345    type Output = Self;
346
347    #[inline]
348    fn add(self, rhs: Self) -> Self {
349        let value = <A as ExtensionAlgebra<F, D, Binomial<F>>>::ext_add(&self.value, &rhs.value);
350        Self::new(value)
351    }
352}
353
354impl<F, A, const D: usize> Add<A> for BinomialExtensionField<F, D, A>
355where
356    F: BinomiallyExtendable<D>,
357    A: Algebra<F>,
358{
359    type Output = Self;
360
361    #[inline]
362    fn add(mut self, rhs: A) -> Self {
363        self.value[0] += rhs;
364        self
365    }
366}
367
368impl<F, A, const D: usize> AddAssign for BinomialExtensionField<F, D, A>
369where
370    F: BinomiallyExtendable<D>,
371    A: ExtensionAlgebra<F, D, Binomial<F>>,
372{
373    #[inline]
374    fn add_assign(&mut self, rhs: Self) {
375        self.value = <A as ExtensionAlgebra<F, D, Binomial<F>>>::ext_add(&self.value, &rhs.value);
376    }
377}
378
379impl<F, A, const D: usize> AddAssign<A> for BinomialExtensionField<F, D, A>
380where
381    F: BinomiallyExtendable<D>,
382    A: Algebra<F>,
383{
384    #[inline]
385    fn add_assign(&mut self, rhs: A) {
386        self.value[0] += rhs;
387    }
388}
389
390impl<F, A, const D: usize> Sum for BinomialExtensionField<F, D, A>
391where
392    F: BinomiallyExtendable<D>,
393    A: ExtensionAlgebra<F, D, Binomial<F>> + Copy,
394{
395    #[inline]
396    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
397        iter.reduce(|acc, x| acc + x).unwrap_or(Self::ZERO)
398    }
399}
400
401impl<F, A, const D: usize> Sub for BinomialExtensionField<F, D, A>
402where
403    F: BinomiallyExtendable<D>,
404    A: ExtensionAlgebra<F, D, Binomial<F>>,
405{
406    type Output = Self;
407
408    #[inline]
409    fn sub(self, rhs: Self) -> Self {
410        let value = <A as ExtensionAlgebra<F, D, Binomial<F>>>::ext_sub(&self.value, &rhs.value);
411        Self::new(value)
412    }
413}
414
415impl<F, A, const D: usize> Sub<A> for BinomialExtensionField<F, D, A>
416where
417    F: BinomiallyExtendable<D>,
418    A: Algebra<F>,
419{
420    type Output = Self;
421
422    #[inline]
423    fn sub(self, rhs: A) -> Self {
424        let mut res = self.value;
425        res[0] -= rhs;
426        Self::new(res)
427    }
428}
429
430impl<F, A, const D: usize> SubAssign for BinomialExtensionField<F, D, A>
431where
432    F: BinomiallyExtendable<D>,
433    A: ExtensionAlgebra<F, D, Binomial<F>>,
434{
435    #[inline]
436    fn sub_assign(&mut self, rhs: Self) {
437        self.value = <A as ExtensionAlgebra<F, D, Binomial<F>>>::ext_sub(&self.value, &rhs.value);
438    }
439}
440
441impl<F, A, const D: usize> SubAssign<A> for BinomialExtensionField<F, D, A>
442where
443    F: BinomiallyExtendable<D>,
444    A: Algebra<F>,
445{
446    #[inline]
447    fn sub_assign(&mut self, rhs: A) {
448        self.value[0] -= rhs;
449    }
450}
451
452impl<F, A, const D: usize> Mul for BinomialExtensionField<F, D, A>
453where
454    F: BinomiallyExtendable<D>,
455    A: ExtensionAlgebra<F, D, Binomial<F>>,
456{
457    type Output = Self;
458
459    #[inline]
460    fn mul(self, rhs: Self) -> Self {
461        let a = self.value;
462        let b = rhs.value;
463        let mut res = Self::default();
464
465        <A as ExtensionAlgebra<F, D, Binomial<F>>>::ext_mul(&a, &b, &mut res.value);
466
467        res
468    }
469}
470
471impl<F, A, const D: usize> Mul<A> for BinomialExtensionField<F, D, A>
472where
473    F: BinomiallyExtendable<D>,
474    A: ExtensionAlgebra<F, D, Binomial<F>>,
475{
476    type Output = Self;
477
478    #[inline]
479    fn mul(self, rhs: A) -> Self {
480        Self::new(<A as ExtensionAlgebra<F, D, Binomial<F>>>::ext_base_mul(
481            self.value, rhs,
482        ))
483    }
484}
485
486impl<F, A, const D: usize> MulAssign for BinomialExtensionField<F, D, A>
487where
488    F: BinomiallyExtendable<D>,
489    A: ExtensionAlgebra<F, D, Binomial<F>>,
490{
491    #[inline]
492    fn mul_assign(&mut self, rhs: Self) {
493        *self = self.clone() * rhs;
494    }
495}
496
497impl<F, A, const D: usize> MulAssign<A> for BinomialExtensionField<F, D, A>
498where
499    F: BinomiallyExtendable<D>,
500    A: ExtensionAlgebra<F, D, Binomial<F>>,
501{
502    #[inline]
503    fn mul_assign(&mut self, rhs: A) {
504        *self = self.clone() * rhs;
505    }
506}
507
508impl<F, A, const D: usize> Product for BinomialExtensionField<F, D, A>
509where
510    F: BinomiallyExtendable<D>,
511    A: ExtensionAlgebra<F, D, Binomial<F>> + Copy,
512{
513    #[inline]
514    fn product<I: Iterator<Item = Self>>(iter: I) -> Self {
515        iter.reduce(|acc, x| acc * x).unwrap_or(Self::ONE)
516    }
517}
518
519impl<F, const D: usize> Div for BinomialExtensionField<F, D>
520where
521    F: BinomiallyExtendable<D>,
522{
523    type Output = Self;
524
525    #[allow(clippy::suspicious_arithmetic_impl)]
526    #[inline]
527    fn div(self, rhs: Self) -> Self::Output {
528        self * rhs.inverse()
529    }
530}
531
532impl<F, const D: usize> DivAssign for BinomialExtensionField<F, D>
533where
534    F: BinomiallyExtendable<D>,
535{
536    #[inline]
537    fn div_assign(&mut self, rhs: Self) {
538        *self = *self / rhs;
539    }
540}
541
542impl<F: Field + HasTwoAdicBinomialExtension<D>, const D: usize> TwoAdicField
543    for BinomialExtensionField<F, D>
544{
545    const TWO_ADICITY: usize = F::EXT_TWO_ADICITY;
546
547    #[inline]
548    fn two_adic_generator(bits: usize) -> Self {
549        Self::new(F::ext_two_adic_generator(bits))
550    }
551}
552
553/// Add two vectors element wise.
554#[inline]
555pub fn vector_add<R: PrimeCharacteristicRing + Add<R2, Output = R>, R2: Dup, const D: usize>(
556    a: &[R; D],
557    b: &[R2; D],
558) -> [R; D] {
559    array::from_fn(|i| a[i].dup() + b[i].dup())
560}
561
562/// Subtract two vectors element wise.
563#[inline]
564pub fn vector_sub<R: PrimeCharacteristicRing + Sub<R2, Output = R>, R2: Dup, const D: usize>(
565    a: &[R; D],
566    b: &[R2; D],
567) -> [R; D] {
568    array::from_fn(|i| a[i].dup() - b[i].dup())
569}
570
571/// Multiply two vectors representing elements in a binomial extension.
572#[inline]
573pub fn binomial_mul<F: Field, R: Algebra<F> + Algebra<R2>, R2: Algebra<F>, const D: usize>(
574    a: &[R; D],
575    b: &[R2; D],
576    res: &mut [R; D],
577    w: F,
578) {
579    match D {
580        2 => quadratic_mul(a, b, res, w),
581        3 => cubic_mul(a, b, res, w),
582        4 => quartic_mul(a, b, res, w),
583        5 => quintic_mul(a, b, res, w),
584        8 => octic_mul(a, b, res, w),
585        _ => {
586            for (i, a_i) in a.iter().enumerate() {
587                for (j, b_j) in b.iter().enumerate() {
588                    if i + j >= D {
589                        res[i + j - D] += a_i.dup() * w * b_j.dup();
590                    } else {
591                        res[i + j] += a_i.dup() * b_j.dup();
592                    }
593                }
594            }
595        }
596    }
597}
598
599/// Square a vector representing an element in a binomial extension.
600///
601/// This is optimized for the case that R is a prime field or its packing.
602#[inline]
603pub fn binomial_square<F: Field, R: Algebra<F>, const D: usize>(
604    a: &[R; D],
605    res: &mut [R; D],
606    w: F,
607) {
608    match D {
609        2 => {
610            let a1_w = a[1].dup() * w;
611            res[0] = R::dot_product(a[..].try_into().unwrap(), &[a[0].dup(), a1_w]);
612            res[1] = a[0].dup() * a[1].double();
613        }
614        3 => cubic_square(a, res, w),
615        4 => quartic_square(a, res, w),
616        5 => quintic_square(a, res, w),
617        8 => octic_square(a, res, w),
618        _ => binomial_mul::<F, R, R, D>(a, a, res, w),
619    }
620}
621
622/// Optimized multiplication for quadratic extension field.
623///
624/// Makes use of the in built field dot product code. This is optimized for the case that
625/// R is a prime field or its packing.
626///
627/// ```text
628///     A = a0 + a1·X
629///     B = b0 + b1·X
630/// ```
631/// Where `X` satisfies `X² = w`. Then the product is:
632/// ```text
633///     A·B = a0·b0 + a1·b1·w + (a0·b1 + a1·b0)·X
634/// ```
635#[inline]
636fn quadratic_mul<F, R, R2, const D: usize>(a: &[R; D], b: &[R2; D], res: &mut [R; D], w: F)
637where
638    F: Field,
639    R: Algebra<F> + Algebra<R2>,
640    R2: Algebra<F>,
641{
642    let b1_w = b[1].dup() * w;
643
644    // Compute a0·b0 + a1·b1·w
645    res[0] = R::dot_product(a[..].try_into().unwrap(), &[b[0].dup().into(), b1_w.into()]);
646
647    // Compute a0·b1 + a1·b0
648    res[1] = R::dot_product(
649        &[a[0].dup(), a[1].dup()],
650        &[b[1].dup().into(), b[0].dup().into()],
651    );
652}
653
654///Section 11.3.6b in Handbook of Elliptic and Hyperelliptic Curve Cryptography.
655#[inline]
656fn quadratic_inv<F: Field, const D: usize>(a: &[F; D], res: &mut [F; D], w: F) {
657    assert_eq!(D, 2);
658    let neg_a1 = -a[1];
659    let scalar = F::dot_product(&[a[0], neg_a1], &[a[0], w * a[1]]).inverse();
660    res[0] = a[0] * scalar;
661    res[1] = neg_a1 * scalar;
662}
663
664/// Section 11.3.6b in Handbook of Elliptic and Hyperelliptic Curve Cryptography.
665#[inline]
666fn cubic_inv<F: Field, const D: usize>(a: &[F; D], res: &mut [F; D], w: F) {
667    assert_eq!(D, 3);
668    let a0_square = a[0].square();
669    let a1_square = a[1].square();
670    let a2_w = w * a[2];
671    let a0_a1 = a[0] * a[1];
672
673    // scalar = (a0^3+wa1^3+w^2a2^3-3wa0a1a2)^-1
674    let scalar = (a0_square * a[0] + w * a[1] * a1_square + a2_w.square() * a[2]
675        - (F::ONE + F::TWO) * a2_w * a0_a1)
676        .inverse();
677
678    //scalar*[a0^2-wa1a2, wa2^2-a0a1, a1^2-a0a2]
679    res[0] = scalar * (a0_square - a[1] * a2_w);
680    res[1] = scalar * (a2_w * a[2] - a0_a1);
681    res[2] = scalar * (a1_square - a[0] * a[2]);
682}
683
684/// karatsuba multiplication for cubic extension field
685#[inline]
686fn cubic_mul<F: Field, R: Algebra<F> + Algebra<R2>, R2: Algebra<F>, const D: usize>(
687    a: &[R; D],
688    b: &[R2; D],
689    res: &mut [R; D],
690    w: F,
691) {
692    assert_eq!(D, 3);
693    // TODO: Test if we should switch to a naive multiplication approach using dot products.
694    // This is mainly used for a degree 3 extension of Complex<Mersenne31> so this approach might be faster.
695
696    let a0_b0 = a[0].dup() * b[0].dup();
697    let a1_b1 = a[1].dup() * b[1].dup();
698    let a2_b2 = a[2].dup() * b[2].dup();
699
700    res[0] = a0_b0.dup()
701        + ((a[1].dup() + a[2].dup()) * (b[1].dup() + b[2].dup()) - a1_b1.dup() - a2_b2.dup()) * w;
702    res[1] = (a[0].dup() + a[1].dup()) * (b[0].dup() + b[1].dup()) - a0_b0.dup() - a1_b1.dup()
703        + a2_b2.dup() * w;
704    res[2] = (a[0].dup() + a[2].dup()) * (b[0].dup() + b[2].dup()) - a0_b0 - a2_b2 + a1_b1;
705}
706
707/// Section 11.3.6a in Handbook of Elliptic and Hyperelliptic Curve Cryptography.
708#[inline]
709fn cubic_square<F: Field, R: Algebra<F>, const D: usize>(a: &[R; D], res: &mut [R; D], w: F) {
710    assert_eq!(D, 3);
711
712    let w_a2 = a[2].dup() * w;
713
714    res[0] = a[0].square() + (a[1].dup() * w_a2.dup()).double();
715    res[1] = w_a2 * a[2].dup() + (a[0].dup() * a[1].dup()).double();
716    res[2] = a[1].square() + (a[0].dup() * a[2].dup()).double();
717}
718
719/// Multiplication in a quartic binomial extension field.
720///
721/// Makes use of the in built field dot product code. This is optimized for the case that
722/// R is a prime field or its packing.
723#[inline]
724pub fn quartic_mul<F, R, R2, const D: usize>(a: &[R; D], b: &[R2; D], res: &mut [R; D], w: F)
725where
726    F: Field,
727    R: Algebra<F> + Algebra<R2>,
728    R2: Algebra<F>,
729{
730    assert_eq!(D, 4);
731    let b_r_rev: [R; 5] = [
732        b[3].dup().into(),
733        b[2].dup().into(),
734        b[1].dup().into(),
735        b[0].dup().into(),
736        w.into(),
737    ];
738
739    // Constant term = a0*b0 + w(a1*b3 + a2*b2 + a3*b1)
740    let w_coeff_0 =
741        R::dot_product::<3>(a[1..].try_into().unwrap(), b_r_rev[..3].try_into().unwrap());
742    res[0] = R::dot_product(&[a[0].dup(), w_coeff_0], b_r_rev[3..].try_into().unwrap());
743
744    // Linear term = a0*b1 + a1*b0 + w(a2*b3 + a3*b2)
745    let w_coeff_1 =
746        R::dot_product::<2>(a[2..].try_into().unwrap(), b_r_rev[..2].try_into().unwrap());
747    res[1] = R::dot_product(
748        &[a[0].dup(), a[1].dup(), w_coeff_1],
749        b_r_rev[2..].try_into().unwrap(),
750    );
751
752    // Square term = a0*b2 + a1*b1 + a2*b0 + w(a3*b3)
753    let b3_w = b[3].dup() * w;
754    res[2] = R::dot_product::<4>(
755        a[..4].try_into().unwrap(),
756        &[
757            b_r_rev[1].dup(),
758            b_r_rev[2].dup(),
759            b_r_rev[3].dup(),
760            b3_w.into(),
761        ],
762    );
763
764    // Cubic term = a0*b3 + a1*b2 + a2*b1 + a3*b0
765    res[3] = R::dot_product::<4>(a[..].try_into().unwrap(), b_r_rev[..4].try_into().unwrap());
766}
767
768/// Compute the inverse of a quartic binomial extension field element.
769#[inline]
770fn quartic_inv<F: Field, const D: usize>(a: &[F; D], res: &mut [F; D], w: F) {
771    assert_eq!(D, 4);
772
773    // We use the fact that the quartic extension is a tower of quadratic extensions.
774    // We can see this by writing our element as a = a0 + a1·X + a2·X² + a3·X³ = (a0 + a2·X²) + (a1 + a3·X²)·X.
775    // Explicitly our tower looks like F < F[x]/(X²-w) < F[x]/(X⁴-w).
776    // Using this, we can compute the inverse of a in three steps:
777
778    // Compute the norm of our element with respect to F[x]/(X²-w).
779    // This is given by:
780    //      ((a0 + a2·X²) + (a1 + a3·X²)·X) * ((a0 + a2·X²) - (a1 + a3·X²)·X)
781    //          = (a0 + a2·X²)² - (a1 + a3·X²)²
782    //          = (a0² + w·a2² - 2w·a1·a3) + (2·a0·a2 - a1² - w·a3²)·X²
783    //          = norm_0 + norm_1·X² = norm
784    let neg_a1 = -a[1];
785    let a3_w = a[3] * w;
786    let norm_0 = F::dot_product(&[a[0], a[2], neg_a1.double()], &[a[0], a[2] * w, a3_w]);
787    let norm_1 = F::dot_product(&[a[0], a[1], -a[3]], &[a[2].double(), neg_a1, a3_w]);
788
789    // Now we compute the inverse of norm = norm_0 + norm_1·X².
790    let mut inv = [F::ZERO; 2];
791    quadratic_inv(&[norm_0, norm_1], &mut inv, w);
792
793    // Then the inverse of a is given by:
794    //      a⁻¹ = ((a0 + a2·X²) - (a1 + a3·X²)·X)·norm⁻¹
795    //          = (a0 + a2·X²)·norm⁻¹ - (a1 + a3·X²)·norm⁻¹·X
796    // Both of these multiplications can be done in the quadratic extension field.
797    let mut out_evn = [F::ZERO; 2];
798    let mut out_odd = [F::ZERO; 2];
799    quadratic_mul(&[a[0], a[2]], &inv, &mut out_evn, w);
800    quadratic_mul(&[a[1], a[3]], &inv, &mut out_odd, w);
801
802    res[0] = out_evn[0];
803    res[1] = -out_odd[0];
804    res[2] = out_evn[1];
805    res[3] = -out_odd[1];
806}
807
808/// Optimized Square function for quadratic extension field.
809///
810/// Makes use of the in built field dot product code. This is optimized for the case that
811/// R is a prime field or its packing.
812#[inline]
813fn quartic_square<F, R, const D: usize>(a: &[R; D], res: &mut [R; D], w: F)
814where
815    F: Field,
816    R: Algebra<F>,
817{
818    assert_eq!(D, 4);
819
820    let two_a0 = a[0].double();
821    let two_a1 = a[1].double();
822    let two_a2 = a[2].double();
823    let a2_w = a[2].dup() * w;
824    let a3_w = a[3].dup() * w;
825
826    // Constant term = a0*a0 + w*a2*a2 + 2*w*a1*a3
827    res[0] = R::dot_product(
828        &[a[0].dup(), a2_w, two_a1],
829        &[a[0].dup(), a[2].dup(), a3_w.dup()],
830    );
831
832    // Linear term = 2*a0*a1 + 2*w*a2*a3)
833    res[1] = R::dot_product(&[two_a0.dup(), two_a2.dup()], &[a[1].dup(), a3_w.dup()]);
834
835    // Square term = a1*a1 + w*a3*a3 + 2*a0*a2
836    res[2] = R::dot_product(
837        &[a[1].dup(), a3_w, two_a0.dup()],
838        &[a[1].dup(), a[3].dup(), a[2].dup()],
839    );
840
841    // Cubic term = 2*a0*a3 + 2*a1*a2)
842    res[3] = R::dot_product(&[two_a0, two_a2], &[a[3].dup(), a[1].dup()]);
843}
844
845/// Multiplication in a quintic binomial extension field.
846///
847/// Makes use of the in built field dot product code. This is optimized for the case that
848/// R is a prime field or its packing.
849pub fn quintic_mul<F, R, R2, const D: usize>(a: &[R; D], b: &[R2; D], res: &mut [R; D], w: F)
850where
851    F: Field,
852    R: Algebra<F> + Algebra<R2>,
853    R2: Algebra<F>,
854{
855    assert_eq!(D, 5);
856    let b_r_rev: [R; 6] = [
857        b[4].dup().into(),
858        b[3].dup().into(),
859        b[2].dup().into(),
860        b[1].dup().into(),
861        b[0].dup().into(),
862        w.into(),
863    ];
864
865    // Constant term = a0*b0 + w(a1*b4 + a2*b3 + a3*b2 + a4*b1)
866    let w_coeff_0 =
867        R::dot_product::<4>(a[1..].try_into().unwrap(), b_r_rev[..4].try_into().unwrap());
868    res[0] = R::dot_product(&[a[0].dup(), w_coeff_0], b_r_rev[4..].try_into().unwrap());
869
870    // Linear term = a0*b1 + a1*b0 + w(a2*b4 + a3*b3 + a4*b2)
871    let w_coeff_1 =
872        R::dot_product::<3>(a[2..].try_into().unwrap(), b_r_rev[..3].try_into().unwrap());
873    res[1] = R::dot_product(
874        &[a[0].dup(), a[1].dup(), w_coeff_1],
875        b_r_rev[3..].try_into().unwrap(),
876    );
877
878    // Square term = a0*b2 + a1*b1 + a2*b0 + w(a3*b4 + a4*b3)
879    let w_coeff_2 =
880        R::dot_product::<2>(a[3..].try_into().unwrap(), b_r_rev[..2].try_into().unwrap());
881    res[2] = R::dot_product(
882        &[a[0].dup(), a[1].dup(), a[2].dup(), w_coeff_2],
883        b_r_rev[2..].try_into().unwrap(),
884    );
885
886    // Cubic term = a0*b3 + a1*b2 + a2*b1 + a3*b0 + w*a4*b4
887    let b4_w = b[4].dup() * w;
888    res[3] = R::dot_product::<5>(
889        a[..5].try_into().unwrap(),
890        &[
891            b_r_rev[1].dup(),
892            b_r_rev[2].dup(),
893            b_r_rev[3].dup(),
894            b_r_rev[4].dup(),
895            b4_w.into(),
896        ],
897    );
898
899    // Quartic term = a0*b4 + a1*b3 + a2*b2 + a3*b1 + a4*b0
900    res[4] = R::dot_product::<5>(a[..].try_into().unwrap(), b_r_rev[..5].try_into().unwrap());
901}
902
903/// Optimized Square function for quintic extension field elements.
904///
905/// Makes use of the in built field dot product code. This is optimized for the case that
906/// R is a prime field or its packing.
907#[inline]
908fn quintic_square<F, R, const D: usize>(a: &[R; D], res: &mut [R; D], w: F)
909where
910    F: Field,
911    R: Algebra<F>,
912{
913    assert_eq!(D, 5);
914
915    let two_a0 = a[0].double();
916    let two_a1 = a[1].double();
917    let two_a2 = a[2].double();
918    let two_a3 = a[3].double();
919    let w_a3 = a[3].dup() * w;
920    let w_a4 = a[4].dup() * w;
921
922    // Constant term = a0*a0 + 2*w(a1*a4 + a2*a3)
923    res[0] = R::dot_product(
924        &[a[0].dup(), w_a4.dup(), w_a3.dup()],
925        &[a[0].dup(), two_a1.dup(), two_a2.dup()],
926    );
927
928    // Linear term = w*a3*a3 + 2*(a0*a1 + w * a2*a4)
929    res[1] = R::dot_product(
930        &[w_a3, two_a0.dup(), w_a4.dup()],
931        &[a[3].dup(), a[1].dup(), two_a2],
932    );
933
934    // Square term = a1*a1 + 2 * (a0*a2 + w*a3*a4)
935    res[2] = R::dot_product(
936        &[a[1].dup(), two_a0.dup(), w_a4.dup()],
937        &[a[1].dup(), a[2].dup(), two_a3],
938    );
939
940    // Cubic term = w*a4*a4 + 2*(a0*a3 + a1*a2)
941    res[3] = R::dot_product(
942        &[w_a4, two_a0.dup(), two_a1.dup()],
943        &[a[4].dup(), a[3].dup(), a[2].dup()],
944    );
945
946    // Quartic term = a2*a2 + 2*(a0*a4 + a1*a3)
947    res[4] = R::dot_product(
948        &[a[2].dup(), two_a0, two_a1],
949        &[a[2].dup(), a[4].dup(), a[3].dup()],
950    );
951}
952
953/// Optimized Square function for octic extension field elements.
954///
955/// Makes use of the in built field dot product code. This is optimized for the case that
956/// R is a prime field or its packing.
957#[inline]
958fn octic_square<F, R, const D: usize>(a: &[R; D], res: &mut [R; D], w: F)
959where
960    F: Field,
961    R: Algebra<F>,
962{
963    assert_eq!(D, 8);
964
965    let a0_2 = a[0].double();
966    let a1_2 = a[1].double();
967    let a2_2 = a[2].double();
968    let a3_2 = a[3].double();
969    let w_a4 = a[4].dup() * w;
970    let w_a5 = a[5].dup() * w;
971    let w_a6 = a[6].dup() * w;
972    let w_a7 = a[7].dup() * w;
973    let w_a5_2 = w_a5.double();
974    let w_a6_2 = w_a6.double();
975    let w_a7_2 = w_a7.double();
976
977    // Constant coefficient = a0² + w (2(a1 * a7 + a2 * a6 + a3 * a5) + a4²)
978    res[0] = R::dot_product(
979        &[a[0].dup(), a[1].dup(), a[2].dup(), a[3].dup(), a[4].dup()],
980        &[a[0].dup(), w_a7_2.dup(), w_a6_2.dup(), w_a5_2.dup(), w_a4],
981    );
982
983    // Linear coefficient = 2(a0 * a1 + w(a2 * a7 + a3 * a6 + a4 * a5))
984    res[1] = R::dot_product(
985        &[a0_2.dup(), a[2].dup(), a[3].dup(), a[4].dup()],
986        &[a[1].dup(), w_a7_2.dup(), w_a6_2.dup(), w_a5_2],
987    );
988
989    // Square coefficient = 2a0 * a2 + a1² + w(2(a3 * a7 + a4 * a6) + a5²)
990    res[2] = R::dot_product(
991        &[a0_2.dup(), a[1].dup(), a[3].dup(), a[4].dup(), a[5].dup()],
992        &[a[2].dup(), a[1].dup(), w_a7_2.dup(), w_a6_2.dup(), w_a5],
993    );
994
995    // Cube coefficient = 2(a0 * a3 + a1 * a2 + w(a4 * a7 + a5 * a6)
996    res[3] = R::dot_product(
997        &[a0_2.dup(), a1_2.dup(), a[4].dup(), a[5].dup()],
998        &[a[3].dup(), a[2].dup(), w_a7_2.dup(), w_a6_2],
999    );
1000
1001    // Quartic coefficient = 2(a0 * a4 + a1 * a3) + a2² + w(2 * a7 * a5 + a6²)
1002    res[4] = R::dot_product(
1003        &[a0_2.dup(), a1_2.dup(), a[2].dup(), a[5].dup(), a[6].dup()],
1004        &[a[4].dup(), a[3].dup(), a[2].dup(), w_a7_2.dup(), w_a6],
1005    );
1006
1007    // Quintic coefficient = 2 * (a0 * a5 + a1 * a4 + a2 * a3 + w * a6 * a7)
1008    res[5] = R::dot_product(
1009        &[a0_2.dup(), a1_2.dup(), a2_2.dup(), a[6].dup()],
1010        &[a[5].dup(), a[4].dup(), a[3].dup(), w_a7_2],
1011    );
1012
1013    // Sextic coefficient = 2(a0 * a6 + a1 * a5 + a2 * a4) + a3² + w * a7²
1014    res[6] = R::dot_product(
1015        &[a0_2.dup(), a1_2.dup(), a2_2.dup(), a[3].dup(), a[7].dup()],
1016        &[a[6].dup(), a[5].dup(), a[4].dup(), a[3].dup(), w_a7],
1017    );
1018
1019    // Final coefficient = 2(a0 * a7 + a1 * a6 + a2 * a5 + a3 * a4)
1020    res[7] = R::dot_product(
1021        &[a0_2, a1_2, a2_2, a3_2],
1022        &[a[7].dup(), a[6].dup(), a[5].dup(), a[4].dup()],
1023    );
1024}
1025
1026/// Compute the inverse of a quintic binomial extension field element.
1027#[inline]
1028fn quintic_inv<F: BinomiallyExtendable<D>, const D: usize>(
1029    a: &BinomialExtensionField<F, D>,
1030) -> BinomialExtensionField<F, D> {
1031    // Writing 'a' for self, we need to compute: `prod_conj = a^{q^4 + q^3 + q^2 + q}`
1032    let a_exp_q = a.frobenius();
1033    let a_exp_q_plus_q_sq = (*a * a_exp_q).frobenius();
1034    let prod_conj = a_exp_q_plus_q_sq * a_exp_q_plus_q_sq.repeated_frobenius(2);
1035
1036    // norm = a * prod_conj is in the base field, so only compute that
1037    // coefficient rather than the full product.
1038    let a_vals = a.value;
1039    let mut b = prod_conj.value;
1040    b.reverse();
1041
1042    let w_coeff = F::dot_product::<4>(a.value[1..].try_into().unwrap(), b[..4].try_into().unwrap());
1043    let norm = F::dot_product::<2>(&[a_vals[0], F::W], &[b[4], w_coeff]);
1044    debug_assert_eq!(BinomialExtensionField::<F, D>::from(norm), *a * prod_conj);
1045
1046    prod_conj * norm.inverse()
1047}
1048
1049/// Compute the (D-N)'th coefficient in the multiplication of two elements in a degree
1050/// D binomial extension field.
1051///
1052/// a_0 * b_{D - N} + ... + a_{D - N} * b_0 + w * (a_{D - N + 1}b_{D - 1} + ... + a_{D - 1}b_{D - N + 1})
1053///
1054/// # Inputs
1055/// - a: An array of coefficients.
1056/// - b: An array of coefficients in reverse order with last element equal to `W`
1057#[inline]
1058fn compute_coefficient<
1059    F,
1060    R,
1061    const D: usize,
1062    const D_PLUS_1: usize,
1063    const N: usize,
1064    const D_PLUS_1_MIN_N: usize,
1065>(
1066    a: &[R; D],
1067    b_rev: &[R; D_PLUS_1],
1068) -> R
1069where
1070    F: Field,
1071    R: Algebra<F>,
1072{
1073    let w_coeff = R::dot_product::<N>(
1074        a[(D - N)..].try_into().unwrap(),
1075        b_rev[..N].try_into().unwrap(),
1076    );
1077    let mut scratch: [R; D_PLUS_1_MIN_N] = array::from_fn(|i| a[i].dup());
1078    scratch[D_PLUS_1_MIN_N - 1] = w_coeff;
1079    R::dot_product(&scratch, b_rev[N..].try_into().unwrap())
1080}
1081
1082/// Multiplication in an octic binomial extension field.
1083///
1084/// Makes use of the in built field dot product code. This is optimized for the case that
1085/// R is a prime field or its packing.
1086#[inline]
1087pub fn octic_mul<F, R, R2, const D: usize>(a: &[R; D], b: &[R2; D], res: &mut [R; D], w: F)
1088where
1089    F: Field,
1090    R: Algebra<F> + Algebra<R2>,
1091    R2: Algebra<F>,
1092{
1093    assert_eq!(D, 8);
1094    let a: &[R; 8] = a[..].try_into().unwrap();
1095    let mut b_r_rev: [R; 9] = [
1096        b[7].dup().into(),
1097        b[6].dup().into(),
1098        b[5].dup().into(),
1099        b[4].dup().into(),
1100        b[3].dup().into(),
1101        b[2].dup().into(),
1102        b[1].dup().into(),
1103        b[0].dup().into(),
1104        w.into(),
1105    ];
1106
1107    // Constant coefficient = a0*b0 + w(a1*b7 + ... + a7*b1)
1108    res[0] = compute_coefficient::<F, R, 8, 9, 7, 2>(a, &b_r_rev);
1109
1110    // Linear coefficient = a0*b1 + a1*b0 + w(a2*b7 + ... + a7*b2)
1111    res[1] = compute_coefficient::<F, R, 8, 9, 6, 3>(a, &b_r_rev);
1112
1113    // Square coefficient = a0*b2 + .. + a2*b0 + w(a3*b7 + ... + a7*b3)
1114    res[2] = compute_coefficient::<F, R, 8, 9, 5, 4>(a, &b_r_rev);
1115
1116    // Cube coefficient = a0*b3 + .. + a3*b0 + w(a4*b7 + ... + a7*b4)
1117    res[3] = compute_coefficient::<F, R, 8, 9, 4, 5>(a, &b_r_rev);
1118
1119    // Quartic coefficient = a0*b4 + ... + a4*b0 + w(a5*b7 + ... + a7*b5)
1120    res[4] = compute_coefficient::<F, R, 8, 9, 3, 6>(a, &b_r_rev);
1121
1122    // Quintic coefficient = a0*b5 + ... + a5*b0 + w(a6*b7 + ... + a7*b6)
1123    res[5] = compute_coefficient::<F, R, 8, 9, 2, 7>(a, &b_r_rev);
1124
1125    // Sextic coefficient = a0*b6 + ... + a6*b0 + w*a7*b7
1126    b_r_rev[8] *= b[7].dup();
1127    res[6] = R::dot_product::<8>(a, b_r_rev[1..].try_into().unwrap());
1128
1129    // Final coefficient = a0*b7 + ... + a7*b0
1130    res[7] = R::dot_product::<8>(a, b_r_rev[..8].try_into().unwrap());
1131}
1132
1133/// Compute the inverse of a octic binomial extension field element.
1134#[inline]
1135fn octic_inv<F: Field, const D: usize>(a: &[F; D], res: &mut [F; D], w: F) {
1136    assert_eq!(D, 8);
1137
1138    // We use the fact that the octic extension is a tower of extensions.
1139    // Explicitly our tower looks like F < F[x]/(X⁴ - w) < F[x]/(X^8 - w).
1140    // Using this, we can compute the inverse of a in three steps:
1141
1142    // Compute the norm of our element with respect to F[x]/(X⁴-w).
1143    // Writing a = a0 + a1·X + a2·X² + a3·X³ + a4·X⁴ + a5·X⁵ + a6·X⁶ + a7·X⁷
1144    //           = (a0 + a2·X² + a4·X⁴ + a6·X⁶) + (a1 + a3·X² + a5·X⁴ + a7·X⁶)·X
1145    //           = evens + odds·X
1146    //
1147    // The norm is given by:
1148    //    norm = (evens + odds·X) * (evens - odds·X)
1149    //          = evens² - odds²·X²
1150    //
1151    // This costs 2 multiplications in the quartic extension field.
1152    let evns = [a[0], a[2], a[4], a[6]];
1153    let odds = [a[1], a[3], a[5], a[7]];
1154    let mut evns_sq = [F::ZERO; 4];
1155    let mut odds_sq = [F::ZERO; 4];
1156    quartic_square(&evns, &mut evns_sq, w);
1157    quartic_square(&odds, &mut odds_sq, w);
1158    // odds_sq is multiplied by X^2 so we need to rotate it and multiply by a factor of w.
1159    let norm = [
1160        evns_sq[0] - w * odds_sq[3],
1161        evns_sq[1] - odds_sq[0],
1162        evns_sq[2] - odds_sq[1],
1163        evns_sq[3] - odds_sq[2],
1164    ];
1165
1166    // Now we compute the inverse of norm inside F[x]/(X⁴ - w). We already have an efficient function for this.
1167    let mut norm_inv = [F::ZERO; 4];
1168    quartic_inv(&norm, &mut norm_inv, w);
1169
1170    // Then the inverse of a is given by:
1171    //      a⁻¹ = (evens - odds·X)·norm⁻¹
1172    //          = evens·norm⁻¹ - odds·norm⁻¹·X
1173    //
1174    // Both of these multiplications can again be done in the quartic extension field.
1175    let mut out_evn = [F::ZERO; 4];
1176    let mut out_odd = [F::ZERO; 4];
1177    quartic_mul(&evns, &norm_inv, &mut out_evn, w);
1178    quartic_mul(&odds, &norm_inv, &mut out_odd, w);
1179
1180    res[0] = out_evn[0];
1181    res[1] = -out_odd[0];
1182    res[2] = out_evn[1];
1183    res[3] = -out_odd[1];
1184    res[4] = out_evn[2];
1185    res[5] = -out_odd[2];
1186    res[6] = out_evn[3];
1187    res[7] = -out_odd[3];
1188}