rusqlite/util/
param_cache.rs1use super::SmallCString;
2use std::cell::RefCell;
3use std::collections::BTreeMap;
4
5#[derive(Default, Clone, Debug)]
7pub(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 if let Some(v) = cache.get(s) {
19 return Some(*v);
20 }
21 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}