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
/// If variable is equal with the given
/// parameter returns true, otherwise false.
pub trait Is<T> {
    fn is(&self, is: T) -> bool;
}

/// If variable value is exactly the given
/// parameter, returns true, or false.
pub trait IfEq<T> {
    fn if_eq(&self, is: T) -> bool;
}

pub trait Then<R, F> {
    fn then(&self, f: F) -> R
    where
        F: Fn() -> R;
}

pub trait ThenPrint {
    fn then_print(&self, msg: &str) -> String;
}

// Generics implementation
impl<T> Is<T> for T
where
    T: std::cmp::PartialEq,
{
    fn is(&self, is: T) -> bool {
        *self == is
    }
}

// Generics implementation
impl<T> IfEq<T> for T
where
    T: std::cmp::PartialEq,
{
    fn if_eq(&self, is: T) -> bool {
        *self == is
    }
}

// Generics implementation
impl ThenPrint for bool {
    fn then_print(&self, msg: &str) -> String {
        if *self {
            return msg.to_owned();
        }
        msg.to_owned()
    }
}

impl<R, F> Then<R, F> for bool {
    fn then(&self, f: F) -> R
    where
        F: Fn() -> R,
    {
        f()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn it_works() {
        assert_eq!(9.if_eq(9).then_print("It works"), "It works".to_owned());
        assert_eq!(9.if_eq(9).then(|| "It works"), "It works".to_owned());
        assert_eq!(9.if_eq(9).then(|| (0..100).collect::<Vec<_>>().len()), 100);
        assert_eq!("alma".if_eq("alma").then(|| "ok"), "ok");
        assert_ne!("alma".if_eq("alma").then(|| "ok"), "_ok");
    }
}