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
use OnceLock;
use AtomicU64;
use crate;
/// Cache-line size used for padding. Covers both x86_64 (64 B + Intel adjacent-line prefetch)
/// and Apple Silicon (128 B L1 line). Matches the `repr(align)` on `CachePadded`.
/// Note: `#[repr(align(…))]` only accepts integer literals, so this constant cannot be used
/// directly in the attribute — the literal `128` in `CachePadded` must match it by hand.
pub const CACHE_LINE: usize = 128;
const _: = assert!;
/// Aligns its payload to a cache line so adjacent elements in a slice
/// can't false-share. Same pattern as `crossbeam_utils::CachePadded`;
/// rolled here to avoid a new dependency.
pub ;
/// Per-shard state. Plain struct — alignment is the caller's responsibility
/// (in practice always `CachePadded<Shard<S>>`). The lock word and the
/// hit/miss counters intentionally share a cache line: they are touched by
/// the same op (a `cache_get` acquires the lock and then bumps a counter),
/// so spatial locality is a win. Counters use `Relaxed` atomics; on stores
/// that allow concurrent readers (read-lock paths), increments can race —
/// this is intentional, trading exactness for lower overhead.
pub
/// The default shard count: `available_parallelism() * 4`, clamped to `[8, 1024]` and rounded
/// up to a power of two.
///
/// The host CPU topology is sampled exactly once per process (memoized in a `OnceLock`) on the
/// first call, then reused for every cache built afterward. A later change to the effective CPU
/// count -- for example a cgroup/container CPU-quota adjustment made after the first sample --
/// does not affect the shard count of subsequently built caches; they all see the value latched
/// at first call.
pub
/// Default shard count for the *default* (unconfigured) shard-count path, scaled down for
/// small `max_size` values.
///
/// Without this, the default shard count is `available_parallelism() * 4` clamped to
/// `[8, 1024]`, with no reference to `max_size` at all. Combined with the 16-entries-per-shard
/// floor in [`per_shard_cap_from_total`] and eager per-shard allocation, `ShardedLruCache::new(100)`
/// on a 64-core box would build 256 shards x 16 = 4096 effective capacity, preallocating 256
/// hash tables plus 256 `Vec`s for a cache asked to hold only 100 entries.
///
/// This helper caps the shard count itself to roughly `max_size / 16` (rounded up to a power
/// of two), never exceeding [`default_shard_count`] and never going below 1, so that a bounded
/// cache ends up with each shard holding roughly 16 entries rather than 16 entries times an
/// oversized shard count.
///
/// An explicit `.shards(n)` on a builder remains authoritative; this helper is only consulted
/// on the *default* (no explicit shard count given) path.
pub
/// Compute the per-shard capacity for a given total and shard count, applying the
/// same policy as the sharded LRU builders: ceiling division (`div_ceil`) with a
/// minimum of 16 per shard when `n_shards > 1`.
///
/// Returns `(per_shard_cap, total_cap)`, where `total_cap = n_shards * per_shard_cap`.
/// The `total_cap` may exceed `total` when the 16-per-shard floor is in effect.
///
/// Returns [`SetMaxSizeError::CapacityOverflow`] when `n_shards * per_shard_cap` does not fit
/// in a `usize`. That happens for a `total` close to `usize::MAX` on a multi-shard cache:
/// `div_ceil` rounds the per-shard share up, and multiplying the rounded share back by
/// `n_shards` then exceeds `usize::MAX`. It is the fallible entry point behind
/// `try_set_max_size`, which must not panic.
pub
/// Compute the per-shard capacity for a given total and shard count, applying the
/// same policy as the sharded LRU builders: ceiling division (`div_ceil`) with a
/// minimum of 16 per shard when `n_shards > 1`.
///
/// Returns `(per_shard_cap, total_cap)`, where `total_cap = n_shards * per_shard_cap`.
/// The `total_cap` may exceed `total` when the 16-per-shard floor is in effect.
///
/// # Panics
///
/// Panics if `n_shards * per_shard_cap` overflows `usize`. Callers that must not panic go
/// through [`checked_per_shard_cap_from_total`] instead.
///
/// Every caller of this function is a sharded store's `set_max_size`, so the panic message names
/// that public operation, the `max_size` it was handed and the shard count it could not be split
/// across -- not this `pub(crate)` helper, which a caller reading the panic has no way to look up.
/// It reads alongside the zero-`max_size` assertion those same methods carry
/// (`max_size must be greater than zero`).
pub
pub
pub
/// The one hash construction every [`BuildHasher`](std::hash::BuildHasher)-backed shard-routing
/// path uses, for both owned and borrowed keys.
///
/// It is not every routing path: a hand-written [`ShardHasher`] routes through its own
/// `shard_hash` bodies and never reaches this function. Such a router keeps owned and borrowed
/// routing in agreement by satisfying the cross-impl contract documented on [`ShardHasher`],
/// which the compiler cannot check. What follows applies to hashers that reach `ShardHasher`
/// through the blanket `BuildHasher` impl, which is every default-path store.
///
/// Owned routing (the blanket [`ShardHasher`] impl) and borrowed routing (`shard_of_borrowed` on
/// each sharded store) must produce the same value for keys that compare equal, or an entry
/// becomes unreachable through the form it was not inserted with. Routing them through a single
/// function is what makes that hold: the two paths cannot drift, because there is only one path.
///
/// The guarantee is not limited to *selecting* the shard. Once inside the shard, the store still
/// has to probe its own map, and that probe needs to agree with routing for the same reason
/// -- a `HashMap::get` that hashes a borrowed key differently from how the owned key was routed
/// and inserted would defeat the point of matching shards. Two separate mechanisms hold that
/// line, one per shard payload, and both are load-bearing:
///
/// * `ShardedUnboundCache`, `ShardedTtlCache` and `ShardedExpiringCache` hold a `HashMap` whose
/// own hash builder is [`DefaultShardHasher`], so the intra-shard probe goes through this
/// exact construction too, not through a second, independently-specializing
/// `BuildHasher::hash_one` call.
/// * `ShardedLruCache`, `ShardedLruTtlCache` and `ShardedExpiringLruCache` hold a
/// [`LruCache`](crate::LruCache), whose hash builder is
/// [`DefaultHashBuilder`](crate::DefaultHashBuilder), a different type. They are safe because
/// `LruCache::hash` (`src/stores/lru.rs`) hand-builds its `Hasher` exactly the way this
/// function does instead of calling `hash_one`. Rewriting that body into `hash_one` (the same
/// cleanup clippy's `manual_hash_one` lint asks for here, hence the `allow` below)
/// reintroduces the misroute on nightly for these three stores; the note on `LruCache::hash`
/// says so at the site.
///
/// Deliberately not [`BuildHasher::hash_one`](std::hash::BuildHasher::hash_one). That is an
/// overridable provided method whose implementation may dispatch on its static type argument, so
/// `hash_one::<&K>` and `hash_one::<&Q>` are not required to agree even when the two values hash
/// identically. `ahash::RandomState` does dispatch that way, through a `CallHasher` table with
/// specialized impls for some reference types (`&u8`..`&i64`, `&u128`/`&i128`/`&usize`/`&isize`)
/// and not others (`&str`, `&String`, `&[u8]`, `&Vec<u8>`), active whenever its `specialize` cfg
/// is on (any nightly compiler). A newtype key such as `struct UserId(u64)` with `Borrow<u64>`
/// would then route its owned inserts and its borrowed lookups to different shards. Building the
/// `Hasher` explicitly depends only on the `Hash` impl, which the `Borrow` contract already
/// requires to agree.
// `manual_hash_one` fires on exactly the construction this function exists to guarantee.
pub
/// Encode a TTL into a nanosecond atomic. A zero duration encodes as `0`
/// (expiry disabled / no expiry).
pub
/// Decode the nanosecond atomic into an optional TTL. `0` means expiry is
/// disabled (entries never expire), so it decodes to `None`.
pub
/// Trait for types that deterministically map a key to a `u64` shard hash.
///
/// No `K: Hash` bound on the trait itself, so custom impls can partition by arbitrary logic
/// (numeric range, string prefix, tenant id). That relaxation is about the routing logic only:
/// every sharded store's own `impl` block still requires `K: Hash + Eq` (plus `K: Clone` on the
/// three LRU-bounded stores), so a non-`Hash` key type remains unusable no matter what the
/// router does.
///
/// # Any `BuildHasher` is a `ShardHasher`
///
/// A blanket impl covers every [`std::hash::BuildHasher`] that is `Clone + Send + Sync +
/// 'static`, for every `K: Hash + ?Sized` (unsized key types such as `str` and `[u8]`
/// included), hashing the key explicitly: build a
/// [`Hasher`](std::hash::Hasher) with
/// [`build_hasher`](std::hash::BuildHasher::build_hasher), feed the key to it with
/// [`Hash::hash`](std::hash::Hash::hash), then [`finish`](std::hash::Hasher::finish) it. The same
/// hasher value therefore works on both cache families: what
/// [`LruCacheBuilder::hasher`](crate::LruCacheBuilder::hasher) accepts,
/// [`ShardedLruCacheBuilder::hasher`](crate::ShardedLruCacheBuilder::hasher) and its five
/// siblings accept too.
///
/// ```rust
/// use cached::ShardedLruCache;
/// use std::hash::RandomState;
///
/// let cache = ShardedLruCache::<u64, u64>::builder()
/// .max_size(1024)
/// .hasher(RandomState::new())
/// .build()
/// .unwrap();
/// ```
///
/// [`DefaultShardHasher`] itself implements `BuildHasher` and reaches `ShardHasher` through
/// this blanket impl, so it is equally usable as the hash builder of a non-sharded store.
///
/// Coherence makes the blanket impl exclusive: a type that implements `BuildHasher` cannot also
/// carry a hand-written `ShardHasher` impl (that is a duplicate-impl error). Custom shard
/// routing (numeric range, string prefix, tenant id) therefore belongs on a type that does
/// **not** implement `BuildHasher`.
///
/// # A hand-written impl keeps the inherent lookups
///
/// A hand-written `ShardHasher` is the supported way to control shard routing, and it costs
/// nothing on the owned-key path. The six inherent lookups on every sharded store (`get`,
/// `remove`, `remove_entry`, `delete`, `contains`, `peek`) take a `&Q where K: Borrow<Q>` and
/// are bounded on `H: ShardHasher<Q>`. At `Q = K` that bound is exactly the one the store
/// already carries, so a router implementing `ShardHasher<K>` keeps all six: `cache.get(&key)`
/// compiles and routes through the custom `shard_hash`; no `.unwrap()`-returning trait call is
/// needed to reach it.
///
/// Borrowed keys stop at those six. Everything else on the sharded surface still takes `&K`:
/// the trait methods (`ConcurrentCached::cache_get` and friends, `ConcurrentCachedExt::get`) and
/// the expiry accessors (`peek_expires_at`, `expires_at`). A `String`-keyed store is looked up by
/// `&str` through `get`/`peek`/`contains`/`remove`/`remove_entry`/`delete` and by `&String`
/// everywhere else.
///
/// Borrowed-key lookups are the opt-in part. `cache.get(&q)` for some `Q` other than `K` needs
/// a *second* impl, `ShardHasher<Q>`, on the same router; without it that one call site does not
/// compile while the owned-key ones still do. Each impl a router adds is one more key type the
/// store can be looked up by, and coherence permits the whole set because a hand-written router
/// is deliberately not a `BuildHasher`.
///
/// Read the error for that missing second impl carefully. What decides the diagnostic is how many
/// `ShardHasher` bounds are in scope for `Q` to resolve to, not whether the hasher is a concrete
/// router or a type parameter: when there is exactly one, inference resolves `Q` to it and rustc
/// reports a type mismatch rather than an unsatisfied bound. Two shapes hit this.
///
/// * A concrete router carrying exactly one `ShardHasher<K>` impl: `cache.get(&7u64)` reports
/// `expected &UserId, found &u64` at the argument, not "`TenantRouter: ShardHasher<u64>` is not
/// satisfied". The fix is to add `impl ShardHasher<u64> for TenantRouter`.
/// * A generic helper bounded only on the store's own hasher bound, which is the likelier way to
/// meet this: `fn lookup<H: ShardHasher<String>>(c: &ShardedUnboundCache<String, u32, H>) ->
/// Option<u32> { c.get("a") }` has one `ShardHasher` bound in scope, so `Q` collapses to
/// `String` before any bound is checked and the call reports `expected &String, found &str` --
/// again a type mismatch, saying nothing about a missing `ShardHasher<str>`. The fix is to add
/// the borrowed form to the helper's bounds, `H: ShardHasher<String> + ShardHasher<str>`, in
/// addition to (not instead of) the store's own bound.
///
/// Give `Q` more than one candidate and the collapse stops: a router with two or more impls, or a
/// helper with two or more `ShardHasher` bounds, fails on the third key type as a genuine
/// unsatisfied bound with the `ShardHasher` diagnostic notes attached.
///
/// ```rust
/// use cached::{ShardHasher, ShardedUnboundCache};
/// use std::borrow::Borrow;
///
/// #[derive(Hash, PartialEq, Eq)]
/// struct UserId(u64);
///
/// impl Borrow<u64> for UserId {
/// fn borrow(&self) -> &u64 {
/// &self.0
/// }
/// }
///
/// /// A random seed sampled once per process. Without it the routing is a published
/// /// function of the key and an attacker who picks the keys can put them all on one
/// /// shard; see the unkeyed-router warning below.
/// fn shard_seed() -> u64 {
/// use std::hash::{BuildHasher, Hasher};
/// static SEED: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
/// *SEED.get_or_init(|| std::hash::RandomState::new().build_hasher().finish())
/// }
///
/// /// Deliberately not a `BuildHasher`: routing, not hashing, is the point.
/// #[derive(Clone)]
/// struct TenantRouter;
///
/// impl TenantRouter {
/// /// The one routing body both impls call, so they cannot disagree.
/// fn route(&self, raw: u64) -> u64 {
/// (raw ^ shard_seed()).wrapping_mul(0x9e3779b97f4a7c15)
/// }
/// }
///
/// impl ShardHasher<UserId> for TenantRouter {
/// fn shard_hash(&self, key: &UserId) -> u64 {
/// self.route(key.0)
/// }
/// }
///
/// // The opt-in second impl. It agrees with the first on keys that compare equal, which is
/// // the contract described below.
/// impl ShardHasher<u64> for TenantRouter {
/// fn shard_hash(&self, key: &u64) -> u64 {
/// self.route(*key)
/// }
/// }
///
/// let cache = ShardedUnboundCache::<UserId, u64>::builder()
/// .hasher(TenantRouter)
/// .build()
/// .unwrap();
/// cache.set(UserId(7), 70);
///
/// // Owned key: the inherent method, resolved through `ShardHasher<UserId>`.
/// assert_eq!(cache.get(&UserId(7)), Some(70));
/// // Borrowed key: the same entry, resolved through `ShardHasher<u64>`.
/// assert_eq!(cache.get(&7u64), Some(70));
/// ```
///
/// If shard routing is not the point and only the hash function is, pass a `BuildHasher`
/// (for example `std::hash::RandomState` or `ahash::RandomState`) to the builder's `hasher`
/// instead: the blanket impl covers every key type at once, so no per-`Q` impl is ever needed.
///
/// # Contract: a router's impls must agree with each other
///
/// If a type implements `ShardHasher` for more than one key type, all of those impls must agree
/// on keys that compare equal. Concretely, for `K: Borrow<Q>`, `shard_hash(&k)` must return the
/// same value as `shard_hash(k.borrow())`.
///
/// Violating this routes an owned insert and an equivalent borrowed lookup to different shards:
/// `get`/`peek`/`contains` report a miss on an entry the cache still holds, and
/// `remove`/`delete` silently no-op instead of removing it. There is no panic and no error, only
/// a cache that appears to lose entries it has. Only `get` bumps the `misses` counter while it
/// does so; `peek` and `contains` are peek-based and touch no counters at all, so
/// `metrics().misses` staying flat under those two probes is not evidence that routing agrees. This is the same species of
/// requirement as [`Borrow`](std::borrow::Borrow)'s own -- that equal keys hash equally -- and
/// the compiler cannot check either one.
///
/// Types reaching `ShardHasher` through the blanket [`BuildHasher`](std::hash::BuildHasher)
/// impl satisfy the contract automatically: one impl covers every key type, its body depends
/// only on the key's [`Hash`](std::hash::Hash) impl, and the `Borrow` contract already requires
/// those to agree. Only a router that hand-writes two or more impls can break it.
///
/// A guard test pins the property for one specific router. Substitute your own router, key type
/// and borrowed form, and paste the whole `#[test]` into your own test suite. Keep both halves:
/// the `assert_eq!` loop alone passes for a router whose impls both return a constant, which
/// agrees with itself while routing every key to shard 0, so the `assert_ne!` is what separates
/// "agrees" from "does nothing".
///
/// ```rust,test_harness
/// use cached::ShardHasher;
/// use std::borrow::Borrow;
///
/// #[derive(Hash, PartialEq, Eq)]
/// struct UserId(u64);
///
/// impl Borrow<u64> for UserId {
/// fn borrow(&self) -> &u64 {
/// &self.0
/// }
/// }
///
/// /// A random seed sampled once per process; see the unkeyed-router warning below.
/// fn shard_seed() -> u64 {
/// use std::hash::{BuildHasher, Hasher};
/// static SEED: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
/// *SEED.get_or_init(|| std::hash::RandomState::new().build_hasher().finish())
/// }
///
/// #[derive(Clone)]
/// struct TenantRouter;
///
/// impl TenantRouter {
/// fn route(&self, raw: u64) -> u64 {
/// (raw ^ shard_seed()).wrapping_mul(0x9e3779b97f4a7c15)
/// }
/// }
///
/// impl ShardHasher<UserId> for TenantRouter {
/// fn shard_hash(&self, key: &UserId) -> u64 {
/// self.route(key.0)
/// }
/// }
///
/// impl ShardHasher<u64> for TenantRouter {
/// fn shard_hash(&self, key: &u64) -> u64 {
/// self.route(*key)
/// }
/// }
///
/// #[test]
/// fn owned_and_borrowed_route_together() {
/// let router = TenantRouter;
/// // Every owned key must route exactly where its borrowed form routes.
/// for raw in [0u64, 1, 7, 0x9e37_79b9, u64::MAX] {
/// let owned = UserId(raw);
/// let borrowed: &u64 = owned.borrow();
/// assert_eq!(
/// ShardHasher::<UserId>::shard_hash(&router, &owned),
/// ShardHasher::<u64>::shard_hash(&router, borrowed),
/// "shard_hash disagrees between UserId({raw}) and its borrowed u64"
/// );
/// }
/// // And keys that are not equal must not all collapse onto one shard.
/// assert_ne!(
/// ShardHasher::<UserId>::shard_hash(&router, &UserId(7)),
/// ShardHasher::<u64>::shard_hash(&router, &8u64)
/// );
/// }
/// ```
///
/// # Shard selection
///
/// The shard index is derived from the upper 32 bits of the returned hash:
/// `(hash >> 32) & shard_mask`. [`DefaultShardHasher`] (ahash when the `ahash`
/// feature is enabled, otherwise std `RandomState`) produces high-quality bits
/// in both halves. Custom implementations should ensure the
/// **upper** 32 bits are well-distributed across keys, not just the lower bits.
///
/// The two hashers reached through the blanket impl that this crate builds on both satisfy
/// that contract: `std::hash::RandomState` finishes a SipHash-1-3 state, and
/// `ahash::RandomState` finishes an aHash state; both diffuse key entropy across
/// all 64 bits, so the upper half is as well-distributed as the lower half. Reaching
/// `ShardHasher` through `BuildHasher` is **not** by itself a guarantee, though: the warning
/// below applies unchanged to a hand-written `BuildHasher` whose `finish` leaves the high bits
/// constant (a `Hasher` accumulating into a `u32` widened to `u64`, for instance).
///
/// # Warning: zero upper bits route everything to shard 0
///
/// If `shard_hash` returns a value whose upper 32 bits are always zero, every key
/// will land on shard 0, defeating the purpose of sharding entirely. A common
/// mistake is returning a bare integer identity:
///
/// ```rust
/// use cached::ShardHasher;
///
/// // BAD -- `key as u64` for small integer keys leaves bits 32-63 all zero.
/// // All entries land on shard 0 regardless of the configured shard count.
/// #[derive(Clone)]
/// struct IdentityHasher;
/// impl ShardHasher<u32> for IdentityHasher {
/// fn shard_hash(&self, key: &u32) -> u64 {
/// *key as u64 // upper 32 bits are always 0!
/// }
/// }
/// ```
///
/// Always mix or multiply the value so entropy is spread into the upper 32 bits.
///
/// # Warning: an unkeyed router is invertible
///
/// A router whose body is a fixed expression of the key (`key.wrapping_mul(CONST)`, a bare
/// multiply-shift, a prefix table) is a published function: the constant, the `>> 32` and the
/// shard mask are all in this documentation. An attacker who influences the keys (a tenant id
/// from a header, a request path, a user-supplied id) can solve offline for keys that all land
/// on one shard. The result is not a wrong answer but a collapse: every request serializes on
/// that shard's `RwLock` (a write lock even for reads, on the three LRU-bounded stores), and on
/// a bounded store the usable capacity drops to `max_size / shards` because the other shards
/// stay empty.
///
/// Mix in a random seed sampled once per process, as the examples above do:
///
/// ```rust
/// use std::hash::{BuildHasher, Hasher};
/// use std::sync::OnceLock;
///
/// fn shard_seed() -> u64 {
/// static SEED: OnceLock<u64> = OnceLock::new();
/// *SEED.get_or_init(|| std::hash::RandomState::new().build_hasher().finish())
/// }
///
/// // Keyed: the same multiply, over a value the attacker cannot predict.
/// fn route(raw: u64) -> u64 {
/// (raw ^ shard_seed()).wrapping_mul(0x9e3779b97f4a7c15)
/// }
/// # assert_ne!(route(7), route(8));
/// ```
///
/// The seed has to be shared by every impl on the router (route through one private helper, as
/// above) or the impls disagree and the cross-impl contract breaks. This warning does not apply
/// to the default path: [`DefaultShardHasher`] is randomly seeded per instance already, as is
/// any `BuildHasher` reaching `ShardHasher` through the blanket impl that seeds itself
/// (`std::hash::RandomState::new`, `ahash::RandomState::new`).
///
/// # Example
///
/// ```rust
/// use cached::ShardHasher;
///
/// /// Distributes `u64` keys using Fibonacci hashing (`key * 2^64/φ`).
/// /// Ensures the upper 32 bits (used for shard selection) are well-distributed.
/// ///
/// /// Unkeyed, so this is for keys you choose yourself. On attacker-influenced keys, xor in a
/// /// per-process random seed first (see the unkeyed-router warning above).
/// #[derive(Clone)]
/// struct FibHasher;
/// impl ShardHasher<u64> for FibHasher {
/// fn shard_hash(&self, key: &u64) -> u64 {
/// key.wrapping_mul(0x9e3779b97f4a7c15)
/// }
/// }
/// ```
///
/// The `'static` bound is required because the hasher is stored inside `Arc<Inner>`,
/// and the `Arc` is cloned across threads — a borrowed or lifetime-parameterized hasher
/// would prevent the cache from being `'static` and therefore from being shared via
/// `thread::spawn` or stored in a `static`.
/// Every thread-safe [`BuildHasher`](std::hash::BuildHasher) routes keys by feeding the key to a
/// freshly built [`Hasher`](std::hash::Hasher) and finishing it.
///
/// This is what lets a single hasher value be handed to both the single-owner builders
/// (`S: BuildHasher`) and the sharded builders (`H: ShardHasher<K>`). It also means the two
/// trait sets are no longer independent: implementing `BuildHasher` on a type commits it to
/// this shard-routing behavior, since coherence rejects a second, hand-written `ShardHasher`
/// impl for the same type.
///
/// Routing builds a [`Hasher`](std::hash::Hasher) with
/// [`build_hasher`](std::hash::BuildHasher::build_hasher), feeds the key to it with
/// [`Hash::hash`](std::hash::Hash::hash), then [`finish`](std::hash::Hasher::finish)s it. Each
/// store's `shard_of_borrowed` reaches a borrowed key's shard by calling `shard_hash` itself, so
/// for a `BuildHasher` the owned and borrowed paths are not merely the same construction, they
/// are the same call, and an owned key and a borrowed key that compare equal cannot land on
/// different shards. This is deliberately not
/// [`BuildHasher::hash_one`](std::hash::BuildHasher::hash_one): that is an overridable
/// provided method whose implementation may dispatch on its static type argument (`ahash`'s does,
/// under nightly's `specialize` cfg), so `hash_one::<&K>` and `hash_one::<&Q>` are not required to
/// agree even when the two values hash identically. Building the `Hasher` explicitly depends only
/// on the `Hash` impl, which the `Borrow` contract already requires to agree.
///
/// The key parameter is `?Sized`, so unsized keys are covered too: a `String`-keyed store routes
/// a `&str` lookup through `ShardHasher<str>` on the very same hasher value.
/// Default shard hasher backed by `ahash::RandomState` (or `std::collections::hash_map::RandomState`
/// when the `ahash` feature is disabled).
///
/// It implements [`BuildHasher`](std::hash::BuildHasher) and picks up
/// [`ShardHasher<K>`] for every `K: Hash + ?Sized` through the blanket impl above, so it is also a valid
/// hash builder for the non-sharded stores and for a plain
/// [`HashMap`](std::collections::HashMap).
] RandomState,
RandomState,
);
/// `DefaultShardHasher` deliberately does not override
/// [`hash_one`](std::hash::BuildHasher::hash_one), so `hash_one` here is the provided body:
/// build a [`Hasher`](std::hash::Hasher), feed the key to it, finish it -- the same construction
/// shard routing uses.
///
/// That matters because `hash_one` may dispatch on its static type argument, and
/// `ahash::RandomState`'s does under nightly's `specialize` cfg: it specializes some reference
/// types (`&u8`..`&i64`, `&u128`/`&i128`/`&usize`/`&isize`) and not others (`&str`, `&String`,
/// `&[u8]`), so `hash_one::<&K>` and `hash_one::<&Q>` are not required to agree even when the two
/// values hash identically. Forwarding this type's `hash_one` to its inner hasher for that
/// specialized path would route a newtype key such as `struct UserId(u64)` with `Borrow<u64>` to
/// one shard on its owned inserts and to another on its borrowed lookups, on any nightly
/// compiler, with no panic and no error.
// Do not override `hash_one` here, however tempting the inner `ahash::RandomState`'s specialized
// path is. `default_shard_hasher_routes_through_build_hasher` in this module's tests asserts
// `shard_hash == hash_one`, but it does NOT pin this on stable: ahash gates its own `hash_one`
// override on `#[cfg(specialize)]`, which is only ever on under nightly, so on stable 1.96 a
// re-added override here would forward to a body identical to the provided one and that assertion
// would still pass. The `nightly-routing` CI job (`.github/workflows/build.yml`) is where the
// hazard actually fires: it runs `cargo test --lib` plus the design-0055 routing suites under a
// toolchain where `specialize` is on.
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;