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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//! Tests if all sub-conditions succeeds.

use crate::condition::*;

/// Returns `true` if all of its conditions return `true`.
///
/// # Example
/// ```
/// use emergent::prelude::*;
///
/// let condition = CombinatorAll::default()
///     .condition(true)
///     .condition(true);
/// assert_eq!(condition.validate(&()), true);
///
/// let condition = CombinatorAll::default()
///     .condition(false)
///     .condition(true);
/// assert_eq!(condition.validate(&()), false);
/// ```
pub struct CombinatorAll<M> {
    pub conditions: Vec<Box<dyn Condition<M>>>,
}

impl<M> Default for CombinatorAll<M> {
    fn default() -> Self {
        Self { conditions: vec![] }
    }
}

impl<M> CombinatorAll<M> {
    /// Constructs new condition with list of sub-conditions.
    pub fn new(conditions: Vec<Box<dyn Condition<M>>>) -> Self {
        Self { conditions }
    }

    /// Add child condition.
    pub fn condition<C>(mut self, condition: C) -> Self
    where
        C: Condition<M> + 'static,
    {
        self.conditions.push(Box::new(condition));
        self
    }
}

impl<M> Condition<M> for CombinatorAll<M> {
    fn validate(&self, memory: &M) -> bool {
        self.conditions
            .iter()
            .all(|condition| condition.validate(memory))
    }
}

impl<M> std::fmt::Debug for CombinatorAll<M> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CombinatorAll").finish()
    }
}