nannou_core/rand.rs
1//! Items related to randomness and random number generators. Also provides some high-level helper
2//! functions.
3//!
4//! Helper functions include [**random_f32()**](./fn.random_f32.html),
5//! [**random_f64()**](./fn.random_f64.html) and [**random_range(min,
6//! max)**](./fn.random_range.html).
7
8pub use self::rand::*;
9pub use rand;
10
11/// A wrapper function around the `random` function that avoids the need for specifying a type in
12/// the case that it cannot be inferred. The primary purpose for this is to simplify the random API
13/// for new rust users.
14///
15/// NOTE: This helper function relies on a thread-local RNG and is currently only available with
16/// the "std" feature enabled.
17#[cfg(feature = "std")]
18pub fn random_f32() -> f32 {
19 rand::random()
20}
21
22/// A wrapper function around the `random` function that avoids the need for specifying a type in
23/// the case that it cannot be inferred. The primary purpose for this is to simplify the random API
24/// for new rust users.
25///
26/// NOTE: This helper function relies on a thread-local RNG and is currently only available with
27/// the "std" feature enabled.
28#[cfg(feature = "std")]
29pub fn random_f64() -> f64 {
30 rand::random()
31}
32
33/// A function for generating a random value within the given range.
34///
35/// The generated value may be within the range [min, max). That is, the result is inclusive of
36/// `min`, but will never be `max`.
37///
38/// If the given `min` is greater than the given `max`, they will be swapped before calling
39/// `gen_range` internally to avoid triggering a `panic!`.
40///
41/// This calls `rand::thread_rng().gen_range(min..max)` internally, in turn using the thread-local
42/// default random number generator.
43///
44/// NOTE: This helper function relies on a thread-local RNG and is currently only available with
45/// the "std" feature enabled.
46#[cfg(feature = "std")]
47pub fn random_range<T>(min: T, max: T) -> T
48where
49 T: PartialOrd + distributions::uniform::SampleUniform,
50{
51 let (min, max) = if min <= max { (min, max) } else { (max, min) };
52 rand::thread_rng().gen_range(min..max)
53}
54
55/// Generates and returns a random ascii character.
56///
57/// The ascii characters that can be generated are:
58///
59/// ABCDEFGHIJKLMNOPQRSTUVWXYZ\
60/// abcdefghijklmnopqrstuvwxyz\
61/// 0123456789)(*&^%$#@!~.
62///
63/// NOTE: This helper function relies on a thread-local RNG and is currently only available with
64/// the "std" feature enabled.
65#[cfg(feature = "std")]
66pub fn random_ascii() -> char {
67 const ASCIISET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
68 abcdefghijklmnopqrstuvwxyz\
69 0123456789)(*&^%$#@!~. ";
70
71 let idx = rand::thread_rng().gen_range(0..ASCIISET.len());
72 ASCIISET[idx] as char
73}