1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
/// Definition of the `RandomGen` trait and its associated iterators.

use super::{BuildRandom, Random};

use std::marker::PhantomData;

/// A (pseudo-)random number generator.
///
/// A `RandomGen` provides facilities to generate (pseudo-)random numbers.
/// Even though it explicitly provides methods for generating `u32` and `u64`
/// values, it is suggested to use [`gen`] and let the type checker infer the
/// appropriate type to be generated.
///
/// # Implementing `RandomGen`
///
/// Instances must implement at least one of [`gen_u32`] or [`gen_u64`], each
/// one has a default implementation in terms of the other. You might want to
/// implement both if there is a more efficient way to do so.
///
/// Note that the output of [`Random`] and [`BuildRandom`] instances can only be
/// as good as their source.
///
/// [`BuildRandom`]: trait.BuildRandom.html
/// [`gen`]: #method.gen
/// [`gen_u32`]: #method.gen_u32
/// [`gen_u64`]: #method.gen_u64
/// [`Random`]: trait.Random.html
///
/// # Examples
///
/// ```
/// # use tiamat::Pcg;
/// use tiamat::RandomGen;
///
/// # fn get_rng() -> Pcg {
/// #     Pcg::new(0xdeadbeef, 1)
/// # }
/// #
/// let mut rng = get_rng();
///
/// println!("{}", if rng.gen() { "Heads!" } else { "Tails!" });
/// println!("The dice landed on {}", rng.build(&(1..7)));
///
/// if rng.build(&(1.0 / 36.0)) {
///     println!("Snake eyes!");
/// } else {
///     println!("No snake eyes :(");
/// }
/// ```
pub trait RandomGen {
    /// Generates a random value.
    ///
    /// Wrapper around [`Random::random`], but allowing for type inference.
    ///
    /// See [`Random::random`]'s documentation (and the documentation of
    /// [`Random`]'s instances) for more.
    ///
    /// [`Random`]: trait.Random.html
    /// [`Random::random`]: trait.Random.html#tymethod.random
    #[inline]
    fn gen<R: Random>(&mut self) -> R
    where
        Self: Sized,
    {
        Random::random(self)
    }

    /// Generates a random value according to some specification.
    ///
    /// Wrapper around [`BuildRandom::build`], but allowing for type inference.
    /// The argument is an instance of `Borrow<B : BuildRandom<R>>` to allow for
    /// passing both `&B` and `B` (etc.).
    ///
    /// See [`BuildRandom::build`]'s documentation (and the documentation of
    /// [`BuildRandom`]'s instances) for more.
    ///
    /// [`BuildRandom`]: trait.BuildRandom.html
    /// [`BuildRandom::build`]: trait.BuildRandom.html#tymethod.build
    #[inline]
    fn build<B, R>(&mut self, builder: &B) -> R
    where
        B: BuildRandom<R>,
        Self: Sized,
    {
        builder.build(self)
    }

    /// Chooses a random element from the slice, where each element has the same
    /// probability of being chosen.
    ///
    /// # Panics
    ///
    /// Panics if the slice has length 0, so that no element could be chosen.
    ///
    /// # Examples
    ///
    /// ```
    /// # use tiamat::Pcg;
    /// use tiamat::RandomGen;
    ///
    /// # fn get_rng() -> Pcg {
    /// #     Pcg::new(0xcafe, 1)
    /// # }
    /// #
    /// let mut rng = get_rng();
    ///
    /// let fav_color = rng.choose_from(&["red", "green", "purple"]);
    /// println!("favorite color is {}", fav_color);
    /// ```
    fn choose_from<'a, T>(&mut self, xs: &'a [T]) -> &'a T
    where
        Self: Sized,
    {
        assert!(!xs.is_empty());
        let idx = (0..xs.len()).build(self);
        &xs[idx]
    }

    /// Returns an iterator over randomly generated values.
    ///
    /// This is the iterating version of [`gen`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use tiamat::Pcg;
    /// use tiamat::RandomGen;
    ///
    /// # fn get_rng() -> Pcg {
    /// #     Pcg::new(0xcafe, 1)
    /// # }
    /// #
    /// let mut rng = get_rng();
    ///
    /// let coin_tosses: Vec<&str> = rng.iter_gen()
    ///     .map(|tails| if tails { "tails" } else { "heads" })
    ///     .take(10)
    ///     .collect();
    /// println!("{:?}", coin_tosses);
    /// ```
    ///
    /// [`gen`]: #method.gen
    fn iter_gen<R: Random>(&mut self) -> IterGen<Self, R>
    where
        Self: Sized,
    {
        IterGen {
            rng: self,
            phantom: Default::default(),
        }
    }

    /// Returns an iterator over randomly built values.
    ///
    /// This is the iterating version of [`build`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use tiamat::Pcg;
    /// use tiamat::RandomGen;
    ///
    /// # fn get_rng() -> Pcg {
    /// #     Pcg::new(0xabcdef01, 1)
    /// # }
    /// #
    /// let mut rng = get_rng();
    ///
    /// let dice_throws: Vec<u8> = rng.iter_build(&(1..7))
    ///     .take(10)
    ///     .collect();
    /// println!("dice_throws: {:?}", dice_throws);
    /// ```
    ///
    /// [`build`]: #method.build
    fn iter_build<'a, B: 'a, R>(&'a mut self, builder: &'a B) -> IterBuild<'a, Self, B, R>
    where
        B: BuildRandom<R>,
        Self: Sized,
    {
        IterBuild {
            rng: self,
            builder,
            phantom: Default::default(),
        }
    }

    /// Returns an iterator over values randomly chosen from a slice.
    ///
    /// This is the iterating version of [`choose_from`]. Note that this means
    /// that each choice is made independantly.
    ///
    /// # Panics
    ///
    /// Panics if `xs` is empty, so that no elements can be chosen.
    ///
    /// [`choose_from`]: #method.choose_from
    fn iter_choose_from<'a, T>(&'a mut self, xs: &'a [T]) -> IterChooseFrom<'a, Self, T>
    where
        Self: Sized,
    {
        assert!(!xs.is_empty());
        IterChooseFrom { rng: self, xs }
    }

    /// Returns a (pseudo-)random, uniformly distributed `u32`.
    ///
    /// Either this or [`gen_u64`] must be implemented by an implementing type.
    /// When using `RandomGen`, it is recommended to use [`gen`] instead and
    /// let the type checker infer the type (or write [`gen::<u32>`]).
    ///
    /// [`gen`]: #method.gen
    /// [`gen_u64`]: #method.gen_u64
    #[inline]
    fn gen_u32(&mut self) -> u32 {
        self.gen_u64() as u32
    }

    /// Returns a (pseudo-)random, uniformly distributed `u64`.
    ///
    /// Either this or [`gen_u32`] must be implemented by an implementing type.
    /// When using `RandomGen`, it is recommended to use [`gen`] instead and
    /// let the type checker infer the type (or write `gen::<u64>`).
    ///
    /// [`gen`]: #method.gen
    /// [`gen_u32`]: #method.gen_u32
    #[inline]
    fn gen_u64(&mut self) -> u64 {
        let first = u64::from(self.gen_u32());
        let second = u64::from(self.gen_u32());
        (first << 32) | second
    }

    /// Fills the buffer with (pseudo-)random bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// # use tiamat::Pcg;
    /// use tiamat::RandomGen;
    ///
    /// # fn get_rng() -> Pcg {
    /// #     Pcg::new(0xdeadbeef, 1)
    /// # }
    /// #
    /// let mut rng = get_rng();
    ///
    /// let mut garbage = Vec::with_capacity(128);
    /// rng.fill_buffer(&mut garbage);
    /// println!("{:?}", garbage);
    /// ```
    #[inline]
    fn fill_buffer(&mut self, buffer: &mut [u8]) {
        for b in buffer.chunks_mut(8) {
            if b.len() == 8 {
                b.copy_from_slice(&unsafe { ::std::mem::transmute::<u64, [u8; 8]>(self.gen_u64()) })
            } else {
                let len = b.len();
                b.copy_from_slice(
                    &unsafe { ::std::mem::transmute::<u64, [u8; 8]>(self.gen_u64()) }[0..len],
                )
            }
        }
    }
}

// TODO: @Speed some instances of `Random` or `BuildRandom` precompute some
// information that is reusable between runs. maybe add a way to do that? (via
// methods on `Random` and `BuildRandom` and giving them an associated type?)
// maybe that'd need specialization though... -- lukaramu, 2017-07-1_
//
// (what *should* happen is that the user creates a `BuildRandom` instance that
// saves the precomputed information by itself -- lukaramu, 2017-07-22)

/// An iterator over randomly generated values.
///
/// This `struct` is created by the [`iter_gen`] method on [`RandomGen`]. See
/// its documentation for more.
///
/// [`iter_gen`]: trait.RandomGen.html#method.iter_gen
/// [`RandomGen`]: trait.RandomGen.html
pub struct IterGen<'a, G: 'a, R> {
    pub(super) rng: &'a mut G,
    pub(super) phantom: PhantomData<*const R>,
}

impl<'a, G: 'a, R: 'a> Iterator for IterGen<'a, G, R>
where
    G: RandomGen,
    R: Random,
{
    type Item = R;

    fn next(&mut self) -> Option<R> {
        Some(self.rng.gen())
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (::std::usize::MAX, None)
    }

    fn count(self) -> usize {
        panic!("this is an infinite iterator and thus has more than usize::MAX elements")
    }
}

/// An iterator over randomly built values.
///
/// This `struct` is created by the [`iter_build`] method on [`RandomGen`]. See
/// its documentation for more.
///
/// [`iter_build`]: trait.RandomGen.html#method.iter_build
/// [`RandomGen`]: trait.RandomGen.html
pub struct IterBuild<'a, G: 'a, B: 'a, R> {
    pub(super) rng: &'a mut G,
    pub(super) builder: &'a B,
    pub(super) phantom: PhantomData<*const R>,
}

impl<'a, G: 'a, B: 'a, R> Iterator for IterBuild<'a, G, B, R>
where
    G: RandomGen,
    B: BuildRandom<R>,
{
    type Item = R;

    fn next(&mut self) -> Option<R> {
        Some(self.rng.build::<B, R>(self.builder))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (::std::usize::MAX, None)
    }

    fn count(self) -> usize {
        panic!("this is an infinite iterator and thus has more than usize::MAX elements")
    }
}

/// An iterator over values randomly chosen from a slice.
///
/// This `struct` is created by the [`iter_choose_from`] method on
/// [`RandomGen`]. See its documentation for more.
///
/// [`iter_choose_from`]: trait.RandomGen.html#method.iter_choose_from
/// [`RandomGen`]: trait.RandomGen.html
pub struct IterChooseFrom<'a, G: 'a, T: 'a> {
    pub(super) rng: &'a mut G,
    pub(super) xs: &'a [T],
}

impl<'a, G: 'a, T: 'a> Iterator for IterChooseFrom<'a, G, T>
where
    G: RandomGen,
{
    type Item = &'a T;

    fn next(&mut self) -> Option<&'a T> {
        Some(self.rng.choose_from(self.xs))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (::std::usize::MAX, None)
    }

    fn count(self) -> usize {
        panic!("this is an infinite iterator and thus has more than usize::MAX elements")
    }
}