simdly 0.1.2

🚀 High-performance Rust library leveraging SIMD and Rayon for fast computations.
Documentation
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
use std::cmp::Ordering;
use std::env;
use std::process::Command;

// CPU features we want to detect
#[derive(PartialEq, Eq, Debug)]
struct CpuFeature {
    name: &'static str,
    rustc_flag: &'static str,
    cfg_flag: &'static str,
    detected: bool,
    nightly_only: bool,
}

impl CpuFeature {
    // Define priority order between CPU Features (Lowest number == Highest Priority)
    fn priority(&self) -> usize {
        match self.name {
            "avx512f" => 0,
            "avx2" => 1,
            "sse4_1" => 2,
            _ => usize::MAX, // lowest priority by default
        }
    }

    // Groups all supported CPU features that use optimizations in this crate
    // used in stable build only
    fn features() -> Vec<CpuFeature> {
        vec![
            CpuFeature {
                name: "sse4_1",
                rustc_flag: "+sse4.1",
                cfg_flag: "sse",
                detected: false,
                nightly_only: false,
            },
            CpuFeature {
                name: "avx2",
                rustc_flag: "+avx2,+avx,+fma",
                cfg_flag: "avx2",
                detected: false,
                nightly_only: false,
            },
            CpuFeature {
                name: "neon",
                rustc_flag: "+neon",
                cfg_flag: "neon",
                detected: false,
                nightly_only: false,
            },
        ]
    }

    // Groups all supported CPU features that use optimizations in this crate
    // used in nightly build only
    fn nightly_features() -> Vec<CpuFeature> {
        vec![
            CpuFeature {
                name: "sse4_1",
                rustc_flag: "+sse4.1",
                cfg_flag: "sse",
                detected: false,
                nightly_only: false,
            },
            CpuFeature {
                name: "avx512f",
                rustc_flag: "+avx512f",
                cfg_flag: "avx512",
                detected: false,
                nightly_only: true,
            },
            CpuFeature {
                name: "avx2",
                rustc_flag: "+avx2,+avx,+fma",
                cfg_flag: "avx2",
                detected: false,
                nightly_only: false,
            },
            CpuFeature {
                name: "neon",
                rustc_flag: "+neon",
                cfg_flag: "neon",
                detected: false,
                nightly_only: false,
            },
        ]
    }
}

impl Ord for CpuFeature {
    fn cmp(&self, other: &Self) -> Ordering {
        self.priority().cmp(&other.priority())
    }
}

impl PartialOrd for CpuFeature {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

// Result type for feature detection
#[derive(Debug)]
enum DetectionResult {
    Success,
    PartialFailure(String), // Some features detected, but with warnings
    Failure(String),        // Complete failure with error message
}

// Feature detection trait to make implementations more modular
trait CpuFeatureDetector {
    fn detect_features(&self, features: &mut [CpuFeature]) -> DetectionResult;
    fn is_applicable(&self) -> bool;
    fn name(&self) -> &'static str;
}

// Linux CPU feature detector
struct LinuxDetector;
impl CpuFeatureDetector for LinuxDetector {
    fn detect_features(&self, features: &mut [CpuFeature]) -> DetectionResult {
        match std::fs::read_to_string("/proc/cpuinfo") {
            Ok(cpuinfo) => {
                let contents = cpuinfo.to_lowercase();
                for feature in features.iter_mut() {
                    feature.detected = contents.contains(feature.name);
                }
                DetectionResult::Success
            }
            Err(e) => DetectionResult::Failure(format!("Failed to read /proc/cpuinfo: {e}")),
        }
    }

    fn is_applicable(&self) -> bool {
        cfg!(target_os = "linux")
    }

    fn name(&self) -> &'static str {
        "Linux"
    }
}

// macOS CPU feature detector
struct MacOSDetector;
impl CpuFeatureDetector for MacOSDetector {
    fn detect_features(&self, features: &mut [CpuFeature]) -> DetectionResult {
        let output = Command::new("sysctl").args(["-a"]).output();

        match output {
            Ok(output) => {
                if !output.status.success() {
                    return DetectionResult::Failure(format!(
                        "sysctl command failed with exit code: {}",
                        output.status
                    ));
                }

                let contents = String::from_utf8_lossy(&output.stdout).to_lowercase();
                let mut detected_any = false;

                for feature in features.iter_mut() {
                    match feature.name {
                        "avx512f" => {
                            feature.detected = contents.contains("hw.optional.avx512f: 1");
                        }
                        "avx2" => {
                            feature.detected = contents.contains("hw.optional.avx2_0: 1");
                        }
                        "sse4_1" => {
                            feature.detected = contents.contains("hw.optional.sse4_1: 1");
                        }
                        "neon" => {
                            feature.detected = contents.contains("hw.optional.neon: 1");
                        }
                        _ => {}
                    }
                    if feature.detected {
                        detected_any = true;
                    }
                }

                if detected_any {
                    DetectionResult::Success
                } else {
                    DetectionResult::PartialFailure(
                        "No CPU features detected in sysctl output".to_string(),
                    )
                }
            }
            Err(e) => DetectionResult::Failure(format!("Failed to execute sysctl: {e}")),
        }
    }

    fn is_applicable(&self) -> bool {
        cfg!(target_os = "macos")
    }

    fn name(&self) -> &'static str {
        "macOS"
    }
}

// Windows CPU feature detector
struct WindowsDetector;
impl CpuFeatureDetector for WindowsDetector {
    fn detect_features(&self, features: &mut [CpuFeature]) -> DetectionResult {
        // Try PowerShell method first (more reliable)
        if let Ok(result) = self.detect_with_powershell(features) {
            return result;
        }

        // Fallback to wmic method
        self.detect_with_wmic(features)
    }

    fn is_applicable(&self) -> bool {
        cfg!(target_os = "windows")
    }

    fn name(&self) -> &'static str {
        "Windows"
    }
}

impl WindowsDetector {
    fn detect_with_powershell(&self, features: &mut [CpuFeature]) -> Result<DetectionResult, ()> {
        let powershell_script = r#"
            try {
                $cpu = Get-WmiObject -Class Win32_Processor | Select-Object -First 1
                $features = @{}
                
                # Get processor name and features
                $name = $cpu.Name.ToLower()
                
                # Basic feature detection based on processor name and generation
                if ($name -match "intel") {
                    # Intel processors
                    if ($name -match "core.*i[3-9]" -or $name -match "xeon") {
                        $features["sse4_1"] = $true
                        if ($name -match "haswell|broadwell|skylake|kaby.*lake|coffee.*lake|ice.*lake|tiger.*lake|alder.*lake|raptor.*lake" -or 
                            $name -match "i[5-9].*[2-9][0-9][0-9][0-9]" -or $name -match "xeon.*e[3-7]") {
                            $features["avx2"] = $true
                        }
                        if ($name -match "skylake.*x|cascade.*lake|cooper.*lake|ice.*lake.*sp|sapphire.*rapids" -or 
                            $name -match "xeon.*platinum|xeon.*gold") {
                            $features["avx512f"] = $true
                        }
                    }
                } elseif ($name -match "amd") {
                    # AMD processors
                    if ($name -match "ryzen|epyc|threadripper") {
                        $features["sse4_1"] = $true
                        $features["avx2"] = $true
                    }
                } elseif ($name -match "arm|qualcomm|snapdragon") {
                    # ARM processors
                    $features["neon"] = $true
                }
                
                # Output results
                foreach ($feature in $features.Keys) {
                    if ($features[$feature]) {
                        Write-Output "$feature=true"
                    }
                }
                
                Write-Output "detection=success"
            } catch {
                Write-Output "detection=error:$($_.Exception.Message)"
            }
        "#;

        let output = Command::new("powershell")
            .args(["-NoProfile", "-Command", powershell_script])
            .output()
            .map_err(|_| ())?;

        if !output.status.success() {
            return Err(());
        }

        let stdout = String::from_utf8_lossy(&output.stdout);
        let mut detected_any = false;

        for line in stdout.lines() {
            if line.starts_with("detection=error:") {
                return Ok(DetectionResult::Failure(
                    line.strip_prefix("detection=error:")
                        .unwrap_or("Unknown PowerShell error")
                        .to_string(),
                ));
            } else if line == "detection=success" {
                continue;
            } else if let Some((feature_name, value)) = line.split_once('=') {
                if value == "true" {
                    for feature in features.iter_mut() {
                        if feature.name == feature_name {
                            feature.detected = true;
                            detected_any = true;
                            break;
                        }
                    }
                }
            }
        }

        Ok(if detected_any {
            DetectionResult::Success
        } else {
            DetectionResult::PartialFailure("No CPU features detected via PowerShell".to_string())
        })
    }

    fn detect_with_wmic(&self, features: &mut [CpuFeature]) -> DetectionResult {
        let output = Command::new("wmic")
            .args(["cpu", "get", "name", "/format:list"])
            .output();

        match output {
            Ok(output) => {
                if !output.status.success() {
                    return DetectionResult::Failure(format!(
                        "wmic command failed with exit code: {}",
                        output.status
                    ));
                }

                let contents = String::from_utf8_lossy(&output.stdout).to_lowercase();
                let mut detected_any = false;

                // Basic heuristic-based detection for common processors
                for feature in features.iter_mut() {
                    match feature.name {
                        "sse4_1" => {
                            feature.detected = contents.contains("intel core i")
                                || contents.contains("intel xeon")
                                || contents.contains("amd ryzen")
                                || contents.contains("amd epyc");
                        }
                        "avx2" => {
                            feature.detected = (contents.contains("intel core i")
                                && (contents.contains("4th gen")
                                    || contents.contains("haswell")
                                    || contents.contains("5th gen")
                                    || contents.contains("broadwell")
                                    || contents.contains("6th gen")
                                    || contents.contains("skylake")
                                    || contents.contains("7th gen")
                                    || contents.contains("kaby")
                                    || contents.contains("8th gen")
                                    || contents.contains("coffee")
                                    || contents.contains("9th gen")
                                    || contents.contains("10th gen")
                                    || contents.contains("11th gen")
                                    || contents.contains("12th gen")
                                    || contents.contains("13th gen")))
                                || contents.contains("amd ryzen")
                                || contents.contains("amd epyc");
                        }
                        "avx512f" => {
                            feature.detected = contents.contains("intel xeon")
                                && (contents.contains("skylake")
                                    || contents.contains("cascade")
                                    || contents.contains("cooper")
                                    || contents.contains("ice lake"));
                        }
                        "neon" => {
                            feature.detected = contents.contains("arm")
                                || contents.contains("qualcomm")
                                || contents.contains("snapdragon");
                        }
                        _ => {}
                    }
                    if feature.detected {
                        detected_any = true;
                    }
                }

                if detected_any {
                    DetectionResult::Success
                } else {
                    DetectionResult::PartialFailure("No CPU features detected via wmic".to_string())
                }
            }
            Err(e) => DetectionResult::Failure(format!("Failed to execute wmic: {e}")),
        }
    }
}

// Factory that creates the appropriate detector for the current OS
struct PlatformDetector;
impl PlatformDetector {
    fn cpu_features_detectors() -> Vec<Box<dyn CpuFeatureDetector>> {
        vec![
            Box::new(LinuxDetector),
            Box::new(MacOSDetector),
            Box::new(WindowsDetector),
        ]
    }

    fn compiler_channel() -> Result<String, String> {
        let rustc = env::var("RUSTC").unwrap_or_else(|_| "rustc".to_string());

        let output = Command::new(&rustc)
            .args(["--version", "--verbose"])
            .output()
            .map_err(|e| format!("Failed to execute rustc ({rustc}): {e}"))?;

        if !output.status.success() {
            return Err(format!(
                "rustc command failed with exit code: {}",
                output.status
            ));
        }

        let version_info = String::from_utf8_lossy(&output.stdout);

        Ok(if version_info.contains("nightly") {
            "nightly".to_string()
        } else {
            "stable".to_string()
        })
    }

    fn detect_cpu_features(features: &mut [CpuFeature]) -> DetectionResult {
        let detectors = Self::cpu_features_detectors();
        let mut last_error = String::new();

        // Find the applicable detector and use it
        for detector in detectors {
            if detector.is_applicable() {
                println!(
                    "cargo:warning=Using {} CPU feature detector",
                    detector.name()
                );

                match detector.detect_features(features) {
                    DetectionResult::Success => {
                        println!("cargo:warning=CPU feature detection successful");
                        return DetectionResult::Success;
                    }
                    DetectionResult::PartialFailure(msg) => {
                        println!("cargo:warning=CPU feature detection partial failure: {msg}");
                        return DetectionResult::PartialFailure(msg);
                    }
                    DetectionResult::Failure(msg) => {
                        last_error = msg;
                        println!("cargo:warning=CPU feature detection failed: {last_error}");
                        continue;
                    }
                }
            }
        }

        // If we reach here, no detector was applicable or all failed
        if last_error.is_empty() {
            DetectionResult::Failure(
                "No applicable CPU feature detector found for this platform".to_string(),
            )
        } else {
            DetectionResult::Failure(last_error)
        }
    }

    fn apply(features: &mut [CpuFeature]) {
        // Sort features by priority (highest first)
        features.sort();

        // Find and use the highest detected feature (if any)
        let cfg_flag = features
            .iter()
            .find(|cpu_feature| cpu_feature.detected)
            .map(|cpu_feature| {
                println!("cargo:rustc-flag=-C");
                println!("cargo:rustc-flag=target-feature={}", cpu_feature.rustc_flag);
                println!(
                    "cargo:warning=Enabled CPU feature optimization: {} ({})",
                    cpu_feature.name, cpu_feature.rustc_flag
                );
                cpu_feature.cfg_flag
            })
            .unwrap_or_else(|| {
                println!("cargo:warning=No CPU features detected, using fallback implementation");
                "fallback"
            });

        println!("cargo:rustc-cfg={cfg_flag}");

        // Configure check-cfg for all possible configurations
        println!("cargo::rustc-check-cfg=cfg(avx512)");
        println!("cargo::rustc-check-cfg=cfg(avx2)");
        println!("cargo::rustc-check-cfg=cfg(sse)");
        println!("cargo::rustc-check-cfg=cfg(neon)");
        println!("cargo::rustc-check-cfg=cfg(fallback)");
    }
}

fn main() {
    // Detect rustc channel (stable, beta, nightly)
    let rustc_channel = match PlatformDetector::compiler_channel() {
        Ok(channel) => channel,
        Err(e) => {
            println!("cargo:warning=Failed to detect rustc channel: {e}");
            println!("cargo:warning=Defaulting to stable channel");
            "stable".to_string()
        }
    };

    // Create a flag for modules that can be used in nightly build only
    println!("cargo:rustc-cfg=rustc_channel=\"{rustc_channel}\"");
    println!("cargo::rustc-check-cfg=cfg(rustc_channel, values(\"nightly\", \"stable\"))");

    let nightly_build = rustc_channel == "nightly";

    // Define the CPU features we're interested in (channel dependent)
    let mut features = if nightly_build {
        CpuFeature::nightly_features()
    } else {
        CpuFeature::features()
    };

    // Determine if we're cross-compiling
    let host = env::var("HOST").unwrap_or_default();
    let target = env::var("TARGET").unwrap_or_default();
    let is_native_build = host == target;

    // Only run CPU detection for native builds
    if is_native_build {
        match PlatformDetector::detect_cpu_features(&mut features) {
            DetectionResult::Success => {
                // Features detected successfully
            }
            DetectionResult::PartialFailure(msg) => {
                println!("cargo:warning=CPU feature detection partially failed: {msg}",);
                println!("cargo:warning=Some optimizations may not be available");
            }
            DetectionResult::Failure(msg) => {
                println!("cargo:warning=CPU feature detection failed: {msg}");
                println!("cargo:warning=Falling back to default implementation");

                // Reset all features to undetected for safety
                for feature in features.iter_mut() {
                    feature.detected = false;
                }
            }
        }
    } else {
        println!("cargo:warning=Cross-compiling detected (host: {host}, target: {target})",);
        println!("cargo:warning=Skipping CPU feature detection, using fallback implementation");
    }

    // Apply the detected features (or fallback if none detected)
    PlatformDetector::apply(&mut features);
}