threaded_keyval/
threaded_keyval.rs

1// cooper-rs/examples/threaded_keyval.rs
2//
3// This is an example app for the Rust "cooper" library.
4//
5// Copyright (c) 2021, Frank Pagliughi <fpagliughi@mindspring.com>
6// All Rights Reserved
7//
8// Licensed under the MIT license:
9//   <LICENSE or http://opensource.org/licenses/MIT>
10// This file may not be copied, modified, or distributed except according
11// to those terms.
12//
13
14use std::collections::HashMap;
15use cooper::ThreadedActor;
16
17/// The internal state type for the Actor
18type State = HashMap<String, String>;
19
20/// An actor that can act as a shared key/value store of strings.
21#[derive(Clone)]
22pub struct SharedMap {
23    actor: ThreadedActor<State>,
24}
25
26impl SharedMap {
27    /// Create a new actor to share a key/value map of string.
28    pub fn new() -> Self {
29        Self { actor: ThreadedActor::new() }
30    }
31
32    /// Insert a value into the shared map.
33    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    /// Gets the value, if any, from the shared map that is
48    /// associated with the key.
49    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
57// --------------------------------------------------------------------------
58
59fn 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