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
use super::*;
impl<K, V> ShardedHashMap<K, V, FxBuildHasher>
where
K: Eq + Hash + Clone + Send + Sync,
V: Clone + Send + Sync,
{
/// Create with default hasher (`FxBuildHasher`).
#[tracing::instrument(level = "trace")]
pub fn new(shard_count: usize) -> Self {
Self::with_shards_and_hasher(shard_count, FxBuildHasher)
}
}
impl<K, V, S> ShardedHashMap<K, V, S>
where
K: Eq + Hash + Clone + Send + Sync,
V: Clone + Send + Sync,
S: BuildHasher + Clone + Send + Sync,
{
#[inline]
fn build_with_count(count: usize, hasher: S) -> Self {
let shards = vec![None; count];
Self {
shards: Arc::new(StdRwLock::new(shards)),
hasher,
shard_count: count,
total_len: Arc::new(AtomicUsize::new(0)),
#[cfg(feature = "advanced")]
version: Arc::new(AtomicUsize::new(0)),
#[cfg(feature = "advanced")]
profiling_enabled: Arc::new(std::sync::atomic::AtomicBool::new(false)),
}
}
/// Create with explicit hasher.
///
/// This preserves backward compatibility while enforcing the default
/// safety cap (`MAX_SHARDS`) to avoid oversized allocations.
#[tracing::instrument(skip(hasher), level = "trace")]
pub fn with_shards_and_hasher(shard_count: usize, hasher: S) -> Self {
let requested = normalized_shard_count(shard_count);
let count = capped_shard_count(requested, MAX_SHARDS);
if requested != count {
tracing::warn!(
requested_shards = requested,
capped_shards = count,
max_shards = MAX_SHARDS,
"requested shard_count exceeded default cap and was clamped"
);
}
Self::build_with_count(count, hasher)
}
/// Create with explicit hasher and a custom cap.
///
/// This is useful when callers need to tune the shard upper bound for
/// workload-specific memory/performance trade-offs.
#[tracing::instrument(skip(hasher), level = "trace")]
pub fn with_shards_and_hasher_capped(shard_count: usize, hasher: S, max_shards: usize) -> Self {
let effective_max = max_shards.max(1);
let requested = normalized_shard_count(shard_count);
let count = capped_shard_count(requested, effective_max);
if requested != count {
tracing::warn!(
requested_shards = requested,
capped_shards = count,
max_shards = effective_max,
"requested shard_count exceeded configured cap and was clamped"
);
}
Self::build_with_count(count, hasher)
}
/// Strict constructor with explicit hasher.
///
/// Returns an error when the requested shard count exceeds `MAX_SHARDS`.
#[tracing::instrument(skip(hasher), level = "trace")]
pub fn try_with_shards_and_hasher(
shard_count: usize,
hasher: S,
) -> Result<Self, ShardCountError> {
Self::try_with_shards_and_hasher_capped(shard_count, hasher, MAX_SHARDS)
}
/// Strict constructor with explicit hasher and a caller-provided cap.
///
/// Returns an error instead of clamping when the effective shard count is
/// out of range.
#[tracing::instrument(skip(hasher), level = "trace")]
pub fn try_with_shards_and_hasher_capped(
shard_count: usize,
hasher: S,
max_shards: usize,
) -> Result<Self, ShardCountError> {
let effective_max = max_shards.max(1);
let count = strict_shard_count(shard_count, effective_max)?;
Ok(Self::build_with_count(count, hasher))
}
/// Current configured shard slots.
#[tracing::instrument(skip(self), level = "trace")]
pub fn shard_count(&self) -> usize {
self.shard_count
}
/// Number of shards actually initialized (allocated).
#[tracing::instrument(skip(self), level = "trace")]
pub fn initialized_shards(&self) -> usize {
let g = std_read_guard(&self.shards, "shards");
g.iter().filter(|o| o.is_some()).count()
}
#[inline]
#[tracing::instrument(skip(self, key), level = "trace")]
fn shard_index(&self, key: &K) -> usize {
(self.hasher.hash_one(key) % self.shard_count as u64) as usize
}
#[inline]
#[tracing::instrument(skip(self), level = "trace")]
fn get_or_init_shard(&self, index: usize) -> StdShard<K, V, S> {
let mut g = std_write_guard(&self.shards, "shards");
if g[index].is_none() {
let map = StdShardMap::with_hasher(self.hasher.clone());
g[index] = Some(Arc::new(StdRwLock::new(map)));
}
if let Some(shard) = g[index].as_ref() {
shard.clone()
} else {
tracing::error!(
shard_index = index,
"shard slot still uninitialized; creating fallback shard"
);
let map = StdShardMap::with_hasher(self.hasher.clone());
let shard = Arc::new(StdRwLock::new(map));
g[index] = Some(shard.clone());
shard
}
}
#[inline]
fn bucketize_entries<I>(&self, entries: I) -> HashMap<usize, Vec<(K, V)>, FxBuildHasher>
where
I: IntoIterator<Item = (K, V)>,
{
let iter = entries.into_iter();
let estimated = iter.size_hint().0.min(self.shard_count);
let mut buckets: HashMap<usize, Vec<(K, V)>, FxBuildHasher> =
HashMap::with_capacity_and_hasher(estimated, FxBuildHasher);
for (k, v) in iter {
let shard_idx = self.shard_index(&k);
buckets.entry(shard_idx).or_default().push((k, v));
}
buckets
}
#[inline]
fn bucketize_keys<I>(&self, keys: I) -> HashMap<usize, Vec<K>, FxBuildHasher>
where
I: IntoIterator<Item = K>,
{
let iter = keys.into_iter();
let estimated = iter.size_hint().0.min(self.shard_count);
let mut buckets: HashMap<usize, Vec<K>, FxBuildHasher> =
HashMap::with_capacity_and_hasher(estimated, FxBuildHasher);
for k in iter {
let shard_idx = self.shard_index(&k);
buckets.entry(shard_idx).or_default().push(k);
}
buckets
}
#[inline]
fn bucketize_key_refs<'a>(
&self,
keys: &'a [K],
) -> HashMap<usize, Vec<(usize, &'a K)>, FxBuildHasher> {
let estimated = keys.len().min(self.shard_count);
let mut buckets: HashMap<usize, Vec<(usize, &'a K)>, FxBuildHasher> =
HashMap::with_capacity_and_hasher(estimated, FxBuildHasher);
for (idx, key) in keys.iter().enumerate() {
let shard_idx = self.shard_index(key);
buckets.entry(shard_idx).or_default().push((idx, key));
}
buckets
}
/// Insert key/value. Returns previous value if existed.
///
/// Complexity: O(1) expected.
///
/// If the key was not present, increments length counter.
///
/// # Arguments
/// - `key`: key to insert.
/// - `value`: value to associate with the key
///
/// # Returns
/// - `Option<V>`: previous value if the key was already present.
///
#[tracing::instrument(skip(self, key, value), level = "trace")]
pub fn insert(&self, key: K, value: V) -> Option<V> {
let shard = self.get_or_init_shard(self.shard_index(&key));
let mut guard: StdWriteGuard<'_, HashMap<K, V, S>> = std_write_guard(&shard, "shard");
let old = guard.insert(key, value);
if old.is_none() {
self.total_len.fetch_add(1, Ordering::Relaxed);
}
old
}
/// Fetch cloned value.
///
/// # Arguments
/// - `key`: key to look up.
///
/// # Returns
/// - `Option<V>`: cloned value if the key exists.
///
#[tracing::instrument(skip(self, key), level = "trace")]
pub fn get(&self, key: &K) -> Option<V> {
let shard = self.get_or_init_shard(self.shard_index(key));
let guard: StdReadGuard<'_, HashMap<K, V, S>> = std_read_guard(&shard, "shard");
guard.get(key).cloned()
}
/// Check if a key exists (returns bool without cloning the value).
///
/// # Arguments
/// - `key`: key to check.
///
/// # Returns
/// - `bool`: true if the key exists in the map, false otherwise.
///
#[tracing::instrument(skip(self, key), level = "trace")]
pub fn contains(&self, key: &K) -> bool {
let shard = self.get_or_init_shard(self.shard_index(key));
let guard: StdReadGuard<'_, HashMap<K, V, S>> = std_read_guard(&shard, "shard");
guard.contains_key(key)
}
/// Remove key, returning previous value.
///
/// # Arguments
/// - `key`: key to remove.
///
/// # Returns
/// - `Option<V>`: previous value if the key existed.
///
#[tracing::instrument(skip(self, key), level = "trace")]
pub fn remove(&self, key: &K) -> Option<V> {
let shard = self.get_or_init_shard(self.shard_index(key));
let mut guard: StdWriteGuard<'_, HashMap<K, V, S>> = std_write_guard(&shard, "shard");
let old = guard.remove(key);
if old.is_some() {
self.total_len.fetch_sub(1, Ordering::Relaxed);
}
old
}
/// Length (cached atomic).
///
/// # Returns
/// - `usize`: total number of key/value pairs in the map.
///
#[inline]
#[tracing::instrument(skip(self), level = "trace")]
pub fn len(&self) -> usize {
self.total_len.load(Ordering::Relaxed)
}
/// Check if map is empty.
///
/// # Returns
/// - `bool`: true if length is zero, false otherwise.
///
#[inline]
#[tracing::instrument(skip(self), level = "trace")]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Clear all data (retains shard allocations).
///
/// # Notes
/// - Resets length counter to zero.
///
#[tracing::instrument(skip(self), level = "trace")]
pub fn clear(&self) {
let slots = std_read_guard(&self.shards, "shards");
for shard in slots.iter().flatten() {
let mut g = std_write_guard(shard, "shard");
g.clear();
}
self.total_len.store(0, Ordering::Relaxed);
}
/// Snapshot iteration over (K,V) clones.
///
/// Semantics:
/// - Collects a list of initialized shard Arcs first (short critical section).
/// - Each shard is read-locked independently; values cloned.
/// - Not a live iterator: modifications after a shard snapshot are not reflected.
/// - If `rayon` enabled, internal flattening per-shard happens in parallel for speed.
///
/// Cost:
/// - O(N) cloning cost for visited entries.
/// - Temporary Vec allocations proportional to initialized shard count (and item copies).
///
/// # Returns
/// - `impl Iterator<Item = (K, V)>`: iterator over cloned key/value pairs.
///
#[tracing::instrument(skip(self), level = "trace")]
pub fn iter(&self) -> impl Iterator<Item = (K, V)> {
let shards_snapshot: Vec<StdShard<K, V, S>> = {
let g = std_read_guard(&self.shards, "shards");
g.iter().filter_map(|o| o.as_ref().cloned()).collect()
};
#[cfg(feature = "rayon")]
{
let items: Vec<(K, V)> = shards_snapshot
.par_iter()
.flat_map(|shard| {
let guard = std_read_guard(shard, "shard");
guard
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect::<Vec<_>>()
})
.collect();
items.into_iter()
}
#[cfg(not(feature = "rayon"))]
{
let mut items = Vec::new();
for shard in shards_snapshot {
let guard = std_read_guard(&shard, "shard");
items.extend(guard.iter().map(|(k, v)| (k.clone(), v.clone())));
}
return items.into_iter();
}
}
/// Batch insert multiple key-value pairs.
///
/// # Arguments
/// - `entries`: iterator of (K, V) pairs
///
/// # Returns
/// - `usize`: number of new entries inserted
///
#[tracing::instrument(skip(self, entries), level = "trace")]
pub fn batch_insert<I>(&self, entries: I) -> usize
where
I: IntoIterator<Item = (K, V)>,
{
let buckets = self.bucketize_entries(entries);
let mut count = 0;
for (shard_idx, pairs) in buckets {
let shard = self.get_or_init_shard(shard_idx);
let mut guard = std_write_guard(&shard, "shard");
for (k, v) in pairs {
if guard.insert(k, v).is_none() {
count += 1;
}
}
}
if count > 0 {
self.total_len.fetch_add(count, Ordering::Relaxed);
}
count
}
/// Batch remove multiple keys.
///
/// # Arguments
/// - `keys`: iterator of keys to remove
///
/// # Returns
/// - `usize`: number of entries actually removed
///
#[tracing::instrument(skip(self, keys), level = "trace")]
pub fn batch_remove<I>(&self, keys: I) -> usize
where
I: IntoIterator<Item = K>,
{
let buckets = self.bucketize_keys(keys);
let mut count = 0;
for (shard_idx, keys) in buckets {
let shard = self.get_or_init_shard(shard_idx);
let mut guard = std_write_guard(&shard, "shard");
for k in keys {
if guard.remove(&k).is_some() {
count += 1;
}
}
}
if count > 0 {
self.total_len.fetch_sub(count, Ordering::Relaxed);
}
count
}
/// Batch get multiple keys.
///
/// # Arguments
/// - `keys`: slice of keys to fetch
///
/// # Returns
/// - `Vec<Option<V>>`: results in same order as keys
///
#[tracing::instrument(skip(self, keys), level = "trace")]
pub fn batch_get(&self, keys: &[K]) -> Vec<Option<V>> {
let mut results = vec![None; keys.len()];
let buckets = self.bucketize_key_refs(keys);
for (shard_idx, items) in buckets {
let shard = self.get_or_init_shard(shard_idx);
let guard = std_read_guard(&shard, "shard");
for (idx, key) in items {
if let Some(val) = guard.get(key) {
results[idx] = Some(val.clone());
}
}
}
results
}
/// Update entry if it exists, or remove it if the function returns None.
///
/// # Arguments
/// - `key`: key to check.
/// - `f`: function that takes the current value and returns `Some(new_value)` to update or `None` to remove.
///
/// # Returns
/// - `Option<V>`: the new value if the key existed and was updated, `None` otherwise.
///
#[tracing::instrument(skip(self, key, f), level = "trace")]
pub fn compute_if_present<F>(&self, key: &K, f: F) -> Option<V>
where
F: FnOnce(&V) -> Option<V>,
{
let shard = self.get_or_init_shard(self.shard_index(key));
let mut guard = std_write_guard(&shard, "shard");
if let Some(old_val) = guard.get(key) {
if let Some(new_val) = f(old_val) {
let result = new_val.clone();
guard.insert(key.clone(), new_val);
Some(result)
} else {
// Remove the entry
guard.remove(key);
self.total_len.fetch_sub(1, Ordering::Relaxed);
None
}
} else {
None
}
}
/// Insert value if key is absent, or return existing value.
///
/// # Arguments
/// - `key`: key to check/insert.
/// - `f`: function that returns the value to insert if the key is absent.
///
/// # Returns
/// - `V`: existing or newly inserted value.
///
#[tracing::instrument(skip(self, key, f), level = "trace")]
pub fn compute_if_absent<F>(&self, key: K, f: F) -> V
where
F: FnOnce() -> V,
{
let shard = self.get_or_init_shard(self.shard_index(&key));
let mut guard = std_write_guard(&shard, "shard");
if let Some(val) = guard.get(&key) {
val.clone()
} else {
let new_v = f();
guard.insert(key, new_v.clone());
self.total_len.fetch_add(1, Ordering::Relaxed);
new_v
}
}
/// Remove entries where predicate returns false.
///
/// Locks each shard independently to maximize parallelism.
///
/// # Arguments
/// - `predicate`: function that returns true to keep, false to remove
///
#[tracing::instrument(skip(self, predicate), level = "trace")]
pub fn retain<F>(&self, predicate: F)
where
F: Fn(&K, &V) -> bool + Sync + Send,
{
let shards_snapshot: Vec<StdShard<K, V, S>> = {
let g = std_read_guard(&self.shards, "shards");
g.iter().filter_map(|o| o.as_ref().cloned()).collect()
};
#[cfg(feature = "rayon")]
{
let removed_count: usize = shards_snapshot
.par_iter()
.map(|shard| {
let mut guard = std_write_guard(shard, "shard");
let initial_len = guard.len();
guard.retain(|k, v| predicate(k, v));
initial_len - guard.len()
})
.sum();
if removed_count > 0 {
self.total_len.fetch_sub(removed_count, Ordering::Relaxed);
}
}
#[cfg(not(feature = "rayon"))]
{
for shard in shards_snapshot {
let mut guard = std_write_guard(&shard, "shard");
let removed_count = guard.len();
guard.retain(|k, v| predicate(k, v));
let removed = removed_count - guard.len();
if removed > 0 {
self.total_len.fetch_sub(removed, Ordering::Relaxed);
}
}
}
}
/// Execute a transaction (basic implementation).
///
/// This method executes a transaction by acquiring locks on all involved shards
/// in a deterministic order to avoid deadlocks.
///
/// # Arguments
/// - `txn`: The transaction to execute.
///
/// # Returns
/// - `TransactionResult<()>`: The result of the transaction.
#[cfg(feature = "advanced")]
#[tracing::instrument(skip(self, txn), level = "trace")]
pub fn execute_transaction(&self, txn: Transaction<K, V>) -> TransactionResult<()> {
// 1. Identify involved shards
let mut shard_indices: Vec<usize> = txn
.ops
.iter()
.map(|op| match op {
TxnOp::Read(k) => self.shard_index(k),
TxnOp::Write(k, _) => self.shard_index(k),
TxnOp::Remove(k) => self.shard_index(k),
})
.collect();
// 2. Sort and deduplicate to prevent deadlocks
shard_indices.sort_unstable();
shard_indices.dedup();
// 3. Acquire locks (pessimistic locking: acquire all write locks)
// Note: In a real MVCC system, we might acquire read locks for reads,
// but for simplicity and correctness here, we use write locks for everything
// to ensure isolation during the transaction execution.
let shards: Vec<_> = shard_indices
.iter()
.map(|&idx| self.get_or_init_shard(idx))
.collect();
let mut guards = Vec::with_capacity(shards.len());
for shard in &shards {
// We must use write locks because we might modify the shards.
// Even for read-only ops in a mixed transaction, we need consistent view.
let guard = std_write_guard(shard, "transaction shard");
guards.push(guard);
}
// 4. Execute operations
// We need to map shard index back to the correct guard.
// Since guards are stored in the same order as sorted shard_indices,
// we can use binary search to find the index.
for op in txn.ops {
match op {
TxnOp::Read(k) => {
let idx = self.shard_index(&k);
let guard_idx = match shard_indices.binary_search(&idx) {
Ok(i) => i,
Err(_) => {
tracing::error!(
shard_index = idx,
"shard index missing in transaction"
);
return TransactionResult::Aborted;
}
};
let guard = &guards[guard_idx];
// Just checking existence/value for now.
// In a real txn, we might return values.
// Here we just ensure it runs.
let _ = guard.get(&k);
}
TxnOp::Write(k, v) => {
let idx = self.shard_index(&k);
let guard_idx = match shard_indices.binary_search(&idx) {
Ok(i) => i,
Err(_) => {
tracing::error!(
shard_index = idx,
"shard index missing in transaction"
);
return TransactionResult::Aborted;
}
};
let guard = &mut guards[guard_idx];
if guard.insert(k, v).is_none() {
self.total_len.fetch_add(1, Ordering::Relaxed);
}
}
TxnOp::Remove(k) => {
let idx = self.shard_index(&k);
let guard_idx = match shard_indices.binary_search(&idx) {
Ok(i) => i,
Err(_) => {
tracing::error!(
shard_index = idx,
"shard index missing in transaction"
);
return TransactionResult::Aborted;
}
};
let guard = &mut guards[guard_idx];
if guard.remove(&k).is_some() {
self.total_len.fetch_sub(1, Ordering::Relaxed);
}
}
}
}
TransactionResult::Committed(())
}
/// Compare and swap: atomically replace value if it matches expected.
///
/// # Arguments
/// - `key`: The key to update.
/// - `expected`: The expected current value.
/// - `new`: The new value to swap in.
///
/// # Returns
/// - `CasResult<V>`: Success with new value, or Failure with current value.
#[cfg(feature = "advanced")]
#[tracing::instrument(skip(self, key, expected, new), level = "trace")]
pub fn compare_and_swap(&self, key: &K, expected: &V, new: V) -> CasResult<V>
where
V: PartialEq,
{
let shard = self.get_or_init_shard(self.shard_index(key));
let mut guard = std_write_guard(&shard, "cas");
match guard.get(key) {
Some(current) if current == expected => {
guard.insert(key.clone(), new.clone());
CasResult::Success(new)
}
Some(current) => CasResult::Failure(current.clone()),
None => CasResult::Failure(new),
}
}
/// Compare and remove: atomically remove entry if value matches expected.
///
/// # Arguments
/// - `key`: The key to remove.
/// - `expected`: The expected current value.
///
/// # Returns
/// - `bool`: true if removed, false if value didn't match or key not found.
#[cfg(feature = "advanced")]
#[tracing::instrument(skip(self, key, expected), level = "trace")]
pub fn compare_and_remove(&self, key: &K, expected: &V) -> bool
where
V: PartialEq,
{
let shard = self.get_or_init_shard(self.shard_index(key));
let mut guard = std_write_guard(&shard, "cas_remove");
match guard.get(key) {
Some(current) if current == expected => {
guard.remove(key);
self.total_len.fetch_sub(1, Ordering::Relaxed);
true
}
_ => false,
}
}
/// Create a copy-on-write snapshot for minimal-locking reads.
///
/// # Returns
/// - `CowSnapshot<K, V>`: Immutable snapshot of current state.
#[cfg(feature = "advanced")]
#[tracing::instrument(skip(self), level = "trace")]
pub fn cow_snapshot(&self) -> CowSnapshot<K, V> {
let data = self.iter().collect();
let version = self.version.load(Ordering::SeqCst) as u64;
CowSnapshot::new(data, version)
}
/// Create a versioned snapshot for time-travel queries.
///
/// # Returns
/// - `IsolatedSnapshot<K, V>`: Snapshot with version information.
#[cfg(feature = "advanced")]
#[tracing::instrument(skip(self), level = "trace")]
pub fn versioned_snapshot(&self) -> IsolatedSnapshot<K, V> {
let data = self.iter().collect();
let version = self.version.fetch_add(1, Ordering::SeqCst) as u64;
IsolatedSnapshot::new(version, data)
}
/// Create a snapshot at a specific version (if available).
///
/// # Arguments
/// - `version`: The version number to snapshot at.
///
/// # Returns
/// - `Option<IsolatedSnapshot<K, V>>`: Snapshot if version is current, None otherwise.
#[cfg(feature = "advanced")]
#[tracing::instrument(skip(self), level = "trace")]
pub fn snapshot_at_version(&self, version: u64) -> Option<IsolatedSnapshot<K, V>> {
let current_version = self.version.load(Ordering::SeqCst) as u64;
if version == current_version {
let data = self.iter().collect();
Some(IsolatedSnapshot::new(version, data))
} else {
None
}
}
/// Get lock profiling data for all shards.
///
/// # Returns
/// - `Vec<LockProfile>`: Per-shard lock statistics.
#[cfg(feature = "advanced")]
#[tracing::instrument(skip(self), level = "trace")]
pub fn lock_profiles(&self) -> Vec<LockProfile> {
let profiling_enabled = self.profiling_enabled.load(Ordering::Relaxed);
if !profiling_enabled {
return Vec::new();
}
let slots = std_read_guard(&self.shards, "lock_profiles");
let mut profiles = Vec::new();
for (idx, slot) in slots.iter().enumerate() {
if let Some(_shard) = slot {
// In a real implementation, we'd track lock stats per shard
// For now, return basic profile structure
profiles.push(LockProfile {
shard_id: idx,
contention_count: 0,
avg_wait_time_ns: 0,
max_wait_time_ns: 0,
reads: 0,
writes: 0,
});
}
}
profiles
}
/// Enable or disable lock profiling.
///
/// # Arguments
/// - `enabled`: Whether to enable profiling.
#[cfg(feature = "advanced")]
#[tracing::instrument(skip(self), level = "trace")]
pub fn enable_profiling(&self, enabled: bool) {
self.profiling_enabled.store(enabled, Ordering::Relaxed);
}
/// Iterate over all keys (snapshot-based).
///
/// # Returns
/// - `Vec<K>`: vector of cloned keys
///
#[tracing::instrument(skip(self), level = "trace")]
pub fn keys(&self) -> impl Iterator<Item = K> {
self.iter().map(|(k, _)| k)
}
/// Iterate over all values (snapshot-based).
///
/// # Returns
/// - `Vec<V>`: vector of cloned values
///
#[tracing::instrument(skip(self), level = "trace")]
pub fn values(&self) -> impl Iterator<Item = V> {
self.iter().map(|(_, v)| v)
}
/// Returns statistics about shard distribution and utilization.
///
/// # Returns
/// - `ShardStats`: structure containing shard metrics
///
#[tracing::instrument(skip(self), level = "trace")]
pub fn shard_stats(&self) -> ShardStats {
let slots = std_read_guard(&self.shards, "shards");
let mut initialized = 0;
let mut loads = Vec::new();
for shard in slots.iter().flatten() {
initialized += 1;
let guard = std_read_guard(shard, "shard");
loads.push(guard.len());
}
let total = slots.len();
let empty = loads.iter().filter(|&&l| l == 0).count();
let max_load = loads.iter().max().copied().unwrap_or(0);
let avg_load = if initialized > 0 {
loads.iter().sum::<usize>() as f64 / initialized as f64
} else {
0.0
};
ShardStats {
initialized,
total,
empty,
avg_load,
max_load,
}
}
/// Returns shard utilization as a percentage (0-100).
///
/// # Returns
/// - `f64`: percentage of shards that have been initialized
///
#[tracing::instrument(skip(self), level = "trace")]
pub fn shard_utilization(&self) -> f64 {
let stats = self.shard_stats();
stats.utilization_percent()
}
/// Returns load statistics for each initialized shard.
#[cfg(feature = "lifecycle")]
#[tracing::instrument(skip(self), level = "trace")]
pub fn per_shard_load(&self) -> Vec<PerShardLoad> {
let slots = std_read_guard(&self.shards, "shards");
let mut stats = Vec::new();
for (i, shard_opt) in slots.iter().enumerate() {
if let Some(shard) = shard_opt {
let guard = std_read_guard(shard, "shard");
stats.push(PerShardLoad {
shard_idx: i,
entry_count: guard.len(),
capacity: guard.capacity(),
});
}
}
stats
}
/// Returns current memory-oriented shard statistics.
#[cfg(feature = "lifecycle")]
#[tracing::instrument(skip(self), level = "trace")]
pub fn memory_stats(&self) -> MemoryStats {
let slots = std_read_guard(&self.shards, "shards");
let mut shards_allocated = 0;
let mut total_capacity = 0usize;
let mut total_entries = 0usize;
for shard in slots.iter().flatten() {
shards_allocated += 1;
let guard = std_read_guard(shard, "shard");
total_capacity += guard.capacity();
total_entries += guard.len();
}
let load_factor = if total_capacity > 0 {
total_entries as f64 / total_capacity as f64
} else {
0.0
};
MemoryStats {
shards_allocated,
total_capacity,
load_factor,
}
}
/// Drains all entries from the map and returns them as an iterator.
///
/// Shard allocations are retained.
#[cfg(feature = "lifecycle")]
#[tracing::instrument(skip(self), level = "trace")]
pub fn drain(&self) -> DrainIterator<K, V> {
let slots = std_read_guard(&self.shards, "shards");
let mut items = Vec::new();
for shard in slots.iter().flatten() {
let mut guard = std_write_guard(shard, "shard");
items.extend(guard.drain());
}
self.total_len.store(0, Ordering::Relaxed);
DrainIterator { items, index: 0 }
}
}