Skip to main content

rusqlite/util/
param_cache.rs

1use super::SmallCString;
2use std::cell::RefCell;
3use std::collections::BTreeMap;
4
5/// Maps parameter names to parameter indices.
6#[derive(Default, Clone, Debug)]
7// BTreeMap seems to do better here unless we want to pull in a custom hash
8// function.
9pub(crate) struct ParamIndexCache(RefCell<BTreeMap<SmallCString, usize>>);
10
11impl ParamIndexCache {
12    pub fn get_or_insert_with<F>(&self, s: &str, func: F) -> Option<usize>
13    where
14        F: FnOnce(&std::ffi::CStr) -> Option<usize>,
15    {
16        let mut cache = self.0.borrow_mut();
17        // Avoid entry API, needs allocation to test membership.
18        if let Some(v) = cache.get(s) {
19            return Some(*v);
20        }
21        // If there's an internal nul in the name it couldn't have been a
22        // parameter, so early return here is ok.
23        let name = SmallCString::new(s).ok()?;
24        let val = func(&name)?;
25        cache.insert(name, val);
26        Some(val)
27    }
28}
29
30#[cfg(test)]
31mod test {
32    #[cfg(all(target_family = "wasm", target_os = "unknown"))]
33    use wasm_bindgen_test::wasm_bindgen_test as test;
34
35    use super::*;
36    #[test]
37    fn test_cache() {
38        let p = ParamIndexCache::default();
39        let v = p.get_or_insert_with("foo", |cstr| {
40            assert_eq!(cstr.to_str().unwrap(), "foo");
41            Some(3)
42        });
43        assert_eq!(v, Some(3));
44        let v = p.get_or_insert_with("foo", |_| {
45            panic!("shouldn't be called this time");
46        });
47        assert_eq!(v, Some(3));
48        let v = p.get_or_insert_with("gar\0bage", |_| {
49            panic!("shouldn't be called here either");
50        });
51        assert_eq!(v, None);
52        let v = p.get_or_insert_with("bar", |cstr| {
53            assert_eq!(cstr.to_str().unwrap(), "bar");
54            None
55        });
56        assert_eq!(v, None);
57        let v = p.get_or_insert_with("bar", |cstr| {
58            assert_eq!(cstr.to_str().unwrap(), "bar");
59            Some(30)
60        });
61        assert_eq!(v, Some(30));
62    }
63}