cachekit 0.6.0

High-performance cache primitives with pluggable eviction policies (LRU, LFU, FIFO, 2Q, Clock-PRO, S3-FIFO) and optional metrics.
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
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
//! HashMap-backed store implementations.
//!
//! Provides three store variants optimized for different concurrency needs:
//! single-threaded with zero-overhead access, global-lock concurrent, and
//! sharded concurrent for high-contention workloads.
//!
//! ## Architecture
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────────────────┐
//! │                        HashMap Store Variants                               │
//! │                                                                             │
//! │  ┌──────────────────────────────────────────────────────────────────────┐   │
//! │  │                     HashMapStore (single-threaded)                   │   │
//! │  │                                                                      │   │
//! │  │   ┌──────────────┐      get(&K) -> &V                                │   │
//! │  │   │ HashMap<K,V> │      (zero-copy, no Arc)                          │   │
//! │  │   └──────────────┘                                                   │   │
//! │  │         │                                                            │   │
//! │  │         └── Direct ownership, best for single-threaded hot paths     │   │
//! │  └──────────────────────────────────────────────────────────────────────┘   │
//! │                                                                             │
//! │  ┌──────────────────────────────────────────────────────────────────────┐   │
//! │  │                 ConcurrentHashMapStore (global lock)                 │   │
//! │  │                                                                      │   │
//! │  │   ┌─────────────────────────┐     get(&K) -> Arc<V>                  │   │
//! │  │   │ RwLock<HashMap<K,Arc<V>>│     (clone Arc, releases lock)         │   │
//! │  │   └─────────────────────────┘                                        │   │
//! │  │         │                                                            │   │
//! │  │         └── Simple concurrency, moderate contention OK               │   │
//! │  └──────────────────────────────────────────────────────────────────────┘   │
//! │                                                                             │
//! │  ┌──────────────────────────────────────────────────────────────────────┐   │
//! │  │                  ShardedHashMapStore (per-shard locks)               │   │
//! │  │                                                                      │   │
//! │  │   key ──► hash(key) % N ──► shard[i]                                 │   │
//! │  │                                                                      │   │
//! │  │   ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐                        │   │
//! │  │   │Shard 0 │ │Shard 1 │ │Shard 2 │ │Shard N │                        │   │
//! │  │   │RwLock  │ │RwLock  │ │RwLock  │ │RwLock  │                        │   │
//! │  │   │HashMap │ │HashMap │ │HashMap │ │HashMap │                        │   │
//! │  │   └────────┘ └────────┘ └────────┘ └────────┘                        │   │
//! │  │         │                                                            │   │
//! │  │         └── High concurrency, independent shard access               │   │
//! │  └──────────────────────────────────────────────────────────────────────┘   │
//! └─────────────────────────────────────────────────────────────────────────────┘
//!
//! Trait Implementations
//! ─────────────────────
//!
//!   HashMapStore<K, V, S>
//!     ├── StoreCore<K, V>      read ops, returns &V
//!     ├── StoreMut<K, V>       write ops, owned V
//!     └── StoreFactory<K, V>   factory (default hasher only)
//!
//!   ConcurrentHashMapStore<K, V, S>
//!     ├── ConcurrentStoreRead<K, V>     read ops, returns Arc<V>
//!     ├── ConcurrentStore<K, V>         write ops, Arc<V>
//!     └── ConcurrentStoreFactory<K, V>  factory (default hasher only)
//!
//!   ShardedHashMapStore<K, V, S>
//!     ├── ConcurrentStoreRead<K, V>     read ops, returns Arc<V>
//!     ├── ConcurrentStore<K, V>         write ops, Arc<V>
//!     └── ConcurrentStoreFactory<K, V>  factory (auto-detects shard count)
//!
//! Concurrency Comparison
//! ──────────────────────
//!
//!   │ Store                   │ Lock Scope │ Contention │ Use Case            │
//!   │─────────────────────────│────────────│────────────│─────────────────────│
//!   │ HashMapStore            │ None       │ N/A        │ Single-threaded     │
//!   │ ConcurrentHashMapStore  │ Global     │ Moderate   │ Simple concurrency  │
//!   │ ShardedHashMapStore     │ Per-shard  │ Low        │ High parallelism    │
//! ```
//!
//! ## Key Components
//!
//! - [`HashMapStore`]: Single-threaded store with zero-overhead `&V` access
//! - [`ConcurrentHashMapStore`]: Thread-safe store with global `RwLock`
//! - [`ShardedHashMapStore`]: Thread-safe store with per-shard locks
//!
//! ## Core Operations
//!
//! | Operation     | Single-threaded      | Concurrent           |
//! |---------------|----------------------|----------------------|
//! | `get`         | `&V` (zero-copy)     | `Arc<V>` (cloned)    |
//! | `try_insert`  | `V` owned            | `Arc<V>` owned       |
//! | `remove`      | `Option<V>`          | `Option<Arc<V>>`     |
//! | `peek`        | `&V` (no metrics)    | N/A                  |
//!
//! ## Performance Trade-offs
//!
//! **Single-threaded (`HashMapStore`):**
//! - Returns `&V` references—no allocation on access
//! - Fastest option when concurrency isn't needed
//! - Custom hasher support for specialized workloads
//!
//! **Global lock (`ConcurrentHashMapStore`):**
//! - Simple implementation, predictable behavior
//! - All operations serialize on the same lock
//! - Good for low-to-moderate concurrency
//!
//! **Sharded (`ShardedHashMapStore`):**
//! - Keys distributed across N independent shards
//! - Operations on different shards run in parallel
//! - Extra hashing cost to select shard
//! - Atomic size counter for global `len()`
//!
//! ## When to Use
//!
//! - [`HashMapStore`]: Single-threaded hot paths, no allocation on access
//! - [`ConcurrentHashMapStore`]: Simple thread-safe caching, moderate load
//! - [`ShardedHashMapStore`]: High-contention concurrent workloads
//!
//! ## Example Usage
//!
//! ```rust
//! use cachekit::store::hashmap::HashMapStore;
//! use cachekit::store::traits::{StoreCore, StoreFull, StoreMut};
//!
//! # fn main() -> Result<(), StoreFull> {
//! let mut store: HashMapStore<&str, i32> = HashMapStore::new(100);
//!
//! // Insert and access
//! store.try_insert("key", 42)?;
//! assert_eq!(store.get(&"key"), Some(&42));  // Returns &V, zero-copy
//!
//! // Peek without metrics
//! assert_eq!(store.peek(&"key"), Some(&42));
//!
//! // Check metrics
//! let m = store.metrics();
//! assert_eq!(m.hits, 1);  // get() counted
//! assert_eq!(m.inserts, 1);
//! # Ok(())
//! # }
//! ```
//!
//! ## Type Constraints
//!
//! - `K: Eq + Hash` — keys must be hashable and comparable
//! - `S: BuildHasher` — custom hasher support (defaults to `RandomState`)
//! - Concurrent variants require `K: Send + Sync`, `V: Send + Sync`
//!
//! ## Thread Safety
//!
//! - [`HashMapStore`] is **not** thread-safe (single-threaded only)
//! - [`ConcurrentHashMapStore`] and [`ShardedHashMapStore`] are `Send + Sync`
//!
//! ## Implementation Notes
//!
//! - Sharded store uses `hash(key) % shard_count` for shard selection
//! - Metrics use `AtomicU64` with relaxed ordering (lock-free)
//! - Factory implementations use default hasher; use `with_hasher` for custom

use std::collections::HashMap;
use std::collections::hash_map::RandomState;
use std::hash::{BuildHasher, Hash};
#[cfg(feature = "concurrency")]
use std::sync::Arc;
#[cfg(feature = "concurrency")]
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::{AtomicU64, Ordering};

#[cfg(feature = "concurrency")]
use parking_lot::RwLock;

#[cfg(feature = "concurrency")]
use crate::store::traits::{ConcurrentStore, ConcurrentStoreFactory, ConcurrentStoreRead};
use crate::store::traits::{StoreCore, StoreFactory, StoreFull, StoreMetrics, StoreMut};

// =============================================================================
// Metrics counters
// =============================================================================

/// Metrics counters using atomics for thread-safe updates.
///
/// All counters use `Ordering::Relaxed` for low-overhead increments.
/// Snapshot reads may reflect a slightly inconsistent view across counters
/// under high concurrency, but individual counters are always accurate.
#[derive(Debug, Default)]
struct StoreCounters {
    /// Successful lookups via `get()`.
    hits: AtomicU64,
    /// Failed lookups via `get()`.
    misses: AtomicU64,
    /// New key insertions.
    inserts: AtomicU64,
    /// Value updates for existing keys.
    updates: AtomicU64,
    /// Explicit removals via `remove()`.
    removes: AtomicU64,
    /// Policy-driven evictions via `record_eviction()`.
    evictions: AtomicU64,
}

impl StoreCounters {
    fn snapshot(&self) -> StoreMetrics {
        StoreMetrics {
            hits: self.hits.load(Ordering::Relaxed),
            misses: self.misses.load(Ordering::Relaxed),
            inserts: self.inserts.load(Ordering::Relaxed),
            updates: self.updates.load(Ordering::Relaxed),
            removes: self.removes.load(Ordering::Relaxed),
            evictions: self.evictions.load(Ordering::Relaxed),
        }
    }

    fn inc_hit(&self) {
        self.hits.fetch_add(1, Ordering::Relaxed);
    }

    fn inc_miss(&self) {
        self.misses.fetch_add(1, Ordering::Relaxed);
    }

    fn inc_insert(&self) {
        self.inserts.fetch_add(1, Ordering::Relaxed);
    }

    fn inc_update(&self) {
        self.updates.fetch_add(1, Ordering::Relaxed);
    }

    fn inc_remove(&self) {
        self.removes.fetch_add(1, Ordering::Relaxed);
    }

    fn inc_eviction(&self) {
        self.evictions.fetch_add(1, Ordering::Relaxed);
    }
}

// =============================================================================
// Single-threaded HashMapStore
// =============================================================================

/// Single-threaded HashMap-backed store with zero-overhead value access.
///
/// Stores values directly (not wrapped in `Arc`) so `get()` returns `&V`
/// without allocation. Implements [`StoreCore`] and [`StoreMut`] traits
/// for integration with single-threaded cache policies.
///
/// # Type Parameters
///
/// - `K`: Key type, must be `Eq + Hash`
/// - `V`: Value type, stored directly (owned)
/// - `S`: Hasher type, defaults to `RandomState`
///
/// # Example
///
/// ```
/// use cachekit::store::hashmap::HashMapStore;
/// use cachekit::store::traits::{StoreCore, StoreFull, StoreMut};
///
/// # fn main() -> Result<(), StoreFull> {
/// let mut store: HashMapStore<String, Vec<u8>> = HashMapStore::new(1000);
///
/// // Insert data
/// store.try_insert("image.png".into(), vec![0x89, 0x50, 0x4E, 0x47])?;
///
/// // Access returns &V (zero-copy)
/// let data: &Vec<u8> = store.get(&"image.png".into()).unwrap();
/// assert_eq!(data[0], 0x89);
///
/// // Mutable access for in-place updates
/// if let Some(data) = store.peek_mut(&"image.png".into()) {
///     data.push(0x0D);
/// }
///
/// // Metrics tracking
/// let m = store.metrics();
/// assert_eq!(m.hits, 1);
/// assert_eq!(m.inserts, 1);
/// # Ok(())
/// # }
/// ```
///
/// # Custom Hasher
///
/// ```ignore
/// use std::hash::BuildHasherDefault;
/// use rustc_hash::FxHasher;  // Add rustc-hash to Cargo.toml
/// use cachekit::store::hashmap::HashMapStore;
///
/// type FxBuildHasher = BuildHasherDefault<FxHasher>;
///
/// let store: HashMapStore<u64, String, FxBuildHasher> =
///     HashMapStore::with_hasher(100, FxBuildHasher::default());
/// ```
#[derive(Debug)]
pub struct HashMapStore<K, V, S = RandomState> {
    map: HashMap<K, V, S>,
    capacity: usize,
    metrics: StoreCounters,
}

impl<K, V> HashMapStore<K, V, RandomState>
where
    K: Eq + Hash,
{
    /// Creates a store with the specified capacity using the default hasher.
    ///
    /// # Example
    ///
    /// ```
    /// use cachekit::store::hashmap::HashMapStore;
    /// use cachekit::store::traits::StoreCore;
    ///
    /// let store: HashMapStore<i32, String> = HashMapStore::new(100);
    /// assert_eq!(store.capacity(), 100);
    /// assert!(store.is_empty());
    /// ```
    pub fn new(capacity: usize) -> Self {
        Self::with_hasher(capacity, RandomState::new())
    }
}

impl<K, V, S> HashMapStore<K, V, S>
where
    K: Eq + Hash,
    S: BuildHasher,
{
    /// Creates a store with the specified capacity and custom hasher.
    ///
    /// Use this when you need a deterministic or faster hasher than the
    /// default `RandomState`.
    ///
    /// # Example
    ///
    /// ```
    /// use std::collections::hash_map::RandomState;
    /// use cachekit::store::hashmap::HashMapStore;
    /// use cachekit::store::traits::StoreCore;
    ///
    /// // Use explicit RandomState (or any BuildHasher impl)
    /// let store: HashMapStore<&str, i32, RandomState> =
    ///     HashMapStore::with_hasher(50, RandomState::new());
    /// assert_eq!(store.capacity(), 50);
    /// ```
    pub fn with_hasher(capacity: usize, hasher: S) -> Self {
        Self {
            map: HashMap::with_capacity_and_hasher(capacity, hasher),
            capacity,
            metrics: StoreCounters::default(),
        }
    }

    /// Returns a reference to the value without updating metrics.
    ///
    /// Useful for internal operations that shouldn't affect hit/miss counts.
    ///
    /// # Example
    ///
    /// ```
    /// use cachekit::store::hashmap::HashMapStore;
    /// use cachekit::store::traits::{StoreCore, StoreFull, StoreMut};
    ///
    /// # fn main() -> Result<(), StoreFull> {
    /// let mut store: HashMapStore<&str, i32> = HashMapStore::new(10);
    /// store.try_insert("key", 42)?;
    ///
    /// // Peek doesn't update metrics
    /// assert_eq!(store.peek(&"key"), Some(&42));
    /// assert_eq!(store.metrics().hits, 0);
    /// # Ok(())
    /// # }
    /// ```
    pub fn peek(&self, key: &K) -> Option<&V> {
        self.map.get(key)
    }

    /// Returns a mutable reference to the value without updating metrics.
    ///
    /// Allows in-place modification of stored values.
    ///
    /// # Example
    ///
    /// ```
    /// use cachekit::store::hashmap::HashMapStore;
    /// use cachekit::store::traits::{StoreFull, StoreMut};
    ///
    /// # fn main() -> Result<(), StoreFull> {
    /// let mut store: HashMapStore<&str, Vec<i32>> = HashMapStore::new(10);
    /// store.try_insert("nums", vec![1, 2, 3])?;
    ///
    /// // Modify in place
    /// if let Some(nums) = store.peek_mut(&"nums") {
    ///     nums.push(4);
    /// }
    ///
    /// assert_eq!(store.peek(&"nums"), Some(&vec![1, 2, 3, 4]));
    /// # Ok(())
    /// # }
    /// ```
    pub fn peek_mut(&mut self, key: &K) -> Option<&mut V> {
        self.map.get_mut(key)
    }

    /// Returns the underlying HashMap's allocated capacity.
    ///
    /// This may be larger than the logical capacity limit set at creation.
    ///
    /// # Example
    ///
    /// ```
    /// use cachekit::store::hashmap::HashMapStore;
    /// use cachekit::store::traits::StoreCore;
    ///
    /// let store: HashMapStore<&str, i32> = HashMapStore::new(100);
    /// assert!(store.map_capacity() >= store.capacity());
    /// ```
    pub fn map_capacity(&self) -> usize {
        self.map.capacity()
    }

    /// Records an eviction in the metrics.
    ///
    /// Call when the policy evicts an entry. Separate from `remove()` to
    /// distinguish user-initiated removals from policy-driven evictions.
    ///
    /// # Example
    ///
    /// ```
    /// use cachekit::store::hashmap::HashMapStore;
    /// use cachekit::store::traits::{StoreCore, StoreFull, StoreMut};
    ///
    /// # fn main() -> Result<(), StoreFull> {
    /// let mut store: HashMapStore<&str, i32> = HashMapStore::new(10);
    /// store.try_insert("key", 1)?;
    ///
    /// // Policy evicts the entry
    /// store.remove(&"key");
    /// store.record_eviction();
    ///
    /// let m = store.metrics();
    /// assert_eq!(m.removes, 1);
    /// assert_eq!(m.evictions, 1);
    /// # Ok(())
    /// # }
    /// ```
    pub fn record_eviction(&self) {
        self.metrics.inc_eviction();
    }
}

impl<K: Clone, V: Clone, S: Clone> Clone for HashMapStore<K, V, S> {
    fn clone(&self) -> Self {
        Self {
            map: self.map.clone(),
            capacity: self.capacity,
            metrics: StoreCounters {
                hits: AtomicU64::new(self.metrics.hits.load(Ordering::Relaxed)),
                misses: AtomicU64::new(self.metrics.misses.load(Ordering::Relaxed)),
                inserts: AtomicU64::new(self.metrics.inserts.load(Ordering::Relaxed)),
                updates: AtomicU64::new(self.metrics.updates.load(Ordering::Relaxed)),
                removes: AtomicU64::new(self.metrics.removes.load(Ordering::Relaxed)),
                evictions: AtomicU64::new(self.metrics.evictions.load(Ordering::Relaxed)),
            },
        }
    }
}

/// Read operations for [`HashMapStore`].
///
/// Returns borrowed `&V` references for zero-copy access.
impl<K, V, S> StoreCore<K, V> for HashMapStore<K, V, S>
where
    K: Eq + Hash,
    S: BuildHasher,
{
    /// Returns a reference to the value for the given key.
    ///
    /// Updates hit/miss metrics. Use [`peek`](HashMapStore::peek) to avoid
    /// metric updates.
    fn get(&self, key: &K) -> Option<&V> {
        match self.map.get(key) {
            Some(value) => {
                self.metrics.inc_hit();
                Some(value)
            },
            None => {
                self.metrics.inc_miss();
                None
            },
        }
    }

    /// Returns `true` if the key exists. Does not update metrics.
    fn contains(&self, key: &K) -> bool {
        self.map.contains_key(key)
    }

    /// Returns the current number of entries.
    fn len(&self) -> usize {
        self.map.len()
    }

    /// Returns the logical capacity limit.
    fn capacity(&self) -> usize {
        self.capacity
    }

    /// Returns a snapshot of the store's metrics.
    fn metrics(&self) -> StoreMetrics {
        self.metrics.snapshot()
    }
}

/// Write operations for [`HashMapStore`].
///
/// Takes and returns owned `V` values directly.
impl<K, V, S> StoreMut<K, V> for HashMapStore<K, V, S>
where
    K: Eq + Hash,
    S: BuildHasher,
{
    /// Inserts or updates a value.
    ///
    /// Returns `Ok(Some(old))` for updates, `Ok(None)` for new insertions.
    ///
    /// # Errors
    ///
    /// Returns [`StoreFull`] if at capacity and the key is new.
    fn try_insert(&mut self, key: K, value: V) -> Result<Option<V>, StoreFull> {
        if !self.map.contains_key(&key) && self.map.len() >= self.capacity {
            return Err(StoreFull);
        }
        let previous = self.map.insert(key, value);
        if previous.is_some() {
            self.metrics.inc_update();
        } else {
            self.metrics.inc_insert();
        }
        Ok(previous)
    }

    /// Removes and returns the value for the given key.
    ///
    /// Updates `removes` metric if an entry was removed.
    fn remove(&mut self, key: &K) -> Option<V> {
        let removed = self.map.remove(key);
        if removed.is_some() {
            self.metrics.inc_remove();
        }
        removed
    }

    /// Removes all entries. Does not update metrics.
    fn clear(&mut self) {
        self.map.clear();
    }
}

/// Factory for creating [`HashMapStore`] instances with default hasher.
///
/// # Example
///
/// ```
/// use cachekit::store::hashmap::HashMapStore;
/// use cachekit::store::traits::{StoreFactory, StoreCore};
///
/// fn create_store<F: StoreFactory<String, i32>>(cap: usize) -> F::Store {
///     F::create(cap)
/// }
///
/// let store = create_store::<HashMapStore<String, i32>>(100);
/// assert_eq!(store.capacity(), 100);
/// ```
impl<K, V> StoreFactory<K, V> for HashMapStore<K, V, RandomState>
where
    K: Eq + Hash,
{
    type Store = HashMapStore<K, V, RandomState>;

    fn create(capacity: usize) -> Self::Store {
        Self::new(capacity)
    }
}

// =============================================================================
// Concurrent HashMap store (global lock)
// =============================================================================

/// Thread-safe HashMap store with a single global `RwLock`.
///
/// Uses `Arc<V>` for values since borrowed references cannot outlive lock
/// guards. Simple concurrency model—all operations serialize on the same
/// lock. For high-contention workloads, consider [`ShardedHashMapStore`].
///
/// # Type Parameters
///
/// - `K`: Key type, must be `Eq + Hash + Send + Sync`
/// - `V`: Value type, must be `Send + Sync` (wrapped in `Arc<V>`)
/// - `S`: Hasher type, must be `Send + Sync`, defaults to `RandomState`
///
/// # Synchronization
///
/// - Read operations (`get`, `contains`, `len`) acquire a read lock
/// - Write operations (`try_insert`, `remove`, `clear`) acquire a write lock
/// - Metrics use atomic counters (lock-free)
///
/// # Example
///
/// ```
/// use std::sync::Arc;
/// use std::thread;
/// use cachekit::store::hashmap::ConcurrentHashMapStore;
/// use cachekit::store::traits::{ConcurrentStore, ConcurrentStoreRead};
///
/// let store = Arc::new(ConcurrentHashMapStore::<String, i32>::new(100));
///
/// // Spawn multiple writers
/// let handles: Vec<_> = (0..4).map(|t| {
///     let store = Arc::clone(&store);
///     thread::spawn(move || {
///         for i in 0..25 {
///             let key = format!("key_{}_{}", t, i);
///             store.try_insert(key, Arc::new(i)).unwrap();
///         }
///     })
/// }).collect();
///
/// for h in handles {
///     h.join().unwrap();
/// }
///
/// assert_eq!(store.len(), 100);
/// ```
#[cfg(feature = "concurrency")]
#[derive(Debug)]
pub struct ConcurrentHashMapStore<K, V, S = RandomState> {
    map: RwLock<HashMap<K, Arc<V>, S>>,
    capacity: usize,
    metrics: StoreCounters,
}

#[cfg(feature = "concurrency")]
impl<K, V> ConcurrentHashMapStore<K, V, RandomState>
where
    K: Eq + Hash + Send,
{
    /// Creates a concurrent store with the specified capacity.
    ///
    /// # Example
    ///
    /// ```
    /// use cachekit::store::hashmap::ConcurrentHashMapStore;
    /// use cachekit::store::traits::ConcurrentStoreRead;
    ///
    /// let store: ConcurrentHashMapStore<String, Vec<u8>> =
    ///     ConcurrentHashMapStore::new(1000);
    /// assert_eq!(store.capacity(), 1000);
    /// ```
    pub fn new(capacity: usize) -> Self {
        Self::with_hasher(capacity, RandomState::new())
    }
}

#[cfg(feature = "concurrency")]
impl<K, V, S> ConcurrentHashMapStore<K, V, S>
where
    K: Eq + Hash + Send,
    S: BuildHasher,
{
    /// Creates a concurrent store with the specified capacity and custom hasher.
    ///
    /// # Example
    ///
    /// ```
    /// use std::collections::hash_map::RandomState;
    /// use cachekit::store::hashmap::ConcurrentHashMapStore;
    /// use cachekit::store::traits::ConcurrentStoreRead;
    ///
    /// // Use explicit RandomState (or any BuildHasher impl)
    /// let store: ConcurrentHashMapStore<u64, String, RandomState> =
    ///     ConcurrentHashMapStore::with_hasher(100, RandomState::new());
    /// assert_eq!(store.capacity(), 100);
    /// ```
    pub fn with_hasher(capacity: usize, hasher: S) -> Self {
        Self {
            map: RwLock::new(HashMap::with_capacity_and_hasher(capacity, hasher)),
            capacity,
            metrics: StoreCounters::default(),
        }
    }

    /// Records an eviction in the metrics.
    ///
    /// Thread-safe via atomic increment.
    ///
    /// # Example
    ///
    /// ```
    /// use std::sync::Arc;
    /// use cachekit::store::hashmap::ConcurrentHashMapStore;
    /// use cachekit::store::traits::{ConcurrentStore, ConcurrentStoreRead, StoreFull};
    ///
    /// # fn main() -> Result<(), StoreFull> {
    /// let store = ConcurrentHashMapStore::<&str, i32>::new(10);
    /// store.try_insert("key", Arc::new(1))?;
    /// store.remove(&"key");
    /// store.record_eviction();
    /// assert_eq!(store.metrics().evictions, 1);
    /// # Ok(())
    /// # }
    /// ```
    pub fn record_eviction(&self) {
        self.metrics.inc_eviction();
    }
}

/// Read operations for [`ConcurrentHashMapStore`].
///
/// All methods acquire a read lock. Multiple readers can access concurrently.
#[cfg(feature = "concurrency")]
impl<K, V, S> ConcurrentStoreRead<K, V> for ConcurrentHashMapStore<K, V, S>
where
    K: Eq + Hash + Send + Sync,
    V: Send + Sync,
    S: BuildHasher + Send + Sync,
{
    /// Returns a clone of the value for the given key.
    ///
    /// Acquires read lock, clones `Arc<V>`, releases lock. The returned
    /// `Arc` can be held indefinitely without blocking other operations.
    fn get(&self, key: &K) -> Option<Arc<V>> {
        match self.map.read().get(key).cloned() {
            Some(value) => {
                self.metrics.inc_hit();
                Some(value)
            },
            None => {
                self.metrics.inc_miss();
                None
            },
        }
    }

    /// Returns `true` if the key exists. Acquires read lock.
    fn contains(&self, key: &K) -> bool {
        self.map.read().contains_key(key)
    }

    /// Returns the current number of entries.
    ///
    /// Acquires read lock. Value may be stale by the time it's used.
    fn len(&self) -> usize {
        self.map.read().len()
    }

    /// Returns the logical capacity limit.
    fn capacity(&self) -> usize {
        self.capacity
    }

    /// Returns a snapshot of the store's metrics.
    fn metrics(&self) -> StoreMetrics {
        self.metrics.snapshot()
    }
}

/// Write operations for [`ConcurrentHashMapStore`].
///
/// All methods acquire a write lock. Writers have exclusive access.
#[cfg(feature = "concurrency")]
impl<K, V, S> ConcurrentStore<K, V> for ConcurrentHashMapStore<K, V, S>
where
    K: Eq + Hash + Send + Sync,
    V: Send + Sync,
    S: BuildHasher + Send + Sync,
{
    /// Inserts or updates a value.
    ///
    /// Acquires write lock for the duration of the operation.
    ///
    /// # Errors
    ///
    /// Returns [`StoreFull`] if at capacity and the key is new.
    fn try_insert(&self, key: K, value: Arc<V>) -> Result<Option<Arc<V>>, StoreFull> {
        let mut map = self.map.write();
        if !map.contains_key(&key) && map.len() >= self.capacity {
            return Err(StoreFull);
        }
        let previous = map.insert(key, value);
        if previous.is_some() {
            self.metrics.inc_update();
        } else {
            self.metrics.inc_insert();
        }
        Ok(previous)
    }

    /// Removes and returns the value for the given key.
    ///
    /// Acquires write lock.
    fn remove(&self, key: &K) -> Option<Arc<V>> {
        let removed = self.map.write().remove(key);
        if removed.is_some() {
            self.metrics.inc_remove();
        }
        removed
    }

    /// Removes all entries. Acquires write lock.
    fn clear(&self) {
        self.map.write().clear()
    }
}

/// Factory for creating [`ConcurrentHashMapStore`] instances.
///
/// # Example
///
/// ```
/// use cachekit::store::hashmap::ConcurrentHashMapStore;
/// use cachekit::store::traits::{ConcurrentStoreFactory, ConcurrentStoreRead};
///
/// fn create<F: ConcurrentStoreFactory<String, i32>>(cap: usize) -> F::Store {
///     F::create(cap)
/// }
///
/// let store = create::<ConcurrentHashMapStore<String, i32>>(50);
/// assert_eq!(store.capacity(), 50);
/// ```
#[cfg(feature = "concurrency")]
impl<K, V> ConcurrentStoreFactory<K, V> for ConcurrentHashMapStore<K, V, RandomState>
where
    K: Eq + Hash + Send + Sync,
    V: Send + Sync,
{
    type Store = ConcurrentHashMapStore<K, V, RandomState>;

    fn create(capacity: usize) -> Self::Store {
        Self::new(capacity)
    }
}

// =============================================================================
// Sharded HashMap store
// =============================================================================

/// Thread-safe HashMap store with per-shard locking for high concurrency.
///
/// Distributes keys across N independent shards, each with its own `RwLock`.
/// Operations on different shards can proceed in parallel, reducing contention
/// compared to [`ConcurrentHashMapStore`].
///
/// # Type Parameters
///
/// - `K`: Key type, must be `Eq + Hash + Send + Sync`
/// - `V`: Value type, must be `Send + Sync` (wrapped in `Arc<V>`)
/// - `S`: Hasher type, must be `Clone + Send + Sync`, defaults to `RandomState`
///
/// # Shard Selection
///
/// Keys are assigned to shards via `hash(key) % shard_count`. The same hasher
/// is used for both shard selection and within-shard HashMap operations.
///
/// # Capacity Enforcement
///
/// Global capacity is enforced via an `AtomicUsize` counter. The counter is
/// updated with compare-and-swap on insert to prevent over-capacity races.
///
/// # Example
///
/// ```
/// use std::sync::Arc;
/// use std::thread;
/// use cachekit::store::hashmap::ShardedHashMapStore;
/// use cachekit::store::traits::{ConcurrentStore, ConcurrentStoreRead};
///
/// // Create store with 8 shards for 8-core machine
/// let store = Arc::new(ShardedHashMapStore::<u64, String>::new(10000, 8));
///
/// // Spawn workers that operate on different key ranges (likely different shards)
/// let handles: Vec<_> = (0..8).map(|t| {
///     let store = Arc::clone(&store);
///     thread::spawn(move || {
///         let base = t * 1000;
///         for i in 0..1000 {
///             store.try_insert(base + i, Arc::new(format!("v{}", base + i))).unwrap();
///         }
///     })
/// }).collect();
///
/// for h in handles {
///     h.join().unwrap();
/// }
///
/// assert_eq!(store.len(), 8000);
/// assert_eq!(store.shard_count(), 8);
/// ```
///
/// # Performance Considerations
///
/// - More shards = less contention but more memory overhead
/// - Optimal shard count is typically 2-4x the number of CPU cores
/// - Keys that hash to the same shard still contend
/// - Use [`ConcurrentStoreFactory`] to auto-detect shard count
#[cfg(feature = "concurrency")]
#[derive(Debug)]
pub struct ShardedHashMapStore<K, V, S = RandomState> {
    shards: Vec<RwLock<HashMap<K, Arc<V>, S>>>,
    capacity: usize,
    size: AtomicUsize,
    metrics: StoreCounters,
    hasher: S,
}

#[cfg(feature = "concurrency")]
impl<K, V> ShardedHashMapStore<K, V, RandomState>
where
    K: Eq + Hash + Send + Sync,
{
    /// Creates a sharded store with the specified capacity and shard count.
    ///
    /// # Arguments
    ///
    /// * `capacity` - Maximum number of entries across all shards
    /// * `shards` - Number of independent shards (minimum 1)
    ///
    /// # Example
    ///
    /// ```
    /// use cachekit::store::hashmap::ShardedHashMapStore;
    /// use cachekit::store::traits::ConcurrentStoreRead;
    ///
    /// let store: ShardedHashMapStore<String, Vec<u8>> =
    ///     ShardedHashMapStore::new(10000, 16);
    /// assert_eq!(store.capacity(), 10000);
    /// assert_eq!(store.shard_count(), 16);
    /// ```
    pub fn new(capacity: usize, shards: usize) -> Self {
        Self::with_hasher(capacity, shards, RandomState::new())
    }
}

#[cfg(feature = "concurrency")]
impl<K, V, S> ShardedHashMapStore<K, V, S>
where
    K: Eq + Hash + Send + Sync,
    S: BuildHasher + Clone,
{
    /// Creates a sharded store with custom hasher.
    ///
    /// The hasher is cloned for each shard's internal HashMap.
    ///
    /// # Example
    ///
    /// ```
    /// use std::collections::hash_map::RandomState;
    /// use cachekit::store::hashmap::ShardedHashMapStore;
    ///
    /// // Use explicit RandomState (or any Clone + BuildHasher impl)
    /// let store: ShardedHashMapStore<u64, String, RandomState> =
    ///     ShardedHashMapStore::with_hasher(1000, 4, RandomState::new());
    /// assert_eq!(store.shard_count(), 4);
    /// ```
    pub fn with_hasher(capacity: usize, shards: usize, hasher: S) -> Self {
        let shard_count = shards.max(1);
        let mut shard_vec = Vec::with_capacity(shard_count);
        for _ in 0..shard_count {
            shard_vec.push(RwLock::new(HashMap::with_hasher(hasher.clone())));
        }
        Self {
            shards: shard_vec,
            capacity,
            size: AtomicUsize::new(0),
            metrics: StoreCounters::default(),
            hasher,
        }
    }

    /// Returns the number of shards.
    ///
    /// # Example
    ///
    /// ```
    /// use cachekit::store::hashmap::ShardedHashMapStore;
    ///
    /// let store: ShardedHashMapStore<u64, i32> = ShardedHashMapStore::new(100, 8);
    /// assert_eq!(store.shard_count(), 8);
    /// ```
    pub fn shard_count(&self) -> usize {
        self.shards.len()
    }

    /// Computes the shard index for a key.
    fn shard_index(&self, key: &K) -> usize {
        (self.hasher.hash_one(key) as usize) % self.shards.len()
    }

    /// Records an eviction in the metrics.
    ///
    /// Thread-safe via atomic increment.
    ///
    /// # Example
    ///
    /// ```
    /// use std::sync::Arc;
    /// use cachekit::store::hashmap::ShardedHashMapStore;
    /// use cachekit::store::traits::{ConcurrentStore, ConcurrentStoreRead, StoreFull};
    ///
    /// # fn main() -> Result<(), StoreFull> {
    /// let store = ShardedHashMapStore::<&str, i32>::new(10, 4);
    /// store.try_insert("key", Arc::new(1))?;
    /// store.remove(&"key");
    /// store.record_eviction();
    /// assert_eq!(store.metrics().evictions, 1);
    /// # Ok(())
    /// # }
    /// ```
    pub fn record_eviction(&self) {
        self.metrics.inc_eviction();
    }
}

/// Read operations for [`ShardedHashMapStore`].
///
/// Each operation only locks the shard containing the target key.
#[cfg(feature = "concurrency")]
impl<K, V, S> ConcurrentStoreRead<K, V> for ShardedHashMapStore<K, V, S>
where
    K: Eq + Hash + Send + Sync,
    V: Send + Sync,
    S: BuildHasher + Clone + Send + Sync,
{
    /// Returns a clone of the value for the given key.
    ///
    /// Only locks the shard containing the key. Other shards remain accessible.
    fn get(&self, key: &K) -> Option<Arc<V>> {
        let idx = self.shard_index(key);
        match self.shards[idx].read().get(key).cloned() {
            Some(value) => {
                self.metrics.inc_hit();
                Some(value)
            },
            None => {
                self.metrics.inc_miss();
                None
            },
        }
    }

    /// Returns `true` if the key exists. Only locks the target shard.
    fn contains(&self, key: &K) -> bool {
        let idx = self.shard_index(key);
        self.shards[idx].read().contains_key(key)
    }

    /// Returns the current number of entries across all shards.
    ///
    /// Uses atomic load—no locking required. Value may be stale under
    /// concurrent modifications.
    fn len(&self) -> usize {
        self.size.load(Ordering::Relaxed)
    }

    /// Returns the global capacity limit.
    fn capacity(&self) -> usize {
        self.capacity
    }

    /// Returns a snapshot of the store's metrics.
    fn metrics(&self) -> StoreMetrics {
        self.metrics.snapshot()
    }
}

/// Write operations for [`ShardedHashMapStore`].
///
/// Each operation only locks the shard containing the target key, except
/// `clear()` which locks all shards.
#[cfg(feature = "concurrency")]
impl<K, V, S> ConcurrentStore<K, V> for ShardedHashMapStore<K, V, S>
where
    K: Eq + Hash + Send + Sync,
    V: Send + Sync,
    S: BuildHasher + Clone + Send + Sync,
{
    /// Inserts or updates a value.
    ///
    /// Only locks the target shard. Uses compare-and-swap on the global
    /// size counter to enforce capacity without locking all shards.
    ///
    /// # Errors
    ///
    /// Returns [`StoreFull`] if at capacity and the key is new.
    fn try_insert(&self, key: K, value: Arc<V>) -> Result<Option<Arc<V>>, StoreFull> {
        let idx = self.shard_index(&key);
        let mut map = self.shards[idx].write();
        match map.entry(key) {
            std::collections::hash_map::Entry::Occupied(mut entry) => {
                let previous = Some(entry.insert(value));
                self.metrics.inc_update();
                Ok(previous)
            },
            std::collections::hash_map::Entry::Vacant(entry) => {
                if self.capacity == 0 {
                    return Err(StoreFull);
                }

                // CAS loop to atomically reserve a slot
                loop {
                    let current = self.size.load(Ordering::Relaxed);
                    if current >= self.capacity {
                        return Err(StoreFull);
                    }
                    if self
                        .size
                        .compare_exchange(current, current + 1, Ordering::AcqRel, Ordering::Relaxed)
                        .is_ok()
                    {
                        break;
                    }
                }

                entry.insert(value);
                self.metrics.inc_insert();
                Ok(None)
            },
        }
    }

    /// Removes and returns the value for the given key.
    ///
    /// Only locks the target shard. Atomically decrements size counter.
    fn remove(&self, key: &K) -> Option<Arc<V>> {
        let idx = self.shard_index(key);
        let removed = self.shards[idx].write().remove(key);
        if removed.is_some() {
            self.size.fetch_sub(1, Ordering::Relaxed);
            self.metrics.inc_remove();
        }
        removed
    }

    /// Removes all entries from all shards.
    ///
    /// Acquires write locks on all shards simultaneously to ensure
    /// consistency. This is the only operation that locks multiple shards.
    fn clear(&self) {
        // Lock all shards first to prevent concurrent modifications
        let mut guards = Vec::with_capacity(self.shards.len());
        for shard in &self.shards {
            guards.push(shard.write());
        }
        for guard in guards.iter_mut() {
            guard.clear();
        }
        self.size.store(0, Ordering::Relaxed);
    }
}

/// Factory for creating [`ShardedHashMapStore`] instances.
///
/// Automatically detects the number of available CPU cores and creates
/// that many shards for optimal parallelism.
///
/// # Example
///
/// ```
/// use cachekit::store::hashmap::ShardedHashMapStore;
/// use cachekit::store::traits::{ConcurrentStoreFactory, ConcurrentStoreRead};
///
/// // Factory auto-detects optimal shard count
/// let store = <ShardedHashMapStore<String, i32>>::create(10000);
/// assert_eq!(store.capacity(), 10000);
/// // shard_count() == number of CPU cores (or 1 if detection fails)
/// ```
#[cfg(feature = "concurrency")]
impl<K, V> ConcurrentStoreFactory<K, V> for ShardedHashMapStore<K, V, RandomState>
where
    K: Eq + Hash + Send + Sync,
    V: Send + Sync,
{
    type Store = ShardedHashMapStore<K, V, RandomState>;

    fn create(capacity: usize) -> Self::Store {
        let shards = std::thread::available_parallelism()
            .map(|count| count.get())
            .unwrap_or(1);
        Self::new(capacity, shards)
    }
}

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

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

    #[test]
    fn hashmap_store_basic_ops() {
        let mut store = HashMapStore::new(2);
        assert_eq!(store.try_insert("k1", "v1".to_string()), Ok(None));
        assert_eq!(store.get(&"k1"), Some(&"v1".to_string()));
        assert!(store.contains(&"k1"));
        assert_eq!(store.len(), 1);
        assert_eq!(store.capacity(), 2);
        assert_eq!(store.remove(&"k1"), Some("v1".to_string()));
        assert!(!store.contains(&"k1"));
    }

    #[test]
    fn hashmap_store_returns_reference() {
        let mut store = HashMapStore::new(2);
        store.try_insert("k1", "hello".to_string()).unwrap();

        // get() returns &V, no allocation
        let value: &String = store.get(&"k1").unwrap();
        assert_eq!(value, "hello");

        // peek() also returns &V without metrics
        let peeked: &String = store.peek(&"k1").unwrap();
        assert_eq!(peeked, "hello");
    }

    #[test]
    fn hashmap_store_capacity_enforced() {
        let mut store = HashMapStore::new(1);
        assert_eq!(store.try_insert("k1", "v1".to_string()), Ok(None));
        assert_eq!(store.try_insert("k2", "v2".to_string()), Err(StoreFull));
        assert_eq!(store.len(), 1);
    }

    #[test]
    fn hashmap_store_update_returns_previous() {
        let mut store = HashMapStore::new(2);
        assert_eq!(store.try_insert("k1", "v1".to_string()), Ok(None));
        assert_eq!(
            store.try_insert("k1", "v2".to_string()),
            Ok(Some("v1".to_string()))
        );
        assert_eq!(store.get(&"k1"), Some(&"v2".to_string()));
    }

    #[test]
    fn hashmap_store_metrics_counts() {
        let mut store = HashMapStore::new(2);

        assert_eq!(store.metrics(), StoreMetrics::default());
        assert_eq!(store.get(&"missing"), None);
        assert_eq!(store.try_insert("k1", "v1".to_string()), Ok(None));
        assert_eq!(
            store.try_insert("k1", "v2".to_string()),
            Ok(Some("v1".to_string()))
        );
        assert_eq!(store.get(&"k1"), Some(&"v2".to_string()));
        assert_eq!(store.remove(&"k1"), Some("v2".to_string()));
        store.record_eviction();

        let metrics = store.metrics();
        assert_eq!(metrics.hits, 1);
        assert_eq!(metrics.misses, 1);
        assert_eq!(metrics.inserts, 1);
        assert_eq!(metrics.updates, 1);
        assert_eq!(metrics.removes, 1);
        assert_eq!(metrics.evictions, 1);
    }

    #[cfg(feature = "concurrency")]
    #[test]
    fn concurrent_store_basic_ops() {
        let store = ConcurrentHashMapStore::new(2);
        let value = Arc::new("v1".to_string());
        assert_eq!(store.try_insert("k1", value.clone()), Ok(None));
        assert_eq!(store.get(&"k1"), Some(value.clone()));
        assert!(store.contains(&"k1"));
        assert_eq!(store.len(), 1);
        assert_eq!(store.capacity(), 2);
        assert_eq!(store.remove(&"k1"), Some(value));
        assert!(!store.contains(&"k1"));
    }

    #[cfg(feature = "concurrency")]
    #[test]
    fn sharded_store_basic_ops() {
        let store = ShardedHashMapStore::new(2, 2);
        let value = Arc::new("v1".to_string());
        assert_eq!(store.try_insert("k1", value.clone()), Ok(None));
        assert_eq!(store.get(&"k1"), Some(value.clone()));
        assert!(store.contains(&"k1"));
        assert_eq!(store.len(), 1);
        assert_eq!(store.capacity(), 2);
        assert_eq!(store.remove(&"k1"), Some(value));
        assert!(!store.contains(&"k1"));
    }

    #[cfg(feature = "concurrency")]
    #[test]
    fn sharded_store_capacity_enforced() {
        let store = ShardedHashMapStore::new(1, 2);
        assert_eq!(store.try_insert("k1", Arc::new("v1".to_string())), Ok(None));
        assert_eq!(
            store.try_insert("k2", Arc::new("v2".to_string())),
            Err(StoreFull)
        );
        assert_eq!(store.len(), 1);
    }
}