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 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
use core::fmt;
use crate::*;
/// Rich interface for consuming random number generators.
#[derive(Clone)]
pub struct Random<R: ?Sized>(pub R);
impl<R: Rng + ?Sized> Random<R> {
/// Returns the next `u32` in the sequence.
///
/// # Examples
///
/// ```
/// let value = urandom::new().next_u32();
/// ```
#[inline]
pub fn next_u32(&mut self) -> u32 {
self.0.next_u32()
}
/// Returns the next `u64` in the sequence.
///
/// # Examples
///
/// ```
/// let value = urandom::new().next_u64();
/// ```
#[inline]
pub fn next_u64(&mut self) -> u64 {
self.0.next_u64()
}
/// Returns a uniform random `f32` in the half-open interval `[1.0, 2.0)`.
///
/// As only 23 bits are necessary to construct a random float in this range,
/// implementations may override this method to provide a more efficient implementation.
///
/// If high quality uniform random floats are desired in open interval `(0.0, 1.0)` without bias see the [`Float01`](distributions::Float01) distribution.
///
/// # Examples
///
/// ```
/// let value = urandom::new().next_f32();
/// assert!(value >= 1.0 && value < 2.0);
/// ```
#[inline]
pub fn next_f32(&mut self) -> f32 {
self.0.next_f32()
}
/// Returns a uniform random `f64` in the half-open interval `[1.0, 2.0)`.
///
/// As only 52 bits are necessary to construct a random double in this range,
/// implementations may override this method to provide a more efficient implementation.
///
/// If high quality uniform random floats are desired in open interval `(0.0, 1.0)` without bias see the [`Float01`](distributions::Float01) distribution.
///
/// # Examples
///
/// ```
/// let value = urandom::new().next_f64();
/// assert!(value >= 1.0 && value < 2.0);
/// ```
#[inline]
pub fn next_f64(&mut self) -> f64 {
self.0.next_f64()
}
/// Fills the destination buffer with random values from the Rng.
///
/// The underlying Rng may implement this as efficiently as possible and may not be the same as simply filling with `next_u32`.
///
/// # Examples
///
/// ```
/// let mut rng = urandom::new();
/// let mut buffer = [0u32; 32];
/// rng.fill_u32(&mut buffer);
/// assert_ne!(buffer, [0; 32]);
/// ```
#[inline]
pub fn fill_u32(&mut self, buffer: &mut [u32]) {
self.0.fill_u32(buffer)
}
/// Fills the destination buffer with uniform random values from the Rng.
///
/// The underlying Rng may implement this as efficiently as possible and may not be the same as simply filling with `next_u64`.
///
/// # Examples
///
/// ```
/// let mut rng = urandom::new();
/// let mut buffer = [0u64; 32];
/// rng.fill_u64(&mut buffer);
/// assert_ne!(buffer, [0; 32]);
/// ```
#[inline]
pub fn fill_u64(&mut self, buffer: &mut [u64]) {
self.0.fill_u64(buffer)
}
/// Fills the destination buffer with uniform random bytes from the Rng.
///
/// The underlying Rng may implement this as efficiently as possible.
///
/// # Examples
///
/// ```
/// let mut rng = urandom::new();
/// let mut buffer = [0u8; 32];
/// rng.fill_bytes(&mut buffer);
/// assert_ne!(buffer, [0u8; 32]);
/// ```
#[inline]
pub fn fill_bytes(&mut self, buffer: &mut [u8]) {
self.0.fill_bytes(buffer)
}
/// Advances the internal state significantly.
///
/// Useful to produce deterministic independent random number generators for parallel computation.
#[inline]
pub fn jump(&mut self) {
self.0.jump();
}
/// Clones the current instance and advances the internal state significantly.
///
/// Useful to produce deterministic independent random number generators for parallel computation.
///
/// # Examples
///
/// ```
/// let mut rng = urandom::new();
/// for _ in 0..10 {
/// parallel_computation(rng.split());
/// }
/// # fn parallel_computation(_: urandom::Random<impl urandom::Rng>) {}
/// ```
#[inline]
pub fn split(&mut self) -> Self where Self: Clone {
let cur = self.clone();
self.0.jump();
return cur;
}
/// Returns a sample from the [`Standard`](distributions::Standard) distribution.
///
/// # Examples
///
/// ```
/// let int: i8 = urandom::new().next();
/// ```
#[inline]
pub fn next<T>(&mut self) -> T where distributions::Standard: Distribution<T> {
distributions::Standard.sample(self)
}
/// Fills the given slice with samples from the [`Standard`](distributions::Standard) distribution.
///
/// Because of its generic nature no optimizations are applied and all values are sampled individually from the distribution.
///
/// # Examples
///
/// ```
/// let mut rng = urandom::new();
/// let mut buffer = [false; 32];
/// rng.fill(&mut buffer);
/// ```
#[inline]
pub fn fill<T>(&mut self, buffer: &mut [T]) where distributions::Standard: Distribution<T> {
let distr = distributions::Standard;
for elem in buffer {
*elem = distr.sample(self);
}
}
/// Returns a sample from the [`Uniform`](distributions::Uniform) distribution within the given interval.
///
/// # Examples
///
/// ```
/// let eyes = urandom::new().range(1..=6);
/// assert!(eyes >= 1 && eyes <= 6);
/// ```
///
/// If more than one sample from a specific interval is desired, it is more efficient to reuse the uniform sampler.
///
/// ```
/// let mut rng = urandom::new();
/// let distr = urandom::distributions::Uniform::from(0..100);
///
/// loop {
/// let value = rng.sample(&distr);
/// assert!(value >= 0 && value < 100);
/// if value == 0 {
/// break;
/// }
/// }
/// ```
#[inline]
pub fn range<T, I>(&mut self, interval: I) -> T where T: distributions::SampleUniform, distributions::Uniform<T>: From<I> {
distributions::Uniform::<T>::from(interval).sample(self)
}
/// Returns a sample from the given distribution.
///
/// See the [`distributions`](distributions) documentation for a list of available distributions.
#[inline]
pub fn sample<T, D>(&mut self, distr: &D) -> T where D: Distribution<T> {
distr.sample(self)
}
/// Returns an iterator of samples from the given distribution.
///
/// See the [`distributions`](distributions) documentation for a list of available distributions.
#[inline]
pub fn samples<T, D>(&mut self, distr: D) -> distributions::Samples<'_, R, D, T> where D: Distribution<T> {
distributions::Samples::new(self, distr)
}
/// Returns `true` with the given probability.
///
/// This is known as the [`Bernoulli`](distributions::Bernoulli) distribution.
///
/// # Precision
///
/// For `p >= 1.0`, the resulting distribution will always generate `true`.
/// For `p <= 0.0`, the resulting distribution will always generate `false`.
#[inline]
pub fn chance(&mut self, p: f64) -> bool {
distributions::Bernoulli::new(p).sample(self)
}
/// Flips a coin.
///
/// Returns `true` when heads and `false` when tails with 50% probability for either result.
///
/// Simply an alias for `rng.next::<bool>()` but describes the intent of the caller.
#[inline]
pub fn coin_flip(&mut self) -> bool {
self.next()
}
/// Returns a random sample from the collection.
///
/// Returns `None` if and only if the collection is empty.
///
/// This method uses `Iterator::size_hint` for optimisation.
/// With an accurate hint and where `Iterator::nth` is a constant-time operation this method can offer `O(1)` performance.
///
/// For slices, prefer [`choose`](Random::choose) which guarantees `O(1)` performance.
///
/// # Examples
///
/// Sample a random fizz, buzz or fizzbuzz number up to 100:
///
/// ```
/// fn is_fizzbuzz(n: &i32) -> bool {
/// n % 3 == 0 || n % 5 == 0
/// }
///
/// let mut rng = urandom::new();
/// let fizzbuzz = rng.single((0..100).filter(is_fizzbuzz)).unwrap();
/// assert!(fizzbuzz % 3 == 0 || fizzbuzz % 5 == 0);
/// ```
///
/// Pick a random emoji:
///
/// ```
/// let mood = urandom::new().single("😀😎😐😕😠😢".chars()).unwrap();
/// println!("I am {}!", mood);
/// ```
pub fn single<I: IntoIterator>(&mut self, collection: I) -> Option<I::Item> {
let mut iter = collection.into_iter();
// Take a short cut for collections with known length
let (len, upper) = iter.size_hint();
if upper == Some(len) {
let index = usize::min(len, self.index(len));
return iter.nth(index);
}
// Reservoir sampling, can be improved
let mut result = None;
let mut denom = 1.0;
iter.for_each(|item| {
if self.chance(1.0 / denom) {
result = Some(item);
}
else {
drop(item);
}
denom += 1.0;
});
result
}
/// Collect random samples from the collection into the buffer until it is filled.
///
/// Although the elements are selected randomly, the order of elements in the buffer is neither stable nor fully random.
/// If random ordering is desired, shuffle the result.
///
/// Returns the number of elements added to the buffer.
/// This equals the length of the buffer unless the iterator contains insufficient elements,
/// in which case this equals the number of elements available.
///
/// Complexity is `O(n)` where `n` is the size of the collection.
pub fn multiple<I: IntoIterator>(&mut self, collection: I, buffer: &mut [I::Item]) -> usize {
let amount = buffer.len();
let mut len = 0;
collection.into_iter().enumerate().for_each(|(i, elem)| {
if len < amount {
buffer[len] = elem;
len += 1;
}
else {
let k = self.index(i + 1 + amount);
if let Some(slot) = buffer.get_mut(k) {
*slot = elem;
}
}
});
len
}
/// Returns a random usize in the `[0, len)` interval, mostly.
///
/// If the `len` is zero an arbitrary value is returned directly from the Rng.
/// When used with indexing the bounds check should fail. Do not assume this value is inbounds.
///
/// # Examples
///
/// ```
/// let mut rng = urandom::new();
/// for len in 1..12345 {
/// let index = rng.index(len);
/// assert!(index < len, "len:{} index:{} was not inbounds", len, index);
/// }
/// ```
pub fn index(&mut self, len: usize) -> usize {
distributions::UniformInt::constant(0, len).sample(self)
}
/// Returns a shared reference to one random element of the slice, or `None` if the slice is empty.
#[inline]
pub fn choose<'a, T>(&mut self, slice: &'a [T]) -> Option<&'a T> {
let index = self.index(slice.len());
slice.get(index)
}
/// Returns a unique reference to one random element of the slice, or `None` if the slice is empty.
#[inline]
pub fn choose_mut<'a, T>(&mut self, slice: &'a mut [T]) -> Option<&'a mut T> {
let index = self.index(slice.len());
slice.get_mut(index)
}
/// Returns an iterator over random chosen elements of the slice with repetition.
///
/// Produces `None` values if the slice is empty.
#[inline]
pub fn choose_iter<'a, T>(&'a mut self, slice: &'a [T]) -> impl 'a + Iterator<Item = &'a T> {
core::iter::from_fn(move || self.choose(slice))
}
/// Standard [Fisher–Yates](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) shuffle.
///
/// # Examples
///
/// ```
/// let mut rng = urandom::new();
/// let mut array = [1, 2, 3, 4, 5];
/// println!("Unshuffled: {:?}", array);
/// rng.shuffle(&mut array);
/// println!("Shuffled: {:?}", array);
/// ```
#[inline]
pub fn shuffle<T>(&mut self, slice: &mut [T]) {
let mut len = slice.len();
while len > 1 {
let k = self.index(len);
slice.swap(k, len - 1);
len -= 1;
}
}
/// Shuffle only the first _n_ elements.
///
/// This is an efficient method to select _n_ elements at random from the slice without repetition, provided the slice may be mutated.
#[inline]
pub fn partial_shuffle<T>(&mut self, slice: &mut [T], mut n: usize) {
if slice.len() > 1 {
n = usize::min(n, slice.len() - 1);
for i in 0..n {
let k = self.range(i..slice.len());
slice.swap(i, k);
}
}
}
}
impl<R: Rng + ?Sized> fmt::Debug for Random<R> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("Random(impl Rng)")
}
}
#[cfg(feature = "std")]
impl<R: Rng> std::io::Read for Random<R> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
self.fill_bytes(buf);
Ok(buf.len())
}
fn read_to_end(&mut self, _buf: &mut Vec<u8>) -> std::io::Result<usize> {
panic!("cannot read_to_end from Rng")
}
fn read_to_string(&mut self, _buf: &mut String) -> std::io::Result<usize> {
panic!("cannot read_to_string from Rng")
}
fn read_exact(&mut self, buf: &mut [u8]) -> std::io::Result<()> {
self.fill_bytes(buf);
Ok(())
}
}
//----------------------------------------------------------------
#[test]
fn test_choose() {
let mut rng = crate::new();
let mut array = [0, 1, 2, 3, 4];
let mut result = [0i32; 5];
for _ in 0..10000 {
result[*rng.choose(&array).unwrap()] += 1;
result[*rng.choose_mut(&mut array).unwrap()] += 1;
}
let mean = (result[0] + result[1] + result[2] + result[3] + result[4]) / 5;
let success = result.iter().all(|&x| (x - mean).abs() < 500);
assert!(success, "mean: {}, result: {:?}", mean, result);
}