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
#![no_std]
#![warn(missing_docs)]

//! Simple and minimalist randomization.
//!
//! NOT FOR CRYPTOGRAPHIC PURPOSES.
//!
//! ## Basic Usage
//!
//! * Pick a generator, [PCG32] or [PCG64], depending on the output type you
//!   want. `PCG32` runs about 20% faster, so if you usually need 32 bits or
//!   less per use you might as well pick that.
//! * Seed your generator from wherever. However you wanna do it that your
//!   platform supports. The generators have a `state` and `inc` value. The
//!   `state` will change with each call, the `inc` is like a stream selection
//!   value that doesn't change when you use the generator. If you don't care
//!   about stream selection just pass your seed value to both arguments and
//!   it'll all "just work".
//! * Call [next_u32](PCG32::next_u32) or [next_u64](PCG64::next_u64) to get
//!   your numbers.
//! * You can use [RandRangeU32] for bounded integer randomization.
//!
//! That's it, that's the whole lib. No generics, no traits, no breaking changes
//! issued as patch releases, none of that.
//!
//! ## Floating Point
//!
//! Unfortunately, there's many possible float distributions a person might
//! want, so you'll have to call one of the float conversion functions yourself.
//! I've included conversions for the five most commonly used floating point
//! ranges.
//!
//! | Range | 32-bit | 64-bit |
//! |:-----:|:-------|:-------|
//! | `[0.0, 1.0)`| [f32_half_open_right] | [f64_half_open_right] |
//! | `(0.0, 1.0]` | [f32_half_open_left] | [f64_half_open_left] |
//! | `(0.0, 1.0)` | [f32_open] | [f64_open] |
//! | `[0.0, 1.0]` | [f32_closed] | [f64_closed] |
//! | `[-1.0, 1.0]` | [f32_closed_neg_pos] | [f64_closed_neg_pos] |

/// Fiddly to use, but totally gets you the minimum without branching.
///
/// Works for any integral type.
macro_rules! branchless_min {
  ($x:expr, $y:expr, $u:ty) => {
    $y ^ (($x ^ $y) & (<$u>::wrapping_neg(($x < $y) as $u)))
  };
}

/// Fiddly to use, but totally gets you the maximum without branching.
///
/// Works for any integral type.
macro_rules! branchless_max {
  ($x:expr, $y:expr, $u:ty) => {
    $x ^ (($x ^ $y) & (<$u>::wrapping_neg(($x < $y) as $u)))
  };
}

#[test]
fn test_branchless_min_and_max() {
  for x in core::u8::MIN..=core::u8::MAX {
    for y in core::u8::MIN..=core::u8::MAX {
      assert_eq!(branchless_min!(x, y, u8), x.min(y));
      assert_eq!(branchless_max!(x, y, u8), x.max(y));
    }
  }
  for x in core::i8::MIN..=core::i8::MAX {
    for y in core::i8::MIN..=core::i8::MAX {
      assert_eq!(branchless_min!(x, y, i8), x.min(y));
      assert_eq!(branchless_max!(x, y, i8), x.max(y));
    }
  }
}

pub mod formulas;
pub use formulas::*;

/// A [permuted congruential
/// generator](https://en.wikipedia.org/wiki/Permuted_congruential_generator)
/// with 32-bit output. Pick this by default.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PCG32 {
  /// State value. Changes with every use.
  pub state: u64,
  /// Inc value. Selects the output stream ordering.
  ///
  /// This doesn't change as the generator is used. You just set it and forget
  /// it. If this value isn't odd, your generator won't have a full period
  /// before it loops. The [seed](PCG32::seed) constructor will ensure that the
  /// `inc` value is set to be odd, but the `From` constructors will not.
  pub inc: u64,
}
impl Default for PCG32 {
  #[inline]
  fn default() -> Self {
    Self::seed(DEFAULT_PCG_SEED as u64, DEFAULT_PCG_INC as u64)
  }
}
impl From<[u64; 2]> for PCG32 {
  /// Uses the provided values exactly.
  #[inline]
  fn from(value: [u64; 2]) -> Self {
    Self {
      state: value[0],
      inc: value[1],
    }
  }
}
impl From<(u64, u64)> for PCG32 {
  /// Uses the provided values exactly.
  #[inline]
  fn from(value: (u64, u64)) -> Self {
    Self {
      state: value.0,
      inc: value.1,
    }
  }
}
impl PCG32 {
  /// Crates a generator from the seed and inc given.
  ///
  /// The precise seeding details are not considered a "stable" part of the API.
  ///
  /// If you wish to exactly create a generator using particular `state` and
  /// `inc` values then use the `From` impl.
  #[inline]
  pub const fn seed(seed: u64, inc: u64) -> Self {
    let inc = (inc << 1) | 1;
    let mut state = pcg_core_state64(0, inc);
    state = state.wrapping_add(seed);
    state = pcg_core_state64(state, inc);
    Self { state, inc }
  }

  /// Runs the generator once and gets a `u32` as output.
  #[inline]
  pub fn next_u32(&mut self) -> u32 {
    let out = xsh_rr_64_32(self.state);
    self.state = pcg_core_state64(self.state, self.inc);
    out
  }

  /// Fill a mutable byte slice from this generator.
  ///
  /// This will perform fastest if the slice is fully aligned to 4-byte bounds,
  /// but will work either way.
  #[inline]
  pub fn fill_bytes(&mut self, bytes: &mut [u8]) {
    let (pre, mid, post) = unsafe { bytes.align_to_mut::<u32>() };
    for byte_mut in pre.iter_mut() {
      *byte_mut = (self.next_u32() >> 24) as u8;
    }
    for u32_mut in mid.iter_mut() {
      *u32_mut = self.next_u32();
    }
    for byte_mut in post.iter_mut() {
      *byte_mut = (self.next_u32() >> 24) as u8;
    }
  }

  /// Advances the generator `delta` steps in `log(delta)` time.
  #[inline]
  pub fn jump(&mut self, delta: u64) {
    self.state = jump_lcg64(delta, self.state, PCG_MULTIPLIER_64, self.inc)
  }
}

/// A [permuted congruential
/// generator](https://en.wikipedia.org/wiki/Permuted_congruential_generator)
/// with 64-bit output. Pick this if you want to do stuff with `f64` values.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PCG64 {
  /// State value. Changes with every use.
  pub state: u128,
  /// Inc value. Selects the output stream ordering.
  ///
  /// This doesn't change as the generator is used. You just set it and forget
  /// it. If this value isn't odd, your generator won't have a full period
  /// before it loops. The [seed](PCG64::seed) constructor will ensure that the
  /// `inc` value is set to be odd, but the `From` constructors will not.
  pub inc: u128,
}
impl Default for PCG64 {
  #[inline]
  fn default() -> Self {
    Self::seed(DEFAULT_PCG_SEED, DEFAULT_PCG_INC)
  }
}
impl From<[u128; 2]> for PCG64 {
  /// Uses the provided values exactly.
  #[inline]
  fn from(value: [u128; 2]) -> Self {
    Self {
      state: value[0],
      inc: value[1],
    }
  }
}
impl From<(u128, u128)> for PCG64 {
  /// Uses the provided values exactly.
  #[inline]
  fn from(value: (u128, u128)) -> Self {
    Self {
      state: value.0,
      inc: value.1,
    }
  }
}
impl PCG64 {
  /// Crates a generator from the seed and inc given.
  ///
  /// The precise seeding details are not considered a "stable" part of the API.
  ///
  /// If you wish to exactly create a generator using particular `state` and
  /// `inc` values then use the `From` impl.
  #[inline]
  pub const fn seed(seed: u128, inc: u128) -> Self {
    let inc = (inc << 1) | 1;
    let mut state = pcg_core_state128(0, inc);
    state = state.wrapping_add(seed);
    state = pcg_core_state128(state, inc);
    Self { state, inc }
  }

  /// Runs the generator once and gets a `u32` as output.
  #[inline]
  pub fn next_u64(&mut self) -> u64 {
    let out = xsh_rr_128_64(self.state);
    self.state = pcg_core_state128(self.state, self.inc);
    out
  }

  /// Fill a mutable byte slice from this generator.
  ///
  /// This will perform fastest if the slice is fully aligned to 8-byte bounds,
  /// but will work either way.
  #[inline]
  pub fn fill_bytes(&mut self, bytes: &mut [u8]) {
    let (pre, mid, post) = unsafe { bytes.align_to_mut::<u64>() };
    for byte_mut in pre.iter_mut() {
      *byte_mut = (self.next_u64() >> 56) as u8;
    }
    for u64_mut in mid.iter_mut() {
      *u64_mut = self.next_u64();
    }
    for byte_mut in post.iter_mut() {
      *byte_mut = (self.next_u64() >> 56) as u8;
    }
  }

  /// Advances the generator `delta` steps in `log(delta)` time.
  #[inline]
  pub fn jump(&mut self, delta: u128) {
    self.state = jump_lcg128(delta, self.state, PCG_MULTIPLIER_128, self.inc)
  }
}

/// An inclusive random range with a `u32` low and high value.
///
/// This type utilizes `u64` math internally, so it's not entirely suitable for
/// 32-bit machines. It'll run, but more slowly than you might like if you're
/// using this in a tight loop.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct RandRangeU32 {
  base: u32,
  width: u32,
  threshold: u32,
}
impl RandRangeU32 {
  /// Attempts to make a new random range. Inputs can be in either order.
  ///
  /// ## Failure
  ///
  /// * If the inputs are 0 and `core::u32::MAX`
  #[inline]
  pub fn try_new(a: u32, b: u32) -> Option<Self> {
    let (base, max) = (a.min(b), a.max(b));
    let width = max.wrapping_sub(base).wrapping_add(1);
    if width > 0 {
      let threshold = width.wrapping_neg() % width;
      Some(Self {
        base,
        width,
        threshold,
      })
    } else {
      None
    }
  }

  /// As [try_new](RandRangeU32::try_new), but `const`, and panics on failure.
  #[inline]
  pub const fn new(a: u32, b: u32) -> Self {
    let (base, max) = (branchless_min!(a, b, u32), branchless_max!(a, b, u32));
    let width = max.wrapping_sub(base).wrapping_add(1);
    let threshold = width.wrapping_neg() % width;
    Self {
      base,
      width,
      threshold,
    }
  }

  /// Inclusive low end of this range.
  #[inline]
  pub const fn low(&self) -> u32 {
    self.base
  }

  /// Inclusive high end of this range.
  #[inline]
  pub const fn high(&self) -> u32 {
    self.base.wrapping_add(self.width).wrapping_sub(1)
  }

  /// Given a uniform input, produces uniform output in range or fails.
  ///
  /// You aren't really intended to use this directly, instead you probably want
  /// to use [sample](RandRangeU32::sample).
  ///
  /// ## Failure
  ///
  /// Most ranges don't evenly distribute across the `u32` space, so some values
  /// will fail to end up in range.
  #[inline]
  pub fn place_in_range(&self, val: u32) -> Option<u32> {
    let mul: u64 = u64::from(val).wrapping_mul(u64::from(self.width));
    let low_part: u32 = mul as u32;
    if low_part < self.threshold {
      None
    } else {
      Some(((mul >> 32) as u32).wrapping_add(self.base))
    }
  }

  /// Sample from a [PCG32](PCG32) one or more times to get a value in range.
  #[inline]
  pub fn sample(&self, gen: &mut PCG32) -> u32 {
    loop {
      if let Some(output) = self.place_in_range(gen.next_u32()) {
        return output;
      }
    }
  }
}