rumtk_core/
cache.rs

1/*
2 * rumtk attempts to implement HL7 and medical protocols for interoperability in medicine.
3 * This toolkit aims to be reliable, simple, performant, and standards compliant.
4 * Copyright (C) 2024  Luis M. Santos, M.D.
5 * Copyright (C) 2025  MedicalMasses L.L.C.
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
20 */
21
22pub use ahash::AHashMap;
23use core::hash::Hash;
24pub use once_cell::unsync::Lazy;
25use std::sync::Arc;
26pub use std::sync::Mutex;
27/**************************** Constants**************************************/
28pub const DEFAULT_CACHE_PAGE_SIZE: usize = 10;
29/// I don't think most scenarios will need more than 10 items worth of memory pre-allocated at a time.
30/**************************** Caches ****************************************/
31
32/**************************** Types *****************************************/
33///
34/// Generic Cache store object. One use case will be to use a search string as the key and store
35/// the search parsing object here.
36///
37pub type RUMCache<K, V> = AHashMap<K, V>;
38pub type LazyRUMCache<K, V> = Lazy<Arc<RUMCache<K, V>>>;
39
40/**************************** Traits ****************************************/
41
42/**************************** Helpers ***************************************/
43pub const fn new_cache<K, V>() -> LazyRUMCache<K, V> {
44    LazyRUMCache::new(|| Arc::new(RUMCache::with_capacity(DEFAULT_CACHE_PAGE_SIZE)))
45}
46
47pub fn get_or_set_from_cache<'a, K, V, F>(
48    cache: &'a mut LazyRUMCache<K, V>,
49    expr: &K,
50    new_fn: F,
51) -> &'a V
52where
53    K: Hash + Eq + Clone,
54    V: Clone,
55    F: Fn(&K) -> V,
56{
57    if !cache.contains_key(expr) {
58        let mut cache_ref = Arc::get_mut(cache).unwrap();
59        cache_ref.insert(expr.clone(), new_fn(expr).clone());
60    }
61    cache.get(expr).unwrap()
62}
63
64pub mod cache_macros {
65    ///
66    /// Searches for item in global cache. If global cache lacks item, create item using factory
67    /// function passed to this macro.
68    ///
69    /// ```
70    /// use rumtk_core::rumtk_cache_fetch;
71    /// use rumtk_core::cache::{new_cache, LazyRUMCache};
72    /// use std::sync::Arc;
73    ///
74    /// type StringCache = LazyRUMCache<String, String>;
75    ///
76    /// fn init_cache(k: &String) -> String {
77    ///    String::from(k)
78    /// }
79    ///
80    /// let mut cache: StringCache = new_cache();
81    ///
82    /// let test_key: String = String::from("Hello World");
83    /// let v = rumtk_cache_fetch!(
84    ///     &mut cache,
85    ///     &test_key,
86    ///     init_cache
87    /// );
88    ///
89    /// assert_eq!(test_key.as_str(), v.as_str(), "The inserted key is not the same to what was passed as input!");
90    ///
91    ///
92    /// ```
93    ///
94    #[macro_export]
95    macro_rules! rumtk_cache_fetch {
96        ( $cache:expr, $key:expr, $func:expr ) => {{
97            use $crate::cache::get_or_set_from_cache;
98            unsafe { get_or_set_from_cache($cache, $key, $func) }
99        }};
100    }
101}