git.delta.rocks / jrsonnet / refs/commits / 91108e4246a4

difftreelog

perf(evaluator) drop lazy closure after evaluation

Лач2020-06-26parent: #1e39819.patch.diff
in: master

1 file changed

modifiedcrates/jsonnet-evaluator/src/val.rsdiffbeforeafterboth
10 rc::Rc,10 rc::Rc,
11};11};
1212
13struct LazyValInternals {13enum LazyValInternals {
14 Computed(Val),
14 pub f: Option<Box<dyn Fn() -> Result<Val>>>,15 Waiting(Box<dyn Fn() -> Result<Val>>),
15 pub cached: RefCell<Option<Val>>,
16}16}
17#[derive(Clone)]17#[derive(Clone)]
18pub struct LazyVal(Rc<LazyValInternals>);18pub struct LazyVal(Rc<RefCell<LazyValInternals>>);
19impl LazyVal {19impl LazyVal {
20 pub fn new(f: Box<dyn Fn() -> Result<Val>>) -> Self {20 pub fn new(f: Box<dyn Fn() -> Result<Val>>) -> Self {
21 LazyVal(Rc::new(LazyValInternals {21 LazyVal(Rc::new(RefCell::new(LazyValInternals::Waiting(f))))
22 f: Some(f),
23 cached: RefCell::new(None),
24 }))
25 }22 }
26 pub fn new_resolved(val: Val) -> Self {23 pub fn new_resolved(val: Val) -> Self {
27 LazyVal(Rc::new(LazyValInternals {24 LazyVal(Rc::new(RefCell::new(LazyValInternals::Computed(val))))
28 f: None,
29 cached: RefCell::new(Some(val)),
30 }))
31 }25 }
32 pub fn evaluate(&self) -> Result<Val> {26 pub fn evaluate(&self) -> Result<Val> {
33 {
34 let cached = self.0.cached.borrow();
35 if cached.is_some() {27 let new_value = match &*self.0.borrow() {
36 return Ok(cached.clone().unwrap());28 LazyValInternals::Computed(v) => return Ok(v.clone()),
29 LazyValInternals::Waiting(f) => f()?,
37 }30 };
38 }
39 let result = (self.0.f.as_ref().unwrap())()?;
40 self.0.cached.borrow_mut().replace(result.clone());31 *self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());
41 Ok(result)32 Ok(new_value)
42 }33 }
43}34}
4435
56}47}
57impl Debug for LazyVal {48impl Debug for LazyVal {
58 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {49 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59 if self.0.cached.borrow().is_some() {
60 write!(f, "{:?}", self.0.cached.borrow().clone().unwrap())
61 } else {
62 write!(f, "Lazy")50 write!(f, "Lazy")
63 }
64 }51 }
65}52}
66impl PartialEq for LazyVal {53impl PartialEq for LazyVal {