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
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
use super::{then::Then, when::When, Execute, Result, ThenFn, WhenFn};

/// Case holds group of when/then clauses
pub struct Case<C, E> {
    #[allow(dead_code)]
    name: String,
    cases: Vec<(Option<When<C, E>>, Option<Box<Execute<C, E>>>)>,
}

impl<C: 'static, E: 'static> Case<C, E> {
    /// Create a new case group
    ///
    /// # Examples
    ///
    /// ```
    /// use tweak::Case;
    ///
    /// let case = Case::<String, ()>::new("string manipulation");
    /// ```
    pub fn new<T: Into<String>>(name: T) -> Self {
        Case {
            name: name.into(),
            cases: vec![],
        }
    }

    // Describe a new condition to test.
    pub fn when<T>(mut self, name: T, f: WhenFn<C, E>) -> Self
    where
        T: Into<String>,
    {
        self.cases.push((Some(When::new(name, f)), None));
        self
    }

    /// Describe an action to run if its `then` block returns `false`.
    pub fn then<T>(mut self, name: T, f: ThenFn<C, E>) -> Self
    where
        T: Into<String>,
    {
        self.push_action(Box::new(Then::new(name, f)));
        self
    }

    /// Describe a group of then/when clauses to run if its `then` block returns `false`.
    pub fn then_case<T, F>(mut self, name: T, f: F) -> Self
    where
        T: Into<String>,
        F: FnOnce(Case<C, E>) -> Case<C, E>,
    {
        let case = f(Case::new(name));
        self.push_action(Box::new(case));
        self
    }

    fn push_action(&mut self, act: Box<Execute<C, E>>) {
        if let Some(case) = self.cases.last_mut() {
            case.1 = Some(act);
        }
    }

    /// Run all described statements.
    pub fn run(&self, ctx: &mut C) -> Result<bool, E> {
        self.exec(ctx)
    }
}

impl<C, E> Execute<C, E> for Case<C, E> {
    fn exec(&self, ctx: &mut C) -> Result<bool, E> {
        let mut changed = false;

        for (check, action) in self.cases.iter() {
            if check.is_none() {
                continue;
            }
            match check.as_ref().unwrap().check(ctx) {
                Ok(true) => {
                    if let Some(a) = action {
                        a.exec(ctx)?;
                    }
                    if !changed {
                        changed = true;
                    }
                }
                e @ Err(_) => return e,
                _ => {}
            }
        }

        Ok(changed)
    }
}

#[cfg(test)]
mod test {
    use super::Case;

    struct Ctx {
        x: i32,
    }
    impl Ctx {
        fn new(x: i32) -> Self {
            Ctx { x }
        }
    }

    #[test]
    fn cascade_when_error() {
        let mut c = Ctx::new(0);
        let res = Case::<Ctx, &str>::new("errored case")
            .when("check", |_| Err("when error"))
            .then("action", |ctx: &mut Ctx| {
                ctx.x = 5;
                Err("when error")
            })
            .run(&mut c);

        assert_eq!(res, Err("when error"));
        assert_eq!(c.x, 0);
    }

    #[test]
    fn cascade_then_error() {
        let mut c = Ctx::new(0);
        let res = Case::<Ctx, &str>::new("errored case")
            .when("check", |_| Ok(true))
            .then("check", |_| Err("then error"))
            .run(&mut c);

        assert_eq!(res, Err("then error"));
        assert_eq!(c.x, 0);
    }

    #[test]
    fn context_mutation() {
        let mut c = Ctx::new(5);
        let res = Case::<Ctx, &str>::new("errored case")
            .when("is 3", |ctx: &mut Ctx| Ok(ctx.x == 3))
            .then("multiply by 3", |ctx: &mut Ctx| {
                ctx.x *= 3;
                Ok(())
            })
            .when("is 5", |ctx: &mut Ctx| Ok(ctx.x == 5))
            .then("multiply by 5", |ctx: &mut Ctx| {
                ctx.x *= 5;
                Ok(())
            })
            .run(&mut c);

        assert_eq!(res, Ok(true));
        assert_eq!(c.x, 25);
    }

    #[test]
    fn nested_cases() {
        let mut c = Ctx::new(5);
        let res = Case::<Ctx, &str>::new("errored case")
            .when("is 3", |ctx: &mut Ctx| Ok(ctx.x == 3))
            .then_case("nested 3", |sub| {
                sub.when("check", |_ctx| Ok(true)).then("action", |ctx| {
                    ctx.x = 33;
                    Ok(())
                })
            })
            .when("is 5", |ctx: &mut Ctx| Ok(ctx.x == 5))
            .then_case("nested 5", |sub| {
                sub.when("check", |_ctx| Ok(true)).then("action", |ctx| {
                    ctx.x = 55;
                    Ok(())
                })
            })
            .run(&mut c);

        assert_eq!(res, Ok(true));
        assert_eq!(c.x, 55);
    }

    #[test]
    fn when_nothing_is_changed() {
        let mut c = Ctx::new(1);
        let res = Case::<Ctx, &str>::new("errored case")
            .when("is 3", |ctx: &mut Ctx| Ok(ctx.x == 3))
            .then("multiply by 3", |ctx: &mut Ctx| {
                ctx.x *= 3;
                Ok(())
            })
            .when("is 5", |ctx: &mut Ctx| Ok(ctx.x == 5))
            .then("multiply by 5", |ctx: &mut Ctx| {
                ctx.x *= 5;
                Ok(())
            })
            .run(&mut c);

        assert_eq!(res, Ok(false));
        assert_eq!(c.x, 1);
    }
}