armature-core 0.8.5

High-performance async HTTP framework core - routing, handlers, middleware
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
//! Cache-Local State Management
//!
//! This module provides data structures and patterns for keeping frequently
//! accessed state in CPU cache, maximizing cache hits and minimizing cache
//! misses.
//!
//! # Key Concepts
//!
//! - **Cache Line Alignment**: Align hot data to cache line boundaries (64 bytes)
//! - **Hot/Cold Separation**: Keep frequently accessed data together
//! - **Padding**: Prevent false sharing between threads
//! - **Prefetching**: Hints for hardware prefetcher
//!
//! # Performance Impact
//!
//! - L1 cache hit: ~4 cycles
//! - L2 cache hit: ~10 cycles
//! - L3 cache hit: ~40 cycles
//! - Main memory: ~200+ cycles
//!
//! Keeping hot data in cache can provide 50x speedup over memory access.

use std::cell::{Cell, RefCell};
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use std::sync::atomic::{AtomicU64, Ordering};

// ============================================================================
// Constants
// ============================================================================

/// Typical CPU cache line size (64 bytes on most x86/ARM)
pub const CACHE_LINE_SIZE: usize = 64;

/// L1 data cache typical size (32KB)
pub const L1_CACHE_SIZE: usize = 32 * 1024;

/// L2 cache typical size (256KB)
pub const L2_CACHE_SIZE: usize = 256 * 1024;

/// L3 cache typical size per core (2MB)
pub const L3_CACHE_SIZE_PER_CORE: usize = 2 * 1024 * 1024;

// ============================================================================
// Cache-Line Aligned Wrapper
// ============================================================================

/// A value aligned to a cache line boundary.
///
/// This prevents false sharing when the value is accessed from multiple
/// threads, as each thread will have the value in its own cache line.
///
/// # Example
///
/// ```rust,ignore
/// use armature_core::cache_local::CacheAligned;
///
/// // Each counter in its own cache line - no false sharing
/// struct Counters {
///     reads: CacheAligned<AtomicU64>,
///     writes: CacheAligned<AtomicU64>,
/// }
/// ```
#[repr(C, align(64))]
#[derive(Debug)]
pub struct CacheAligned<T> {
    value: T,
    // Padding is implicit due to align(64)
}

impl<T> CacheAligned<T> {
    /// Create a new cache-aligned value.
    #[inline]
    pub const fn new(value: T) -> Self {
        Self { value }
    }

    /// Get inner value.
    #[inline]
    pub fn into_inner(self) -> T {
        self.value
    }

    /// Get reference to inner value.
    #[inline]
    pub fn get(&self) -> &T {
        &self.value
    }

    /// Get mutable reference to inner value.
    #[inline]
    pub fn get_mut(&mut self) -> &mut T {
        &mut self.value
    }
}

impl<T: Default> Default for CacheAligned<T> {
    fn default() -> Self {
        Self::new(T::default())
    }
}

impl<T: Clone> Clone for CacheAligned<T> {
    fn clone(&self) -> Self {
        Self::new(self.value.clone())
    }
}

impl<T> Deref for CacheAligned<T> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

impl<T> DerefMut for CacheAligned<T> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.value
    }
}

// ============================================================================
// Padded Value (for arrays)
// ============================================================================

/// A value with explicit padding to fill a cache line.
///
/// Use this in arrays where each element should have its own cache line.
/// Uses maximum padding (56 bytes) to ensure cache line isolation regardless
/// of the inner type size (up to 8 bytes).
///
/// # Example
///
/// ```rust,ignore
/// use armature_core::cache_local::Padded;
/// use std::sync::atomic::AtomicU64;
///
/// // Array of counters, each in its own cache line
/// let counters: [Padded<AtomicU64>; 8] = Default::default();
/// ```
#[repr(C, align(64))]
#[derive(Debug)]
pub struct Padded<T> {
    value: T,
}

impl<T> Padded<T> {
    /// Create a new padded value.
    #[inline]
    pub const fn new(value: T) -> Self {
        Self { value }
    }

    /// Get inner value.
    #[inline]
    pub fn into_inner(self) -> T {
        self.value
    }
}

impl<T: Default> Default for Padded<T> {
    fn default() -> Self {
        Self::new(T::default())
    }
}

impl<T: Clone> Clone for Padded<T> {
    fn clone(&self) -> Self {
        Self::new(self.value.clone())
    }
}

impl<T> Deref for Padded<T> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

impl<T> DerefMut for Padded<T> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.value
    }
}

// ============================================================================
// Hot/Cold Separation
// ============================================================================

/// Container for separating hot (frequently accessed) and cold (rarely accessed) data.
///
/// Hot data is kept inline for cache locality, while cold data is boxed to
/// keep it out of the hot path's cache lines.
///
/// # Example
///
/// ```rust,ignore
/// use armature_core::cache_local::HotCold;
///
/// // Hot: request count, last access time
/// // Cold: full request history, debug info
/// struct RequestState {
///     data: HotCold<HotData, ColdData>,
/// }
///
/// struct HotData {
///     count: u64,
///     last_access: Instant,
/// }
///
/// struct ColdData {
///     history: Vec<RequestInfo>,
///     debug_log: String,
/// }
/// ```
#[derive(Debug)]
pub struct HotCold<H, C> {
    /// Hot data - kept inline
    pub hot: H,
    /// Cold data - boxed to keep out of cache
    cold: Box<C>,
}

impl<H, C> HotCold<H, C> {
    /// Create new hot/cold container.
    pub fn new(hot: H, cold: C) -> Self {
        Self {
            hot,
            cold: Box::new(cold),
        }
    }

    /// Access hot data (cache-friendly).
    #[inline(always)]
    pub fn hot(&self) -> &H {
        &self.hot
    }

    /// Access hot data mutably.
    #[inline(always)]
    pub fn hot_mut(&mut self) -> &mut H {
        &mut self.hot
    }

    /// Access cold data (may cause cache miss).
    #[inline]
    pub fn cold(&self) -> &C {
        &self.cold
    }

    /// Access cold data mutably.
    #[inline]
    pub fn cold_mut(&mut self) -> &mut C {
        &mut self.cold
    }

    /// Decompose into parts.
    pub fn into_parts(self) -> (H, C) {
        (self.hot, *self.cold)
    }
}

impl<H: Clone, C: Clone> Clone for HotCold<H, C> {
    fn clone(&self) -> Self {
        Self::new(self.hot.clone(), (*self.cold).clone())
    }
}

// ============================================================================
// Local State Cache
// ============================================================================

/// Thread-local cache for frequently accessed state.
///
/// Provides O(1) access to cached values with automatic invalidation
/// based on a global version counter. Values are handed out as `Rc<T>`
/// clones, so they remain valid even if the cache is refreshed or
/// invalidated afterwards.
///
/// # Example
///
/// ```rust,ignore
/// use armature_core::cache_local::LocalStateCache;
///
/// thread_local! {
///     static CONFIG_CACHE: LocalStateCache<Config> = LocalStateCache::new();
/// }
///
/// fn get_config(global: &GlobalConfig) -> Rc<Config> {
///     CONFIG_CACHE.with(|cache| {
///         cache.get_or_refresh(global.version(), || global.snapshot())
///     })
/// }
/// ```
pub struct LocalStateCache<T> {
    /// Cached value
    value: RefCell<Option<Rc<T>>>,
    /// Version when cached
    version: Cell<u64>,
    /// Hit count
    hits: Cell<u64>,
    /// Miss count
    misses: Cell<u64>,
}

impl<T> LocalStateCache<T> {
    /// Create a new empty cache.
    pub const fn new() -> Self {
        Self {
            value: RefCell::new(None),
            version: Cell::new(0),
            hits: Cell::new(0),
            misses: Cell::new(0),
        }
    }

    /// Get cached value or refresh if stale.
    ///
    /// Returns a cheap `Rc` clone of the cached value; the clone stays
    /// valid across later refreshes or invalidations.
    #[inline]
    pub fn get_or_refresh<F>(&self, current_version: u64, refresh: F) -> Rc<T>
    where
        F: FnOnce() -> T,
    {
        if self.version.get() == current_version
            && let Some(ref value) = *self.value.borrow()
        {
            self.hits.set(self.hits.get() + 1);
            LOCALITY_STATS.record_cache_hit();
            return Rc::clone(value);
        }

        // Cache miss - refresh
        self.misses.set(self.misses.get() + 1);
        LOCALITY_STATS.record_cache_miss();

        let new_value = Rc::new(refresh());
        *self.value.borrow_mut() = Some(Rc::clone(&new_value));
        self.version.set(current_version);

        new_value
    }

    /// Invalidate the cache.
    #[inline]
    pub fn invalidate(&self) {
        *self.value.borrow_mut() = None;
        self.version.set(0);
    }

    /// Get cache statistics.
    pub fn stats(&self) -> LocalCacheStats {
        LocalCacheStats {
            hits: self.hits.get(),
            misses: self.misses.get(),
        }
    }
}

impl<T> Default for LocalStateCache<T> {
    fn default() -> Self {
        Self::new()
    }
}

/// Statistics for a local cache.
#[derive(Debug, Clone, Copy)]
pub struct LocalCacheStats {
    /// Cache hits
    pub hits: u64,
    /// Cache misses
    pub misses: u64,
}

impl LocalCacheStats {
    /// Get hit ratio.
    pub fn hit_ratio(&self) -> f64 {
        let total = self.hits + self.misses;
        if total > 0 {
            self.hits as f64 / total as f64
        } else {
            0.0
        }
    }
}

// ============================================================================
// Compact State
// ============================================================================

/// Compact state that fits in a single cache line.
///
/// Packs multiple small values into 64 bytes for efficient access.
/// All fields are accessed together with a single cache line fetch.
///
/// # Example
///
/// ```rust,ignore
/// use armature_core::cache_local::CompactState;
///
/// let state = CompactState::<4>::new();
/// state.set(0, 42);
/// state.set(1, 100);
/// let val = state.get(0);
/// ```
#[repr(C, align(64))]
pub struct CompactState<const N: usize> {
    /// Values packed into cache line
    values: [AtomicU64; N],
}

impl<const N: usize> CompactState<N> {
    /// Create new compact state.
    pub fn new() -> Self {
        // Ensure we fit in a cache line
        const {
            assert!(
                std::mem::size_of::<[AtomicU64; N]>() <= CACHE_LINE_SIZE,
                "CompactState exceeds cache line size"
            );
        }

        Self {
            values: std::array::from_fn(|_| AtomicU64::new(0)),
        }
    }

    /// Get value at index.
    #[inline]
    pub fn get(&self, index: usize) -> u64 {
        self.values[index].load(Ordering::Relaxed)
    }

    /// Set value at index.
    #[inline]
    pub fn set(&self, index: usize, value: u64) {
        self.values[index].store(value, Ordering::Relaxed);
    }

    /// Increment value at index.
    #[inline]
    pub fn increment(&self, index: usize) -> u64 {
        self.values[index].fetch_add(1, Ordering::Relaxed)
    }

    /// Add to value at index.
    #[inline]
    pub fn add(&self, index: usize, delta: u64) -> u64 {
        self.values[index].fetch_add(delta, Ordering::Relaxed)
    }

    /// Get all values as array.
    pub fn all(&self) -> [u64; N] {
        std::array::from_fn(|i| self.get(i))
    }
}

impl<const N: usize> Default for CompactState<N> {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Prefetch Hints
// ============================================================================

/// Prefetch hint level.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PrefetchLevel {
    /// Prefetch to L1 cache (fastest, smallest)
    L1,
    /// Prefetch to L2 cache
    L2,
    /// Prefetch to L3 cache (slowest, largest)
    L3,
    /// Non-temporal (don't pollute cache)
    NonTemporal,
}

/// Prefetch data into cache.
///
/// This is a hint to the CPU - it may be ignored.
///
/// # Example
///
/// ```rust,ignore
/// use armature_core::cache_local::{prefetch, PrefetchLevel};
///
/// let data = vec![0u64; 1000];
///
/// // Prefetch before processing
/// for i in (0..1000).step_by(8) {
///     prefetch(&data[i], PrefetchLevel::L1);
/// }
/// ```
#[inline]
pub fn prefetch<T>(ptr: &T, level: PrefetchLevel) {
    let addr = ptr as *const T as *const u8;
    prefetch_ptr(addr, level);
}

/// Prefetch raw pointer.
#[inline]
pub fn prefetch_ptr(ptr: *const u8, level: PrefetchLevel) {
    // Use platform-specific prefetch instructions where available
    #[cfg(target_arch = "x86_64")]
    {
        use std::arch::x86_64::*;
        unsafe {
            match level {
                PrefetchLevel::L1 => _mm_prefetch(ptr as *const i8, _MM_HINT_T0),
                PrefetchLevel::L2 => _mm_prefetch(ptr as *const i8, _MM_HINT_T1),
                PrefetchLevel::L3 => _mm_prefetch(ptr as *const i8, _MM_HINT_T2),
                PrefetchLevel::NonTemporal => _mm_prefetch(ptr as *const i8, _MM_HINT_NTA),
            }
        }
    }

    #[cfg(target_arch = "aarch64")]
    {
        // ARM prefetch
        unsafe {
            match level {
                PrefetchLevel::L1 => {
                    std::arch::asm!("prfm pldl1keep, [{x}]", x = in(reg) ptr, options(readonly, nostack));
                }
                PrefetchLevel::L2 => {
                    std::arch::asm!("prfm pldl2keep, [{x}]", x = in(reg) ptr, options(readonly, nostack));
                }
                PrefetchLevel::L3 => {
                    std::arch::asm!("prfm pldl3keep, [{x}]", x = in(reg) ptr, options(readonly, nostack));
                }
                PrefetchLevel::NonTemporal => {
                    std::arch::asm!("prfm pldl1strm, [{x}]", x = in(reg) ptr, options(readonly, nostack));
                }
            }
        }
    }

    #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
    {
        // Fallback: do nothing, let hardware handle it
        let _ = (ptr, level);
    }
}

/// Prefetch a range of memory.
#[inline]
pub fn prefetch_range<T>(slice: &[T], level: PrefetchLevel) {
    let ptr = slice.as_ptr() as *const u8;
    let len = std::mem::size_of_val(slice);

    for offset in (0..len).step_by(CACHE_LINE_SIZE) {
        prefetch_ptr(unsafe { ptr.add(offset) }, level);
    }
}

// ============================================================================
// Struct of Arrays (SoA) Layout
// ============================================================================

/// Struct-of-Arrays storage for better cache locality.
///
/// Instead of Array-of-Structs (AoS) which interleaves fields,
/// SoA groups same fields together for sequential access.
///
/// # Example
///
/// ```rust,ignore
/// // AoS (bad cache utilization when only accessing one field):
/// // [Point{x,y,z}, Point{x,y,z}, Point{x,y,z}...]
///
/// // SoA (good cache utilization):
/// // [x, x, x...], [y, y, y...], [z, z, z...]
///
/// let mut points = SoaStorage::<3, 1000>::new();
/// let idx = points.push().unwrap();
/// points.set_field(0, idx, 1.0);  // Set x[idx] = 1.0
/// ```
pub struct SoaStorage<const FIELDS: usize, const CAPACITY: usize> {
    /// Storage for each field (zero-initialized)
    data: [Box<[f64; CAPACITY]>; FIELDS],
    /// Number of elements
    len: usize,
}

impl<const FIELDS: usize, const CAPACITY: usize> SoaStorage<FIELDS, CAPACITY> {
    /// Create new SoA storage.
    pub fn new() -> Self {
        Self {
            data: std::array::from_fn(|_| {
                // Allocate on the heap directly to avoid large stack arrays
                vec![0.0f64; CAPACITY]
                    .into_boxed_slice()
                    .try_into()
                    .expect("boxed slice length matches CAPACITY")
            }),
            len: 0,
        }
    }

    /// Get current length.
    #[inline]
    pub fn len(&self) -> usize {
        self.len
    }

    /// Check if empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Get capacity.
    #[inline]
    pub const fn capacity(&self) -> usize {
        CAPACITY
    }

    /// Get field value at index.
    #[inline]
    pub fn get_field(&self, field: usize, index: usize) -> f64 {
        assert!(field < FIELDS && index < self.len);
        self.data[field][index]
    }

    /// Set field value at index.
    #[inline]
    pub fn set_field(&mut self, field: usize, index: usize, value: f64) {
        assert!(field < FIELDS && index < self.len);
        self.data[field][index] = value;
    }

    /// Push a new element (all fields start zeroed; set them via `set_field`).
    pub fn push(&mut self) -> Option<usize> {
        if self.len < CAPACITY {
            let index = self.len;
            self.len += 1;
            Some(index)
        } else {
            None
        }
    }

    /// Get a field slice for sequential access.
    ///
    /// This is cache-friendly for operations on a single field.
    pub fn field_slice(&self, field: usize) -> &[f64] {
        assert!(field < FIELDS);
        &self.data[field][..self.len]
    }

    /// Prefetch a field for upcoming access.
    #[inline]
    pub fn prefetch_field(&self, field: usize, level: PrefetchLevel) {
        assert!(field < FIELDS);
        prefetch_range(self.field_slice(field), level);
    }
}

impl<const FIELDS: usize, const CAPACITY: usize> Default for SoaStorage<FIELDS, CAPACITY> {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Global Statistics
// ============================================================================

/// Statistics for cache locality operations.
#[derive(Debug, Default)]
pub struct LocalityStats {
    /// Local cache hits
    cache_hits: AtomicU64,
    /// Local cache misses
    cache_misses: AtomicU64,
    /// Prefetch operations
    prefetches: AtomicU64,
}

impl LocalityStats {
    fn record_cache_hit(&self) {
        self.cache_hits.fetch_add(1, Ordering::Relaxed);
    }

    fn record_cache_miss(&self) {
        self.cache_misses.fetch_add(1, Ordering::Relaxed);
    }

    #[allow(dead_code)]
    fn record_prefetch(&self) {
        self.prefetches.fetch_add(1, Ordering::Relaxed);
    }

    /// Get cache hits.
    pub fn cache_hits(&self) -> u64 {
        self.cache_hits.load(Ordering::Relaxed)
    }

    /// Get cache misses.
    pub fn cache_misses(&self) -> u64 {
        self.cache_misses.load(Ordering::Relaxed)
    }

    /// Get prefetch count.
    pub fn prefetches(&self) -> u64 {
        self.prefetches.load(Ordering::Relaxed)
    }

    /// Get cache hit ratio.
    pub fn hit_ratio(&self) -> f64 {
        let hits = self.cache_hits() as f64;
        let total = hits + self.cache_misses() as f64;
        if total > 0.0 { hits / total } else { 0.0 }
    }
}

/// Global locality statistics.
static LOCALITY_STATS: LocalityStats = LocalityStats {
    cache_hits: AtomicU64::new(0),
    cache_misses: AtomicU64::new(0),
    prefetches: AtomicU64::new(0),
};

/// Get global locality statistics.
pub fn locality_stats() -> &'static LocalityStats {
    &LOCALITY_STATS
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_cache_aligned_size() {
        assert_eq!(std::mem::align_of::<CacheAligned<u64>>(), CACHE_LINE_SIZE);
        assert!(std::mem::size_of::<CacheAligned<u64>>() >= CACHE_LINE_SIZE);
    }

    #[test]
    fn test_cache_aligned_basic() {
        let aligned = CacheAligned::new(42u64);
        assert_eq!(*aligned, 42);
    }

    #[test]
    fn test_cache_aligned_deref() {
        let mut aligned = CacheAligned::new(vec![1, 2, 3]);
        aligned.push(4);
        assert_eq!(&*aligned, &vec![1, 2, 3, 4]);
    }

    #[test]
    fn test_padded_size() {
        assert!(std::mem::size_of::<Padded<u64>>() >= CACHE_LINE_SIZE);
    }

    #[test]
    fn test_padded_basic() {
        let padded = Padded::new(100u64);
        assert_eq!(*padded, 100);
    }

    #[test]
    fn test_hot_cold_separation() {
        let data: HotCold<u64, Vec<String>> = HotCold::new(42, vec!["cold".into()]);

        assert_eq!(*data.hot(), 42);
        assert_eq!(data.cold().len(), 1);
    }

    #[test]
    fn test_hot_cold_mutation() {
        let mut data: HotCold<u64, Vec<u64>> = HotCold::new(0, vec![]);

        *data.hot_mut() = 100;
        data.cold_mut().push(1);

        assert_eq!(*data.hot(), 100);
        assert_eq!(data.cold().len(), 1);
    }

    #[test]
    fn test_local_state_cache() {
        let cache: LocalStateCache<u64> = LocalStateCache::new();

        // First access - miss
        let val1 = cache.get_or_refresh(1, || 42);
        assert_eq!(*val1, 42);

        // Same version - hit
        let val2 = cache.get_or_refresh(1, || 100);
        assert_eq!(*val2, 42); // Still 42, not 100

        // Different version - miss
        let val3 = cache.get_or_refresh(2, || 100);
        assert_eq!(*val3, 100);
    }

    #[test]
    fn test_local_state_cache_value_survives_refresh() {
        // Regression: get_or_refresh used to return a reference into the
        // cache that dangled after a later refresh or invalidate.
        let cache: LocalStateCache<String> = LocalStateCache::new();

        let val1 = cache.get_or_refresh(1, || "first".to_string());

        // Overwrite the cached slot and then invalidate entirely
        let val2 = cache.get_or_refresh(2, || "second".to_string());
        cache.invalidate();

        // Earlier clones remain valid
        assert_eq!(*val1, "first");
        assert_eq!(*val2, "second");
    }

    #[test]
    fn test_local_cache_stats() {
        let cache: LocalStateCache<u64> = LocalStateCache::new();

        cache.get_or_refresh(1, || 1); // miss
        cache.get_or_refresh(1, || 2); // hit
        cache.get_or_refresh(1, || 3); // hit

        let stats = cache.stats();
        assert_eq!(stats.hits, 2);
        assert_eq!(stats.misses, 1);
        assert!((stats.hit_ratio() - 0.666).abs() < 0.01);
    }

    #[test]
    fn test_compact_state() {
        let state = CompactState::<4>::new();

        state.set(0, 100);
        state.set(1, 200);
        assert_eq!(state.get(0), 100);
        assert_eq!(state.get(1), 200);

        state.increment(0);
        assert_eq!(state.get(0), 101);

        state.add(1, 50);
        assert_eq!(state.get(1), 250);
    }

    #[test]
    fn test_compact_state_all() {
        let state = CompactState::<4>::new();
        state.set(0, 1);
        state.set(1, 2);
        state.set(2, 3);
        state.set(3, 4);

        let all = state.all();
        assert_eq!(all, [1, 2, 3, 4]);
    }

    #[test]
    fn test_soa_storage() {
        let mut storage = SoaStorage::<3, 100>::new();

        let idx = storage.push().unwrap();
        storage.set_field(0, idx, 1.0);
        storage.set_field(1, idx, 2.0);
        storage.set_field(2, idx, 3.0);

        assert_eq!(storage.get_field(0, idx), 1.0);
        assert_eq!(storage.get_field(1, idx), 2.0);
        assert_eq!(storage.get_field(2, idx), 3.0);
    }

    #[test]
    fn test_soa_field_slice() {
        let mut storage = SoaStorage::<2, 100>::new();

        for _ in 0..10 {
            let idx = storage.push().unwrap();
            storage.set_field(0, idx, idx as f64);
        }

        let slice = storage.field_slice(0);
        assert_eq!(slice.len(), 10);
    }

    #[test]
    fn test_soa_unset_fields_are_zeroed() {
        // Regression: pushed-but-unset fields used to be uninitialized memory.
        let mut storage = SoaStorage::<2, 8>::new();

        let idx = storage.push().unwrap();
        // Only set field 0; field 1 must read as 0.0 rather than garbage
        storage.set_field(0, idx, 7.0);

        assert_eq!(storage.get_field(0, idx), 7.0);
        assert_eq!(storage.get_field(1, idx), 0.0);
        assert_eq!(storage.field_slice(1), &[0.0]);
    }

    #[test]
    fn test_soa_push_clamped_to_capacity() {
        // Regression: overflowing push used to transiently push len past
        // CAPACITY, allowing out-of-bounds field slices.
        let mut storage = SoaStorage::<1, 4>::new();

        for _ in 0..4 {
            assert!(storage.push().is_some());
        }

        // Full: further pushes fail and len stays clamped
        assert!(storage.push().is_none());
        assert!(storage.push().is_none());
        assert_eq!(storage.len(), 4);
        assert_eq!(storage.field_slice(0).len(), 4);
    }

    #[test]
    fn test_prefetch_levels() {
        // Just test that prefetch doesn't crash
        let data = vec![0u64; 100];
        prefetch(&data[0], PrefetchLevel::L1);
        prefetch(&data[50], PrefetchLevel::L2);
        prefetch(&data[99], PrefetchLevel::L3);
    }

    #[test]
    fn test_locality_stats() {
        let stats = locality_stats();
        let _ = stats.cache_hits();
        let _ = stats.cache_misses();
        let _ = stats.hit_ratio();
    }
}