1use alloc::vec;
15use alloc::vec::Vec;
16
17use crate::field::{Fp, P};
18use crate::ntt::Ntt;
19use crate::par;
20
21const ODD_PRIMES: [u64; 5] = [3, 5, 17, 257, 65537];
22
23pub fn is_supported_len(n: usize) -> bool {
25 n > 0 && (P - 1) % n as u64 == 0
26}
27
28trait Fibre: Sync {
30 fn apply(&self, x: &mut [Fp], scratch: &mut Vec<Fp>);
31}
32
33#[derive(Clone, Debug)]
34enum Axis {
35 Trivial,
36 Ntt(Ntt),
37 Direct(Vec<Fp>, usize),
39 Rader(Rader),
40}
41
42#[derive(Clone, Debug)]
45struct Rader {
46 q: usize,
47 gin: Vec<u32>,
49 gout: Vec<u32>,
51 ntt: Ntt,
52 b_hat: Vec<Fp>,
54}
55
56impl Rader {
57 fn new(q: usize, w: Fp) -> Self {
58 let l = q - 1;
59 assert!(l.is_power_of_two());
60 let g = (2..q as u64).find(|&g| is_generator(g, q as u64)).unwrap();
61 let ginv = pow_mod(g, q as u64 - 2, q as u64);
62 let mut gin = Vec::with_capacity(l);
63 let mut gout = Vec::with_capacity(l);
64 let (mut a, mut b) = (1u64, 1u64);
65 for _ in 0..l {
66 gin.push(a as u32);
67 gout.push(b as u32);
68 a = a * g % q as u64;
69 b = b * ginv % q as u64;
70 }
71 let ntt = Ntt::new(l).with_threads(1);
72 let inv_l = Fp::new(l as u64).inv();
73 let mut b_hat: Vec<Fp> = gout.iter().map(|&e| w.pow(e as u64) * inv_l).collect();
74 ntt.forward_bitrev(&mut b_hat);
75 Rader { q, gin, gout, ntt, b_hat }
76 }
77
78 fn apply(&self, x: &mut [Fp], scratch: &mut Vec<Fp>) {
79 let l = self.q - 1;
80 scratch.clear();
81 scratch.extend(self.gin.iter().map(|&i| x[i as usize]));
82 let x0 = x[0];
83 let total: Fp = x.iter().sum();
84 self.ntt.forward_bitrev(scratch);
85 for (s, b) in scratch.iter_mut().zip(&self.b_hat) {
86 *s *= *b;
87 }
88 self.ntt.inverse_from_bitrev_unscaled(scratch);
89 x[0] = total;
90 for m in 0..l {
91 x[self.gout[m] as usize] = x0 + scratch[m];
92 }
93 }
94}
95
96fn pow_mod(mut b: u64, mut e: u64, m: u64) -> u64 {
97 let mut r = 1u64;
98 b %= m;
99 while e > 0 {
100 if e & 1 == 1 {
101 r = r * b % m;
102 }
103 b = b * b % m;
104 e >>= 1;
105 }
106 r
107}
108
109fn is_generator(g: u64, q: u64) -> bool {
111 pow_mod(g, (q - 1) / 2, q) != 1
112}
113
114impl Axis {
115 fn new(len: usize, root: Fp) -> Self {
116 if len == 1 {
117 Axis::Trivial
118 } else if len.is_power_of_two() {
119 Axis::Ntt(Ntt::with_root(len, root).with_threads(1))
120 } else if len <= 5 {
121 let mut m = Vec::with_capacity(len * len);
122 for j in 0..len {
123 let wj = root.pow(j as u64);
124 let mut w = Fp::ONE;
125 for _ in 0..len {
126 m.push(w);
127 w *= wj;
128 }
129 }
130 Axis::Direct(m, len)
131 } else {
132 Axis::Rader(Rader::new(len, root))
133 }
134 }
135}
136
137impl Fibre for Axis {
138 fn apply(&self, buf: &mut [Fp], scratch: &mut Vec<Fp>) {
139 match self {
140 Axis::Trivial => {}
141 Axis::Ntt(p) => p.forward(buf),
142 Axis::Direct(m, q) => {
143 scratch.clear();
144 for k in 0..*q {
145 let row = &m[k * q..(k + 1) * q];
146 scratch.push(row.iter().zip(buf.iter()).map(|(a, b)| *a * *b).sum());
147 }
148 buf.copy_from_slice(scratch);
149 }
150 Axis::Rader(r) => r.apply(buf, scratch),
151 }
152 }
153}
154
155fn apply_axes<T: Fibre>(data: &mut [Fp], dims: &[usize], axes: &[T], threads: usize) {
158 let total = data.len();
159 let mut stride = 1;
160 for ax in (0..dims.len()).rev() {
161 let a = dims[ax];
162 if a > 1 {
163 let axis = &axes[ax];
164 if stride == 1 {
165 let per = (total / threads.max(1)).max(a).div_ceil(a) * a;
167 par::for_each_chunk(data, per, threads, |group| {
168 let mut scratch = Vec::new();
169 for fib in group.chunks_exact_mut(a) {
170 axis.apply(fib, &mut scratch);
171 }
172 });
173 } else {
174 strided_axis(data, a, stride, axis, threads);
175 }
176 }
177 stride *= a;
178 }
179}
180
181fn strided_axis<T: Fibre>(data: &mut [Fp], a: usize, stride: usize, axis: &T, threads: usize) {
183 let block = a * stride;
184 let blocks = data.len() / block;
185 let run_block = |blk: &mut [Fp]| {
186 let mut fibre = vec![Fp::ZERO; a];
187 let mut scratch = Vec::new();
188 for off in 0..stride {
189 for k in 0..a {
190 fibre[k] = blk[off + k * stride];
191 }
192 axis.apply(&mut fibre, &mut scratch);
193 for k in 0..a {
194 blk[off + k * stride] = fibre[k];
195 }
196 }
197 };
198 if threads <= 1 || blocks >= threads {
199 par::for_each_chunk(data, block, threads.min(blocks), run_block);
200 return;
201 }
202 #[cfg(feature = "std")]
205 for blk in data.chunks_exact_mut(block) {
206 let per = stride.div_ceil(threads);
207 let view: &[Fp] = blk;
208 let results: Vec<Vec<Fp>> = std::thread::scope(|s| {
209 let handles: Vec<_> = (0..stride)
210 .step_by(per)
211 .map(|start| {
212 s.spawn(move || {
213 let end = (start + per).min(stride);
214 let mut out = Vec::with_capacity((end - start) * a);
215 let mut fibre = vec![Fp::ZERO; a];
216 let mut scratch = Vec::new();
217 for off in start..end {
218 for k in 0..a {
219 fibre[k] = view[off + k * stride];
220 }
221 axis.apply(&mut fibre, &mut scratch);
222 out.extend_from_slice(&fibre);
223 }
224 out
225 })
226 })
227 .collect();
228 handles.into_iter().map(|h| h.join().unwrap()).collect()
229 });
230 let mut off = 0;
231 for out in results {
232 for fib in out.chunks_exact(a) {
233 for k in 0..a {
234 blk[off + k * stride] = fib[k];
235 }
236 off += 1;
237 }
238 }
239 }
240 #[cfg(not(feature = "std"))]
241 par::for_each_chunk(data, block, 1, run_block);
242}
243
244#[derive(Clone, Debug)]
246pub struct Dft {
247 n: usize,
248 factors: Vec<usize>,
249 axes: Vec<Axis>,
250 in_map: Vec<u32>,
252 out_map: Vec<u32>,
254 inv_n: Fp,
255 threads: usize,
256}
257
258impl Dft {
259 pub fn new(n: usize) -> Self {
262 assert!(is_supported_len(n), "no primitive {n}-th root of unity in F_p (n must divide p-1)");
263 let mut factors = Vec::new();
264 let two = 1usize << n.trailing_zeros();
265 if two > 1 {
266 factors.push(two);
267 }
268 let mut rest = n / two;
269 for &q in &ODD_PRIMES {
270 if rest as u64 % q == 0 {
271 factors.push(q as usize);
272 rest /= q as usize;
273 }
274 }
275 debug_assert_eq!(rest, 1);
276 let omega = Fp::root_of_unity(n as u64);
277 let axes = factors.iter().map(|&f| Axis::new(f, omega.pow((n / f) as u64))).collect();
279
280 let (in_map, out_map) = if factors.len() > 1 {
282 let coef_in: Vec<u64> = factors.iter().map(|&f| (n / f) as u64).collect();
283 let coef_out: Vec<u64> = factors
284 .iter()
285 .map(|&f| {
286 let m = (n / f) as u64;
287 m * inv_mod(m % f as u64, f as u64) % n as u64
288 })
289 .collect();
290 let mut in_map = vec![0u32; n];
291 let mut out_map = vec![0u32; n];
292 let mut digits = vec![0usize; factors.len()];
293 for pos in 0..n {
294 let (mut a, mut b) = (0u64, 0u64);
295 for (i, &d) in digits.iter().enumerate() {
296 a = (a + d as u64 * coef_in[i]) % n as u64;
297 b = (b + d as u64 * coef_out[i]) % n as u64;
298 }
299 in_map[pos] = a as u32;
300 out_map[pos] = b as u32;
301 for i in (0..factors.len()).rev() {
302 digits[i] += 1;
303 if digits[i] < factors[i] {
304 break;
305 }
306 digits[i] = 0;
307 }
308 }
309 (in_map, out_map)
310 } else {
311 (Vec::new(), Vec::new())
312 };
313 Dft { n, factors, axes, in_map, out_map, inv_n: Fp::new(n as u64).inv(), threads: 0 }
314 }
315
316 pub fn with_threads(mut self, threads: usize) -> Self {
318 self.threads = threads;
319 self
320 }
321
322 pub fn len(&self) -> usize {
323 self.n
324 }
325
326 pub fn is_empty(&self) -> bool {
327 self.n == 0
328 }
329
330 pub fn factors(&self) -> &[usize] {
332 &self.factors
333 }
334
335 pub fn forward(&self, x: &[Fp]) -> Vec<Fp> {
337 let mut y = x.to_vec();
338 self.forward_in_place(&mut y);
339 y
340 }
341
342 pub fn inverse(&self, y: &[Fp]) -> Vec<Fp> {
344 let mut x = y.to_vec();
345 self.inverse_in_place(&mut x);
346 x
347 }
348
349 pub fn forward_in_place(&self, x: &mut [Fp]) {
352 let mut scratch = Vec::new();
353 self.run(x, &mut scratch, par::threads_for(self.n, self.threads));
354 }
355
356 pub fn inverse_in_place(&self, x: &mut [Fp]) {
358 let t = par::threads_for(self.n, self.threads);
359 let mut scratch = Vec::new();
360 self.run_inverse(x, &mut scratch, t);
361 }
362
363 pub fn forward_batch(&self, data: &mut [Fp]) {
365 let t = self.batch_threads(data);
366 par::for_each_chunk(data, self.rows_per_task(data, t), t, |rows| {
367 let mut s = Vec::new();
368 rows.chunks_exact_mut(self.n).for_each(|r| self.run(r, &mut s, 1));
369 });
370 }
371
372 pub fn inverse_batch(&self, data: &mut [Fp]) {
374 let t = self.batch_threads(data);
375 par::for_each_chunk(data, self.rows_per_task(data, t), t, |rows| {
376 let mut s = Vec::new();
377 rows.chunks_exact_mut(self.n).for_each(|r| self.run_inverse(r, &mut s, 1));
378 });
379 }
380
381 fn batch_threads(&self, data: &[Fp]) -> usize {
382 assert!(data.len() % self.n == 0, "batch length must be a multiple of n");
383 par::threads_for(data.len(), self.threads).min((data.len() / self.n).max(1))
384 }
385
386 fn rows_per_task(&self, data: &[Fp], t: usize) -> usize {
387 (data.len() / self.n).div_ceil(t.max(1)).max(1) * self.n
388 }
389
390 fn run(&self, x: &mut [Fp], scratch: &mut Vec<Fp>, threads: usize) {
391 assert_eq!(x.len(), self.n, "input length mismatch");
392 if self.factors.len() <= 1 {
393 apply_axes(x, &self.factors, &self.axes, threads);
394 return;
395 }
396 scratch.clear();
397 scratch.extend(self.in_map.iter().map(|&i| x[i as usize]));
398 apply_axes(scratch, &self.factors, &self.axes, threads);
399 for (g, &o) in scratch.iter().zip(&self.out_map) {
400 x[o as usize] = *g;
401 }
402 }
403
404 fn run_inverse(&self, x: &mut [Fp], scratch: &mut Vec<Fp>, threads: usize) {
405 self.run(x, scratch, threads);
407 x[1..].reverse();
408 let inv = self.inv_n;
409 x.iter_mut().for_each(|v| *v *= inv);
410 }
411}
412
413impl Fibre for Dft {
414 fn apply(&self, x: &mut [Fp], scratch: &mut Vec<Fp>) {
415 self.run(x, scratch, 1);
416 }
417}
418
419struct InvDft<'a>(&'a Dft);
421
422impl Fibre for InvDft<'_> {
423 fn apply(&self, x: &mut [Fp], scratch: &mut Vec<Fp>) {
424 self.0.run_inverse(x, scratch, 1);
425 }
426}
427
428fn inv_mod(a: u64, m: u64) -> u64 {
429 if m == 1 {
430 return 0;
431 }
432 let (mut r0, mut r1) = (a as i128, m as i128);
433 let (mut s0, mut s1) = (1i128, 0i128);
434 while r1 != 0 {
435 let q = r0 / r1;
436 (r0, r1) = (r1, r0 - q * r1);
437 (s0, s1) = (s1, s0 - q * s1);
438 }
439 assert_eq!(r0, 1, "not coprime");
440 s0.rem_euclid(m as i128) as u64
441}
442
443#[derive(Clone, Debug)]
446pub struct GroupDft {
447 dims: Vec<usize>,
448 plans: Vec<Dft>,
449 threads: usize,
450}
451
452impl GroupDft {
453 pub fn new(dims: &[usize]) -> Self {
456 GroupDft { dims: dims.to_vec(), plans: dims.iter().map(|&a| Dft::new(a)).collect(), threads: 0 }
457 }
458
459 pub fn with_threads(mut self, threads: usize) -> Self {
461 self.threads = threads;
462 self
463 }
464
465 pub fn dims(&self) -> &[usize] {
466 &self.dims
467 }
468
469 pub fn len(&self) -> usize {
470 self.dims.iter().product()
471 }
472
473 pub fn is_empty(&self) -> bool {
474 self.len() == 0
475 }
476
477 pub fn forward(&self, x: &[Fp]) -> Vec<Fp> {
478 let mut y = x.to_vec();
479 self.forward_in_place(&mut y);
480 y
481 }
482
483 pub fn inverse(&self, x: &[Fp]) -> Vec<Fp> {
484 let mut y = x.to_vec();
485 self.inverse_in_place(&mut y);
486 y
487 }
488
489 pub fn forward_in_place(&self, x: &mut [Fp]) {
490 assert_eq!(x.len(), self.len(), "input length mismatch");
491 let t = par::threads_for(x.len(), self.threads);
492 apply_axes(x, &self.dims, &self.plans, t);
493 }
494
495 pub fn inverse_in_place(&self, x: &mut [Fp]) {
496 assert_eq!(x.len(), self.len(), "input length mismatch");
497 let t = par::threads_for(x.len(), self.threads);
498 let inv: Vec<InvDft<'_>> = self.plans.iter().map(InvDft).collect();
499 apply_axes(x, &self.dims, &inv, t);
500 }
501}