dicetest 0.4.0

Framework for writing tests with randomly generated test data
Documentation
use crate::adapters::{ArcDie, BoxedDie, FlatMapDie, FlattenDie, MapDie, RcDie};
use crate::{DieOnce, Fate};

/// Trait for generating pseudorandom values of type `T`.
///
/// The [`Die`] trait represents a subset of [`DieOnce`]. It mirrors all methods of
/// [`DieOnce`] without the suffix `_once`. These methods must behave in the same way.
/// For example an implementation of [`Die`] must produce the same value with its methods
/// [`roll`] and [`roll_once`] if they are called with the same [`Fate`].
///
/// [`roll_once`]: DieOnce::roll_once
/// [`roll`]: Die::roll
pub trait Die<T>: DieOnce<T> {
    /// Generates a pseudorandom value.
    ///
    /// The [`Fate`] is the only source of the randomness. Besides that, the generation is
    /// deterministic.
    fn roll(&self, fate: Fate) -> T;

    /// Creates a new [`Die`] by mapping the generated values of `self`.
    ///
    /// The function `f` will be applied to the generated values of `self`. The results of the
    /// function are the generated values of the new [`Die`].
    fn map<U, F>(self, f: F) -> MapDie<T, U, Self, F>
    where
        Self: Sized,
        F: Fn(T) -> U,
    {
        MapDie::new(self, f)
    }

    /// Creates a new [`Die`] whose values are generated by the generated [`Die`]s of `self`.
    fn flatten<U>(self) -> FlattenDie<U, T, Self>
    where
        Self: Sized,
        T: DieOnce<U>,
    {
        FlattenDie::new(self)
    }

    /// Creates a new [`Die`] similar to [`map`], except that the mapping produces [`DieOnce`]s.
    ///
    /// The function `f` will be applied to the generated values of `self`. The results of the
    /// function are [`DieOnce`]s that generates the values for the new [`Die`].
    ///
    /// It is semantically equivalent to `self.map(f).flatten()`.
    ///
    /// [`map`]: Die::map
    fn flat_map<U, UD, F>(self, f: F) -> FlatMapDie<T, U, Self, UD, F>
    where
        Self: Sized,
        UD: DieOnce<U>,
        F: Fn(T) -> UD,
    {
        FlatMapDie::new(self, f)
    }

    /// Puts `self` behind a [`Box`] pointer.
    fn boxed<'a>(self) -> BoxedDie<'a, T>
    where
        Self: Sized + 'a,
    {
        BoxedDie::new(self)
    }

    /// Puts `self` behind an [`Rc`](std::rc::Rc) pointer.
    fn rc<'a>(self) -> RcDie<'a, T>
    where
        Self: Sized + 'a,
    {
        RcDie::new(self)
    }

    /// Puts `self` behind an [`Arc`](std::sync::Arc) pointer.
    fn arc(self) -> ArcDie<T>
    where
        Self: Sized + 'static,
    {
        ArcDie::new(self)
    }
}

impl<T, TD: Die<T>> DieOnce<T> for &TD {
    fn roll_once(self, fate: Fate) -> T {
        (*self).roll(fate)
    }
}

impl<T, TD: Die<T>> Die<T> for &TD {
    fn roll(&self, fate: Fate) -> T {
        (**self).roll(fate)
    }
}