forked from moka-rs/moka
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathentry_selector.rs
586 lines (568 loc) · 20.7 KB
/
entry_selector.rs
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
use crate::Entry;
use super::Cache;
use std::{
borrow::Borrow,
hash::{BuildHasher, Hash},
sync::Arc,
};
/// Provides advanced methods to select or insert an entry of the cache.
///
/// Many methods here return an [`Entry`], a snapshot of a single key-value pair in
/// the cache, carrying additional information like `is_fresh`.
///
/// `OwnedKeyEntrySelector` is constructed from the [`entry`][entry-method] method on
/// the cache.
///
/// [`Entry`]: ../struct.Entry.html
/// [entry-method]: ./struct.Cache.html#method.entry
pub struct OwnedKeyEntrySelector<'a, K, V, S> {
owned_key: K,
hash: u64,
cache: &'a Cache<K, V, S>,
}
impl<'a, K, V, S> OwnedKeyEntrySelector<'a, K, V, S>
where
K: Hash + Eq + Send + Sync + 'static,
V: Clone + Send + Sync + 'static,
S: BuildHasher + Clone + Send + Sync + 'static,
{
pub(crate) fn new(owned_key: K, hash: u64, cache: &'a Cache<K, V, S>) -> Self {
Self {
owned_key,
hash,
cache,
}
}
/// Returns the corresponding [`Entry`] for the key given when this entry
/// selector was constructed. If the entry does not exist, inserts one by calling
/// the [`default`][std-default-function] function of the value type `V`.
///
/// [`Entry`]: ../struct.Entry.html
/// [std-default-function]: https://doc.rust-lang.org/stable/std/default/trait.Default.html#tymethod.default
///
/// # Example
///
/// ```rust
/// use moka::sync::Cache;
///
/// let cache: Cache<String, Option<u32>> = Cache::new(100);
/// let key = "key1".to_string();
///
/// let entry = cache.entry(key.clone()).or_default();
/// assert!(entry.is_fresh());
/// assert_eq!(entry.key(), &key);
/// assert_eq!(entry.into_value(), None);
///
/// let entry = cache.entry(key).or_default();
/// // Not fresh because the value was already in the cache.
/// assert!(!entry.is_fresh());
/// ```
pub fn or_default(self) -> Entry<K, V>
where
V: Default,
{
let key = Arc::new(self.owned_key);
self.cache
.get_or_insert_with_hash(key, self.hash, Default::default)
}
/// Returns the corresponding [`Entry`] for the key given when this entry
/// selector was constructed. If the entry does not exist, inserts one by using
/// the the given `default` value for `V`.
///
/// [`Entry`]: ../struct.Entry.html
///
/// # Example
///
/// ```rust
/// use moka::sync::Cache;
///
/// let cache: Cache<String, u32> = Cache::new(100);
/// let key = "key1".to_string();
///
/// let entry = cache.entry(key.clone()).or_insert(3);
/// assert!(entry.is_fresh());
/// assert_eq!(entry.key(), &key);
/// assert_eq!(entry.into_value(), 3);
///
/// let entry = cache.entry(key).or_insert(6);
/// // Not fresh because the value was already in the cache.
/// assert!(!entry.is_fresh());
/// assert_eq!(entry.into_value(), 3);
/// ```
pub fn or_insert(self, default: V) -> Entry<K, V> {
let key = Arc::new(self.owned_key);
let init = || default;
self.cache.get_or_insert_with_hash(key, self.hash, init)
}
/// Returns the corresponding [`Entry`] for the key given when this entry
/// selector was constructed. If the entry does not exist, evaluates the `init`
/// closure and inserts the output.
///
/// [`Entry`]: ../struct.Entry.html
///
/// # Example
///
/// ```rust
/// use moka::sync::Cache;
///
/// let cache: Cache<String, String> = Cache::new(100);
/// let key = "key1".to_string();
///
/// let entry = cache
/// .entry(key.clone())
/// .or_insert_with(|| "value1".to_string());
/// assert!(entry.is_fresh());
/// assert_eq!(entry.key(), &key);
/// assert_eq!(entry.into_value(), "value1");
///
/// let entry = cache
/// .entry(key)
/// .or_insert_with(|| "value2".to_string());
/// // Not fresh because the value was already in the cache.
/// assert!(!entry.is_fresh());
/// assert_eq!(entry.into_value(), "value1");
/// ```
///
/// # Concurrent calls on the same key
///
/// This method guarantees that concurrent calls on the same not-existing entry
/// are coalesced into one evaluation of the `init` closure. Only one of the
/// calls evaluates its closure (thus returned entry's `is_fresh` method returns
/// `true`), and other calls wait for that closure to complete (and their
/// `is_fresh` return `false`).
///
/// For more detail about the coalescing behavior, see
/// [`Cache::get_with`][get-with-method].
///
/// [get-with-method]: ./struct.Cache.html#method.get_with
pub fn or_insert_with(self, init: impl FnOnce() -> V) -> Entry<K, V> {
let key = Arc::new(self.owned_key);
let replace_if = None as Option<fn(&V) -> bool>;
self.cache
.get_or_insert_with_hash_and_fun(key, self.hash, init, replace_if, true)
}
/// Works like [`or_insert_with`](#method.or_insert_with), but takes an additional
/// `replace_if` closure.
///
/// This method will evaluate the `init` closure and insert the output to the
/// cache when:
///
/// - The key does not exist.
/// - Or, `replace_if` closure returns `true`.
pub fn or_insert_with_if(
self,
init: impl FnOnce() -> V,
replace_if: impl FnMut(&V) -> bool,
) -> Entry<K, V> {
let key = Arc::new(self.owned_key);
self.cache
.get_or_insert_with_hash_and_fun(key, self.hash, init, Some(replace_if), true)
}
/// Returns the corresponding [`Entry`] for the key given when this entry
/// selector was constructed. If the entry does not exist, evaluates the `init`
/// closure, and inserts an entry if `Some(value)` was returned. If `None` was
/// returned from the closure, this method does not insert an entry and returns
/// `None`.
///
/// [`Entry`]: ../struct.Entry.html
///
/// # Example
///
/// ```rust
/// use moka::sync::Cache;
///
/// let cache: Cache<String, u32> = Cache::new(100);
/// let key = "key1".to_string();
///
/// let none_entry = cache
/// .entry(key.clone())
/// .or_optionally_insert_with(|| None);
/// assert!(none_entry.is_none());
///
/// let some_entry = cache
/// .entry(key.clone())
/// .or_optionally_insert_with(|| Some(3));
/// assert!(some_entry.is_some());
/// let entry = some_entry.unwrap();
/// assert!(entry.is_fresh());
/// assert_eq!(entry.key(), &key);
/// assert_eq!(entry.into_value(), 3);
///
/// let some_entry = cache
/// .entry(key)
/// .or_optionally_insert_with(|| Some(6));
/// let entry = some_entry.unwrap();
/// // Not fresh because the value was already in the cache.
/// assert!(!entry.is_fresh());
/// assert_eq!(entry.into_value(), 3);
/// ```
///
/// # Concurrent calls on the same key
///
/// This method guarantees that concurrent calls on the same not-existing entry
/// are coalesced into one evaluation of the `init` closure. Only one of the
/// calls evaluates its closure (thus returned entry's `is_fresh` method returns
/// `true`), and other calls wait for that closure to complete (and their
/// `is_fresh` return `false`).
///
/// For more detail about the coalescing behavior, see
/// [`Cache::optionally_get_with`][opt-get-with-method].
///
/// [opt-get-with-method]: ./struct.Cache.html#method.optionally_get_with
pub fn or_optionally_insert_with(
self,
init: impl FnOnce() -> Option<V>,
) -> Option<Entry<K, V>> {
let key = Arc::new(self.owned_key);
self.cache
.get_or_optionally_insert_with_hash_and_fun(key, self.hash, init, true)
}
/// Returns the corresponding [`Entry`] for the key given when this entry
/// selector was constructed. If the entry does not exist, evaluates the `init`
/// closure, and inserts an entry if `Ok(value)` was returned. If `Err(_)` was
/// returned from the closure, this method does not insert an entry and returns
/// the `Err` wrapped by [`std::sync::Arc`][std-arc].
///
/// [`Entry`]: ../struct.Entry.html
/// [std-arc]: https://doc.rust-lang.org/stable/std/sync/struct.Arc.html
///
/// # Example
///
/// ```rust
/// use moka::sync::Cache;
///
/// let cache: Cache<String, u32> = Cache::new(100);
/// let key = "key1".to_string();
///
/// let error_entry = cache
/// .entry(key.clone())
/// .or_try_insert_with(|| Err("error"));
/// assert!(error_entry.is_err());
///
/// let ok_entry = cache
/// .entry(key.clone())
/// .or_try_insert_with(|| Ok::<u32, &str>(3));
/// assert!(ok_entry.is_ok());
/// let entry = ok_entry.unwrap();
/// assert!(entry.is_fresh());
/// assert_eq!(entry.key(), &key);
/// assert_eq!(entry.into_value(), 3);
///
/// let ok_entry = cache
/// .entry(key)
/// .or_try_insert_with(|| Ok::<u32, &str>(6));
/// let entry = ok_entry.unwrap();
/// // Not fresh because the value was already in the cache.
/// assert!(!entry.is_fresh());
/// assert_eq!(entry.into_value(), 3);
/// ```
///
/// # Concurrent calls on the same key
///
/// This method guarantees that concurrent calls on the same not-existing entry
/// are coalesced into one evaluation of the `init` closure (as long as these
/// closures return the same error type). Only one of the calls evaluates its
/// closure (thus returned entry's `is_fresh` method returns `true`), and other
/// calls wait for that closure to complete (and their `is_fresh` return
/// `false`).
///
/// For more detail about the coalescing behavior, see
/// [`Cache::try_get_with`][try-get-with-method].
///
/// [try-get-with-method]: ./struct.Cache.html#method.try_get_with
pub fn or_try_insert_with<F, E>(self, init: F) -> Result<Entry<K, V>, Arc<E>>
where
F: FnOnce() -> Result<V, E>,
E: Send + Sync + 'static,
{
let key = Arc::new(self.owned_key);
self.cache
.get_or_try_insert_with_hash_and_fun(key, self.hash, init, true)
}
}
/// Provides advanced methods to select or insert an entry of the cache.
///
/// Many methods here return an [`Entry`], a snapshot of a single key-value pair in
/// the cache, carrying additional information like `is_fresh`.
///
/// `RefKeyEntrySelector` is constructed from the
/// [`entry_by_ref`][entry-by-ref-method] method on the cache.
///
/// [`Entry`]: ../struct.Entry.html
/// [entry-by-ref-method]: ./struct.Cache.html#method.entry_by_ref
pub struct RefKeyEntrySelector<'a, K, Q, V, S>
where
Q: ?Sized,
{
ref_key: &'a Q,
hash: u64,
cache: &'a Cache<K, V, S>,
}
impl<'a, K, Q, V, S> RefKeyEntrySelector<'a, K, Q, V, S>
where
K: Borrow<Q> + Hash + Eq + Send + Sync + 'static,
Q: ToOwned<Owned = K> + Hash + Eq + ?Sized,
V: Clone + Send + Sync + 'static,
S: BuildHasher + Clone + Send + Sync + 'static,
{
pub(crate) fn new(ref_key: &'a Q, hash: u64, cache: &'a Cache<K, V, S>) -> Self {
Self {
ref_key,
hash,
cache,
}
}
/// Returns the corresponding [`Entry`] for the reference of the key given when
/// this entry selector was constructed. If the entry does not exist, inserts one
/// by cloning the key and calling the [`default`][std-default-function] function
/// of the value type `V`.
///
/// [`Entry`]: ../struct.Entry.html
/// [std-default-function]: https://doc.rust-lang.org/stable/std/default/trait.Default.html#tymethod.default
///
/// # Example
///
/// ```rust
/// use moka::sync::Cache;
///
/// let cache: Cache<String, Option<u32>> = Cache::new(100);
/// let key = "key1".to_string();
///
/// let entry = cache.entry_by_ref(&key).or_default();
/// assert!(entry.is_fresh());
/// assert_eq!(entry.key(), &key);
/// assert_eq!(entry.into_value(), None);
///
/// let entry = cache.entry_by_ref(&key).or_default();
/// // Not fresh because the value was already in the cache.
/// assert!(!entry.is_fresh());
/// ```
pub fn or_default(self) -> Entry<K, V>
where
V: Default,
{
self.cache
.get_or_insert_with_hash_by_ref(self.ref_key, self.hash, Default::default)
}
/// Returns the corresponding [`Entry`] for the reference of the key given when
/// this entry selector was constructed. If the entry does not exist, inserts one
/// by cloning the key and using the given `default` value for `V`.
///
/// [`Entry`]: ../struct.Entry.html
///
/// # Example
///
/// ```rust
/// use moka::sync::Cache;
///
/// let cache: Cache<String, u32> = Cache::new(100);
/// let key = "key1".to_string();
///
/// let entry = cache.entry_by_ref(&key).or_insert(3);
/// assert!(entry.is_fresh());
/// assert_eq!(entry.key(), &key);
/// assert_eq!(entry.into_value(), 3);
///
/// let entry = cache.entry_by_ref(&key).or_insert(6);
/// // Not fresh because the value was already in the cache.
/// assert!(!entry.is_fresh());
/// assert_eq!(entry.into_value(), 3);
/// ```
pub fn or_insert(self, default: V) -> Entry<K, V> {
let init = || default;
self.cache
.get_or_insert_with_hash_by_ref(self.ref_key, self.hash, init)
}
/// Returns the corresponding [`Entry`] for the reference of the key given when
/// this entry selector was constructed. If the entry does not exist, inserts one
/// by cloning the key and evaluating the `init` closure for the value.
///
/// [`Entry`]: ../struct.Entry.html
///
/// # Example
///
/// ```rust
/// use moka::sync::Cache;
///
/// let cache: Cache<String, String> = Cache::new(100);
/// let key = "key1".to_string();
///
/// let entry = cache
/// .entry_by_ref(&key)
/// .or_insert_with(|| "value1".to_string());
/// assert!(entry.is_fresh());
/// assert_eq!(entry.key(), &key);
/// assert_eq!(entry.into_value(), "value1");
///
/// let entry = cache
/// .entry_by_ref(&key)
/// .or_insert_with(|| "value2".to_string());
/// // Not fresh because the value was already in the cache.
/// assert!(!entry.is_fresh());
/// assert_eq!(entry.into_value(), "value1");
/// ```
///
/// # Concurrent calls on the same key
///
/// This method guarantees that concurrent calls on the same not-existing entry
/// are coalesced into one evaluation of the `init` closure. Only one of the
/// calls evaluates its closure (thus returned entry's `is_fresh` method returns
/// `true`), and other calls wait for that closure to complete (and their
/// `is_fresh` return `false`).
///
/// For more detail about the coalescing behavior, see
/// [`Cache::get_with`][get-with-method].
///
/// [get-with-method]: ./struct.Cache.html#method.get_with
pub fn or_insert_with(self, init: impl FnOnce() -> V) -> Entry<K, V> {
let replace_if = None as Option<fn(&V) -> bool>;
self.cache.get_or_insert_with_hash_by_ref_and_fun(
self.ref_key,
self.hash,
init,
replace_if,
true,
)
}
/// Works like [`or_insert_with`](#method.or_insert_with), but takes an additional
/// `replace_if` closure.
///
/// This method will evaluate the `init` closure and insert the output to the
/// cache when:
///
/// - The key does not exist.
/// - Or, `replace_if` closure returns `true`.
pub fn or_insert_with_if(
self,
init: impl FnOnce() -> V,
replace_if: impl FnMut(&V) -> bool,
) -> Entry<K, V> {
self.cache.get_or_insert_with_hash_by_ref_and_fun(
self.ref_key,
self.hash,
init,
Some(replace_if),
true,
)
}
/// Returns the corresponding [`Entry`] for the reference of the key given when
/// this entry selector was constructed. If the entry does not exist, clones the
/// key and evaluates the `init` closure. If `Some(value)` was returned by the
/// closure, inserts an entry with the value . If `None` was returned, this
/// method does not insert an entry and returns `None`.
///
/// [`Entry`]: ../struct.Entry.html
///
/// # Example
///
/// ```rust
/// use moka::sync::Cache;
///
/// let cache: Cache<String, u32> = Cache::new(100);
/// let key = "key1".to_string();
///
/// let none_entry = cache
/// .entry_by_ref(&key)
/// .or_optionally_insert_with(|| None);
/// assert!(none_entry.is_none());
///
/// let some_entry = cache
/// .entry_by_ref(&key)
/// .or_optionally_insert_with(|| Some(3));
/// assert!(some_entry.is_some());
/// let entry = some_entry.unwrap();
/// assert!(entry.is_fresh());
/// assert_eq!(entry.key(), &key);
/// assert_eq!(entry.into_value(), 3);
///
/// let some_entry = cache
/// .entry_by_ref(&key)
/// .or_optionally_insert_with(|| Some(6));
/// let entry = some_entry.unwrap();
/// // Not fresh because the value was already in the cache.
/// assert!(!entry.is_fresh());
/// assert_eq!(entry.into_value(), 3);
/// ```
///
/// # Concurrent calls on the same key
///
/// This method guarantees that concurrent calls on the same not-existing entry
/// are coalesced into one evaluation of the `init` closure. Only one of the
/// calls evaluates its closure (thus returned entry's `is_fresh` method returns
/// `true`), and other calls wait for that closure to complete (and their
/// `is_fresh` return `false`).
///
/// For more detail about the coalescing behavior, see
/// [`Cache::optionally_get_with`][opt-get-with-method].
///
/// [opt-get-with-method]: ./struct.Cache.html#method.optionally_get_with
pub fn or_optionally_insert_with(
self,
init: impl FnOnce() -> Option<V>,
) -> Option<Entry<K, V>> {
self.cache
.get_or_optionally_insert_with_hash_by_ref_and_fun(self.ref_key, self.hash, init, true)
}
/// Returns the corresponding [`Entry`] for the reference of the key given when
/// this entry selector was constructed. If the entry does not exist, clones the
/// key and evaluates the `init` closure. If `Ok(value)` was returned from the
/// closure, inserts an entry with the value. If `Err(_)` was returned, this
/// method does not insert an entry and returns the `Err` wrapped by
/// [`std::sync::Arc`][std-arc].
///
/// [`Entry`]: ../struct.Entry.html
/// [std-arc]: https://doc.rust-lang.org/stable/std/sync/struct.Arc.html
///
/// # Example
///
/// ```rust
/// use moka::sync::Cache;
///
/// let cache: Cache<String, u32> = Cache::new(100);
/// let key = "key1".to_string();
///
/// let error_entry = cache
/// .entry_by_ref(&key)
/// .or_try_insert_with(|| Err("error"));
/// assert!(error_entry.is_err());
///
/// let ok_entry = cache
/// .entry_by_ref(&key)
/// .or_try_insert_with(|| Ok::<u32, &str>(3));
/// assert!(ok_entry.is_ok());
/// let entry = ok_entry.unwrap();
/// assert!(entry.is_fresh());
/// assert_eq!(entry.key(), &key);
/// assert_eq!(entry.into_value(), 3);
///
/// let ok_entry = cache
/// .entry_by_ref(&key)
/// .or_try_insert_with(|| Ok::<u32, &str>(6));
/// let entry = ok_entry.unwrap();
/// // Not fresh because the value was already in the cache.
/// assert!(!entry.is_fresh());
/// assert_eq!(entry.into_value(), 3);
/// ```
///
/// # Concurrent calls on the same key
///
/// This method guarantees that concurrent calls on the same not-existing entry
/// are coalesced into one evaluation of the `init` closure (as long as these
/// closures return the same error type). Only one of the calls evaluates its
/// closure (thus returned entry's `is_fresh` method returns `true`), and other
/// calls wait for that closure to complete (and their `is_fresh` return
/// `false`).
///
/// For more detail about the coalescing behavior, see
/// [`Cache::try_get_with`][try-get-with-method].
///
/// [try-get-with-method]: ./struct.Cache.html#method.try_get_with
pub fn or_try_insert_with<F, E>(self, init: F) -> Result<Entry<K, V>, Arc<E>>
where
F: FnOnce() -> Result<V, E>,
E: Send + Sync + 'static,
{
self.cache
.get_or_try_insert_with_hash_by_ref_and_fun(self.ref_key, self.hash, init, true)
}
}