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
//! Weight-aware store with dual entry-count and byte-based capacity limits.
//!
//! Enforces both a maximum number of entries and a maximum total weight
//! (e.g., bytes). Ideal for caches where values vary significantly in size
//! and you want fair eviction pressure based on actual memory usage.
//!
//! ## Architecture
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────────────────┐
//! │ Weight Store Layout │
//! │ │
//! │ ┌──────────────────────────────────────────────────────────────────────┐ │
//! │ │ Dual Capacity Limits │ │
//! │ │ │ │
//! │ │ Entry Limit: max 100 entries Weight Limit: max 10MB total │ │
//! │ │ │ │ │ │
//! │ │ ▼ ▼ │ │
//! │ │ ┌─────────┐ ┌─────────────┐ │ │
//! │ │ │ len() │ │total_weight │ │ │
//! │ │ │ = 3 │ │ = 2.5MB │ │ │
//! │ │ └─────────┘ └─────────────┘ │ │
//! │ └──────────────────────────────────────────────────────────────────────┘ │
//! │ │
//! │ ┌──────────────────────────────────────────────────────────────────────┐ │
//! │ │ Storage: HashMap<K, WeightEntry<V>> │ │
//! │ │ │ │
//! │ │ key WeightEntry │ │
//! │ │ ──── ─────────────────────────── │ │
//! │ │ "img1" ──► { value: Arc<[u8; 1MB]>, weight: 1_000_000 } │ │
//! │ │ "img2" ──► { value: Arc<[u8; 1MB]>, weight: 1_000_000 } │ │
//! │ │ "icon" ──► { value: Arc<[u8; 500KB]>, weight: 500_000 } │ │
//! │ │ │ │
//! │ │ Weight is precomputed on insert to avoid repeated computation. │ │
//! │ └──────────────────────────────────────────────────────────────────────┘ │
//! │ │
//! │ ┌──────────────────────────────────────────────────────────────────────┐ │
//! │ │ Weight Function: F: Fn(&V) -> usize │ │
//! │ │ │ │
//! │ │ Examples: │ │
//! │ │ • |s: &String| s.len() // String byte length │ │
//! │ │ • |v: &Vec<u8>| v.len() // Vec capacity │ │
//! │ │ • |img: &Image| img.width * img.height * 4 // RGBA pixels │ │
//! │ │ • |_: &T| 1 // Treat as entry-count only │ │
//! │ └──────────────────────────────────────────────────────────────────────┘ │
//! └─────────────────────────────────────────────────────────────────────────────┘
//!
//! Capacity Enforcement
//! ────────────────────
//!
//! try_insert(key, value):
//! │
//! ├─► Existing key (UPDATE)
//! │ │
//! │ ├── new_weight = weight_fn(&value)
//! │ ├── next_total = total_weight - old_weight + new_weight
//! │ │
//! │ └── next_total > capacity_weight? ──► Err(StoreFull)
//! │ └──► Ok(Some(old_value))
//! │
//! └─► New key (INSERT)
//! │
//! ├── len() >= capacity_entries? ──► Err(StoreFull)
//! │
//! ├── new_weight = weight_fn(&value)
//! ├── total_weight + new_weight > capacity_weight? ──► Err(StoreFull)
//! │
//! └── Ok(None)
//!
//! Component Comparison
//! ────────────────────
//!
//! │ Store │ Entry Limit │ Weight Limit │ Thread Safety │
//! │────────────────────────│─────────────│──────────────│───────────────│
//! │ WeightStore │ ✓ │ ✓ │ Single-thread │
//! │ ConcurrentWeightStore │ ✓ │ ✓ │ Send + Sync │
//! ```
//!
//! ## Key Components
//!
//! - [`WeightStore`]: Single-threaded store with entry + weight limits
//! - [`ConcurrentWeightStore`]: Thread-safe wrapper using `RwLock`
//! - `WeightEntry`: Internal struct storing value + precomputed weight
//!
//! ## Core Operations
//!
//! | Operation | Description | Complexity |
//! |-----------------|-----------------------------------------|------------|
//! | `try_insert` | Insert/update with dual limit checks | O(1) avg |
//! | `get` | Lookup by key (updates metrics) | O(1) avg |
//! | `peek` | Lookup without metrics | O(1) avg |
//! | `remove` | Remove and adjust total weight | O(1) avg |
//! | `total_weight` | Current sum of all entry weights | O(1) |
//!
//! ## Performance Trade-offs
//!
//! **Advantages:**
//! - Fair eviction pressure based on actual size, not entry count
//! - Weight precomputed on insert—reads don't recompute
//! - Dual limits prevent both entry-count and memory exhaustion
//! - Weight function is caller-defined for maximum flexibility
//!
//! **Costs:**
//! - Weight function called on every insert/update
//! - Uses `Arc<V>` even for single-threaded store (needed for weight_fn)
//! - Slightly more state to track than simple HashMap stores
//!
//! ## When to Use
//!
//! - Values vary significantly in size (images, documents, serialized data)
//! - Memory budget matters more than entry count
//! - You need observability into total cached bytes
//! - Eviction policy should consider size, not just access patterns
//!
//! ## Example Usage
//!
//! ```rust
//! use std::sync::Arc;
//! use cachekit::store::weight::WeightStore;
//!
//! // Cache with max 100 entries OR 1MB total, whichever is hit first
//! let mut store = WeightStore::with_capacity(100, 1_000_000, |v: &Vec<u8>| v.len());
//!
//! // Insert entries
//! store.try_insert("small", Arc::new(vec![0u8; 100])).unwrap();
//! store.try_insert("large", Arc::new(vec![0u8; 10_000])).unwrap();
//!
//! assert_eq!(store.len(), 2);
//! assert_eq!(store.total_weight(), 10_100);
//!
//! // Remove adjusts weight
//! store.remove(&"large");
//! assert_eq!(store.total_weight(), 100);
//! ```
//!
//! ## Type Constraints
//!
//! - `K: Eq + Hash` — keys must be hashable
//! - `F: Fn(&V) -> usize` — weight function computes size from value
//! - Concurrent: `K: Send + Sync`, `V: Send + Sync`, `F: Send + Sync`
//!
//! ## Thread Safety
//!
//! - [`WeightStore`] is **not** thread-safe (single-threaded only)
//! - [`ConcurrentWeightStore`] is `Send + Sync` via `parking_lot::RwLock`
//!
//! ## Implementation Notes
//!
//! - Weight is stored per entry in `WeightEntry` to avoid recomputation
//! - Updates recompute weight and adjust `total_weight` atomically
//! - Does **not** implement `StoreCore`/`StoreMut` (uses `Arc<V>` API)
//! - Metrics use atomic counters for concurrent compatibility
use Hash;
use Arc;
use ;
use RwLock;
use FxHashMap;
use crate;
/// Internal entry storing value and its precomputed weight.
///
/// Weight is computed once on insert/update to avoid repeated weight
/// function calls during reads or accounting operations.
/// Metrics counters using atomics for thread-safe updates.
///
/// All counters use `Ordering::Relaxed` for low-overhead increments.
// =============================================================================
// Single-threaded WeightStore
// =============================================================================
/// Single-threaded store with dual entry-count and weight-based capacity limits.
///
/// Enforces both a maximum number of entries and a maximum total weight.
/// Weight is computed via a caller-provided function and cached per entry.
/// Uses `Arc<V>` for values to enable weight function access.
///
/// # Type Parameters
///
/// - `K`: Key type, must be `Eq + Hash`
/// - `V`: Value type, wrapped in `Arc<V>`
/// - `F`: Weight function, `Fn(&V) -> usize`
///
/// # Example
///
/// ```
/// use std::sync::Arc;
/// use cachekit::store::weight::WeightStore;
///
/// // Image cache: max 50 images OR 100MB, whichever is hit first
/// let mut store = WeightStore::with_capacity(
/// 50, // max entries
/// 100_000_000, // max weight (100MB)
/// |img: &Vec<u8>| img.len(), // weight = byte length
/// );
///
/// // Insert images
/// let small_img = Arc::new(vec![0u8; 1_000]); // 1KB
/// let large_img = Arc::new(vec![0u8; 10_000_000]); // 10MB
///
/// store.try_insert("thumbnail", small_img).unwrap();
/// store.try_insert("fullsize", large_img).unwrap();
///
/// assert_eq!(store.len(), 2);
/// assert_eq!(store.total_weight(), 10_001_000);
/// assert_eq!(store.capacity_weight(), 100_000_000);
///
/// // Check metrics
/// let _ = store.get(&"thumbnail");
/// let _ = store.get(&"missing");
/// assert_eq!(store.metrics().hits, 1);
/// assert_eq!(store.metrics().misses, 1);
/// ```
///
/// # Weight Function Examples
///
/// ```
/// use std::sync::Arc;
/// use cachekit::store::weight::WeightStore;
///
/// // String length
/// let mut s1: WeightStore<&str, String, _> =
/// WeightStore::with_capacity(100, 10_000, |s: &String| s.len());
///
/// // Fixed weight (degrades to entry-count only)
/// let mut s2: WeightStore<&str, i32, _> =
/// WeightStore::with_capacity(100, 100, |_: &i32| 1);
///
/// // Struct with custom size calculation
/// struct Document { content: String, metadata: Vec<u8> }
/// let mut s3: WeightStore<&str, Document, _> = WeightStore::with_capacity(
/// 100, 1_000_000,
/// |doc: &Document| doc.content.len() + doc.metadata.len()
/// );
/// ```
,
// =============================================================================
// Concurrent WeightStore
// =============================================================================
/// Thread-safe store with dual entry-count and weight-based capacity limits.
///
/// Wraps [`WeightStore`] with a `parking_lot::RwLock` for thread-safe access.
/// Implements [`ConcurrentStore`] and [`ConcurrentStoreRead`] traits.
///
/// # Type Parameters
///
/// - `K`: Key type, must be `Eq + Hash + Send + Sync`
/// - `V`: Value type, must be `Send + Sync`
/// - `F`: Weight function, must be `Fn(&V) -> usize + Send + Sync`
///
/// # Example
///
/// ```
/// use std::sync::Arc;
/// use std::thread;
/// use cachekit::store::weight::ConcurrentWeightStore;
/// use cachekit::store::traits::{ConcurrentStore, ConcurrentStoreRead};
///
/// let store = Arc::new(ConcurrentWeightStore::with_capacity(
/// 100, // max entries
/// 1_000_000, // max weight (1MB)
/// |data: &Vec<u8>| data.len(),
/// ));
///
/// // Spawn 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);
/// let data = Arc::new(vec![0u8; 100]); // 100 bytes each
/// let _ = store.try_insert(key, data);
/// }
/// })
/// }).collect();
///
/// for h in handles {
/// h.join().unwrap();
/// }
///
/// assert_eq!(store.len(), 100);
/// assert_eq!(store.total_weight(), 10_000); // 100 entries × 100 bytes
/// ```
,
/// Read operations for [`ConcurrentWeightStore`].
///
/// All methods acquire a read lock on the inner store.
/// Write operations for [`ConcurrentWeightStore`].
///
/// All methods acquire a write lock on the inner store.
// =============================================================================
// Tests
// =============================================================================