[][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

Marks External object as something that does not exist.

Present

Marks External object as something that exists.

VerificationError

Error reported if external object state test failed for object that was ensured to meet that state.

Enums

CheckEnsureResult

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

Traits

Ensure

Types of objects that can be brought to target state T.

Existential

Existential types are types that can ensure Present<T> or Absent<T> states for External type T.

External

External objects that state of can be represented in the type system.

ExternalState

State representations of External object in the type system.

Meet

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

Functions

ensure

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