Skip to main content

StatefulPredicate

Trait StatefulPredicate 

Source
pub trait StatefulPredicate<T>: Default + Predicate<T> {
    // Required method
    fn test(&self, value: &T) -> bool;

    // Provided methods
    fn error(&self) -> ErrorMessage { ... }
    unsafe fn optimize(_value: &T) { ... }
}
Expand description

A stateful assertion that must hold for an instance of a type to be considered refined.

Required Methods§

Source

fn test(&self, value: &T) -> bool

Whether a value satisfies the predicate.

§Correctness

Implementations of this method must be pure functions. They must be infallible and must always return the same result when provided the same input value. If you have a situation that requires impurity to “materialize” a predicate, use the Default::default implementation to “inject” that logic into the predicate. Even then, under no circumstance can the test function itself be impure.

Provided Methods§

Source

fn error(&self) -> ErrorMessage

An error message to display when the predicate doesn’t hold.

Source

unsafe fn optimize(_value: &T)

Applies a potentially unsafe optimization to call sites that can take advantage of information provided by the predicate. This function is unused by refined unless the optimized feature is enabled.

As all predicate tests should be pure, implementing this function is recommended for most predicate implementations. The most common implementation will look like:

unsafe fn optimize(value: &T) {
    core::hint::assert_unchecked(Self::test(value));
}

Note that core::hint::assert_unchecked acts as an assert in debug builds, meaning that tests should be able to detect correctness issues as well. It is only in optimized builds that no check is performed.

§Safety

Implementation of this function takes a correctness property and turns it in to a soundness property. This means that incorrect implementation of this function can lead to undefined behavior. If you have any doubt about the purity of your test implementation, do not implement this function (and, probably, you should reconsider your approach).

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§

Source§

impl<S: TypeString, T: AsRef<str>> StatefulPredicate<T> for Regex<S>

Available on crate features alloc and regex only.