From 0859e9581fd450397056a5b0db83de377bf79680 Mon Sep 17 00:00:00 2001 From: Yuri Astrakhan Date: Thu, 9 Nov 2023 17:24:54 -0500 Subject: [PATCH] Inline format args Makes the code a bit easier to read. Plus a few unneeded commas. Some of these require migration to 2021 edition first (another PR) --- MIGRATION-GUIDE.md | 7 +--- README.md | 4 +- examples/async_example.rs | 2 +- examples/eviction_listener.rs | 2 +- examples/sync_example.rs | 2 +- src/cht/map/bucket.rs | 2 +- src/common.rs | 2 +- src/common/concurrent/deques.rs | 10 +---- src/common/concurrent/entry_info.rs | 2 +- src/common/timer_wheel.rs | 8 ++-- src/future/base_cache.rs | 18 ++++----- src/future/cache.rs | 57 +++++++++++++---------------- src/future/notifier.rs | 10 ++--- src/future/value_initializer.rs | 8 ++-- src/notification/notifier.rs | 10 ++--- src/sync/cache.rs | 57 +++++++++++++---------------- src/sync/segment.rs | 23 ++++++------ src/sync/value_initializer.rs | 3 +- src/sync_base/base_cache.rs | 18 ++++----- tests/entry_api_actix_rt2.rs | 12 +++--- tests/entry_api_async_std.rs | 12 +++--- tests/entry_api_sync.rs | 26 ++++++------- tests/entry_api_tokio.rs | 26 ++++++------- tests/runtime_actix_rt2.rs | 2 +- tests/runtime_async_std.rs | 2 +- tests/runtime_tokio.rs | 2 +- 26 files changed, 145 insertions(+), 182 deletions(-) diff --git a/MIGRATION-GUIDE.md b/MIGRATION-GUIDE.md index d5354d1b..ec82e2bc 100644 --- a/MIGRATION-GUIDE.md +++ b/MIGRATION-GUIDE.md @@ -211,10 +211,7 @@ use moka::notification::ListenerFuture; use moka::future::FutureExt; let eviction_listener = move |k, v: PathBuf, cause| -> ListenerFuture { - println!( - "\n== An entry has been evicted. k: {:?}, v: {:?}, cause: {:?}", - k, v, cause - ); + println!("\n== An entry has been evicted. k: {k:?}, v: {v:?}, cause: {cause:?}"); let file_mgr2 = Arc::clone(&file_mgr1); // Create a Future that removes the data file at the path `v`. @@ -224,7 +221,7 @@ let eviction_listener = move |k, v: PathBuf, cause| -> ListenerFuture { // Remove the data file. We must handle error cases here to // prevent the listener from panicking. if let Err(_e) = mgr.remove_data_file(v.as_path()).await { - eprintln!("Failed to remove a data file at {:?}", v); + eprintln!("Failed to remove a data file at {v:?}"); } } // Convert the regular Future into ListenerFuture. This method is diff --git a/README.md b/README.md index 616f31fd..01fbaf5d 100644 --- a/README.md +++ b/README.md @@ -180,7 +180,7 @@ use moka::sync::Cache; use std::thread; fn value(n: usize) -> String { - format!("value {}", n) + format!("value {n}") } fn main() { @@ -282,7 +282,7 @@ async fn main() { const NUM_KEYS_PER_TASK: usize = 64; fn value(n: usize) -> String { - format!("value {}", n) + format!("value {n}") } // Create a cache that can store up to 10,000 entries. diff --git a/examples/async_example.rs b/examples/async_example.rs index e4e2f210..62e1e11c 100644 --- a/examples/async_example.rs +++ b/examples/async_example.rs @@ -7,7 +7,7 @@ async fn main() { const NUM_KEYS_PER_TASK: usize = 64; fn value(n: usize) -> String { - format!("value {}", n) + format!("value {n}") } // Create a cache that can store up to 10,000 entries. diff --git a/examples/eviction_listener.rs b/examples/eviction_listener.rs index 84712c52..a6f04819 100644 --- a/examples/eviction_listener.rs +++ b/examples/eviction_listener.rs @@ -9,7 +9,7 @@ fn main() { .max_capacity(2) .time_to_live(Duration::from_secs(1)) .eviction_listener(|key, value, cause| { - println!("Evicted ({:?},{:?}) because {:?}", key, value, cause) + println!("Evicted ({key:?},{value:?}) because {cause:?}") }) .build(); // Overload capacity of the cache. diff --git a/examples/sync_example.rs b/examples/sync_example.rs index 5947f506..58373b03 100644 --- a/examples/sync_example.rs +++ b/examples/sync_example.rs @@ -4,7 +4,7 @@ use moka::sync::Cache; use std::thread; fn value(n: usize) -> String { - format!("value {}", n) + format!("value {n}") } fn main() { diff --git a/src/cht/map/bucket.rs b/src/cht/map/bucket.rs index 5a0ab437..3f451e85 100644 --- a/src/cht/map/bucket.rs +++ b/src/cht/map/bucket.rs @@ -443,7 +443,7 @@ impl<'g, K: 'g, V: 'g> BucketArray { // We need to return here to see if rehashing is still needed. return None; } - Err(e @ TryLockError::Poisoned(_)) => panic!("{:?}", e), + Err(e @ TryLockError::Poisoned(_)) => panic!("{e:?}"), }; let next_array = self.next_array(guard, rehash_op); diff --git a/src/common.rs b/src/common.rs index a7a3d0bd..f9c1cc62 100644 --- a/src/common.rs +++ b/src/common.rs @@ -30,7 +30,7 @@ impl From for CacheRegion { 1 => Self::MainProbation, 2 => Self::MainProtected, 3 => Self::Other, - _ => panic!("No such CacheRegion variant for {}", n), + _ => panic!("No such CacheRegion variant for {n}"), } } } diff --git a/src/common/concurrent/deques.rs b/src/common/concurrent/deques.rs index efabc798..5716e5aa 100644 --- a/src/common/concurrent/deques.rs +++ b/src/common/concurrent/deques.rs @@ -106,10 +106,7 @@ impl Deques { unsafe { deq.move_to_back(node) }; } } else { - panic!( - "move_to_back_ao_in_deque - node is not a member of {} deque. {:?}", - deq_name, p, - ) + panic!("move_to_back_ao_in_deque - node is not a member of {deq_name} deque. {p:?}") } } } @@ -187,10 +184,7 @@ impl Deques { deq.unlink_and_drop(node); } } else { - panic!( - "unlink_node - node is not a member of {} deque. {:?}", - deq_name, p - ) + panic!("unlink_node - node is not a member of {deq_name} deque. {p:?}") } } diff --git a/src/common/concurrent/entry_info.rs b/src/common/concurrent/entry_info.rs index 6ffce412..d8ff315f 100644 --- a/src/common/concurrent/entry_info.rs +++ b/src/common/concurrent/entry_info.rs @@ -179,7 +179,7 @@ mod test { if let Some(size) = expected { assert_eq!(size_of::>(), size); } else { - panic!("No expected size for {:?} with Rust version {}", arch, ver); + panic!("No expected size for {arch:?} with Rust version {ver}"); } } } diff --git a/src/common/timer_wheel.rs b/src/common/timer_wheel.rs index 6badd648..c5ac7f21 100644 --- a/src/common/timer_wheel.rs +++ b/src/common/timer_wheel.rs @@ -327,9 +327,7 @@ impl TimerWheel { let deque = &mut self.wheels[level][index]; debug_assert!( deque.len() > 0, - "BUG: The queue is empty. level: {}, index: {}", - level, - index + "BUG: The queue is empty. level: {level}, index: {index}" ); // Rotate the nodes in the queue until we see the sentinel at the back of the @@ -664,7 +662,7 @@ mod tests { let entry = maybe_entry.expect("entry is none"); match entry { TimerEvent::Expired(node) => *node.element.entry_info().key_hash().key, - _ => panic!("Expected an expired entry. Got {:?}", entry), + _ => panic!("Expected an expired entry. Got {entry:?}"), } } @@ -672,7 +670,7 @@ mod tests { let entry = maybe_entry.expect("entry is none"); match entry { TimerEvent::Rescheduled(entry) => *entry.key_hash().key, - _ => panic!("Expected a rescheduled entry. Got {:?}", entry), + _ => panic!("Expected a rescheduled entry. Got {entry:?}"), } } diff --git a/src/future/base_cache.rs b/src/future/base_cache.rs index 802131ec..96bdb8cc 100644 --- a/src/future/base_cache.rs +++ b/src/future/base_cache.rs @@ -2718,8 +2718,7 @@ mod tests { assert_eq!( cache.inner.frequency_sketch.read().await.table_len(), len as usize, - "{}", - name + "{name}" ); } @@ -2939,8 +2938,9 @@ mod tests { new_duration.map(Duration::from_secs) } expected => { - panic!("Unexpected call to expire_after_create: caller_line {}, expected: {:?}", - line!(), expected + panic!( + "Unexpected call to expire_after_create: caller_line {}, expected: {expected:?}", + line!() ); } } @@ -2992,9 +2992,8 @@ mod tests { } expected => { panic!( - "Unexpected call to expire_after_read: caller_line {}, expected: {:?}", - line!(), - expected + "Unexpected call to expire_after_read: caller_line {}, expected: {expected:?}", + line!() ); } } @@ -3037,8 +3036,9 @@ mod tests { new_duration_secs.map(Duration::from_secs) } expected => { - panic!("Unexpected call to expire_after_update: caller_line {}, expected: {:?}", - line!(), expected + panic!( + "Unexpected call to expire_after_update: caller_line {}, expected: {expected:?}", + line!() ); } } diff --git a/src/future/cache.rs b/src/future/cache.rs index fbb0b35d..1352a760 100644 --- a/src/future/cache.rs +++ b/src/future/cache.rs @@ -77,7 +77,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; /// const NUM_KEYS_PER_TASK: usize = 64; /// /// fn value(n: usize) -> String { -/// format!("value {}", n) +/// format!("value {n}") /// } /// /// // Create a cache that can store up to 10,000 entries. @@ -491,12 +491,12 @@ use std::sync::atomic::{AtomicBool, Ordering}; /// let mut path = self.base_dir.to_path_buf(); /// path.push(key.as_ref()); /// -/// assert!(!path.exists(), "Path already exists: {:?}", path); +/// assert!(!path.exists(), "Path already exists: {path:?}"); /// /// // create the file at the path and write the contents to the file. /// fs::write(&path, contents).await?; /// self.file_count += 1; -/// println!("Created a data file at {:?} (file count: {})", path, self.file_count); +/// println!("Created a data file at {path:?} (file count: {})", self.file_count); /// Ok(path) /// } /// @@ -525,7 +525,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; /// // Arc> so it can be shared across threads. /// let mut base_dir = std::env::temp_dir(); /// base_dir.push(Uuid::new_v4().as_hyphenated().to_string()); -/// println!("base_dir: {:?}", base_dir); +/// println!("base_dir: {base_dir:?}"); /// std::fs::create_dir(&base_dir)?; /// /// let file_mgr = DataFileManager::new(base_dir); @@ -536,10 +536,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; /// /// // Create an eviction lister closure. /// let eviction_listener = move |k, v: PathBuf, cause| -> ListenerFuture { -/// println!( -/// "\n== An entry has been evicted. k: {:?}, v: {:?}, cause: {:?}", -/// k, v, cause -/// ); +/// println!("\n== An entry has been evicted. k: {k:?}, v: {v:?}, cause: {cause:?}"); /// let file_mgr2 = Arc::clone(&file_mgr1); /// /// // Create a Future that removes the data file at the path `v`. @@ -549,7 +546,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; /// // Remove the data file. We must handle error cases here to /// // prevent the listener from panicking. /// if let Err(_e) = mgr.remove_data_file(v.as_path()).await { -/// eprintln!("Failed to remove a data file at {:?}", v); +/// eprintln!("Failed to remove a data file at {v:?}"); /// } /// } /// // Convert the regular Future into ListenerFuture. This method is @@ -580,7 +577,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; /// Ok(path) as anyhow::Result<_> /// }) /// .await -/// .map_err(|e| anyhow!("{}", e))?; +/// .map_err(|e| anyhow!("{e}"))?; /// /// // Read the data file at the path and print the contents. /// println!("\n== read_data_file()"); @@ -589,8 +586,8 @@ use std::sync::atomic::{AtomicBool, Ordering}; /// let contents = mgr /// .read_data_file(path.as_path()) /// .await -/// .with_context(|| format!("Failed to read data from {:?}", path))?; -/// println!("contents: {}", contents); +/// .with_context(|| format!("Failed to read data from {path:?}"))?; +/// println!("contents: {contents}"); /// } /// /// // Sleep for five seconds. While sleeping, the cache entry for key "user1" @@ -989,14 +986,14 @@ where /// .map(|task_id| { /// let my_cache = cache.clone(); /// tokio::spawn(async move { - /// println!("Task {} started.", task_id); + /// println!("Task {task_id} started."); /// /// // Insert and get the value for key1. Although all four async /// // tasks will call `get_with` at the same time, the `init` /// // async block must be resolved only once. /// let value = my_cache /// .get_with("key1", async move { - /// println!("Task {} inserting a value.", task_id); + /// println!("Task {task_id} inserting a value."); /// Arc::new(vec![0u8; TEN_MIB]) /// }) /// .await; @@ -1005,7 +1002,7 @@ where /// assert_eq!(value.len(), TEN_MIB); /// assert!(my_cache.get(&"key1").await.is_some()); /// - /// println!("Task {} got the value. (len: {})", task_id, value.len()); + /// println!("Task {task_id} got the value. (len: {})", value.len()); /// }) /// }) /// .collect(); @@ -1108,7 +1105,7 @@ where /// /// // This async function tries to get HTML from the given URI. /// async fn get_html(task_id: u8, uri: &str) -> Option { - /// println!("get_html() called by task {}.", task_id); + /// println!("get_html() called by task {task_id}."); /// reqwest::get(uri).await.ok()?.text().await.ok() /// } /// @@ -1121,7 +1118,7 @@ where /// .map(|task_id| { /// let my_cache = cache.clone(); /// tokio::spawn(async move { - /// println!("Task {} started.", task_id); + /// println!("Task {task_id} started."); /// /// // Try to insert and get the value for key1. Although /// // all four async tasks will call `try_get_with` @@ -1137,8 +1134,7 @@ where /// assert!(my_cache.get(&"key1").await.is_some()); /// /// println!( - /// "Task {} got the value. (len: {})", - /// task_id, + /// "Task {task_id} got the value. (len: {})", /// value.unwrap().len() /// ); /// }) @@ -1232,7 +1228,7 @@ where /// /// // This async function tries to get HTML from the given URI. /// async fn get_html(task_id: u8, uri: &str) -> Result { - /// println!("get_html() called by task {}.", task_id); + /// println!("get_html() called by task {task_id}."); /// reqwest::get(uri).await?.text().await /// } /// @@ -1245,7 +1241,7 @@ where /// .map(|task_id| { /// let my_cache = cache.clone(); /// tokio::spawn(async move { - /// println!("Task {} started.", task_id); + /// println!("Task {task_id} started."); /// /// // Try to insert and get the value for key1. Although /// // all four async tasks will call `try_get_with` @@ -1261,8 +1257,7 @@ where /// assert!(my_cache.get(&"key1").await.is_some()); /// /// println!( - /// "Task {} got the value. (len: {})", - /// task_id, + /// "Task {task_id} got the value. (len: {})", /// value.unwrap().len() /// ); /// }) @@ -2351,9 +2346,9 @@ mod tests { tokio::spawn(async move { barrier.wait().await; - cache.insert(10, format!("{}-100", id)).await; + cache.insert(10, format!("{id}-100")).await; cache.get(&10).await; - cache.insert(20, format!("{}-200", id)).await; + cache.insert(20, format!("{id}-200")).await; cache.invalidate(&10).await; }) }) @@ -2368,9 +2363,9 @@ mod tests { std::thread::spawn(move || { rt.block_on(barrier.wait()); - rt.block_on(cache.insert(10, format!("{}-100", id))); + rt.block_on(cache.insert(10, format!("{id}-100"))); rt.block_on(cache.get(&10)); - rt.block_on(cache.insert(20, format!("{}-200", id))); + rt.block_on(cache.insert(20, format!("{id}-200"))); rt.block_on(cache.invalidate(&10)); }) }) @@ -3072,7 +3067,7 @@ mod tests { const NUM_KEYS: usize = 50; fn make_value(key: usize) -> String { - format!("val: {}", key) + format!("val: {key}") } let cache = Cache::builder() @@ -3109,7 +3104,7 @@ mod tests { const NUM_TASKS: usize = 16; fn make_value(key: usize) -> String { - format!("val: {}", key) + format!("val: {key}") } let cache = Cache::builder() @@ -4877,7 +4872,7 @@ mod tests { cache.insert('b', "bob").await; cache.insert('c', "cindy").await; - let debug_str = format!("{:?}", cache); + let debug_str = format!("{cache:?}"); assert!(debug_str.starts_with('{')); assert!(debug_str.contains(r#"'a': "alice""#)); assert!(debug_str.contains(r#"'b': "bob""#)); @@ -4915,7 +4910,7 @@ mod tests { } for (i, (actual, expected)) in actual.iter().zip(expected).enumerate() { - assert_eq!(actual, expected, "expected[{}]", i); + assert_eq!(actual, expected, "expected[{i}]"); } break; diff --git a/src/future/notifier.rs b/src/future/notifier.rs index 356865ed..cbfbc095 100644 --- a/src/future/notifier.rs +++ b/src/future/notifier.rs @@ -67,16 +67,12 @@ fn log_panic(payload: &(dyn std::any::Any + Send + 'static), cache_name: Option< .or_else(|| payload.downcast_ref::().map(Into::into)); let cn = cache_name - .map(|name| format!("[{}] ", name)) + .map(|name| format!("[{name}] ")) .unwrap_or_default(); if let Some(m) = message { - log::error!( - "{}Disabled the eviction listener because it panicked at '{}'", - cn, - m - ); + log::error!("{cn}Disabled the eviction listener because it panicked at '{m}'"); } else { - log::error!("{}Disabled the eviction listener because it panicked", cn); + log::error!("{cn}Disabled the eviction listener because it panicked"); } } diff --git a/src/future/value_initializer.rs b/src/future/value_initializer.rs index 751f4d68..6b5c11b3 100644 --- a/src/future/value_initializer.rs +++ b/src/future/value_initializer.rs @@ -336,8 +336,7 @@ fn panic_if_retry_exhausted_for_panicking(retries: usize, max: usize) { if retries >= max { panic!( "Too many retries. Tried to read the return value from the `init` future \ - but failed {} times. Maybe the `init` kept panicking?", - retries + but failed {retries} times. Maybe the `init` kept panicking?" ); } } @@ -346,9 +345,8 @@ fn panic_if_retry_exhausted_for_aborting(retries: usize, max: usize) { if retries >= max { panic!( "Too many retries. Tried to read the return value from the `init` future \ - but failed {} times. Maybe the future containing `get_with`/`try_get_with` \ - kept being aborted?", - retries + but failed {retries} times. Maybe the future containing `get_with`/`try_get_with` \ + kept being aborted?" ); } } diff --git a/src/notification/notifier.rs b/src/notification/notifier.rs index cb7eaeda..5d70696b 100644 --- a/src/notification/notifier.rs +++ b/src/notification/notifier.rs @@ -53,16 +53,12 @@ fn log_panic(payload: &(dyn std::any::Any + Send + 'static), cache_name: Option< .or_else(|| payload.downcast_ref::().map(Into::into)); let cn = cache_name - .map(|name| format!("[{}] ", name)) + .map(|name| format!("[{name}] ")) .unwrap_or_default(); if let Some(m) = message { - log::error!( - "{}Disabled the eviction listener because it panicked at '{}'", - cn, - m - ); + log::error!("{cn}Disabled the eviction listener because it panicked at '{m}'"); } else { - log::error!("{}Disabled the eviction listener because it panicked", cn); + log::error!("{cn}Disabled the eviction listener because it panicked"); } } diff --git a/src/sync/cache.rs b/src/sync/cache.rs index 5cffb8cd..d1622127 100644 --- a/src/sync/cache.rs +++ b/src/sync/cache.rs @@ -68,7 +68,7 @@ use std::{ /// use std::thread; /// /// fn value(n: usize) -> String { -/// format!("value {}", n) +/// format!("value {n}") /// } /// /// const NUM_THREADS: usize = 16; @@ -436,12 +436,12 @@ use std::{ /// let mut path = self.base_dir.to_path_buf(); /// path.push(key.as_ref()); /// -/// assert!(!path.exists(), "Path already exists: {:?}", path); +/// assert!(!path.exists(), "Path already exists: {path:?}"); /// /// // create the file at the path and write the contents to the file. /// fs::write(&path, contents)?; /// self.file_count += 1; -/// println!("Created a data file at {:?} (file count: {})", path, self.file_count); +/// println!("Created a data file at {path:?} (file count: {})", self.file_count); /// Ok(path) /// } /// @@ -469,7 +469,7 @@ use std::{ /// // Arc> so it can be shared across threads. /// let mut base_dir = std::env::temp_dir(); /// base_dir.push(Uuid::new_v4().as_hyphenated().to_string()); -/// println!("base_dir: {:?}", base_dir); +/// println!("base_dir: {base_dir:?}"); /// std::fs::create_dir(&base_dir)?; /// /// let file_mgr = DataFileManager::new(base_dir); @@ -480,10 +480,7 @@ use std::{ /// // Create an eviction lister closure. /// let eviction_listener = move |k, v: PathBuf, cause| { /// // Try to remove the data file at the path `v`. -/// println!( -/// "\n== An entry has been evicted. k: {:?}, v: {:?}, cause: {:?}", -/// k, v, cause -/// ); +/// println!("\n== An entry has been evicted. k: {k:?}, v: {v:?}, cause: {cause:?}"); /// /// // Acquire the write lock of the DataFileManager. We must handle /// // error cases here to prevent the listener from panicking. @@ -494,7 +491,7 @@ use std::{ /// Ok(mut mgr) => { /// // Remove the data file using the DataFileManager. /// if let Err(_e) = mgr.remove_data_file(v.as_path()) { -/// eprintln!("Failed to remove a data file at {:?}", v); +/// eprintln!("Failed to remove a data file at {v:?}"); /// } /// } /// } @@ -523,7 +520,7 @@ use std::{ /// .with_context(|| format!("Failed to create a data file"))?; /// Ok(path) /// }) -/// .map_err(|e| anyhow!("{}", e))?; +/// .map_err(|e| anyhow!("{e}"))?; /// /// // Read the data file at the path and print the contents. /// println!("\n== read_data_file()"); @@ -533,8 +530,8 @@ use std::{ /// .map_err(|_e| anyhow::anyhow!("The lock has been poisoned"))?; /// let contents = mgr /// .read_data_file(path.as_path()) -/// .with_context(|| format!("Failed to read data from {:?}", path))?; -/// println!("contents: {}", contents); +/// .with_context(|| format!("Failed to read data from {path:?}"))?; +/// println!("contents: {contents}"); /// } /// /// // Sleep for five seconds. While sleeping, the cache entry for key "user1" @@ -895,13 +892,13 @@ where /// .map(|task_id| { /// let my_cache = cache.clone(); /// thread::spawn(move || { - /// println!("Thread {} started.", task_id); + /// println!("Thread {task_id} started."); /// /// // Try to insert and get the value for key1. Although all four /// // threads will call `get_with` at the same time, the `init` closure /// // must be evaluated only once. /// let value = my_cache.get_with("key1", || { - /// println!("Thread {} inserting a value.", task_id); + /// println!("Thread {task_id} inserting a value."); /// Arc::new(vec![0u8; TEN_MIB]) /// }); /// @@ -909,7 +906,7 @@ where /// assert_eq!(value.len(), TEN_MIB); /// assert!(my_cache.get(&"key1").is_some()); /// - /// println!("Thread {} got the value. (len: {})", task_id, value.len()); + /// println!("Thread {task_id} got the value. (len: {})", value.len()); /// }) /// }) /// .collect(); @@ -1113,7 +1110,7 @@ where /// /// /// This function tries to get the file size in bytes. /// fn get_file_size(thread_id: u8, path: impl AsRef) -> Option { - /// println!("get_file_size() called by thread {}.", thread_id); + /// println!("get_file_size() called by thread {thread_id}."); /// std::fs::metadata(path).ok().map(|m| m.len()) /// } /// @@ -1124,7 +1121,7 @@ where /// .map(|thread_id| { /// let my_cache = cache.clone(); /// thread::spawn(move || { - /// println!("Thread {} started.", thread_id); + /// println!("Thread {thread_id} started."); /// /// // Try to insert and get the value for key1. Although all four /// // threads will call `optionally_get_with` at the same time, @@ -1139,8 +1136,7 @@ where /// assert!(my_cache.get(&"key1").is_some()); /// /// println!( - /// "Thread {} got the value. (len: {})", - /// thread_id, + /// "Thread {thread_id} got the value. (len: {})", /// value.unwrap() /// ); /// }) @@ -1307,7 +1303,7 @@ where /// /// /// This function tries to get the file size in bytes. /// fn get_file_size(thread_id: u8, path: impl AsRef) -> Result { - /// println!("get_file_size() called by thread {}.", thread_id); + /// println!("get_file_size() called by thread {thread_id}."); /// Ok(std::fs::metadata(path)?.len()) /// } /// @@ -1318,7 +1314,7 @@ where /// .map(|thread_id| { /// let my_cache = cache.clone(); /// thread::spawn(move || { - /// println!("Thread {} started.", thread_id); + /// println!("Thread {thread_id} started."); /// /// // Try to insert and get the value for key1. Although all four /// // threads will call `try_get_with` at the same time, @@ -1333,8 +1329,7 @@ where /// assert!(my_cache.get(&"key1").is_some()); /// /// println!( - /// "Thread {} got the value. (len: {})", - /// thread_id, + /// "Thread {thread_id} got the value. (len: {})", /// value.unwrap() /// ); /// }) @@ -2074,9 +2069,9 @@ mod tests { .map(|id| { let cache = cache.clone(); std::thread::spawn(move || { - cache.insert(10, format!("{}-100", id)); + cache.insert(10, format!("{id}-100")); cache.get(&10); - cache.insert(20, format!("{}-200", id)); + cache.insert(20, format!("{id}-200")); cache.invalidate(&10); }) }) @@ -2728,7 +2723,7 @@ mod tests { const NUM_KEYS: usize = 50; fn make_value(key: usize) -> String { - format!("val: {}", key) + format!("val: {key}") } let cache = Cache::builder() @@ -2765,7 +2760,7 @@ mod tests { const NUM_THREADS: usize = 16; fn make_value(key: usize) -> String { - format!("val: {}", key) + format!("val: {key}") } let cache = Cache::builder() @@ -4149,7 +4144,7 @@ mod tests { assert_eq!(actual.len(), expected.len()); for (i, (actual, expected)) in actual.iter().zip(&expected).enumerate() { - assert_eq!(actual, expected, "expected[{}]", i); + assert_eq!(actual, expected, "expected[{i}]"); } assert!(cache.key_locks_map_is_empty()); @@ -4303,7 +4298,7 @@ mod tests { cache.insert('b', "bob"); cache.insert('c', "cindy"); - let debug_str = format!("{:?}", cache); + let debug_str = format!("{cache:?}"); assert!(debug_str.starts_with('{')); assert!(debug_str.contains(r#"'a': "alice""#)); assert!(debug_str.contains(r#"'b': "bob""#)); @@ -4336,12 +4331,12 @@ mod tests { retries += 1; continue; } else { - assert_eq!(actual.len(), expected.len(), "Retries exhausted",); + assert_eq!(actual.len(), expected.len(), "Retries exhausted"); } } for (i, (actual, expected)) in actual.iter().zip(expected).enumerate() { - assert_eq!(actual, expected, "expected[{}]", i,); + assert_eq!(actual, expected, "expected[{i}]"); } break; diff --git a/src/sync/segment.rs b/src/sync/segment.rs index 937f82b5..7cc73a54 100644 --- a/src/sync/segment.rs +++ b/src/sync/segment.rs @@ -1053,10 +1053,10 @@ mod tests { .map(|id| { let cache = cache.clone(); std::thread::spawn(move || { - cache.insert(10, format!("{}-100", id)); + cache.insert(10, format!("{id}-100")); cache.get(&10); cache.run_pending_tasks(); - cache.insert(20, format!("{}-200", id)); + cache.insert(20, format!("{id}-200")); cache.invalidate(&10); }) }) @@ -1178,7 +1178,7 @@ mod tests { let names = ["alice", "alex"].iter().cloned().collect::>(); cache.invalidate_entries_if(move |_k, &v| names.contains(v))?; - assert_eq!(cache.invalidation_predicate_count(), SEGMENTS,); + assert_eq!(cache.invalidation_predicate_count(), SEGMENTS); expected.insert(Arc::new(0), ("alice", RemovalCause::Explicit)); expected.insert(Arc::new(2), ("alex", RemovalCause::Explicit)); @@ -1210,7 +1210,7 @@ mod tests { cache.invalidate_entries_if(|_k, &v| v == "alice")?; cache.invalidate_entries_if(|_k, &v| v == "bob")?; - assert_eq!(cache.invalidation_predicate_count(), SEGMENTS * 2,); + assert_eq!(cache.invalidation_predicate_count(), SEGMENTS * 2); expected.insert(Arc::new(1), ("bob", RemovalCause::Explicit)); expected.insert(Arc::new(3), ("alice", RemovalCause::Explicit)); @@ -1239,7 +1239,7 @@ mod tests { const NUM_KEYS: usize = 50; fn make_value(key: usize) -> String { - format!("val: {}", key) + format!("val: {key}") } // let cache = SegmentedCache::builder(5) @@ -1277,7 +1277,7 @@ mod tests { const NUM_THREADS: usize = 16; fn make_value(key: usize) -> String { - format!("val: {}", key) + format!("val: {key}") } let cache = SegmentedCache::builder(4) @@ -1908,7 +1908,7 @@ mod tests { cache.insert('b', "bob"); cache.insert('c', "cindy"); - let debug_str = format!("{:?}", cache); + let debug_str = format!("{cache:?}"); assert!(debug_str.starts_with('{')); assert!(debug_str.contains(r#"'a': "alice""#)); assert!(debug_str.contains(r#"'b': "bob""#)); @@ -1942,12 +1942,12 @@ mod tests { cache.run_pending_tasks(); continue; } else { - assert_eq!(actual.len(), expected.len(), "Retries exhausted",); + assert_eq!(actual.len(), expected.len(), "Retries exhausted"); } } for (i, (actual, expected)) in actual.iter().zip(expected).enumerate() { - assert_eq!(actual, expected, "expected[{}]", i); + assert_eq!(actual, expected, "expected[{i}]"); } break; @@ -1977,7 +1977,7 @@ mod tests { cache.run_pending_tasks(); continue; } else { - assert_eq!(actual.len(), expected.len(), "Retries exhausted",); + assert_eq!(actual.len(), expected.len(), "Retries exhausted"); } } @@ -1985,8 +1985,7 @@ mod tests { assert_eq!( actual.get(actual_key), expected.get(actual_key), - "expected[{}]", - actual_key, + "expected[{actual_key}]", ); } diff --git a/src/sync/value_initializer.rs b/src/sync/value_initializer.rs index 1bf32bcd..c8496fcd 100644 --- a/src/sync/value_initializer.rs +++ b/src/sync/value_initializer.rs @@ -93,8 +93,7 @@ where } else { panic!( "Too many retries. Tried to read the return value from the `init` \ - closure but failed {} times. Maybe the `init` kept panicking?", - retries + closure but failed {retries} times. Maybe the `init` kept panicking?" ); } } diff --git a/src/sync_base/base_cache.rs b/src/sync_base/base_cache.rs index 0723319e..a81b13e6 100644 --- a/src/sync_base/base_cache.rs +++ b/src/sync_base/base_cache.rs @@ -2457,8 +2457,7 @@ mod tests { assert_eq!( cache.inner.frequency_sketch.read().table_len(), len as usize, - "{}", - name + "{name}" ); }; @@ -2675,8 +2674,9 @@ mod tests { new_duration.map(Duration::from_secs) } expected => { - panic!("Unexpected call to expire_after_create: caller_line {}, expected: {:?}", - line!(), expected + panic!( + "Unexpected call to expire_after_create: caller_line {}, expected: {expected:?}", + line!() ); } } @@ -2728,9 +2728,8 @@ mod tests { } expected => { panic!( - "Unexpected call to expire_after_read: caller_line {}, expected: {:?}", - line!(), - expected + "Unexpected call to expire_after_read: caller_line {}, expected: {expected:?}", + line!() ); } } @@ -2773,8 +2772,9 @@ mod tests { new_duration_secs.map(Duration::from_secs) } expected => { - panic!("Unexpected call to expire_after_update: caller_line {}, expected: {:?}", - line!(), expected + panic!( + "Unexpected call to expire_after_update: caller_line {}, expected: {expected:?}", + line!() ); } } diff --git a/tests/entry_api_actix_rt2.rs b/tests/entry_api_actix_rt2.rs index 1254864e..df4d3b6a 100644 --- a/tests/entry_api_actix_rt2.rs +++ b/tests/entry_api_actix_rt2.rs @@ -29,14 +29,14 @@ fn test_get_with() -> Result<(), Box> { rt.spawn(async move { my_barrier.wait().await; - println!("Task {} started.", task_id); + println!("Task {task_id} started."); let key = "key1".to_string(); let value = match task_id % 4 { 0 => { my_cache .get_with(key.clone(), async move { - println!("Task {} inserting a value.", task_id); + println!("Task {task_id} inserting a value."); my_call_counter.fetch_add(1, Ordering::AcqRel); Arc::new(vec![0u8; TEN_MIB]) }) @@ -45,7 +45,7 @@ fn test_get_with() -> Result<(), Box> { 1 => { my_cache .get_with_by_ref(key.as_str(), async move { - println!("Task {} inserting a value.", task_id); + println!("Task {task_id} inserting a value."); my_call_counter.fetch_add(1, Ordering::AcqRel); Arc::new(vec![0u8; TEN_MIB]) }) @@ -54,7 +54,7 @@ fn test_get_with() -> Result<(), Box> { 2 => my_cache .entry(key.clone()) .or_insert_with(async move { - println!("Task {} inserting a value.", task_id); + println!("Task {task_id} inserting a value."); my_call_counter.fetch_add(1, Ordering::AcqRel); Arc::new(vec![0u8; TEN_MIB]) }) @@ -63,7 +63,7 @@ fn test_get_with() -> Result<(), Box> { 3 => my_cache .entry_by_ref(key.as_str()) .or_insert_with(async move { - println!("Task {} inserting a value.", task_id); + println!("Task {task_id} inserting a value."); my_call_counter.fetch_add(1, Ordering::AcqRel); Arc::new(vec![0u8; TEN_MIB]) }) @@ -75,7 +75,7 @@ fn test_get_with() -> Result<(), Box> { assert_eq!(value.len(), TEN_MIB); assert!(my_cache.get(key.as_str()).await.is_some()); - println!("Task {} got the value. (len: {})", task_id, value.len()); + println!("Task {task_id} got the value. (len: {})", value.len()); }) }) .collect(); diff --git a/tests/entry_api_async_std.rs b/tests/entry_api_async_std.rs index 4b3ab926..6ec3ae56 100644 --- a/tests/entry_api_async_std.rs +++ b/tests/entry_api_async_std.rs @@ -26,14 +26,14 @@ async fn test_get_with() { async_std::task::spawn(async move { my_barrier.wait().await; - println!("Task {} started.", task_id); + println!("Task {task_id} started."); let key = "key1".to_string(); let value = match task_id % 4 { 0 => { my_cache .get_with(key.clone(), async move { - println!("Task {} inserting a value.", task_id); + println!("Task {task_id} inserting a value."); my_call_counter.fetch_add(1, Ordering::AcqRel); Arc::new(vec![0u8; TEN_MIB]) }) @@ -42,7 +42,7 @@ async fn test_get_with() { 1 => { my_cache .get_with_by_ref(key.as_str(), async move { - println!("Task {} inserting a value.", task_id); + println!("Task {task_id} inserting a value."); my_call_counter.fetch_add(1, Ordering::AcqRel); Arc::new(vec![0u8; TEN_MIB]) }) @@ -51,7 +51,7 @@ async fn test_get_with() { 2 => my_cache .entry(key.clone()) .or_insert_with(async move { - println!("Task {} inserting a value.", task_id); + println!("Task {task_id} inserting a value."); my_call_counter.fetch_add(1, Ordering::AcqRel); Arc::new(vec![0u8; TEN_MIB]) }) @@ -60,7 +60,7 @@ async fn test_get_with() { 3 => my_cache .entry_by_ref(key.as_str()) .or_insert_with(async move { - println!("Task {} inserting a value.", task_id); + println!("Task {task_id} inserting a value."); my_call_counter.fetch_add(1, Ordering::AcqRel); Arc::new(vec![0u8; TEN_MIB]) }) @@ -72,7 +72,7 @@ async fn test_get_with() { assert_eq!(value.len(), TEN_MIB); assert!(my_cache.get(key.as_str()).await.is_some()); - println!("Task {} got the value. (len: {})", task_id, value.len()); + println!("Task {task_id} got the value. (len: {})", value.len()); }) }) .collect(); diff --git a/tests/entry_api_sync.rs b/tests/entry_api_sync.rs index 69fb7175..c038a132 100644 --- a/tests/entry_api_sync.rs +++ b/tests/entry_api_sync.rs @@ -36,31 +36,31 @@ macro_rules! generate_test_get_with { thread::spawn(move || { my_barrier.wait(); - println!("Thread {} started.", thread_id); + println!("Thread {thread_id} started."); let key = "key1".to_string(); let value = match thread_id % 4 { 0 => my_cache.get_with(key.clone(), || { - println!("Thread {} inserting a value.", thread_id); + println!("Thread {thread_id} inserting a value."); my_call_counter.fetch_add(1, Ordering::AcqRel); Arc::new(vec![0u8; TEN_MIB]) }), 1 => my_cache.get_with_by_ref(key.as_str(), || { - println!("Thread {} inserting a value.", thread_id); + println!("Thread {thread_id} inserting a value."); my_call_counter.fetch_add(1, Ordering::AcqRel); Arc::new(vec![0u8; TEN_MIB]) }), 2 => my_cache .entry(key.clone()) .or_insert_with(|| { - println!("Thread {} inserting a value.", thread_id); + println!("Thread {thread_id} inserting a value."); my_call_counter.fetch_add(1, Ordering::AcqRel); Arc::new(vec![0u8; TEN_MIB]) }).into_value(), 3 => my_cache .entry_by_ref(key.as_str()) .or_insert_with(|| { - println!("Thread {} inserting a value.", thread_id); + println!("Thread {thread_id} inserting a value."); my_call_counter.fetch_add(1, Ordering::AcqRel); Arc::new(vec![0u8; TEN_MIB]) }).into_value(), @@ -70,7 +70,7 @@ macro_rules! generate_test_get_with { assert_eq!(value.len(), TEN_MIB); assert!(my_cache.get(key.as_str()).is_some()); - println!("Thread {} got the value. (len: {})", thread_id, value.len()); + println!("Thread {thread_id} got the value. (len: {})", value.len()); }) }) .collect(); @@ -99,7 +99,7 @@ macro_rules! generate_test_optionally_get_with { path: impl AsRef, call_counter: &AtomicUsize, ) -> Option { - println!("get_file_size() called by thread {}.", thread_id); + println!("get_file_size() called by thread {thread_id}."); call_counter.fetch_add(1, Ordering::AcqRel); std::fs::metadata(path).ok().map(|m| m.len()) } @@ -113,7 +113,7 @@ macro_rules! generate_test_optionally_get_with { thread::spawn(move || { my_barrier.wait(); - println!("Thread {} started.", thread_id); + println!("Thread {thread_id} started."); let key = "key1".to_string(); let value = match thread_id % 4 { @@ -144,8 +144,7 @@ macro_rules! generate_test_optionally_get_with { assert!(my_cache.get(key.as_str()).is_some()); println!( - "Thread {} got the value. (len: {})", - thread_id, + "Thread {thread_id} got the value. (len: {})", value.unwrap() ); }) @@ -176,7 +175,7 @@ macro_rules! generate_test_try_get_with { path: impl AsRef, call_counter: &AtomicUsize, ) -> Result { - println!("get_file_size() called by thread {}.", thread_id); + println!("get_file_size() called by thread {thread_id}."); call_counter.fetch_add(1, Ordering::AcqRel); Ok(std::fs::metadata(path)?.len()) } @@ -190,7 +189,7 @@ macro_rules! generate_test_try_get_with { thread::spawn(move || { my_barrier.wait(); - println!("Thread {} started.", thread_id); + println!("Thread {thread_id} started."); let key = "key1".to_string(); let value = match thread_id % 4 { @@ -221,8 +220,7 @@ macro_rules! generate_test_try_get_with { assert!(my_cache.get(key.as_str()).is_some()); println!( - "Thread {} got the value. (len: {})", - thread_id, + "Thread {thread_id} got the value. (len: {})", value.unwrap() ); }) diff --git a/tests/entry_api_tokio.rs b/tests/entry_api_tokio.rs index aa6a0338..0407cbba 100644 --- a/tests/entry_api_tokio.rs +++ b/tests/entry_api_tokio.rs @@ -27,14 +27,14 @@ async fn test_get_with() { tokio::spawn(async move { my_barrier.wait().await; - println!("Task {} started.", task_id); + println!("Task {task_id} started."); let key = "key1".to_string(); let value = match task_id % 4 { 0 => { my_cache .get_with(key.clone(), async move { - println!("Task {} inserting a value.", task_id); + println!("Task {task_id} inserting a value."); my_call_counter.fetch_add(1, Ordering::AcqRel); Arc::new(vec![0u8; TEN_MIB]) }) @@ -43,7 +43,7 @@ async fn test_get_with() { 1 => { my_cache .get_with_by_ref(key.as_str(), async move { - println!("Task {} inserting a value.", task_id); + println!("Task {task_id} inserting a value."); my_call_counter.fetch_add(1, Ordering::AcqRel); Arc::new(vec![0u8; TEN_MIB]) }) @@ -52,7 +52,7 @@ async fn test_get_with() { 2 => my_cache .entry(key.clone()) .or_insert_with(async move { - println!("Task {} inserting a value.", task_id); + println!("Task {task_id} inserting a value."); my_call_counter.fetch_add(1, Ordering::AcqRel); Arc::new(vec![0u8; TEN_MIB]) }) @@ -61,7 +61,7 @@ async fn test_get_with() { 3 => my_cache .entry_by_ref(key.as_str()) .or_insert_with(async move { - println!("Task {} inserting a value.", task_id); + println!("Task {task_id} inserting a value."); my_call_counter.fetch_add(1, Ordering::AcqRel); Arc::new(vec![0u8; TEN_MIB]) }) @@ -73,7 +73,7 @@ async fn test_get_with() { assert_eq!(value.len(), TEN_MIB); assert!(my_cache.get(key.as_str()).await.is_some()); - println!("Task {} got the value. (len: {})", task_id, value.len()); + println!("Task {task_id} got the value. (len: {})", value.len()); }) }) .collect(); @@ -89,7 +89,7 @@ async fn test_optionally_get_with() { let barrier = Arc::new(Barrier::new(NUM_THREADS as usize)); async fn get_html(task_id: u8, uri: &str, call_counter: &AtomicUsize) -> Option { - println!("get_html() called by task {}.", task_id); + println!("get_html() called by task {task_id}."); call_counter.fetch_add(1, Ordering::AcqRel); reqwest::get(uri).await.ok()?.text().await.ok() } @@ -103,7 +103,7 @@ async fn test_optionally_get_with() { tokio::spawn(async move { my_barrier.wait().await; - println!("Task {} started.", task_id); + println!("Task {task_id} started."); let key = "key1".to_string(); let value = match task_id % 4 { @@ -140,8 +140,7 @@ async fn test_optionally_get_with() { assert!(my_cache.get(key.as_str()).await.is_some()); println!( - "Task {} got the value. (len: {})", - task_id, + "Task {task_id} got the value. (len: {})", value.unwrap().len() ); }) @@ -163,7 +162,7 @@ async fn test_try_get_with() { uri: &str, call_counter: &AtomicUsize, ) -> Result { - println!("get_html() called by task {}.", task_id); + println!("get_html() called by task {task_id}."); call_counter.fetch_add(1, Ordering::AcqRel); reqwest::get(uri).await?.text().await } @@ -177,7 +176,7 @@ async fn test_try_get_with() { tokio::spawn(async move { my_barrier.wait().await; - println!("Task {} started.", task_id); + println!("Task {task_id} started."); let key = "key1".to_string(); let value = match task_id % 4 { @@ -211,8 +210,7 @@ async fn test_try_get_with() { assert!(my_cache.get(key.as_str()).await.is_some()); println!( - "Task {} got the value. (len: {})", - task_id, + "Task {task_id} got the value. (len: {})", value.unwrap().len() ); }) diff --git a/tests/runtime_actix_rt2.rs b/tests/runtime_actix_rt2.rs index 2a487694..82237100 100644 --- a/tests/runtime_actix_rt2.rs +++ b/tests/runtime_actix_rt2.rs @@ -13,7 +13,7 @@ async fn main() -> Result<(), Box> { const NUM_KEYS_PER_TASK: usize = 64; fn value(n: usize) -> String { - format!("value {}", n) + format!("value {n}") } // Create a cache that can store up to 10,000 entries. diff --git a/tests/runtime_async_std.rs b/tests/runtime_async_std.rs index 8d762d32..26d915f9 100644 --- a/tests/runtime_async_std.rs +++ b/tests/runtime_async_std.rs @@ -14,7 +14,7 @@ async fn main() { const NUM_KEYS_PER_TASK: usize = 64; fn value(n: usize) -> String { - format!("value {}", n) + format!("value {n}") } // Create a cache that can store up to 10,000 entries. diff --git a/tests/runtime_tokio.rs b/tests/runtime_tokio.rs index 9b4d4c74..e107c061 100644 --- a/tests/runtime_tokio.rs +++ b/tests/runtime_tokio.rs @@ -12,7 +12,7 @@ async fn main() { const NUM_KEYS_PER_TASK: usize = 64; fn value(n: usize) -> String { - format!("value {}", n) + format!("value {n}") } // Create a cache that can store up to 10,000 entries.