[][src]Crate ensure

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.

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.

Structs

Absent

Mark T as something that does not exist.

Present

Mark T as something that exists.

VerificationError

Enums

CheckEnsureResult

Result of verification if object is in target state with check_ensure()

Traits

Ensure

Implement for types of objects that can be brought to target state T

Existential

Types implement Existential trait if they implement both Ensure<Present<T>> and Ensure<Absent<T>>.

Meet

Function that can be used to bring object in its target state

Functions

ensure

Run ensure() on object implementing Ensure and return its value. This is useful with closures implementing Ensure.