1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
use { BehaviourResult, BehaviourNode };

/// A decorator which only evaluates the child node if the callback function returns `true`.
///
pub struct ConditionalDecorator<'a, T, F> {
    pub name: &'static str,
    pub child: Box<BehaviourNode<T> + 'a>,
    callback: F
}

impl <'a, T, F: FnMut(&mut T) -> bool + 'a> ConditionalDecorator<'a, T, F> {

    pub fn with_child(name: &'static str, callback: F, child: Box<BehaviourNode<T> + 'a>) -> ConditionalDecorator<'a, T, F> {
        ConditionalDecorator {
            name: name,
            callback: callback,
            child: child
        }
    }

}

impl <'a, T: Clone, F: FnMut(&mut T) -> bool> BehaviourNode<T> for ConditionalDecorator<'a, T, F> {

    fn evaluate(&mut self, target: &mut T) -> BehaviourResult {
        if self.callback.call_mut((&mut target.clone(),)) {
            self.child.evaluate(target)
        } else {
            BehaviourResult::Failure
        }
    }

}