rscrypto 0.1.1

Pure Rust cryptography, hardware-accelerated: BLAKE3, SHA-2/3, AES-GCM, ChaCha20-Poly1305, Ed25519, X25519, HMAC, HKDF, Argon2, CRC. no_std, WASM, ten CPU architectures.
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
#[cfg(test)]
extern crate std;

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  #[cfg(not(miri))] // get() returns portable() under Miri, which has different arch
  fn test_get_returns_valid() {
    let det = get();

    assert_eq!(det.arch, Arch::current());
  }

  #[test]
  #[cfg(not(miri))] // Uses syscalls for feature detection
  fn test_detect_uncached_consistent() {
    let d1 = detect_uncached();
    let d2 = detect_uncached();
    assert_eq!(d1.caps, d2.caps);
    assert_eq!(d1.arch, d2.arch);
  }

  #[test]
  #[cfg(not(miri))] // get() uses syscalls for feature detection
  // `feature = "portable-only"` intentionally short-circuits `caps()` to
  // `Caps::NONE`, which would mismatch `get().caps` on a SIMD-capable host.
  // The convenience-function contract under SIMD-on dispatch is what this
  // test asserts; the portable-only override has its own coverage in
  // `test_caps_returns_none_with_portable_only_feature` below.
  #[cfg(not(feature = "portable-only"))]
  fn test_convenience_functions() {
    let det = get();
    assert_eq!(caps(), det.caps);
    assert_eq!(arch(), det.arch);
  }

  #[test]
  #[cfg(all(feature = "portable-only", not(miri)))]
  fn test_caps_returns_none_with_portable_only_feature() {
    // The `portable-only` feature must collapse `caps()` to the empty cap
    // set so every dispatcher falls through to its portable backend.
    assert_eq!(caps(), Caps::NONE, "portable-only must zero out caps()");
    // `arch()` is unaffected — only the cap surface is suppressed.
    let det = get();
    assert_eq!(arch(), det.arch);
  }

  #[test]
  #[cfg(all(target_arch = "x86_64", not(miri)))]
  fn test_x86_64_baseline() {
    use crate::platform::caps::x86;
    let det = get();
    assert!(det.caps.has(x86::SSE2));
  }

  #[test]
  #[cfg(all(target_arch = "aarch64", not(miri)))]
  fn test_aarch64_baseline() {
    use crate::platform::caps::aarch64;
    let det = get();
    assert!(det.caps.has(aarch64::NEON));
  }

  #[test]
  #[cfg(miri)]
  fn test_miri_returns_portable() {
    let det = get();
    assert_eq!(det.caps, Caps::NONE);
    assert_eq!(det.arch, Arch::Other);
  }

  // ─────────────────────────────────────────────────────────────────────────────
  // Compile-Time Detection Tests (caps_static)
  // ─────────────────────────────────────────────────────────────────────────────

  #[test]
  fn test_caps_static_is_const() {
    // Verify caps_static() can be used in const context
    const STATIC_CAPS: Caps = caps_static();
    let _ = STATIC_CAPS; // Use it to avoid dead code warning
  }

  #[test]
  #[cfg(target_arch = "x86_64")]
  fn test_caps_static_x86_64_baseline() {
    use crate::platform::caps::x86;

    // x86_64 guarantees SSE2
    let caps = caps_static();
    assert!(caps.has(x86::SSE2), "x86_64 must have SSE2 baseline in caps_static");
  }

  #[test]
  #[cfg(target_arch = "aarch64")]
  fn test_caps_static_aarch64_baseline() {
    use crate::platform::caps::aarch64;

    // aarch64 guarantees NEON
    let caps = caps_static();
    assert!(
      caps.has(aarch64::NEON),
      "aarch64 must have NEON baseline in caps_static"
    );
  }

  #[test]
  #[cfg(not(miri))] // Miri can't detect runtime features, returns Caps::NONE
  // The "static is a subset of runtime" invariant assumes runtime detection
  // is enabled. With `portable-only`, runtime is intentionally `Caps::NONE`,
  // and `caps_static()` may be non-empty — they're allowed to disagree
  // because the override is the whole point of the feature.
  #[cfg(not(feature = "portable-only"))]
  fn test_caps_static_subset_of_runtime() {
    // Compile-time detected features must be a subset of runtime detected features
    let static_caps = caps_static();
    let runtime_caps = caps();

    // Every compile-time feature must be present at runtime
    assert!(
      runtime_caps.has(static_caps),
      "caps_static() must be subset of caps(): static={:?}, runtime={:?}",
      static_caps,
      runtime_caps
    );
  }

  #[test]
  fn test_caps_static_consistent() {
    // caps_static() must return the same value every time
    let a = caps_static();
    let b = caps_static();
    assert_eq!(a, b, "caps_static() must be deterministic");
  }

  #[test]
  #[cfg(all(target_arch = "x86_64", not(miri)))]
  fn test_caps_static_x86_features() {
    use crate::platform::caps::x86;

    let caps = caps_static();

    // Test that feature groups are consistent with their baselines
    // If AVX2 is enabled at compile time, it should be detected
    if cfg!(target_feature = "avx2") {
      assert!(caps.has(x86::AVX2), "AVX2 must be detected when target_feature enabled");
    }

    // If AVX-512F is enabled, foundation should be detected
    if cfg!(target_feature = "avx512f") {
      assert!(
        caps.has(x86::AVX512F),
        "AVX512F must be detected when target_feature enabled"
      );
    }

    // If VPCLMULQDQ is enabled, it should be detected
    if cfg!(target_feature = "vpclmulqdq") {
      assert!(
        caps.has(x86::VPCLMULQDQ),
        "VPCLMULQDQ must be detected when target_feature enabled"
      );
    }
  }

  #[test]
  #[cfg(all(target_arch = "aarch64", not(miri)))]
  fn test_caps_static_aarch64_features() {
    use crate::platform::caps::aarch64;

    let caps = caps_static();

    // If AES is enabled at compile time, both AES and PMULL should be detected
    if cfg!(target_feature = "aes") {
      assert!(
        caps.has(aarch64::AES),
        "AES must be detected when target_feature enabled"
      );
      assert!(
        caps.has(aarch64::PMULL),
        "PMULL must be detected when aes target_feature enabled"
      );
    }

    // If SHA3 is enabled, both SHA3 and SHA512 should be detected
    if cfg!(target_feature = "sha3") {
      assert!(
        caps.has(aarch64::SHA3),
        "SHA3 must be detected when target_feature enabled"
      );
      assert!(
        caps.has(aarch64::SHA512),
        "SHA512 must be detected when sha3 target_feature enabled"
      );
    }

    // If SME is enabled, it should be detected (fixing prior drift)
    if cfg!(target_feature = "sme") {
      assert!(
        caps.has(aarch64::SME),
        "SME must be detected when target_feature enabled"
      );
    }
  }

  // ─────────────────────────────────────────────────────────────────────────────
  // Apple Silicon Detection Tests
  // ─────────────────────────────────────────────────────────────────────────────

  #[test]
  #[cfg(all(target_arch = "aarch64", target_os = "macos", feature = "std", not(miri)))]
  fn test_apple_silicon_detection_runs() {
    // Just verify detection doesn't crash and returns a valid result
    let chip_gen = detect_apple_silicon_gen();
    // On actual Apple Silicon, we should get Some variant
    // On Rosetta 2 or non-Apple aarch64, we might get None
    if let Some(detected) = chip_gen {
      // Verify the generation is valid
      assert!(matches!(
        detected,
        AppleSiliconGen::M1 | AppleSiliconGen::M2 | AppleSiliconGen::M3 | AppleSiliconGen::M4
      ));
    }
  }

  // ─────────────────────────────────────────────────────────────────────────────
  // SVE Vector Length Detection Tests
  // ─────────────────────────────────────────────────────────────────────────────

  #[test]
  #[cfg(all(target_arch = "aarch64", target_os = "linux", not(miri)))]
  fn test_sve_vlen_detection_runs() {
    // Just verify detection doesn't crash
    let vlen = detect_sve_vlen();
    // VL should be 0 (no SVE) or a valid power-of-2 in [128, 2048]
    if vlen > 0 {
      assert!(vlen >= 128, "SVE VL too small: {vlen}");
      assert!(vlen <= 2048, "SVE VL too large: {vlen}");
      assert!(vlen.is_power_of_two(), "SVE VL not power of 2: {vlen}");
    }
  }

  // ─────────────────────────────────────────────────────────────────────────────
  // Hybrid Intel Detection Tests
  // ─────────────────────────────────────────────────────────────────────────────

  #[test]
  #[cfg(all(any(target_arch = "x86_64", target_arch = "x86"), feature = "std"))]
  fn test_is_intel_hybrid_amd_returns_false() {
    // AMD CPUs should never be detected as Intel hybrid
    assert!(!is_intel_hybrid(true, 6, 0x97)); // Even with ADL model
    assert!(!is_intel_hybrid(true, 25, 0)); // Zen 4
    assert!(!is_intel_hybrid(true, 26, 0)); // Zen 5
  }

  #[test]
  #[cfg(all(any(target_arch = "x86_64", target_arch = "x86"), feature = "std"))]
  fn test_is_intel_hybrid_known_models() {
    // Alder Lake models
    assert!(is_intel_hybrid(false, 6, 0x97)); // ADL-S
    assert!(is_intel_hybrid(false, 6, 0x9A)); // ADL-P

    // Raptor Lake models
    assert!(is_intel_hybrid(false, 6, 0xB7)); // RPL-S
    assert!(is_intel_hybrid(false, 6, 0xBA)); // RPL-P

    // Non-hybrid Intel models should return false
    assert!(!is_intel_hybrid(false, 6, 0x8F)); // Sapphire Rapids
    assert!(!is_intel_hybrid(false, 6, 0x6A)); // Ice Lake-SP
  }

  #[test]
  #[allow(unsafe_code)]
  #[cfg(all(any(target_arch = "x86_64", target_arch = "x86"), feature = "std"))]
  fn test_hybrid_avx512_override_default() {
    // Without env var set, override should be false
    // Note: We can't easily test with env var set due to test isolation
    // but we verify the default behavior
    // SAFETY: This test runs in isolation and doesn't rely on this env var being
    // present for other threads. The remove_var is unsafe due to potential data
    // races with other threads reading env vars, but test isolation mitigates this.
    unsafe { std::env::remove_var("RSCRYPTO_FORCE_AVX512") };
    assert!(!hybrid_avx512_override());
  }

  #[test]
  #[cfg(all(target_arch = "x86_64", not(miri)))]
  fn test_x86_64_model_extraction() {
    // Just verify CPUID model extraction works
    let det = detect_uncached();
    assert_eq!(det.arch, Arch::X86_64);
    assert!(det.caps.count() >= 1);
  }

  #[test]
  #[cfg(all(
    target_arch = "aarch64",
    not(miri),
    any(target_os = "macos", target_os = "ios", target_os = "tvos", target_os = "watchos")
  ))]
  fn test_macos_extended_features() {
    // Test that new feature detection works on macOS
    use crate::platform::caps::aarch64;
    let det = get();

    // Verify extended features are detected on capable hardware
    // On M1+, we should detect these features:
    std::eprintln!("Detected features: {}", det.caps.count());
    std::eprintln!("  I8MM: {}", det.caps.has(aarch64::I8MM));
    std::eprintln!("  BF16: {}", det.caps.has(aarch64::BF16));
    std::eprintln!("  FRINTTS: {}", det.caps.has(aarch64::FRINTTS));
    std::eprintln!("  LSE2: {}", det.caps.has(aarch64::LSE2));

    // FRINTTS is detectable via std::arch on macOS; LSE2 is not exposed by
    // Apple's sysctl and therefore cannot be asserted here.
    assert!(det.caps.has(aarch64::FRINTTS), "FRINTTS should be detected on M1+");
  }

  #[test]
  #[cfg(all(
    target_arch = "aarch64",
    feature = "std",
    not(miri),
    any(target_os = "macos", target_os = "ios", target_os = "tvos", target_os = "watchos")
  ))]
  fn test_detect_apple_sme_features_exists() {
    // Verify the SME detection function exists and returns valid caps
    let sme_caps = detect_apple_sme_features();
    // The function should always return valid Caps (may be empty on M1-M3)
    // On M4+, SME should be detected
    std::eprintln!("SME caps detected: {}", sme_caps.count());
    std::eprintln!("  SME: {}", sme_caps.has(crate::platform::caps::aarch64::SME));
    std::eprintln!("  SME2: {}", sme_caps.has(crate::platform::caps::aarch64::SME2));
  }

  #[test]
  #[cfg(all(
    target_arch = "aarch64",
    feature = "std",
    not(miri),
    any(target_os = "macos", target_os = "ios", target_os = "tvos", target_os = "watchos")
  ))]
  fn test_detect_apple_silicon_gen_exists() {
    // Verify chip generation detection works
    if let Some(chip_gen) = detect_apple_silicon_gen() {
      std::eprintln!("Detected Apple Silicon generation: {:?}", chip_gen);
      // Basic sanity checks
      match chip_gen {
        AppleSiliconGen::M1 | AppleSiliconGen::M2 | AppleSiliconGen::M3 => {
          // M1-M3 should not have SME
          std::eprintln!("M1-M3 chip detected (no SME expected)");
        }
        AppleSiliconGen::M4 => {
          // M4 should have SME
          std::eprintln!("M4 chip detected (SME expected)");
        }
        AppleSiliconGen::M5 => {
          // M5 should have SME2
          std::eprintln!("M5 chip detected (SME2 expected)");
        }
      }
    } else {
      std::eprintln!("Unknown or A-series chip detected");
    }
  }

  // ─────────────────────────────────────────────────────────────────────────────
  // Arch Round-Trip Tests
  // ─────────────────────────────────────────────────────────────────────────────

  // Mirror of the arch_to_u8 mapping used in atomic_cache (no_std).
  // Note: Arch doesn't have #[repr(u8)], so this is a custom mapping
  // where Other=0 (the uninitialized/fallback value).
  fn test_arch_to_u8(arch: Arch) -> u8 {
    match arch {
      Arch::X86_64 => 1,
      Arch::X86 => 2,
      Arch::Aarch64 => 3,
      Arch::Arm => 4,
      Arch::Riscv64 => 5,
      Arch::Riscv32 => 6,
      Arch::Power => 7,
      Arch::S390x => 8,
      Arch::Wasm32 => 10,
      Arch::Wasm64 => 11,
      Arch::Other => 0,
    }
  }

  fn test_arch_from_u8(v: u8) -> Arch {
    match v {
      1 => Arch::X86_64,
      2 => Arch::X86,
      3 => Arch::Aarch64,
      4 => Arch::Arm,
      5 => Arch::Riscv64,
      6 => Arch::Riscv32,
      7 => Arch::Power,
      8 => Arch::S390x,
      10 => Arch::Wasm32,
      11 => Arch::Wasm64,
      _ => Arch::Other,
    }
  }

  /// Verify arch_to_u8 and arch_from_u8 are inverses.
  #[test]
  fn test_arch_round_trip() {
    let variants: &[Arch] = &[
      Arch::Other,
      Arch::X86_64,
      Arch::X86,
      Arch::Aarch64,
      Arch::Arm,
      Arch::Riscv64,
      Arch::Riscv32,
      Arch::Power,
      Arch::S390x,
      Arch::Wasm32,
      Arch::Wasm64,
    ];

    for &arch in variants {
      let encoded = test_arch_to_u8(arch);
      let decoded = test_arch_from_u8(encoded);
      assert_eq!(
        arch, decoded,
        "Arch round-trip failed: {:?} -> {} -> {:?}",
        arch, encoded, decoded
      );
    }

    // Verify out-of-range values map to Other
    assert_eq!(test_arch_from_u8(12), Arch::Other);
    assert_eq!(test_arch_from_u8(255), Arch::Other);
  }

  /// Verify all Arch variants have distinct encoded u8 values.
  #[test]
  fn test_arch_no_collisions() {
    use alloc::collections::BTreeSet;

    let variants: &[Arch] = &[
      Arch::Other,
      Arch::X86_64,
      Arch::X86,
      Arch::Aarch64,
      Arch::Arm,
      Arch::Riscv64,
      Arch::Riscv32,
      Arch::Power,
      Arch::S390x,
      Arch::Wasm32,
      Arch::Wasm64,
    ];

    let mut seen = BTreeSet::new();
    for &arch in variants {
      let val = test_arch_to_u8(arch);
      assert!(
        seen.insert(val),
        "Arch::{:?} has duplicate encoded u8 value {}",
        arch,
        val
      );
    }

    assert_eq!(seen.len(), 11, "Expected 11 Arch variants with unique encodings");
  }

  // ─────────────────────────────────────────────────────────────────────────────
  // Override Mechanism Tests
  // ─────────────────────────────────────────────────────────────────────────────

  #[test]
  fn test_has_override_exists() {
    // Verify the override API exists and returns a bool.
    // Note: Due to global state from other tests, we can't assert a specific value.
    let _ = has_override();
  }

  #[test]
  fn test_detected_portable_constructor() {
    let det = Detected::portable();
    assert_eq!(det.caps, Caps::NONE);
    assert_eq!(det.arch, Arch::Other);
  }

  #[test]
  fn test_detected_equality() {
    let a = Detected::portable();
    let b = Detected::portable();
    assert_eq!(a, b);

    let c = Detected {
      caps: Caps::bit(0),
      arch: Arch::X86_64,
    };
    assert_ne!(a, c);
  }

  #[test]
  fn test_detected_debug() {
    let det = Detected::portable();
    let s = alloc::format!("{:?}", det);
    assert!(s.contains("Detected"));
    assert!(s.contains("caps"));
    assert!(s.contains("arch"));
  }
}