use std::collections::HashMap;
use cooper::Actor;
type State = HashMap<String, String>;
#[derive(Clone)]
pub struct SharedMap {
actor: Actor<State>,
}
impl SharedMap {
pub fn new() -> Self {
Self { actor: Actor::new() }
}
pub async fn insert<K,V>(&self, key: K, val: V)
where
K: Into<String>,
V: Into<String>,
{
let key = key.into();
let val = val.into();
self.actor.cast(|state| Box::pin(async move {
state.insert(key, val);
})).await
}
pub async fn get<K>(&self, key: K) -> Option<String>
where
K: Into<String>,
{
let key = key.into();
self.actor.call(|state| Box::pin(async move {
state.get(&key).map(|v| v.to_string())
})).await
}
}
fn main() {
let map = SharedMap::new();
let h = smol::spawn(async move {
println!("Inserting entry 'city'...");
map.insert("city", "Boston").await;
println!("Retrieving entry...");
match map.get("city").await {
Some(s) => println!("Got: {}", s),
None => println!("Error: No entry found"),
}
});
smol::block_on(h);
}