threaded_keyval/
threaded_keyval.rs1use std::collections::HashMap;
15use cooper::ThreadedActor;
16
17type State = HashMap<String, String>;
19
20#[derive(Clone)]
22pub struct SharedMap {
23 actor: ThreadedActor<State>,
24}
25
26impl SharedMap {
27 pub fn new() -> Self {
29 Self { actor: ThreadedActor::new() }
30 }
31
32 pub fn insert<K,V>(&self, key: K, val: V)
34 where
35 K: Into<String>,
36 V: Into<String>,
37 {
38 let key = key.into();
39 let val = val.into();
40
41 self.actor.cast(move |state| {
42 state.insert(key, val);
43 });
44 }
45
46
47 pub fn get<K: Into<String>>(&self, key: K) -> Option<String> {
50 let key = key.into();
51 self.actor.call(move |state| {
52 state.get(&key).map(|v| v.to_string())
53 })
54 }
55}
56
57fn main() {
60 let map = SharedMap::new();
61
62 println!("Inserting entry 'city'...");
63 map.insert("city", "Boston");
64
65 println!("Retrieving entry...");
66 match map.get("city") {
67 Some(s) => println!("Got: {}", s),
68 None => println!("Error: No entry found"),
69 }
70}
71