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
/*!
Object implementing `Ensure` trait are in unknown inital state and can be brought to a target state.

By calling `met()` we can be ensured that object is in its target state regardles if it was already in that state or had to be brought to it.
If object was already in target state nothing happens. Otherwise `met()` will call `meet()` on provided `MeetAction` type to bring the object into its target state.

If object implements `Clone` method `met_verify()` can be used to make sure that object fulfills `Met` condition after `MeetAction` type has been preformed.

Closures returning `TryMetResult` that also return closure in `TryMetResult::MeetAction` variant automatically implement `Ensure` trait. 
Helper function `ensure` can be used to call `met()` on such closure.

# Example

This program will create file only if it does not exist.

```rust
use std::path::Path;
use std::fs::File;
use ensure::ensure;
use ensure::TryMetResult::*;

let path = Path::new("/tmp/foo.txt");

ensure(|| {
    if path.exists() {
        Met(())
    } else {
        MeetAction(|| {
            File::create(&path).unwrap();
        })
    }
});
```
*/

use std::fmt;
use std::error::Error;

/// Result of verification if object is in target state with `try_met()`
#[derive(Debug)]
pub enum TryMetResult<M, U> {
    Met(M),
    MeetAction(U),
}

/// Result of ensuring target state with `met()`
#[derive(Debug)]
pub enum MetResult<N, M> {
    AlreadyMet(N),
    Met(M),
}

impl<T> MetResult<T, T> {
    /// When `Ensure::Met` and `Ensure::MeetAction::Met` types are the same `coalesce()` will return single return type regardless of actual result
    pub fn coalesce(self) -> T {
        match self {
            MetResult::AlreadyMet(met) | MetResult::Met(met) => met
        }
    }
}

#[derive(Debug)]
pub struct UnmetError;

impl fmt::Display for UnmetError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "verification of target state failed after it was ensured to be met")
    }
}

impl Error for UnmetError {}

/// Implement for types of objects that can be brought to target state
pub trait Ensure: Sized {
    type MeetAction: MeetAction;
    type Met;

    /// Check if already `Met` or provide `MeetAction` which can be performed by calling `meet()`
    fn try_met(self) -> TryMetResult<Self::Met, Self::MeetAction>;

    /// Meet the Ensure by calling `try_met()` and if not `Met` calling `meet()` on `MeetAction`
    fn met(self) -> MetResult<Self::Met, <Self::MeetAction as MeetAction>::Met> {
        match self.try_met() {
            TryMetResult::Met(met) => MetResult::AlreadyMet(met),
            TryMetResult::MeetAction(meet) => MetResult::Met(meet.meet()),
        }
    }

    /// Ensure it is `met()` and then verify it is in fact `Met` with `try_met()`
    fn met_verify(self) -> Result<Self::Met, UnmetError> where Self: Clone {
        let verify = self.clone();
        match self.met() {
            MetResult::AlreadyMet(met) => Ok(met),
            MetResult::Met(_action_met) => match verify.try_met() {
                TryMetResult::Met(met) => Ok(met),
                TryMetResult::MeetAction(_action) => Err(UnmetError),
            }
        }
    }
}

/// Function that can be used to bring object in its target state
pub trait MeetAction {
    type Met;

    fn meet(self) -> Self::Met;
}

impl<MET, MA, IMF> Ensure for IMF 
where IMF: FnOnce() -> TryMetResult<MET, MA>, MA: MeetAction {
    type MeetAction = MA;
    type Met = MET;

    fn try_met(self) -> TryMetResult<Self::Met, Self::MeetAction> {
        self()
    }
}

impl<MET, MF> MeetAction for MF
where MF: FnOnce() -> MET {
    type Met = MET;

    fn meet(self) -> Self::Met {
        self()
    }
}

/// Run `met()` on object implementing `Ensure` and return its value.
/// This is useful with closures implementing `Ensure`.
pub fn ensure<E>(ensure: E) -> MetResult<E::Met, <E::MeetAction as MeetAction>::Met> where E:  Ensure {
    ensure.met()
}

/// Mark `T` as something that exists
pub struct Existing<T>(pub T);
/// Mark `T` as something that does not exists
pub struct NonExisting<T>(pub T);

/// Extends any `T` with method allowing to declare it as existing or non-existing
pub trait Existential: Sized {
    fn assume_existing(self) -> Existing<Self> {
        Existing(self)
    }

    fn assume_non_existing(self) -> NonExisting<Self> {
        NonExisting(self)
    }
}

impl<T> Existential for T {}

#[cfg(test)]
mod test {
    use super::*;
    use super::MetResult::*;
    use assert_matches::*;

    #[test]
    fn test_closure() {
        fn test(met: bool) -> impl Ensure<Met = u8, MeetAction = impl MeetAction<Met = u16>> {
            move || {
                match met {
                    true => TryMetResult::Met(1),
                    _ => TryMetResult::MeetAction(move || 2)
                }
            }
        }

        assert_matches!(test(true).met(), AlreadyMet(1));
        assert_matches!(test(false).met(), Met(2));

        assert_matches!(ensure(test(true)), AlreadyMet(1));
        assert_matches!(ensure(test(false)), Met(2));
    }

    #[test]
    fn test_coalesce() {
        fn test(met: bool) -> impl Ensure<Met = u8, MeetAction = impl MeetAction<Met = u8>> {
            move || {
                match met {
                    true => TryMetResult::Met(1),
                    _ => TryMetResult::MeetAction(move || 2)
                }
            }
        }

        assert_eq!(ensure(test(true)).coalesce(), 1);
        assert_eq!(ensure(test(false)).coalesce(), 2);
    }
}