ensure

Crates.ioensure
lib.rsensure
version0.3.1
sourcesrc
created_at2019-02-05 18:02:33.957137
updated_at2019-08-27 15:56:31.548047
descriptionEnsure target state of an object
homepage
repositoryhttps://github.com/jpastuszek/ensure
max_upload_size
id112946
size14,536
Jakub Pastuszek (jpastuszek)

documentation

https://docs.rs/ensure

README

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");
}
Commit count: 37

cargo fmt