use alloc::vec::Vec;
use core::array;
use core::ops::{AddAssign, Mul};
use p3_dft::TwoAdicSubgroupDft;
use p3_field::{AbstractField, TwoAdicField};
#[inline(always)]
pub fn dot_product<T, const N: usize>(u: [T; N], v: [T; N]) -> T
where
T: Copy + AddAssign + Mul<Output = T>,
{
debug_assert_ne!(N, 0);
let mut dp = u[0] * v[0];
for i in 1..N {
dp += u[i] * v[i];
}
dp
}
pub fn apply_circulant<AF: AbstractField, const N: usize>(
circ_matrix: &[u64; N],
input: [AF; N],
) -> [AF; N] {
let mut matrix: [AF; N] = circ_matrix.map(AF::from_canonical_u64);
let mut output = array::from_fn(|_| AF::zero());
for out_i in output.iter_mut().take(N - 1) {
*out_i = AF::dot_product(&matrix, &input);
matrix.rotate_right(1);
}
output[N - 1] = AF::dot_product(&matrix, &input);
output
}
pub const fn first_row_to_first_col<const N: usize, T: Copy>(v: &[T; N]) -> [T; N] {
let mut output = [v[0]; N];
let mut i = 1;
loop {
if i >= N {
break;
}
output[i] = v[N - i];
i += 1;
}
output
}
#[inline]
pub fn apply_circulant_fft<F: TwoAdicField, const N: usize, FFT: TwoAdicSubgroupDft<F>>(
fft: FFT,
column: [u64; N],
input: &[F; N],
) -> [F; N] {
let column = column.map(F::from_canonical_u64).to_vec();
let matrix = fft.dft(column);
let input = fft.dft(input.to_vec());
let product = matrix
.iter()
.zip(input)
.map(|(&x, y)| x * y)
.collect::<Vec<_>>();
let output = fft.idft(product);
output.try_into().unwrap()
}
#[cfg(test)]
mod tests {
use super::first_row_to_first_col;
#[test]
fn rotation() {
let input = [0, 1, 2, 3, 4, 5];
let output = [0, 5, 4, 3, 2, 1];
assert_eq!(first_row_to_first_col(&input), output);
}
}