matecito/
lib.rs

1pub(crate) mod bloom_filter;
2pub(crate) mod cache;
3pub(crate) mod matecito_internal;
4
5use std::sync::Arc;
6
7/// Matecito is an experimental concurrent cache. Its main purpose is to
8/// give a thread safe interface to use an in-memory storage for some
9/// expensive computations.
10///
11/// # Example
12///
13/// ```no_run
14/// use matecito::Matecito;
15///
16/// // Initialize the cache with space for 1024 objects.
17/// let m = Matecito::<u64, String>::new(2usize.pow(10));
18/// let m1 = m.clone();
19/// std::thread::spawn(move || {
20///     m1.put(123, "asd".to_string());
21///     m1.put(01010101, "321".to_string());
22/// });
23/// // We need to give the cache a sec to populate the values.
24/// std::thread::sleep(std::time::Duration::from_millis(1));   
25/// assert_eq!(Some("asd".to_string()), m.get(123));
26///
27/// ```
28
29pub struct Matecito<K, T>(Arc<cache::Cache<K, T>>);
30
31impl<K: Clone + Ord + std::hash::Hash, T: std::fmt::Debug + Clone> Matecito<K, T> {
32    // num_elements should be a power of two
33    pub fn new(num_elements: usize) -> Self {
34        let put_threshold = 1000;
35        Self(Arc::new(cache::Cache::new(num_elements, put_threshold)))
36    }
37
38    pub fn put(&self, key: K, value: T) {
39        self.0.put(key, value)
40    }
41
42    pub fn get(&self, key: K) -> Option<T> {
43        self.0.get(key)
44    }
45}
46
47impl<K, T> Clone for Matecito<K, T> {
48    fn clone(&self) -> Self {
49        let cache = self.0.clone();
50        Self(cache)
51    }
52}
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57    #[test]
58    fn test_simple() {
59        let m = Matecito::<u64, String>::new(2usize.pow(10));
60        let m1 = m.clone();
61        std::thread::spawn(move || {
62            m1.put(123, "asd".to_string());
63            m1.put(01010101, "321".to_string());
64        });
65
66        std::thread::sleep(std::time::Duration::from_millis(1));
67
68        let m2 = m.clone();
69        let result = std::thread::spawn(move || m2.get(123)).join();
70        assert_eq!(Some("asd".to_string()), result.unwrap());
71
72        let m3 = m.clone();
73        let result = std::thread::spawn(move || m3.get(01010101)).join();
74        assert_eq!(Some("321".to_string()), result.unwrap());
75
76        let m4 = m.clone();
77        let result = std::thread::spawn(move || m4.get(0xf00)).join();
78        assert_eq!(None, result.unwrap());
79    }
80}