dicetest/
die.rs

1use crate::adapters::{ArcDie, BoxedDie, FlatMapDie, FlattenDie, MapDie, RcDie};
2use crate::{DieOnce, Fate};
3
4/// Trait for generating pseudorandom values of type `T`.
5///
6/// The [`Die`] trait represents a subset of [`DieOnce`]. It mirrors all methods of
7/// [`DieOnce`] without the suffix `_once`. These methods must behave in the same way.
8/// For example an implementation of [`Die`] must produce the same value with its methods
9/// [`roll`] and [`roll_once`] if they are called with the same [`Fate`].
10///
11/// [`roll_once`]: DieOnce::roll_once
12/// [`roll`]: Die::roll
13pub trait Die<T>: DieOnce<T> {
14    /// Generates a pseudorandom value.
15    ///
16    /// The [`Fate`] is the only source of the randomness. Besides that, the generation is
17    /// deterministic.
18    fn roll(&self, fate: Fate) -> T;
19
20    /// Creates a new [`Die`] by mapping the generated values of `self`.
21    ///
22    /// The function `f` will be applied to the generated values of `self`. The results of the
23    /// function are the generated values of the new [`Die`].
24    fn map<U, F>(self, f: F) -> MapDie<T, U, Self, F>
25    where
26        Self: Sized,
27        F: Fn(T) -> U,
28    {
29        MapDie::new(self, f)
30    }
31
32    /// Creates a new [`Die`] whose values are generated by the generated [`Die`]s of `self`.
33    fn flatten<U>(self) -> FlattenDie<U, T, Self>
34    where
35        Self: Sized,
36        T: DieOnce<U>,
37    {
38        FlattenDie::new(self)
39    }
40
41    /// Creates a new [`Die`] similar to [`map`], except that the mapping produces [`DieOnce`]s.
42    ///
43    /// The function `f` will be applied to the generated values of `self`. The results of the
44    /// function are [`DieOnce`]s that generates the values for the new [`Die`].
45    ///
46    /// It is semantically equivalent to `self.map(f).flatten()`.
47    ///
48    /// [`map`]: Die::map
49    fn flat_map<U, UD, F>(self, f: F) -> FlatMapDie<T, U, Self, UD, F>
50    where
51        Self: Sized,
52        UD: DieOnce<U>,
53        F: Fn(T) -> UD,
54    {
55        FlatMapDie::new(self, f)
56    }
57
58    /// Puts `self` behind a [`Box`] pointer.
59    fn boxed<'a>(self) -> BoxedDie<'a, T>
60    where
61        Self: Sized + 'a,
62    {
63        BoxedDie::new(self)
64    }
65
66    /// Puts `self` behind an [`Rc`](std::rc::Rc) pointer.
67    fn rc<'a>(self) -> RcDie<'a, T>
68    where
69        Self: Sized + 'a,
70    {
71        RcDie::new(self)
72    }
73
74    /// Puts `self` behind an [`Arc`](std::sync::Arc) pointer.
75    fn arc(self) -> ArcDie<T>
76    where
77        Self: Sized + 'static,
78    {
79        ArcDie::new(self)
80    }
81}
82
83impl<T, TD: Die<T>> DieOnce<T> for &TD {
84    fn roll_once(self, fate: Fate) -> T {
85        (*self).roll(fate)
86    }
87}
88
89impl<T, TD: Die<T>> Die<T> for &TD {
90    fn roll(&self, fate: Fate) -> T {
91        (**self).roll(fate)
92    }
93}