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
use crate::{ops::compute, Entry};
use super::Cache;
use std::{
borrow::Borrow,
future::Future,
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,
}
}
/// Performs a compute operation on a cached entry by using the given closure
/// `f`. A compute operation is either put, remove or no-operation (nop).
///
/// The closure `f` should take the current entry of `Option<Entry<K, V>>` for
/// the key, and return a `Future` that resolves to an `ops::compute::Op<V>`
/// enum.
///
/// This method works as the followings:
///
/// 1. Apply the closure `f` to the current cached `Entry`, and get a `Future`.
/// 2. Resolve the `Future`, and get an `ops::compute::Op<V>`.
/// 3. Execute the op on the cache:
/// - `Op::Put(V)`: Put the new value `V` to the cache.
/// - `Op::Remove`: Remove the current cached entry.
/// - `Op::Nop`: Do nothing.
/// 4. Return an `ops::compute::CompResult<K, V>` as the followings:
///
/// | [`Op<V>`] | [`Entry<K, V>`] already exists? | [`CompResult<K, V>`] | Notes |
/// |:--------- |:--- |:--------------------------- |:------------------------------- |
/// | `Put(V)` | no | `Inserted(Entry<K, V>)` | The new entry is returned. |
/// | `Put(V)` | yes | `ReplacedWith(Entry<K, V>)` | The new entry is returned. |
/// | `Remove` | no | `StillNone(Arc<K>)` | |
/// | `Remove` | yes | `Removed(Entry<K, V>)` | The removed entry is returned. |
/// | `Nop` | no | `StillNone(Arc<K>)` | |
/// | `Nop` | yes | `Unchanged(Entry<K, V>)` | The existing entry is returned. |
///
/// # See Also
///
/// - If you want the `Future` resolve to `Result<Op<V>>` instead of `Op<V>`, and
/// modify entry only when resolved to `Ok(V)`, use the
/// [`and_try_compute_with`] method.
/// - If you only want to update or insert, use the [`and_upsert_with`] method.
///
/// [`Entry<K, V>`]: ../struct.Entry.html
/// [`Op<V>`]: ../ops/compute/enum.Op.html
/// [`CompResult<K, V>`]: ../ops/compute/enum.CompResult.html
/// [`and_upsert_with`]: #method.and_upsert_with
/// [`and_try_compute_with`]: #method.and_try_compute_with
///
/// # Example
///
/// ```rust
/// // Cargo.toml
/// //
/// // [dependencies]
/// // moka = { version = "0.12.8", features = ["future"] }
/// // tokio = { version = "1", features = ["rt-multi-thread", "macros" ] }
///
/// use moka::{
/// future::Cache,
/// ops::compute::{CompResult, Op},
/// };
///
/// #[tokio::main]
/// async fn main() {
/// let cache: Cache<String, u64> = Cache::new(100);
/// let key = "key1".to_string();
///
/// /// Increment a cached `u64` counter. If the counter is greater than or
/// /// equal to 2, remove it.
/// async fn inclement_or_remove_counter(
/// cache: &Cache<String, u64>,
/// key: &str,
/// ) -> CompResult<String, u64> {
/// cache
/// .entry(key.to_string())
/// .and_compute_with(|maybe_entry| {
/// let op = if let Some(entry) = maybe_entry {
/// let counter = entry.into_value();
/// if counter < 2 {
/// Op::Put(counter.saturating_add(1)) // Update
/// } else {
/// Op::Remove
/// }
/// } else {
/// Op::Put(1) // Insert
/// };
/// // Return a Future that is resolved to `op` immediately.
/// std::future::ready(op)
/// })
/// .await
/// }
///
/// // This should insert a new counter value 1 to the cache, and return the
/// // value with the kind of the operation performed.
/// let result = inclement_or_remove_counter(&cache, &key).await;
/// let CompResult::Inserted(entry) = result else {
/// panic!("`Inserted` should be returned: {result:?}");
/// };
/// assert_eq!(entry.into_value(), 1);
///
/// // This should increment the cached counter value by 1.
/// let result = inclement_or_remove_counter(&cache, &key).await;
/// let CompResult::ReplacedWith(entry) = result else {
/// panic!("`ReplacedWith` should be returned: {result:?}");
/// };
/// assert_eq!(entry.into_value(), 2);
///
/// // This should remove the cached counter from the cache, and returns the
/// // _removed_ value.
/// let result = inclement_or_remove_counter(&cache, &key).await;
/// let CompResult::Removed(entry) = result else {
/// panic!("`Removed` should be returned: {result:?}");
/// };
/// assert_eq!(entry.into_value(), 2);
///
/// // The key should not exist.
/// assert!(!cache.contains_key(&key));
///
/// // This should start over; insert a new counter value 1 to the cache.
/// let result = inclement_or_remove_counter(&cache, &key).await;
/// let CompResult::Inserted(entry) = result else {
/// panic!("`Inserted` should be returned: {result:?}");
/// };
/// assert_eq!(entry.into_value(), 1);
/// }
/// ```
///
/// # Concurrent calls on the same key
///
/// This method guarantees that concurrent calls on the same key are executed
/// serially. That is, `and_compute_with` calls on the same key never run
/// concurrently. The calls are serialized by the order of their invocation. It
/// uses a key-level lock to achieve this.
pub async fn and_compute_with<F, Fut>(self, f: F) -> compute::CompResult<K, V>
where
F: FnOnce(Option<Entry<K, V>>) -> Fut,
Fut: Future<Output = compute::Op<V>>,
{
let key = Arc::new(self.owned_key);
self.cache
.compute_with_hash_and_fun(key, self.hash, f)
.await
}
/// Performs a compute operation on a cached entry by using the given closure
/// `f`. A compute operation is either put, remove or no-operation (nop).
///
/// The closure `f` should take the current entry of `Option<Entry<K, V>>` for
/// the key, and return a `Future` that resolves to a
/// `Result<ops::compute::Op<V>, E>`.
///
/// This method works as the followings:
///
/// 1. Apply the closure `f` to the current cached `Entry`, and get a `Future`.
/// 2. Resolve the `Future`, and get a `Result<ops::compute::Op<V>, E>`.
/// 3. If resolved to `Err(E)`, return it.
/// 4. Else, execute the op on the cache:
/// - `Ok(Op::Put(V))`: Put the new value `V` to the cache.
/// - `Ok(Op::Remove)`: Remove the current cached entry.
/// - `Ok(Op::Nop)`: Do nothing.
/// 5. Return an `Ok(ops::compute::CompResult<K, V>)` as the followings:
///
/// | [`Op<V>`] | [`Entry<K, V>`] already exists? | [`CompResult<K, V>`] | Notes |
/// |:--------- |:--- |:--------------------------- |:------------------------------- |
/// | `Put(V)` | no | `Inserted(Entry<K, V>)` | The new entry is returned. |
/// | `Put(V)` | yes | `ReplacedWith(Entry<K, V>)` | The new entry is returned. |
/// | `Remove` | no | `StillNone(Arc<K>)` | |
/// | `Remove` | yes | `Removed(Entry<K, V>)` | The removed entry is returned. |
/// | `Nop` | no | `StillNone(Arc<K>)` | |
/// | `Nop` | yes | `Unchanged(Entry<K, V>)` | The existing entry is returned. |
///
/// # See Also
///
/// - If you want the `Future` resolve to `Op<V>` instead of `Result<Op<V>>`, use
/// the [`and_compute_with`] method.
/// - If you only want to update or insert, use the [`and_upsert_with`] method.
///
/// [`Entry<K, V>`]: ../struct.Entry.html
/// [`Op<V>`]: ../ops/compute/enum.Op.html
/// [`CompResult<K, V>`]: ../ops/compute/enum.CompResult.html
/// [`and_upsert_with`]: #method.and_upsert_with
/// [`and_compute_with`]: #method.and_compute_with
///
/// # Example
///
/// See [`try_append_value_async.rs`] in the `examples` directory.
///
/// [`try_append_value_async.rs`]:
/// https://github.com/moka-rs/moka/tree/main/examples/try_append_value_async.rs
///
/// # Concurrent calls on the same key
///
/// This method guarantees that concurrent calls on the same key are executed
/// serially. That is, `and_try_compute_with` calls on the same key never run
/// concurrently. The calls are serialized by the order of their invocation. It
/// uses a key-level lock to achieve this.
pub async fn and_try_compute_with<F, Fut, E>(self, f: F) -> Result<compute::CompResult<K, V>, E>
where
F: FnOnce(Option<Entry<K, V>>) -> Fut,
Fut: Future<Output = Result<compute::Op<V>, E>>,
E: Send + Sync + 'static,
{
let key = Arc::new(self.owned_key);
self.cache
.try_compute_with_hash_and_fun(key, self.hash, f)
.await
}
/// Performs an upsert of an [`Entry`] by using the given closure `f`. The word
/// "upsert" here means "update" or "insert".
///
/// The closure `f` should take the current entry of `Option<Entry<K, V>>` for
/// the key, and return a `Future` that resolves to a new value `V`.
///
/// This method works as the followings:
///
/// 1. Apply the closure `f` to the current cached `Entry`, and get a `Future`.
/// 2. Resolve the `Future`, and get a new value `V`.
/// 3. Upsert the new value to the cache.
/// 4. Return the `Entry` having the upserted value.
///
/// # See Also
///
/// - If you want to optionally upsert, that is to upsert only when certain
/// conditions meet, use the [`and_compute_with`] method.
/// - If you try to upsert, that is to make the `Future` resolve to `Result<V>`
/// instead of `V`, and upsert only when resolved to `Ok(V)`, use the
/// [`and_try_compute_with`] method.
///
/// [`Entry`]: ../struct.Entry.html
/// [`and_compute_with`]: #method.and_compute_with
/// [`and_try_compute_with`]: #method.and_try_compute_with
///
/// # Example
///
/// ```rust
/// // Cargo.toml
/// //
/// // [dependencies]
/// // moka = { version = "0.12.8", features = ["future"] }
/// // tokio = { version = "1", features = ["rt-multi-thread", "macros" ] }
///
/// use moka::future::Cache;
///
/// #[tokio::main]
/// async fn main() {
/// let cache: Cache<String, u64> = Cache::new(100);
/// let key = "key1".to_string();
///
/// let entry = cache
/// .entry(key.clone())
/// .and_upsert_with(|maybe_entry| {
/// let counter = if let Some(entry) = maybe_entry {
/// entry.into_value().saturating_add(1) // Update
/// } else {
/// 1 // Insert
/// };
/// // Return a Future that is resolved to `counter` immediately.
/// std::future::ready(counter)
/// })
/// .await;
/// // It was not an update.
/// assert!(!entry.is_old_value_replaced());
/// assert_eq!(entry.key(), &key);
/// assert_eq!(entry.into_value(), 1);
///
/// let entry = cache
/// .entry(key.clone())
/// .and_upsert_with(|maybe_entry| {
/// let counter = if let Some(entry) = maybe_entry {
/// entry.into_value().saturating_add(1)
/// } else {
/// 1
/// };
/// std::future::ready(counter)
/// })
/// .await;
/// // It was an update.
/// assert!(entry.is_old_value_replaced());
/// assert_eq!(entry.key(), &key);
/// assert_eq!(entry.into_value(), 2);
/// }
/// ```
///
/// # Concurrent calls on the same key
///
/// This method guarantees that concurrent calls on the same key are executed
/// serially. That is, `and_upsert_with` calls on the same key never run
/// concurrently. The calls are serialized by the order of their invocation. It
/// uses a key-level lock to achieve this.
pub async fn and_upsert_with<F, Fut>(self, f: F) -> Entry<K, V>
where
F: FnOnce(Option<Entry<K, V>>) -> Fut,
Fut: Future<Output = V>,
{
let key = Arc::new(self.owned_key);
self.cache.upsert_with_hash_and_fun(key, self.hash, f).await
}
/// 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
/// // Cargo.toml
/// //
/// // [dependencies]
/// // moka = { version = "0.12", features = ["future"] }
/// // tokio = { version = "1", features = ["rt-multi-thread", "macros" ] }
///
/// use moka::future::Cache;
///
/// #[tokio::main]
/// async fn main() {
/// let cache: Cache<String, Option<u32>> = Cache::new(100);
/// let key = "key1".to_string();
///
/// let entry = cache.entry(key.clone()).or_default().await;
/// assert!(entry.is_fresh());
/// assert_eq!(entry.key(), &key);
/// assert_eq!(entry.into_value(), None);
///
/// let entry = cache.entry(key).or_default().await;
/// // Not fresh because the value was already in the cache.
/// assert!(!entry.is_fresh());
/// }
/// ```
pub async 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)
.await
}
/// 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
/// // Cargo.toml
/// //
/// // [dependencies]
/// // moka = { version = "0.12", features = ["future"] }
/// // tokio = { version = "1", features = ["rt-multi-thread", "macros" ] }
///
/// use moka::future::Cache;
///
/// #[tokio::main]
/// async fn main() {
/// let cache: Cache<String, u32> = Cache::new(100);
/// let key = "key1".to_string();
///
/// let entry = cache.entry(key.clone()).or_insert(3).await;
/// assert!(entry.is_fresh());
/// assert_eq!(entry.key(), &key);
/// assert_eq!(entry.into_value(), 3);
///
/// let entry = cache.entry(key).or_insert(6).await;
/// // Not fresh because the value was already in the cache.
/// assert!(!entry.is_fresh());
/// assert_eq!(entry.into_value(), 3);
/// }
/// ```
pub async 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)
.await
}
/// Returns the corresponding [`Entry`] for the key given when this entry
/// selector was constructed. If the entry does not exist, resolves the `init`
/// future and inserts the output.
///
/// [`Entry`]: ../struct.Entry.html
///
/// # Example
///
/// ```rust
/// // Cargo.toml
/// //
/// // [dependencies]
/// // moka = { version = "0.12", features = ["future"] }
/// // tokio = { version = "1", features = ["rt-multi-thread", "macros" ] }
///
/// use moka::future::Cache;
///
/// #[tokio::main]
/// async fn main() {
/// let cache: Cache<String, String> = Cache::new(100);
/// let key = "key1".to_string();
///
/// let entry = cache
/// .entry(key.clone())
/// .or_insert_with(async { "value1".to_string() })
/// .await;
/// assert!(entry.is_fresh());
/// assert_eq!(entry.key(), &key);
/// assert_eq!(entry.into_value(), "value1");
///
/// let entry = cache
/// .entry(key)
/// .or_insert_with(async { "value2".to_string() })
/// .await;
/// // 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` future. Only one of the calls
/// evaluates its future (thus returned entry's `is_fresh` method returns
/// `true`), and other calls wait for that future to resolve (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 async fn or_insert_with(self, init: impl Future<Output = V>) -> Entry<K, V> {
futures_util::pin_mut!(init);
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)
.await
}
/// Works like [`or_insert_with`](#method.or_insert_with), but takes an additional
/// `replace_if` closure.
///
/// This method will resolve the `init` future and insert the output to the
/// cache when:
///
/// - The key does not exist.
/// - Or, `replace_if` closure returns `true`.
pub async fn or_insert_with_if(
self,
init: impl Future<Output = V>,
replace_if: impl FnMut(&V) -> bool + Send,
) -> Entry<K, V> {
futures_util::pin_mut!(init);
let key = Arc::new(self.owned_key);
self.cache
.get_or_insert_with_hash_and_fun(key, self.hash, init, Some(replace_if), true)
.await
}
/// Returns the corresponding [`Entry`] for the key given when this entry
/// selector was constructed. If the entry does not exist, resolves the `init`
/// future, and inserts an entry if `Some(value)` was returned. If `None` was
/// returned from the future, this method does not insert an entry and returns
/// `None`.
///
/// [`Entry`]: ../struct.Entry.html
///
/// # Example
///
/// ```rust
/// // Cargo.toml
/// //
/// // [dependencies]
/// // moka = { version = "0.12", features = ["future"] }
/// // tokio = { version = "1", features = ["rt-multi-thread", "macros" ] }
///
/// use moka::future::Cache;
///
/// #[tokio::main]
/// async fn main() {
/// let cache: Cache<String, u32> = Cache::new(100);
/// let key = "key1".to_string();
///
/// let none_entry = cache
/// .entry(key.clone())
/// .or_optionally_insert_with(async { None })
/// .await;
/// assert!(none_entry.is_none());
///
/// let some_entry = cache
/// .entry(key.clone())
/// .or_optionally_insert_with(async { Some(3) })
/// .await;
/// 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(async { Some(6) })
/// .await;
/// 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` future. Only one of the calls
/// evaluates its future (thus returned entry's `is_fresh` method returns
/// `true`), and other calls wait for that future to resolve (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 async fn or_optionally_insert_with(
self,
init: impl Future<Output = Option<V>>,
) -> Option<Entry<K, V>> {
futures_util::pin_mut!(init);
let key = Arc::new(self.owned_key);
self.cache
.get_or_optionally_insert_with_hash_and_fun(key, self.hash, init, true)
.await
}
/// Returns the corresponding [`Entry`] for the key given when this entry
/// selector was constructed. If the entry does not exist, resolves the `init`
/// future, and inserts an entry if `Ok(value)` was returned. If `Err(_)` was
/// returned from the future, 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
/// // Cargo.toml
/// //
/// // [dependencies]
/// // moka = { version = "0.12", features = ["future"] }
/// // tokio = { version = "1", features = ["rt-multi-thread", "macros" ] }
///
/// use moka::future::Cache;
///
/// #[tokio::main]
/// async fn main() {
/// let cache: Cache<String, u32> = Cache::new(100);
/// let key = "key1".to_string();
///
/// let error_entry = cache
/// .entry(key.clone())
/// .or_try_insert_with(async { Err("error") })
/// .await;
/// assert!(error_entry.is_err());
///
/// let ok_entry = cache
/// .entry(key.clone())
/// .or_try_insert_with(async { Ok::<u32, &str>(3) })
/// .await;
/// 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(async { Ok::<u32, &str>(6) })
/// .await;
/// 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` future (as long as these
/// futures return the same error type). Only one of the calls evaluates its
/// future (thus returned entry's `is_fresh` method returns `true`), and other
/// calls wait for that future to resolve (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 async fn or_try_insert_with<F, E>(self, init: F) -> Result<Entry<K, V>, Arc<E>>
where
F: Future<Output = Result<V, E>>,
E: Send + Sync + 'static,
{
futures_util::pin_mut!(init);
let key = Arc::new(self.owned_key);
self.cache
.get_or_try_insert_with_hash_and_fun(key, self.hash, init, true)
.await
}
}
/// 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,
}
}
/// Performs a compute operation on a cached entry by using the given closure
/// `f`. A compute operation is either put, remove or no-operation (nop).
///
/// The closure `f` should take the current entry of `Option<Entry<K, V>>` for
/// the key, and return a `Future` that resolves to an `ops::compute::Op<V>`
/// enum.
///
/// This method works as the followings:
///
/// 1. Apply the closure `f` to the current cached `Entry`, and get a `Future`.
/// 2. Resolve the `Future`, and get an `ops::compute::Op<V>`.
/// 3. Execute the op on the cache:
/// - `Op::Put(V)`: Put the new value `V` to the cache.
/// - `Op::Remove`: Remove the current cached entry.
/// - `Op::Nop`: Do nothing.
/// 4. Return an `ops::compute::CompResult<K, V>` as the followings:
///
/// | [`Op<V>`] | [`Entry<K, V>`] already exists? | [`CompResult<K, V>`] | Notes |
/// |:--------- |:--- |:--------------------------- |:------------------------------- |
/// | `Put(V)` | no | `Inserted(Entry<K, V>)` | The new entry is returned. |
/// | `Put(V)` | yes | `ReplacedWith(Entry<K, V>)` | The new entry is returned. |
/// | `Remove` | no | `StillNone(Arc<K>)` | |
/// | `Remove` | yes | `Removed(Entry<K, V>)` | The removed entry is returned. |
/// | `Nop` | no | `StillNone(Arc<K>)` | |
/// | `Nop` | yes | `Unchanged(Entry<K, V>)` | The existing entry is returned. |
///
/// # See Also
///
/// - If you want the `Future` resolve to `Result<Op<V>>` instead of `Op<V>`, and
/// modify entry only when resolved to `Ok(V)`, use the
/// [`and_try_compute_with`] method.
/// - If you only want to update or insert, use the [`and_upsert_with`] method.
///
/// [`Entry<K, V>`]: ../struct.Entry.html
/// [`Op<V>`]: ../ops/compute/enum.Op.html
/// [`CompResult<K, V>`]: ../ops/compute/enum.CompResult.html
/// [`and_upsert_with`]: #method.and_upsert_with
/// [`and_try_compute_with`]: #method.and_try_compute_with
///
/// # Example
///
/// ```rust
/// // Cargo.toml
/// //
/// // [dependencies]
/// // moka = { version = "0.12.8", features = ["future"] }
/// // tokio = { version = "1", features = ["rt-multi-thread", "macros" ] }
///
/// use moka::{
/// future::Cache,
/// ops::compute::{CompResult, Op},
/// };
///
/// #[tokio::main]
/// async fn main() {
/// let cache: Cache<String, u64> = Cache::new(100);
/// let key = "key1";
///
/// /// Increment a cached `u64` counter. If the counter is greater than or
/// /// equal to 2, remove it.
/// async fn inclement_or_remove_counter(
/// cache: &Cache<String, u64>,
/// key: &str,
/// ) -> CompResult<String, u64> {
/// cache
/// .entry_by_ref(key)
/// .and_compute_with(|maybe_entry| {
/// let op = if let Some(entry) = maybe_entry {
/// let counter = entry.into_value();
/// if counter < 2 {
/// Op::Put(counter.saturating_add(1)) // Update
/// } else {
/// Op::Remove
/// }
/// } else {
/// Op::Put(1) // Insert
/// };
/// // Return a Future that is resolved to `op` immediately.
/// std::future::ready(op)
/// })
/// .await
/// }
///
/// // This should insert a now counter value 1 to the cache, and return the
/// // value with the kind of the operation performed.
/// let result = inclement_or_remove_counter(&cache, &key).await;
/// let CompResult::Inserted(entry) = result else {
/// panic!("`Inserted` should be returned: {result:?}");
/// };
/// assert_eq!(entry.into_value(), 1);
///
/// // This should increment the cached counter value by 1.
/// let result = inclement_or_remove_counter(&cache, &key).await;
/// let CompResult::ReplacedWith(entry) = result else {
/// panic!("`ReplacedWith` should be returned: {result:?}");
/// };
/// assert_eq!(entry.into_value(), 2);
///
/// // This should remove the cached counter from the cache, and returns the
/// // _removed_ value.
/// let result = inclement_or_remove_counter(&cache, &key).await;
/// let CompResult::Removed(entry) = result else {
/// panic!("`Removed` should be returned: {result:?}");
/// };
/// assert_eq!(entry.into_value(), 2);
///
/// // The key should no longer exist.
/// assert!(!cache.contains_key(key));
///
/// // This should start over; insert a new counter value 1 to the cache.
/// let result = inclement_or_remove_counter(&cache, &key).await;
/// let CompResult::Inserted(entry) = result else {
/// panic!("`Inserted` should be returned: {result:?}");
/// };
/// assert_eq!(entry.into_value(), 1);
/// }
/// ```
///
/// # Concurrent calls on the same key
///
/// This method guarantees that concurrent calls on the same key are executed
/// serially. That is, `and_compute_with` calls on the same key never run
/// concurrently. The calls are serialized by the order of their invocation. It
/// uses a key-level lock to achieve this.
pub async fn and_compute_with<F, Fut>(self, f: F) -> compute::CompResult<K, V>
where
F: FnOnce(Option<Entry<K, V>>) -> Fut,
Fut: Future<Output = compute::Op<V>>,
{
let key = Arc::new(self.ref_key.to_owned());
self.cache
.compute_with_hash_and_fun(key, self.hash, f)
.await
}
/// Performs a compute operation on a cached entry by using the given closure
/// `f`. A compute operation is either put, remove or no-operation (nop).
///
/// The closure `f` should take the current entry of `Option<Entry<K, V>>` for
/// the key, and return a `Future` that resolves to a
/// `Result<ops::compute::Op<V>, E>`.
///
/// This method works as the followings:
///
/// 1. Apply the closure `f` to the current cached `Entry`, and get a `Future`.
/// 2. Resolve the `Future`, and get a `Result<ops::compute::Op<V>, E>`.
/// 3. If resolved to `Err(E)`, return it.
/// 4. Else, execute the op on the cache:
/// - `Ok(Op::Put(V))`: Put the new value `V` to the cache.
/// - `Ok(Op::Remove)`: Remove the current cached entry.
/// - `Ok(Op::Nop)`: Do nothing.
/// 5. Return an `Ok(ops::compute::CompResult<K, V>)` as the followings:
///
/// | [`Op<V>`] | [`Entry<K, V>`] already exists? | [`CompResult<K, V>`] | Notes |
/// |:--------- |:--- |:--------------------------- |:------------------------------- |
/// | `Put(V)` | no | `Inserted(Entry<K, V>)` | The new entry is returned. |
/// | `Put(V)` | yes | `ReplacedWith(Entry<K, V>)` | The new entry is returned. |
/// | `Remove` | no | `StillNone(Arc<K>)` | |
/// | `Remove` | yes | `Removed(Entry<K, V>)` | The removed entry is returned. |
/// | `Nop` | no | `StillNone(Arc<K>)` | |
/// | `Nop` | yes | `Unchanged(Entry<K, V>)` | The existing entry is returned. |
///
/// # See Also
///
/// - If you want the `Future` resolve to `Op<V>` instead of `Result<Op<V>>`, use
/// the [`and_compute_with`] method.
/// - If you only want to update or insert, use the [`and_upsert_with`] method.
///
/// [`Entry<K, V>`]: ../struct.Entry.html
/// [`Op<V>`]: ../ops/compute/enum.Op.html
/// [`CompResult<K, V>`]: ../ops/compute/enum.CompResult.html
/// [`and_upsert_with`]: #method.and_upsert_with
/// [`and_compute_with`]: #method.and_compute_with
///
/// # Example
///
/// See [`try_append_value_async.rs`] in the `examples` directory.
///
/// [`try_append_value_async.rs`]:
/// https://github.com/moka-rs/moka/tree/main/examples/try_append_value_async.rs
///
/// # Concurrent calls on the same key
///
/// This method guarantees that concurrent calls on the same key are executed
/// serially. That is, `and_try_compute_with` calls on the same key never run
/// concurrently. The calls are serialized by the order of their invocation. It
/// uses a key-level lock to achieve this.
pub async fn and_try_compute_with<F, Fut, E>(self, f: F) -> Result<compute::CompResult<K, V>, E>
where
F: FnOnce(Option<Entry<K, V>>) -> Fut,
Fut: Future<Output = Result<compute::Op<V>, E>>,
E: Send + Sync + 'static,
{
let key = Arc::new(self.ref_key.to_owned());
self.cache
.try_compute_with_hash_and_fun(key, self.hash, f)
.await
}
/// Performs an upsert of an [`Entry`] by using the given closure `f`. The word
/// "upsert" here means "update" or "insert".
///
/// The closure `f` should take the current entry of `Option<Entry<K, V>>` for
/// the key, and return a `Future` that resolves to a new value `V`.
///
/// This method works as the followings:
///
/// 1. Apply the closure `f` to the current cached `Entry`, and get a `Future`.
/// 2. Resolve the `Future`, and get a new value `V`.
/// 3. Upsert the new value to the cache.
/// 4. Return the `Entry` having the upserted value.
///
/// # See Also
///
/// - If you want to optionally upsert, that is to upsert only when certain
/// conditions meet, use the [`and_compute_with`] method.
/// - If you try to upsert, that is to make the `Future` resolve to `Result<V>`
/// instead of `V`, and upsert only when resolved to `Ok(V)`, use the
/// [`and_try_compute_with`] method.
///
/// [`Entry`]: ../struct.Entry.html
/// [`and_compute_with`]: #method.and_compute_with
/// [`and_try_compute_with`]: #method.and_try_compute_with
///
/// # Example
///
/// ```rust
/// // Cargo.toml
/// //
/// // [dependencies]
/// // moka = { version = "0.12.8", features = ["future"] }
/// // tokio = { version = "1", features = ["rt-multi-thread", "macros" ] }
///
/// use moka::future::Cache;
///
/// #[tokio::main]
/// async fn main() {
/// let cache: Cache<String, u64> = Cache::new(100);
/// let key = "key1";
///
/// let entry = cache
/// .entry_by_ref(key)
/// .and_upsert_with(|maybe_entry| {
/// let counter = if let Some(entry) = maybe_entry {
/// entry.into_value().saturating_add(1) // Update
/// } else {
/// 1 // Insert
/// };
/// // Return a Future that is resolved to `counter` immediately.
/// std::future::ready(counter)
/// })
/// .await;
/// // It was not an update.
/// assert!(!entry.is_old_value_replaced());
/// assert_eq!(entry.key(), &key);
/// assert_eq!(entry.into_value(), 1);
///
/// let entry = cache
/// .entry_by_ref(key)
/// .and_upsert_with(|maybe_entry| {
/// let counter = if let Some(entry) = maybe_entry {
/// entry.into_value().saturating_add(1)
/// } else {
/// 1
/// };
/// std::future::ready(counter)
/// })
/// .await;
/// // It was an update.
/// assert!(entry.is_old_value_replaced());
/// assert_eq!(entry.key(), &key);
/// assert_eq!(entry.into_value(), 2);
/// }
/// ```
///
/// # Concurrent calls on the same key
///
/// This method guarantees that concurrent calls on the same key are executed
/// serially. That is, `and_upsert_with` calls on the same key never run
/// concurrently. The calls are serialized by the order of their invocation. It
/// uses a key-level lock to achieve this.
pub async fn and_upsert_with<F, Fut>(self, f: F) -> Entry<K, V>
where
F: FnOnce(Option<Entry<K, V>>) -> Fut,
Fut: Future<Output = V>,
{
let key = Arc::new(self.ref_key.to_owned());
self.cache.upsert_with_hash_and_fun(key, self.hash, f).await
}
/// 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
/// // Cargo.toml
/// //
/// // [dependencies]
/// // moka = { version = "0.12", features = ["future"] }
/// // tokio = { version = "1", features = ["rt-multi-thread", "macros" ] }
///
/// use moka::future::Cache;
///
/// #[tokio::main]
/// async fn main() {
/// let cache: Cache<String, Option<u32>> = Cache::new(100);
/// let key = "key1".to_string();
///
/// let entry = cache.entry_by_ref(&key).or_default().await;
/// assert!(entry.is_fresh());
/// assert_eq!(entry.key(), &key);
/// assert_eq!(entry.into_value(), None);
///
/// let entry = cache.entry_by_ref(&key).or_default().await;
/// // Not fresh because the value was already in the cache.
/// assert!(!entry.is_fresh());
/// }
/// ```
pub async 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)
.await
}
/// 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
/// // Cargo.toml
/// //
/// // [dependencies]
/// // moka = { version = "0.12", features = ["future"] }
/// // tokio = { version = "1", features = ["rt-multi-thread", "macros" ] }
///
/// use moka::future::Cache;
///
/// #[tokio::main]
/// async fn main() {
/// let cache: Cache<String, u32> = Cache::new(100);
/// let key = "key1".to_string();
///
/// let entry = cache.entry_by_ref(&key).or_insert(3).await;
/// 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).await;
/// // Not fresh because the value was already in the cache.
/// assert!(!entry.is_fresh());
/// assert_eq!(entry.into_value(), 3);
/// }
/// ```
pub async 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)
.await
}
/// 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 resolving the `init` future for the value.
///
/// [`Entry`]: ../struct.Entry.html
///
/// # Example
///
/// ```rust
/// // Cargo.toml
/// //
/// // [dependencies]
/// // moka = { version = "0.12", features = ["future"] }
/// // tokio = { version = "1", features = ["rt-multi-thread", "macros" ] }
///
/// use moka::future::Cache;
///
/// #[tokio::main]
/// async fn main() {
/// let cache: Cache<String, String> = Cache::new(100);
/// let key = "key1".to_string();
///
/// let entry = cache
/// .entry_by_ref(&key)
/// .or_insert_with(async { "value1".to_string() })
/// .await;
/// 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(async { "value2".to_string() })
/// .await;
/// // 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` future. Only one of the calls
/// evaluates its future (thus returned entry's `is_fresh` method returns
/// `true`), and other calls wait for that future to resolve (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 async fn or_insert_with(self, init: impl Future<Output = V>) -> Entry<K, V> {
futures_util::pin_mut!(init);
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)
.await
}
/// Works like [`or_insert_with`](#method.or_insert_with), but takes an additional
/// `replace_if` closure.
///
/// This method will resolve the `init` future and insert the output to the
/// cache when:
///
/// - The key does not exist.
/// - Or, `replace_if` closure returns `true`.
pub async fn or_insert_with_if(
self,
init: impl Future<Output = V>,
replace_if: impl FnMut(&V) -> bool + Send,
) -> Entry<K, V> {
futures_util::pin_mut!(init);
self.cache
.get_or_insert_with_hash_by_ref_and_fun(
self.ref_key,
self.hash,
init,
Some(replace_if),
true,
)
.await
}
/// 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 resolves the `init` future. If `Some(value)` was returned by the
/// future, 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
/// // Cargo.toml
/// //
/// // [dependencies]
/// // moka = { version = "0.12", features = ["future"] }
/// // tokio = { version = "1", features = ["rt-multi-thread", "macros" ] }
///
/// use moka::future::Cache;
///
/// #[tokio::main]
/// async fn main() {
/// 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(async { None })
/// .await;
/// assert!(none_entry.is_none());
///
/// let some_entry = cache
/// .entry_by_ref(&key)
/// .or_optionally_insert_with(async { Some(3) })
/// .await;
/// 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(async { Some(6) })
/// .await;
/// 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` future. Only one of the calls
/// evaluates its future (thus returned entry's `is_fresh` method returns
/// `true`), and other calls wait for that future to resolve (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 async fn or_optionally_insert_with(
self,
init: impl Future<Output = Option<V>>,
) -> Option<Entry<K, V>> {
futures_util::pin_mut!(init);
self.cache
.get_or_optionally_insert_with_hash_by_ref_and_fun(self.ref_key, self.hash, init, true)
.await
}
/// 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 resolves the `init` future. If `Ok(value)` was returned from the
/// future, 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
/// // Cargo.toml
/// //
/// // [dependencies]
/// // moka = { version = "0.12", features = ["future"] }
/// // tokio = { version = "1", features = ["rt-multi-thread", "macros" ] }
///
/// use moka::future::Cache;
///
/// #[tokio::main]
/// async fn main() {
/// 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(async { Err("error") })
/// .await;
/// assert!(error_entry.is_err());
///
/// let ok_entry = cache
/// .entry_by_ref(&key)
/// .or_try_insert_with(async { Ok::<u32, &str>(3) })
/// .await;
/// 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(async { Ok::<u32, &str>(6) })
/// .await;
/// 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` future (as long as these
/// futures return the same error type). Only one of the calls evaluates its
/// future (thus returned entry's `is_fresh` method returns `true`), and other
/// calls wait for that future to resolve (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 async fn or_try_insert_with<F, E>(self, init: F) -> Result<Entry<K, V>, Arc<E>>
where
F: Future<Output = Result<V, E>>,
E: Send + Sync + 'static,
{
futures_util::pin_mut!(init);
self.cache
.get_or_try_insert_with_hash_by_ref_and_fun(self.ref_key, self.hash, init, true)
.await
}
}