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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
/*!
Object implementing `Ensure` trait are in unknown inital external state and can be brought to a target state.

This can be seen as `TryInto` trait for objects with side effects with unknown initial external state and desired target state.

By calling `ensure()` 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 `ensure()` will call `meet()` on provided `EnsureAction` type to bring the object into its target state.

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

Closures returning `Result<CheckEnsureResult, E>` that also return closure in `CheckEnsureResult::EnsureAction` variant automatically implement `Ensure` trait.
Helper function `ensure` can be used to call `ensure()` on such closure.

# Example

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

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

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

ensure(|| {
    Ok(if path.exists() {
        Met(())
    } else {
        EnsureAction(|| {
            File::create(&path).map(|file| drop(file))
        })
    })
}).expect("failed to create file");
```

# Existential types

This crate also provides `Present<T>` and `Absent<T>` wrapper types to mark ensured external states in type system.

If `T` implements `Ensure<Present<T>>` and `Ensure<Absetnt<T>>` it automatically implements `Existential<T>` trait
that provides methods `ensure_present()` and `ensure_absent()`.

See tests for example usage.
*/

use std::fmt;
use std::fmt::Debug;
use std::error::Error;
use std::ops::Deref;
use std::cmp::Ordering;

/// Result of verification if object is in target state with `check_ensure()`
#[derive(Debug)]
pub enum CheckEnsureResult<M, A> {
    Met(M),
    EnsureAction(A),
}

/// Error reported if external object state test failed for object that was ensured to meet that
/// state.
#[derive(Debug)]
pub struct VerificationError;

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

/// Error raised if `Ensure::ensure_verify()` failed verification.
impl Error for VerificationError {}

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

    fn meet(self) -> Result<Self::Met, Self::Error>;
}

/// Types of objects that can be brought to target state `T`.
pub trait Ensure<T>: Sized {
    type EnsureAction: Meet<Met = T>;

    /// Checks if target state is already `Met` or provides `EnsureAction` object which can by used to bring external state to target state by calling its `meet()` method
    fn check_ensure(self) -> Result<CheckEnsureResult<T, Self::EnsureAction>, <Self::EnsureAction as Meet>::Error>;

    /// Ensures target state by calling `check_ensure()` and if not `Met` calling `meet()` on `EnsureAction`
    fn ensure(self) -> Result<T, <Self::EnsureAction as Meet>::Error> {
        match self.check_ensure()? {
            CheckEnsureResult::Met(met) => Ok(met),
            CheckEnsureResult::EnsureAction(meet) => meet.meet(),
        }
    }

    /// Ensures target state and then verify that `EnsureAction` actually brought external state to target state by calling `check_ensure()` on clone of `self`
    fn ensure_verify(self) -> Result<T, <Self::EnsureAction as Meet>::Error> where Self: Clone, <Self::EnsureAction as Meet>::Error: From<VerificationError> {
        let verify = self.clone();
        match self.check_ensure()? {
            CheckEnsureResult::Met(met) => Ok(met),
            CheckEnsureResult::EnsureAction(action) => {
                let result = action.meet()?;
                match verify.check_ensure()? {
                    CheckEnsureResult::Met(_met) => Ok(result),
                    CheckEnsureResult::EnsureAction(_action) => Err(VerificationError.into()),
                }
            }
        }
    }
}

impl<T, E, A, F> Ensure<T> for F
where F: FnOnce() -> Result<CheckEnsureResult<T, A>, E>, A: Meet<Met = T, Error = E> {
    type EnsureAction = A;

    fn check_ensure(self) -> Result<CheckEnsureResult<T, Self::EnsureAction>, E> {
        self()
    }
}

impl<T, E, F> Meet for F
where F: FnOnce() -> Result<T, E> {
    type Met = T;
    type Error = E;

    fn meet(self) -> Result<Self::Met, Self::Error> {
        self()
    }
}

/// Runs `ensure()` on object implementing `Ensure` and return its value.
/// This is useful with closures implementing `Ensure`.
pub fn ensure<T, E, R, A>(ensure: R) -> Result<T, E> where R: Ensure<T, EnsureAction = A>, A: Meet<Met = T, Error = E> {
    ensure.ensure()
}

/// External objects that state of can be represented in the type system.
pub trait External { }

/// State representations of `External` object in the type system.
pub trait ExternalState<T> where T: External {
    /// Gets base undefined state representation from concrete state.
    fn invalidate_state(self) -> T;
}

impl<T> ExternalState<T> for T where T: External {
    fn invalidate_state(self) -> T {
        self
    }
}

/// Marks `External` object as something that exists.
pub struct Present<T>(pub T) where T: External;

impl<T> ExternalState<T> for Present<T> where T: External {
    fn invalidate_state(self) -> T {
        self.0
    }
}

/// Marks `External` object as something that does not exist.
pub struct Absent<T>(pub T) where T: External;

impl<T> ExternalState<T> for Absent<T> where T: External {
    fn invalidate_state(self) -> T {
        self.0
    }
}

impl<T> Deref for Present<T> where T: External {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> Debug for Present<T> where T: External + Debug {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("Present")
            .field(&self.0)
            .finish()
    }
}

impl<T> PartialEq for Present<T> where T: External + PartialEq {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl<T> PartialOrd for Present<T> where T: External + PartialOrd {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.0.partial_cmp(&other.0)
    }
}

impl<T> Eq for Present<T> where T: External + Eq {}

impl<T> Ord for Present<T> where T: External + Ord {
    fn cmp(&self, other: &Self) -> Ordering {
        self.0.cmp(&other.0)
    }
}

impl<T> Deref for Absent<T> where T: External {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> Debug for Absent<T> where T: External + Debug {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("Absent")
            .field(&self.0)
            .finish()
    }
}

impl<T> PartialEq for Absent<T> where T: External + PartialEq {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl<T> PartialOrd for Absent<T> where T: External + PartialOrd {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.0.partial_cmp(&other.0)
    }
}

impl<T> Eq for Absent<T> where T: External + Eq {}

impl<T> Ord for Absent<T> where T: External + Ord {
    fn cmp(&self, other: &Self) -> Ordering {
        self.0.cmp(&other.0)
    }
}

/// Existential types are types that can ensure `Present<T>` or `Absent<T>` states for `External` type `T`.
pub trait Existential<T> where T: External {
    type Error;

    /// Ensure that `T` is `Present<T>`
    fn ensure_present(self) -> Result<Present<T>, Self::Error>;
    /// Ensure that `T` is `Absent<T>`
    fn ensure_absent(self) -> Result<Absent<T>, Self::Error>;
}

/// Types implement `Existential` trait if they implement both `Ensure<Present<T>>` and `Ensure<Absent<T>>`.
impl<T, E, R, PA, AA> Existential<T> for R where
    R: Ensure<Present<T>, EnsureAction = PA>, PA: Meet<Met = Present<T>, Error = E>,
    R: Ensure<Absent<T>, EnsureAction = AA>, AA: Meet<Met = Absent<T>, Error = E>,
    T: External
{
    type Error = E;

    fn ensure_present(self) -> Result<Present<T>, Self::Error> {
        self.ensure()
    }
    fn ensure_absent(self) -> Result<Absent<T>, Self::Error> {
        self.ensure()
    }
}

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

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

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

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

    struct Resource;

    impl External for Resource {}

    struct CreateResourceAction(Resource);
    impl Meet for CreateResourceAction {
        type Met = Present<Resource>;
        type Error = ();

        fn meet(self) -> Result<Present<Resource>, ()> {
            Ok(Present(self.0))
        }
    }

    impl Ensure<Present<Resource>> for Resource {
        type EnsureAction = CreateResourceAction;

        fn check_ensure(self) -> Result<CheckEnsureResult<Present<Resource>, Self::EnsureAction>, ()> {
            Ok(if true {
                Met(Present(self))
            } else {
                EnsureAction(CreateResourceAction(self))
            })
        }
    }

    struct DeleteResourceAction(Resource);
    impl Meet for DeleteResourceAction {
        type Met = Absent<Resource>;
        type Error = ();

        fn meet(self) -> Result<Absent<Resource>, ()> {
            Ok(Absent(self.0))
        }
    }

    impl Ensure<Absent<Resource>> for Resource {
        type EnsureAction = DeleteResourceAction;

        fn check_ensure(self) -> Result<CheckEnsureResult<Absent<Resource>, Self::EnsureAction>, ()> {
            Ok(if true {
                Met(Absent(self))
            } else {
                EnsureAction(DeleteResourceAction(self))
            })
        }
    }

    #[test]
    fn test_ensure() {
        let _r: Result<Present<Resource>, ()> = Resource.ensure();
        let _r: Result<Absent<Resource>, ()> = Resource.ensure();
    }

    #[test]
    fn test_existential() {
        let _r: Result<Present<Resource>, ()> = Resource.ensure_present();
        let _r: Result<Absent<Resource>, ()> = Resource.ensure_absent();
    }
}