scirs2-core 0.4.3

Core utilities and common functionality for SciRS2 (scirs2-core)
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
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
//! Concurrent data structures for safe shared-state parallelism.
//!
//! This module provides high-performance, lock-based concurrent data structures:
//!
//! - [`ConcurrentHashMap`] — sharded-lock hash map for high-throughput concurrent access
//! - [`BoundedQueue`] — bounded MPMC (multi-producer, multi-consumer) queue
//! - [`ConcurrentAccumulator`] — lock-free parallel accumulator for reductions
//! - [`WriterPreferenceRwLock`] — read-write lock that gives priority to writers
//! - [`DoubleBuffer`] — double-buffered exchange for producer/consumer patterns
//!
//! All structures are `Send + Sync` and avoid `unwrap()` in favour of explicit error handling.
//!
//! # Example
//!
//! ```rust
//! use scirs2_core::concurrent::{ConcurrentHashMap, BoundedQueue};
//!
//! // Concurrent hash map
//! let map: ConcurrentHashMap<String, u64> = ConcurrentHashMap::new();
//! map.insert("key".into(), 42);
//! assert_eq!(map.get(&"key".to_string()), Some(42));
//!
//! // Bounded MPMC queue
//! let queue: BoundedQueue<i32> = BoundedQueue::new(16);
//! queue.push(1).expect("should succeed");
//! assert_eq!(queue.pop(), Some(1));
//! ```

use std::collections::HashMap;
use std::hash::{BuildHasher, Hash, Hasher};
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
use std::time::Duration;

use crate::error::{CoreError, CoreResult, ErrorContext};

// ===========================================================================
// ConcurrentHashMap (sharded lock)
// ===========================================================================

/// Default number of shards for [`ConcurrentHashMap`].
const DEFAULT_SHARD_COUNT: usize = 64;

/// A concurrent hash map using shard-level locking for high throughput.
///
/// The map is split into `N` independent shards, each protected by its own
/// mutex.  This dramatically reduces contention compared to a single global
/// lock when many threads operate on different keys simultaneously.
pub struct ConcurrentHashMap<K, V, S = std::hash::RandomState> {
    shards: Vec<Mutex<HashMap<K, V, S>>>,
    shard_count: usize,
    hash_builder: S,
    len: AtomicUsize,
}

impl<K, V> ConcurrentHashMap<K, V, std::hash::RandomState>
where
    K: Eq + Hash + Clone,
    V: Clone,
{
    /// Create a new concurrent hash map with the default number of shards.
    pub fn new() -> Self {
        Self::with_shard_count(DEFAULT_SHARD_COUNT)
    }

    /// Create a concurrent hash map with the specified number of shards.
    pub fn with_shard_count(n: usize) -> Self {
        let shard_count = n.max(1);
        let hash_builder = std::hash::RandomState::new();
        let shards = (0..shard_count)
            .map(|_| Mutex::new(HashMap::with_hasher(hash_builder.clone())))
            .collect();
        Self {
            shards,
            shard_count,
            hash_builder,
            len: AtomicUsize::new(0),
        }
    }
}

impl<K, V, S> ConcurrentHashMap<K, V, S>
where
    K: Eq + Hash + Clone,
    V: Clone,
    S: BuildHasher + Clone,
{
    fn shard_index(&self, key: &K) -> usize {
        (self.hash_builder.hash_one(&key) as usize) % self.shard_count
    }

    fn lock_shard(&self, idx: usize) -> CoreResult<MutexGuard<'_, HashMap<K, V, S>>> {
        self.shards[idx].lock().map_err(|e| {
            CoreError::ComputationError(ErrorContext::new(format!(
                "concurrent hash map shard {idx} mutex poisoned: {e}"
            )))
        })
    }

    /// Insert a key-value pair, returning the previous value if the key already existed.
    pub fn insert(&self, key: K, value: V) -> Option<V> {
        let idx = self.shard_index(&key);
        let mut shard = match self.lock_shard(idx) {
            Ok(s) => s,
            Err(_) => return None,
        };
        let prev = shard.insert(key, value);
        if prev.is_none() {
            self.len.fetch_add(1, Ordering::Release);
        }
        prev
    }

    /// Retrieve a clone of the value associated with the key.
    pub fn get(&self, key: &K) -> Option<V> {
        let idx = self.shard_index(key);
        let shard = match self.lock_shard(idx) {
            Ok(s) => s,
            Err(_) => return None,
        };
        shard.get(key).cloned()
    }

    /// Remove a key and return its value.
    pub fn remove(&self, key: &K) -> Option<V> {
        let idx = self.shard_index(key);
        let mut shard = match self.lock_shard(idx) {
            Ok(s) => s,
            Err(_) => return None,
        };
        let removed = shard.remove(key);
        if removed.is_some() {
            self.len.fetch_sub(1, Ordering::Release);
        }
        removed
    }

    /// Check whether the map contains the key.
    pub fn contains_key(&self, key: &K) -> bool {
        let idx = self.shard_index(key);
        match self.lock_shard(idx) {
            Ok(shard) => shard.contains_key(key),
            Err(_) => false,
        }
    }

    /// Approximate number of entries (may be slightly stale under contention).
    pub fn len(&self) -> usize {
        self.len.load(Ordering::Acquire)
    }

    /// Whether the map is empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Apply a function to the value associated with `key`, returning the result.
    ///
    /// If the key doesn't exist, returns `None`.
    pub fn get_and_modify<F, R>(&self, key: &K, f: F) -> Option<R>
    where
        F: FnOnce(&mut V) -> R,
    {
        let idx = self.shard_index(key);
        let mut shard = match self.lock_shard(idx) {
            Ok(s) => s,
            Err(_) => return None,
        };
        shard.get_mut(key).map(f)
    }

    /// Insert if the key does not already exist, using a closure to create the value.
    ///
    /// Returns a clone of the existing or newly-inserted value.
    pub fn get_or_insert_with<F>(&self, key: K, f: F) -> V
    where
        F: FnOnce() -> V,
    {
        let idx = self.shard_index(&key);
        let mut shard = match self.lock_shard(idx) {
            Ok(s) => s,
            Err(_) => return f(),
        };
        if let Some(existing) = shard.get(&key) {
            return existing.clone();
        }
        let value = f();
        let cloned = value.clone();
        shard.insert(key, value);
        self.len.fetch_add(1, Ordering::Release);
        cloned
    }

    /// Collect all keys into a Vec.
    pub fn keys(&self) -> Vec<K> {
        let mut result = Vec::new();
        for shard_mutex in &self.shards {
            if let Ok(shard) = shard_mutex.lock() {
                result.extend(shard.keys().cloned());
            }
        }
        result
    }

    /// Clear all entries.
    pub fn clear(&self) {
        for shard_mutex in &self.shards {
            if let Ok(mut shard) = shard_mutex.lock() {
                shard.clear();
            }
        }
        self.len.store(0, Ordering::Release);
    }
}

// Safety: The sharded mutexes ensure thread-safe access.
unsafe impl<K: Send, V: Send, S: Send> Send for ConcurrentHashMap<K, V, S> {}
unsafe impl<K: Send + Sync, V: Send + Sync, S: Send + Sync> Sync for ConcurrentHashMap<K, V, S> {}

impl<K, V> Default for ConcurrentHashMap<K, V, std::hash::RandomState>
where
    K: Eq + Hash + Clone,
    V: Clone,
{
    fn default() -> Self {
        Self::new()
    }
}

// ===========================================================================
// BoundedQueue (MPMC)
// ===========================================================================

/// A bounded, multi-producer, multi-consumer (MPMC) queue.
///
/// Pushing to a full queue returns an error rather than blocking.
/// Popping from an empty queue returns `None`.
/// Blocking variants (`push_blocking`, `pop_blocking`) are available.
pub struct BoundedQueue<T> {
    buffer: Mutex<std::collections::VecDeque<T>>,
    capacity: usize,
    not_empty: Condvar,
    not_full: Condvar,
    len: AtomicUsize,
    closed: AtomicBool,
}

impl<T> BoundedQueue<T> {
    /// Create a new bounded queue with the given capacity.
    pub fn new(capacity: usize) -> Self {
        let cap = capacity.max(1);
        Self {
            buffer: Mutex::new(std::collections::VecDeque::with_capacity(cap)),
            capacity: cap,
            not_empty: Condvar::new(),
            not_full: Condvar::new(),
            len: AtomicUsize::new(0),
            closed: AtomicBool::new(false),
        }
    }

    /// Try to push an item, returning `Err(item)` if the queue is full or closed.
    pub fn push(&self, item: T) -> Result<(), T> {
        if self.closed.load(Ordering::Acquire) {
            return Err(item);
        }
        let mut buf = match self.buffer.lock() {
            Ok(b) => b,
            Err(_) => return Err(item),
        };
        if buf.len() >= self.capacity {
            return Err(item);
        }
        buf.push_back(item);
        self.len.fetch_add(1, Ordering::Release);
        self.not_empty.notify_one();
        Ok(())
    }

    /// Push an item, blocking until space is available or the queue is closed.
    pub fn push_blocking(&self, item: T) -> CoreResult<()> {
        self.push_blocking_timeout(item, None)
    }

    /// Push an item with an optional timeout.
    pub fn push_blocking_timeout(&self, mut item: T, timeout: Option<Duration>) -> CoreResult<()> {
        let deadline = timeout.map(|d| std::time::Instant::now() + d);

        loop {
            if self.closed.load(Ordering::Acquire) {
                return Err(CoreError::ComputationError(ErrorContext::new(
                    "queue is closed".to_string(),
                )));
            }

            let mut buf = self.buffer.lock().map_err(|e| {
                CoreError::ComputationError(ErrorContext::new(format!("queue mutex poisoned: {e}")))
            })?;

            if buf.len() < self.capacity {
                buf.push_back(item);
                self.len.fetch_add(1, Ordering::Release);
                self.not_empty.notify_one();
                return Ok(());
            }

            // Wait for space.
            if let Some(dl) = deadline {
                let remaining = dl.saturating_duration_since(std::time::Instant::now());
                if remaining.is_zero() {
                    return Err(CoreError::ComputationError(ErrorContext::new(
                        "push timed out".to_string(),
                    )));
                }
                let (b, timeout_result) =
                    self.not_full.wait_timeout(buf, remaining).map_err(|e| {
                        CoreError::ComputationError(ErrorContext::new(format!(
                            "condvar wait failed: {e}"
                        )))
                    })?;
                drop(b);
                if timeout_result.timed_out() {
                    return Err(CoreError::ComputationError(ErrorContext::new(
                        "push timed out".to_string(),
                    )));
                }
            } else {
                let _b = self.not_full.wait(buf).map_err(|e| {
                    CoreError::ComputationError(ErrorContext::new(format!(
                        "condvar wait failed: {e}"
                    )))
                })?;
            }
        }
    }

    /// Try to pop an item, returning `None` if the queue is empty.
    pub fn pop(&self) -> Option<T> {
        let mut buf = match self.buffer.lock() {
            Ok(b) => b,
            Err(_) => return None,
        };
        let item = buf.pop_front();
        if item.is_some() {
            self.len.fetch_sub(1, Ordering::Release);
            self.not_full.notify_one();
        }
        item
    }

    /// Pop an item, blocking until one is available or the queue is closed.
    pub fn pop_blocking(&self) -> CoreResult<Option<T>> {
        self.pop_blocking_timeout(None)
    }

    /// Pop an item with an optional timeout.
    pub fn pop_blocking_timeout(&self, timeout: Option<Duration>) -> CoreResult<Option<T>> {
        let deadline = timeout.map(|d| std::time::Instant::now() + d);

        loop {
            let mut buf = self.buffer.lock().map_err(|e| {
                CoreError::ComputationError(ErrorContext::new(format!("queue mutex poisoned: {e}")))
            })?;

            if let Some(item) = buf.pop_front() {
                self.len.fetch_sub(1, Ordering::Release);
                self.not_full.notify_one();
                return Ok(Some(item));
            }

            if self.closed.load(Ordering::Acquire) {
                return Ok(None);
            }

            if let Some(dl) = deadline {
                let remaining = dl.saturating_duration_since(std::time::Instant::now());
                if remaining.is_zero() {
                    return Ok(None); // timed out
                }
                let (b, timeout_result) =
                    self.not_empty.wait_timeout(buf, remaining).map_err(|e| {
                        CoreError::ComputationError(ErrorContext::new(format!(
                            "condvar wait failed: {e}"
                        )))
                    })?;
                drop(b);
                if timeout_result.timed_out() {
                    return Ok(None);
                }
            } else {
                let _b = self.not_empty.wait(buf).map_err(|e| {
                    CoreError::ComputationError(ErrorContext::new(format!(
                        "condvar wait failed: {e}"
                    )))
                })?;
            }
        }
    }

    /// Number of items currently in the queue.
    pub fn len(&self) -> usize {
        self.len.load(Ordering::Acquire)
    }

    /// Whether the queue is empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Maximum capacity of the queue.
    pub fn capacity(&self) -> usize {
        self.capacity
    }

    /// Close the queue; no more pushes are accepted.
    ///
    /// Blocked consumers will wake up and receive `None`.
    pub fn close(&self) {
        self.closed.store(true, Ordering::Release);
        self.not_empty.notify_all();
        self.not_full.notify_all();
    }

    /// Whether the queue is closed.
    pub fn is_closed(&self) -> bool {
        self.closed.load(Ordering::Acquire)
    }
}

unsafe impl<T: Send> Send for BoundedQueue<T> {}
unsafe impl<T: Send> Sync for BoundedQueue<T> {}

// ===========================================================================
// ConcurrentAccumulator (for parallel reductions)
// ===========================================================================

/// A concurrent accumulator for parallel reductions.
///
/// Supports atomic `f64` accumulation via sharded slots to reduce contention,
/// plus a generic `T` accumulator that uses a mutex.
pub struct ConcurrentAccumulator<T: Clone> {
    /// Sharded accumulators to reduce contention.
    shards: Vec<Mutex<T>>,
    shard_count: usize,
    /// Combining function: `combine(accumulator, new_value) -> accumulator`.
    combiner: Arc<dyn Fn(T, T) -> T + Send + Sync>,
    /// Identity / zero element for the accumulation.
    identity: T,
    /// Counter for round-robin shard selection.
    counter: AtomicUsize,
}

impl<T: Clone + Send + Sync + 'static> ConcurrentAccumulator<T> {
    /// Create a new accumulator with the given identity element and combiner function.
    ///
    /// `shard_count` controls the number of independent accumulator slots (more = less contention).
    pub fn new<F>(identity: T, combiner: F, shard_count: usize) -> Self
    where
        F: Fn(T, T) -> T + Send + Sync + 'static,
    {
        let sc = shard_count.max(1);
        let shards = (0..sc).map(|_| Mutex::new(identity.clone())).collect();
        Self {
            shards,
            shard_count: sc,
            combiner: Arc::new(combiner),
            identity,
            counter: AtomicUsize::new(0),
        }
    }

    /// Accumulate a value into one of the shards.
    pub fn accumulate(&self, value: T) {
        let idx = self.counter.fetch_add(1, Ordering::Relaxed) % self.shard_count;
        if let Ok(mut shard) = self.shards[idx].lock() {
            let old = shard.clone();
            *shard = (self.combiner)(old, value);
        }
    }

    /// Combine all shards and return the final accumulated value.
    pub fn result(&self) -> T {
        let mut acc = self.identity.clone();
        for shard_mutex in &self.shards {
            if let Ok(shard) = shard_mutex.lock() {
                acc = (self.combiner)(acc, shard.clone());
            }
        }
        acc
    }

    /// Reset all shards to the identity element.
    pub fn reset(&self) {
        for shard_mutex in &self.shards {
            if let Ok(mut shard) = shard_mutex.lock() {
                *shard = self.identity.clone();
            }
        }
        self.counter.store(0, Ordering::Relaxed);
    }
}

unsafe impl<T: Clone + Send> Send for ConcurrentAccumulator<T> {}
unsafe impl<T: Clone + Send + Sync> Sync for ConcurrentAccumulator<T> {}

// ---------------------------------------------------------------------------
// Specialised f64 accumulator using AtomicU64 for lock-free sum
// ---------------------------------------------------------------------------

/// A lock-free accumulator specialised for `f64` summation.
///
/// Uses atomic compare-and-swap on the bits of an `f64` for true lock-free operation.
pub struct AtomicF64Accumulator {
    bits: AtomicU64,
    count: AtomicU64,
}

impl AtomicF64Accumulator {
    /// Create a new accumulator initialised to 0.0.
    pub fn new() -> Self {
        Self {
            bits: AtomicU64::new(0.0_f64.to_bits()),
            count: AtomicU64::new(0),
        }
    }

    /// Atomically add `value` to the accumulator.
    pub fn add(&self, value: f64) {
        loop {
            let current_bits = self.bits.load(Ordering::Acquire);
            let current = f64::from_bits(current_bits);
            let new = current + value;
            let new_bits = new.to_bits();
            if self
                .bits
                .compare_exchange_weak(current_bits, new_bits, Ordering::AcqRel, Ordering::Acquire)
                .is_ok()
            {
                self.count.fetch_add(1, Ordering::Relaxed);
                return;
            }
        }
    }

    /// Read the current accumulated value.
    pub fn value(&self) -> f64 {
        f64::from_bits(self.bits.load(Ordering::Acquire))
    }

    /// Number of values accumulated so far.
    pub fn count(&self) -> u64 {
        self.count.load(Ordering::Acquire)
    }

    /// Reset to 0.0.
    pub fn reset(&self) {
        self.bits.store(0.0_f64.to_bits(), Ordering::Release);
        self.count.store(0, Ordering::Release);
    }
}

impl Default for AtomicF64Accumulator {
    fn default() -> Self {
        Self::new()
    }
}

// ===========================================================================
// WriterPreferenceRwLock
// ===========================================================================

/// A read-write lock that gives priority to writers.
///
/// When a writer is waiting, new readers are blocked until the writer has been serviced.
/// This prevents writer starvation under heavy read load.
pub struct WriterPreferenceRwLock<T> {
    data: std::sync::RwLock<T>,
    /// Number of writers waiting.
    writers_waiting: AtomicUsize,
    /// Gate that readers must pass through; blocked when writers are waiting.
    reader_gate: Mutex<()>,
    reader_gate_cv: Condvar,
}

impl<T> WriterPreferenceRwLock<T> {
    /// Create a new writer-preference RwLock wrapping `data`.
    pub fn new(data: T) -> Self {
        Self {
            data: std::sync::RwLock::new(data),
            writers_waiting: AtomicUsize::new(0),
            reader_gate: Mutex::new(()),
            reader_gate_cv: Condvar::new(),
        }
    }

    /// Acquire a read lock.
    ///
    /// If a writer is waiting, this will block until the writer has been serviced.
    pub fn read(&self) -> CoreResult<ReadGuard<'_, T>> {
        // Wait until no writers are waiting.
        {
            let mut gate = self.reader_gate.lock().map_err(|e| {
                CoreError::ComputationError(ErrorContext::new(format!("gate mutex poisoned: {e}")))
            })?;
            while self.writers_waiting.load(Ordering::Acquire) > 0 {
                gate = self.reader_gate_cv.wait(gate).map_err(|e| {
                    CoreError::ComputationError(ErrorContext::new(format!(
                        "condvar wait failed: {e}"
                    )))
                })?;
            }
        }
        let guard = self.data.read().map_err(|e| {
            CoreError::ComputationError(ErrorContext::new(format!("rwlock poisoned: {e}")))
        })?;
        Ok(ReadGuard { guard })
    }

    /// Acquire a write lock.
    ///
    /// Writers are given priority: once a writer starts waiting,
    /// new readers are blocked until the writer is serviced.
    pub fn write(&self) -> CoreResult<WriteGuard<'_, T>> {
        self.writers_waiting.fetch_add(1, Ordering::Release);
        let guard = self.data.write().map_err(|e| {
            self.writers_waiting.fetch_sub(1, Ordering::Release);
            CoreError::ComputationError(ErrorContext::new(format!("rwlock poisoned: {e}")))
        })?;
        self.writers_waiting.fetch_sub(1, Ordering::Release);
        // Wake blocked readers now that this writer has the lock.
        self.reader_gate_cv.notify_all();
        Ok(WriteGuard { guard })
    }

    /// Try to acquire a read lock without blocking.
    pub fn try_read(&self) -> CoreResult<Option<ReadGuard<'_, T>>> {
        if self.writers_waiting.load(Ordering::Acquire) > 0 {
            return Ok(None);
        }
        match self.data.try_read() {
            Ok(guard) => Ok(Some(ReadGuard { guard })),
            Err(std::sync::TryLockError::WouldBlock) => Ok(None),
            Err(std::sync::TryLockError::Poisoned(e)) => Err(CoreError::ComputationError(
                ErrorContext::new(format!("rwlock poisoned: {e}")),
            )),
        }
    }

    /// Try to acquire a write lock without blocking.
    pub fn try_write(&self) -> CoreResult<Option<WriteGuard<'_, T>>> {
        match self.data.try_write() {
            Ok(guard) => Ok(Some(WriteGuard { guard })),
            Err(std::sync::TryLockError::WouldBlock) => Ok(None),
            Err(std::sync::TryLockError::Poisoned(e)) => Err(CoreError::ComputationError(
                ErrorContext::new(format!("rwlock poisoned: {e}")),
            )),
        }
    }
}

unsafe impl<T: Send> Send for WriterPreferenceRwLock<T> {}
unsafe impl<T: Send + Sync> Sync for WriterPreferenceRwLock<T> {}

/// RAII read guard for [`WriterPreferenceRwLock`].
pub struct ReadGuard<'a, T> {
    guard: std::sync::RwLockReadGuard<'a, T>,
}

impl<T> std::ops::Deref for ReadGuard<'_, T> {
    type Target = T;
    fn deref(&self) -> &T {
        &self.guard
    }
}

/// RAII write guard for [`WriterPreferenceRwLock`].
pub struct WriteGuard<'a, T> {
    guard: std::sync::RwLockWriteGuard<'a, T>,
}

impl<T> std::ops::Deref for WriteGuard<'_, T> {
    type Target = T;
    fn deref(&self) -> &T {
        &self.guard
    }
}

impl<T> std::ops::DerefMut for WriteGuard<'_, T> {
    fn deref_mut(&mut self) -> &mut T {
        &mut self.guard
    }
}

// ===========================================================================
// DoubleBuffer
// ===========================================================================

/// A double-buffered exchange for efficient producer/consumer handoff.
///
/// The producer writes to the "back" buffer while the consumer reads from the
/// "front" buffer.  When the producer is done writing, it swaps the buffers
/// (atomically from the consumer's perspective).
pub struct DoubleBuffer<T> {
    buffers: [Mutex<T>; 2],
    /// 0 or 1 – index of the "front" (consumer) buffer.
    front_index: AtomicUsize,
    /// Signals that a new frame is ready.
    new_frame: Condvar,
    new_frame_mutex: Mutex<bool>,
}

impl<T: Clone> DoubleBuffer<T> {
    /// Create a double buffer with two copies of `initial`.
    pub fn new(initial: T) -> Self {
        Self {
            buffers: [Mutex::new(initial.clone()), Mutex::new(initial)],
            front_index: AtomicUsize::new(0),
            new_frame: Condvar::new(),
            new_frame_mutex: Mutex::new(false),
        }
    }

    /// Read a clone of the current front buffer.
    pub fn read_front(&self) -> CoreResult<T> {
        let idx = self.front_index.load(Ordering::Acquire);
        let guard = self.buffers[idx].lock().map_err(|e| {
            CoreError::ComputationError(ErrorContext::new(format!("buffer mutex poisoned: {e}")))
        })?;
        Ok(guard.clone())
    }

    /// Write to the back buffer via a closure, then swap.
    pub fn write_and_swap<F>(&self, f: F) -> CoreResult<()>
    where
        F: FnOnce(&mut T),
    {
        let front = self.front_index.load(Ordering::Acquire);
        let back = 1 - front;
        {
            let mut guard = self.buffers[back].lock().map_err(|e| {
                CoreError::ComputationError(ErrorContext::new(format!(
                    "buffer mutex poisoned: {e}"
                )))
            })?;
            f(&mut guard);
        }
        // Swap front and back.
        self.front_index.store(back, Ordering::Release);
        // Signal consumers.
        if let Ok(mut flag) = self.new_frame_mutex.lock() {
            *flag = true;
            self.new_frame.notify_all();
        }
        Ok(())
    }

    /// Block until a new frame is available, then read it.
    pub fn wait_and_read(&self, timeout: Duration) -> CoreResult<Option<T>> {
        let mut flag = self.new_frame_mutex.lock().map_err(|e| {
            CoreError::ComputationError(ErrorContext::new(format!("mutex poisoned: {e}")))
        })?;
        if !*flag {
            let (f, timeout_result) = self.new_frame.wait_timeout(flag, timeout).map_err(|e| {
                CoreError::ComputationError(ErrorContext::new(format!("condvar wait failed: {e}")))
            })?;
            flag = f;
            if timeout_result.timed_out() && !*flag {
                return Ok(None);
            }
        }
        *flag = false;
        drop(flag);
        self.read_front().map(Some)
    }

    /// Replace the back buffer entirely, then swap.
    pub fn publish(&self, value: T) -> CoreResult<()> {
        self.write_and_swap(|buf| {
            *buf = value;
        })
    }
}

unsafe impl<T: Send> Send for DoubleBuffer<T> {}
unsafe impl<T: Send + Sync> Sync for DoubleBuffer<T> {}

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

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Arc;
    use std::thread;

    // ----- ConcurrentHashMap -----

    #[test]
    fn test_hashmap_basic() {
        let map: ConcurrentHashMap<String, i32> = ConcurrentHashMap::new();
        assert!(map.is_empty());

        map.insert("a".to_string(), 1);
        map.insert("b".to_string(), 2);
        assert_eq!(map.len(), 2);
        assert_eq!(map.get(&"a".to_string()), Some(1));
        assert_eq!(map.get(&"b".to_string()), Some(2));
        assert_eq!(map.get(&"c".to_string()), None);
    }

    #[test]
    fn test_hashmap_remove() {
        let map: ConcurrentHashMap<String, i32> = ConcurrentHashMap::new();
        map.insert("x".to_string(), 10);
        assert_eq!(map.remove(&"x".to_string()), Some(10));
        assert_eq!(map.len(), 0);
        assert!(map.is_empty());
    }

    #[test]
    fn test_hashmap_concurrent() {
        let map = Arc::new(ConcurrentHashMap::<u64, u64>::new());
        let mut handles = Vec::new();

        for t in 0..8 {
            let m = map.clone();
            handles.push(thread::spawn(move || {
                for i in 0..1000 {
                    let key = t * 1000 + i;
                    m.insert(key, key * 2);
                }
            }));
        }

        for h in handles {
            h.join().expect("thread join");
        }

        assert_eq!(map.len(), 8000);
        assert_eq!(map.get(&0), Some(0));
        assert_eq!(map.get(&7999), Some(7999 * 2));
    }

    #[test]
    fn test_hashmap_get_or_insert_with() {
        let map: ConcurrentHashMap<String, i32> = ConcurrentHashMap::new();
        let v = map.get_or_insert_with("key".to_string(), || 42);
        assert_eq!(v, 42);
        let v2 = map.get_or_insert_with("key".to_string(), || 99);
        assert_eq!(v2, 42); // already inserted
    }

    #[test]
    fn test_hashmap_get_and_modify() {
        let map: ConcurrentHashMap<String, i32> = ConcurrentHashMap::new();
        map.insert("k".to_string(), 10);
        let result = map.get_and_modify(&"k".to_string(), |v| {
            *v += 5;
            *v
        });
        assert_eq!(result, Some(15));
    }

    #[test]
    fn test_hashmap_keys_and_clear() {
        let map: ConcurrentHashMap<u32, u32> = ConcurrentHashMap::new();
        for i in 0..10 {
            map.insert(i, i);
        }
        let keys = map.keys();
        assert_eq!(keys.len(), 10);
        map.clear();
        assert!(map.is_empty());
    }

    #[test]
    fn test_hashmap_contains_key() {
        let map: ConcurrentHashMap<String, i32> = ConcurrentHashMap::new();
        map.insert("hello".into(), 1);
        assert!(map.contains_key(&"hello".to_string()));
        assert!(!map.contains_key(&"world".to_string()));
    }

    // ----- BoundedQueue -----

    #[test]
    fn test_queue_basic() {
        let q: BoundedQueue<i32> = BoundedQueue::new(4);
        assert!(q.is_empty());
        assert_eq!(q.capacity(), 4);

        q.push(1).expect("push 1");
        q.push(2).expect("push 2");
        assert_eq!(q.len(), 2);

        assert_eq!(q.pop(), Some(1));
        assert_eq!(q.pop(), Some(2));
        assert_eq!(q.pop(), None);
    }

    #[test]
    fn test_queue_full() {
        let q: BoundedQueue<i32> = BoundedQueue::new(2);
        q.push(1).expect("push");
        q.push(2).expect("push");
        assert!(q.push(3).is_err()); // full
    }

    #[test]
    fn test_queue_concurrent() {
        let q = Arc::new(BoundedQueue::<u32>::new(1024));
        let mut handles = Vec::new();

        // Producers
        for t in 0..4 {
            let q2 = q.clone();
            handles.push(thread::spawn(move || {
                for i in 0..250 {
                    let val = t * 250 + i;
                    while q2.push(val).is_err() {
                        thread::yield_now();
                    }
                }
            }));
        }

        // Consumer
        let q3 = q.clone();
        let consumer = thread::spawn(move || {
            let mut count = 0u32;
            while count < 1000 {
                if q3.pop().is_some() {
                    count += 1;
                } else {
                    thread::yield_now();
                }
            }
            count
        });

        for h in handles {
            h.join().expect("producer");
        }
        let total = consumer.join().expect("consumer");
        assert_eq!(total, 1000);
    }

    #[test]
    fn test_queue_close() {
        let q: BoundedQueue<i32> = BoundedQueue::new(8);
        q.push(1).expect("push");
        q.close();
        assert!(q.is_closed());
        assert!(q.push(2).is_err()); // closed
        assert_eq!(q.pop(), Some(1)); // can still drain
    }

    // ----- ConcurrentAccumulator -----

    #[test]
    fn test_accumulator_sum() {
        let acc = ConcurrentAccumulator::new(0i64, |a, b| a + b, 4);
        for i in 1..=100 {
            acc.accumulate(i);
        }
        assert_eq!(acc.result(), 5050);
    }

    #[test]
    fn test_accumulator_concurrent() {
        let acc = Arc::new(ConcurrentAccumulator::new(0u64, |a, b| a + b, 8));
        let mut handles = Vec::new();

        for _ in 0..8 {
            let a = acc.clone();
            handles.push(thread::spawn(move || {
                for i in 0..1000u64 {
                    a.accumulate(i);
                }
            }));
        }

        for h in handles {
            h.join().expect("thread");
        }

        // Each thread sums 0..999 = 499500; 8 threads = 3996000
        assert_eq!(acc.result(), 8 * 499500);
    }

    #[test]
    fn test_accumulator_reset() {
        let acc = ConcurrentAccumulator::new(0i32, |a, b| a + b, 4);
        acc.accumulate(10);
        acc.accumulate(20);
        assert_eq!(acc.result(), 30);
        acc.reset();
        assert_eq!(acc.result(), 0);
    }

    // ----- AtomicF64Accumulator -----

    #[test]
    fn test_atomic_f64() {
        let acc = AtomicF64Accumulator::new();
        acc.add(1.0);
        acc.add(2.0);
        acc.add(3.0);
        assert!((acc.value() - 6.0).abs() < 1e-10);
        assert_eq!(acc.count(), 3);
    }

    #[test]
    fn test_atomic_f64_concurrent() {
        let acc = Arc::new(AtomicF64Accumulator::new());
        let mut handles = Vec::new();

        for _ in 0..8 {
            let a = acc.clone();
            handles.push(thread::spawn(move || {
                for _ in 0..10000 {
                    a.add(1.0);
                }
            }));
        }
        for h in handles {
            h.join().expect("thread");
        }
        assert!((acc.value() - 80000.0).abs() < 1.0);
        assert_eq!(acc.count(), 80000);
    }

    #[test]
    fn test_atomic_f64_reset() {
        let acc = AtomicF64Accumulator::new();
        acc.add(42.0);
        acc.reset();
        assert!((acc.value()).abs() < 1e-15);
        assert_eq!(acc.count(), 0);
    }

    // ----- WriterPreferenceRwLock -----

    #[test]
    fn test_rwlock_basic() {
        let lock = WriterPreferenceRwLock::new(42);
        {
            let r = lock.read().expect("read");
            assert_eq!(*r, 42);
        }
        {
            let mut w = lock.write().expect("write");
            *w = 99;
        }
        {
            let r = lock.read().expect("read");
            assert_eq!(*r, 99);
        }
    }

    #[test]
    fn test_rwlock_concurrent_readers() {
        let lock = Arc::new(WriterPreferenceRwLock::new(vec![1, 2, 3]));
        let mut handles = Vec::new();

        for _ in 0..8 {
            let l = lock.clone();
            handles.push(thread::spawn(move || {
                for _ in 0..100 {
                    let r = l.read().expect("read");
                    assert!(!r.is_empty());
                }
            }));
        }

        for h in handles {
            h.join().expect("thread");
        }
    }

    #[test]
    fn test_rwlock_try_read_write() {
        let lock = WriterPreferenceRwLock::new(0);
        let r = lock.try_read().expect("try_read");
        assert!(r.is_some());
        drop(r);

        let w = lock.try_write().expect("try_write");
        assert!(w.is_some());
    }

    // ----- DoubleBuffer -----

    #[test]
    fn test_double_buffer_basic() {
        let db = DoubleBuffer::new(0i32);
        assert_eq!(db.read_front().expect("read"), 0);

        db.publish(42).expect("publish");
        assert_eq!(db.read_front().expect("read"), 42);
    }

    #[test]
    fn test_double_buffer_write_and_swap() {
        let db = DoubleBuffer::new(vec![0u8; 4]);
        db.write_and_swap(|buf| {
            buf[0] = 1;
            buf[1] = 2;
        })
        .expect("write");
        let front = db.read_front().expect("read");
        assert_eq!(front[0], 1);
        assert_eq!(front[1], 2);
    }

    #[test]
    fn test_double_buffer_wait_timeout() {
        let db = Arc::new(DoubleBuffer::new(0));
        let db2 = db.clone();

        let producer = thread::spawn(move || {
            thread::sleep(Duration::from_millis(50));
            db2.publish(99).expect("publish");
        });

        let result = db.wait_and_read(Duration::from_secs(2)).expect("wait");
        assert_eq!(result, Some(99));
        producer.join().expect("producer");
    }

    #[test]
    fn test_double_buffer_concurrent() {
        let db = Arc::new(DoubleBuffer::new(0u64));
        let db_w = db.clone();

        let writer = thread::spawn(move || {
            for i in 1..=100u64 {
                db_w.publish(i).expect("publish");
            }
        });

        // Reader should always see valid (non-torn) values.
        let db_r = db.clone();
        let reader = thread::spawn(move || {
            let mut max_seen = 0u64;
            for _ in 0..200 {
                let v = db_r.read_front().expect("read");
                if v > max_seen {
                    max_seen = v;
                }
                thread::yield_now();
            }
            max_seen
        });

        writer.join().expect("writer");
        let max_seen = reader.join().expect("reader");
        assert!(max_seen > 0);
    }
}

// ---------------------------------------------------------------------------
// Lock-free data structure submodules
// ---------------------------------------------------------------------------

pub mod compressed_trie;
pub mod persistent_vector;
pub mod queue;
pub mod skip_list;
pub mod stack;

pub use compressed_trie::CompressedTrie;
pub use persistent_vector::PersistentRrbVec;
pub use queue::LockFreeQueue;
pub use skip_list::SkipList;
pub use stack::LockFreeStack;

// ---------------------------------------------------------------------------
// Advanced concurrency submodules
// ---------------------------------------------------------------------------

pub mod async_utils;
pub mod barrier;
pub mod parallel_iter;
pub mod work_stealing;
pub use async_utils as concurrent_async;

pub use barrier::{CountDownLatch, CyclicBarrier, PhaseBarrier, SpinBarrier};
pub use concurrent_async::{
    BackoffStrategy, FutureExecutor, JoinFuture, RetryPolicy, Semaphore, SemaphoreGuard,
    TokenBucketRateLimiter,
};
pub use parallel_iter::{
    parallel_filter, parallel_for_each, parallel_map, parallel_merge_sort, parallel_partition,
    parallel_prefix_sum, parallel_reduce, parallel_scan, ScanMode,
};
pub use work_stealing::{
    Priority, PriorityTaskQueue, SchedulerConfig, SchedulerStats, StealResult, WorkStealingDeque,
    WorkStealingScheduler,
};