1use crate::bind::AccelerationTier;
8
9pub const CELL_BATCH_NATIVE: usize = 512;
11pub const CELL_BATCH_WASM: usize = 64;
13
14pub fn cell_batch_cap() -> usize {
16 #[cfg(target_arch = "wasm32")]
17 {
18 CELL_BATCH_WASM
19 }
20 #[cfg(not(target_arch = "wasm32"))]
21 {
22 CELL_BATCH_NATIVE
23 }
24}
25
26pub fn detect_available_tier() -> AccelerationTier {
28 #[cfg(target_arch = "wasm32")]
29 {
30 AccelerationTier::ScalarCpu
31 }
32 #[cfg(not(target_arch = "wasm32"))]
33 {
34 #[cfg(target_arch = "x86_64")]
35 if is_x86_feature_detected!("avx512f") {
36 return AccelerationTier::VectorSimd512;
37 }
38 AccelerationTier::ScalarCpu
39 }
40}
41
42pub fn add_f64_slices(a: &[f64], b: &[f64], out: &mut [f64]) {
44 let n = a.len().min(b.len()).min(out.len());
45 #[cfg(all(target_arch = "x86_64", not(target_arch = "wasm32")))]
46 {
47 if is_x86_feature_detected!("avx512f") {
48 unsafe {
49 add_avx512(a, b, out, n);
50 }
51 return;
52 }
53 }
54 for i in 0..n {
55 out[i] = a[i] + b[i];
56 }
57}
58
59#[cfg(all(target_arch = "x86_64", not(target_arch = "wasm32")))]
60#[target_feature(enable = "avx512f")]
61unsafe fn add_avx512(a: &[f64], b: &[f64], out: &mut [f64], n: usize) {
62 use std::arch::x86_64::*;
63 let mut i = 0;
64 while i + 8 <= n {
65 let va = _mm512_loadu_pd(a.as_ptr().add(i));
66 let vb = _mm512_loadu_pd(b.as_ptr().add(i));
67 _mm512_storeu_pd(out.as_mut_ptr().add(i), _mm512_add_pd(va, vb));
68 i += 8;
69 }
70 while i < n {
71 out[i] = a[i] + b[i];
72 i += 1;
73 }
74}
75
76#[cfg(test)]
77mod tests {
78 use super::*;
79
80 #[test]
81 fn wasm_or_native_cap_is_bounded() {
82 let cap = cell_batch_cap();
83 assert!(cap == CELL_BATCH_NATIVE || cap == CELL_BATCH_WASM);
84 assert!(cap <= CELL_BATCH_NATIVE);
85 }
86
87 #[test]
88 fn scalar_add_matches_manual() {
89 let a = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0];
90 let b = [0.5; 9];
91 let mut out = [0.0; 9];
92 add_f64_slices(&a, &b, &mut out);
93 for i in 0..9 {
94 assert!((out[i] - (a[i] + b[i])).abs() < 1e-12);
95 }
96 }
97
98 #[test]
99 fn wasm_never_advertises_simd() {
100 #[cfg(target_arch = "wasm32")]
101 assert_eq!(detect_available_tier(), AccelerationTier::ScalarCpu);
102 }
103}