use std::collections::HashMap;
use std::hash::Hash;
use tokio::sync::RwLock;
pub trait RwLockMapExt<K, V> {
fn cloned_keys(&self) -> impl std::future::Future<Output = Vec<K>> + Send
where
K: Clone;
fn cloned_values(&self) -> impl std::future::Future<Output = Vec<V>> + Send
where
V: Clone;
fn cloned_get<'a>(&'a self, key: &'a K) -> impl std::future::Future<Output = Option<V>> + Send
where
V: Clone;
}
impl<K, V> RwLockMapExt<K, V> for RwLock<HashMap<K, V>>
where
K: Eq + Hash + Send + Sync,
V: Send + Sync,
{
async fn cloned_keys(&self) -> Vec<K>
where
K: Clone,
{
self.read().await.keys().cloned().collect()
}
async fn cloned_values(&self) -> Vec<V>
where
V: Clone,
{
self.read().await.values().cloned().collect()
}
async fn cloned_get(&self, key: &K) -> Option<V>
where
V: Clone,
{
self.read().await.get(key).cloned()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn cloned_keys_returns_all_keys() {
let mut map = HashMap::new();
map.insert("a".to_string(), 1);
map.insert("b".to_string(), 2);
let lock = RwLock::new(map);
let mut keys = lock.cloned_keys().await;
keys.sort();
assert_eq!(keys, vec!["a".to_string(), "b".to_string()]);
}
#[tokio::test]
async fn cloned_values_returns_all_values() {
let mut map = HashMap::new();
map.insert("a".to_string(), 1);
map.insert("b".to_string(), 2);
let lock = RwLock::new(map);
let mut values = lock.cloned_values().await;
values.sort();
assert_eq!(values, vec![1, 2]);
}
#[tokio::test]
async fn cloned_keys_empty_map() {
let lock: RwLock<HashMap<String, i32>> = RwLock::new(HashMap::new());
assert!(lock.cloned_keys().await.is_empty());
}
#[tokio::test]
async fn cloned_get_returns_a_clone_of_the_value_for_an_existing_key() {
let mut map = HashMap::new();
map.insert("a".to_string(), 1);
map.insert("b".to_string(), 2);
let lock = RwLock::new(map);
assert_eq!(lock.cloned_get(&"a".to_string()).await, Some(1));
}
#[tokio::test]
async fn cloned_get_returns_none_for_a_missing_key() {
let mut map = HashMap::new();
map.insert("a".to_string(), 1);
let lock = RwLock::new(map);
assert_eq!(lock.cloned_get(&"missing".to_string()).await, None);
}
}