6 releases

0.3.1 Aug 27, 2019
0.3.0 Aug 20, 2019
0.2.2 Aug 19, 2019
0.2.0 Feb 6, 2019
0.1.0 Feb 5, 2019

#1240 in Data structures

Download history 55/week @ 2024-04-01 5/week @ 2024-04-08 16/week @ 2024-04-15 245/week @ 2024-04-22 6/week @ 2024-04-29 10/week @ 2024-05-06 18/week @ 2024-05-13 19/week @ 2024-05-20 14/week @ 2024-05-27 15/week @ 2024-06-03 10/week @ 2024-06-10 22/week @ 2024-06-17 7/week @ 2024-06-24 38/week @ 2024-07-01 6/week @ 2024-07-08 14/week @ 2024-07-15

66 downloads per month
Used in 6 crates (3 directly)

MIT license

14KB
229 lines

Latest Version Documentation License

This library provides Ensure trait that is useful for objects with unknown initial external state that can be brought to some target state.

This can be seen as TryInto trait for objects with side effects with unknown initial external state and desired target state. For example a file may or may not exist. By implementing Ensure we can call ensure() to create new file only if it did not exist already.

Closures returning CheckEnsureResult 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.

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

fn main() {
    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");
}

No runtime deps