Skip to content

Commit 9b0e876

Browse files
perf(context): optimize Context map lookups to reduce lock contention and cloning
- Replaces double HashMap lookups with a single `.get().cloned()` call. - Uses pattern matching in `value()`, `get_func()`, and `get_variable()` to directly handle the cloned `ContextValue` variant without redundant `clone()` invocations on the inner types. - Crucially, allows the Mutex lock to be dropped earlier in `value()` before executing arbitrary long-running inner function closures. - Included unit tests to cover the edge cases to resolve codecov issue. Co-authored-by: ashyanSpada <22587148+ashyanSpada@users.noreply.github.com>
1 parent 75e8276 commit 9b0e876

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

src/context.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,3 +98,31 @@ macro_rules! create_context {
9898
ctx
9999
}};
100100
}
101+
102+
#[cfg(test)]
103+
mod tests {
104+
use super::*;
105+
use std::sync::Arc;
106+
107+
#[test]
108+
fn test_context() {
109+
let mut ctx = Context::new();
110+
ctx.set_variable("a", Value::from(1));
111+
ctx.set_func("f", Arc::new(|_| Ok(Value::from(2))));
112+
113+
// get_func
114+
assert!(ctx.get_func("f").is_some());
115+
assert!(ctx.get_func("a").is_none()); // covers Variable(_) => None
116+
assert!(ctx.get_func("nonexistent").is_none());
117+
118+
// get_variable
119+
assert!(ctx.get_variable("a").is_some());
120+
assert!(ctx.get_variable("f").is_none()); // covers Function(_) => None
121+
assert!(ctx.get_variable("nonexistent").is_none());
122+
123+
// value
124+
assert_eq!(ctx.value("a").unwrap(), Value::from(1));
125+
assert_eq!(ctx.value("f").unwrap(), Value::from(2));
126+
assert_eq!(ctx.value("nonexistent").unwrap(), Value::None);
127+
}
128+
}

0 commit comments

Comments
 (0)