goose_eggs/
text.rs

1//! Functionality for efficiently generating random text.
2
3use rand::distr::Alphanumeric;
4use rand::{rng, Rng};
5
6/// Generate a random "word" of the specified length of random
7/// alphanumeric characters.
8///
9/// # Example
10/// ```rust
11/// use goose_eggs::text::random_word;
12///
13/// // Generate a random "word" comprised of 10 alphanumeric characters.
14/// let word = random_word(10);
15/// assert_eq!(word.len(), 10);
16/// ```
17pub fn random_word(length: usize) -> String {
18    rng()
19        .sample_iter(&Alphanumeric)
20        .take(length)
21        .map(char::from)
22        .collect()
23}
24
25/// Generate a random "sentence" comprised of random alphanumeric "words"
26/// each ranging between 3 and 12 characters.
27///
28/// # Example
29/// ```rust
30/// use goose_eggs::text::random_words;
31///
32/// // Generate a random "sentence" comprised of 5 alphanumeric "words".
33/// let sentence = random_words(5);
34/// assert!(sentence.len() >= 3*5 && sentence.len() <= 12*5);
35/// ```
36pub fn random_words(number: usize) -> String {
37    let mut words: Vec<String> = Vec::new();
38    for _ in 1..number {
39        let mut rng = rng();
40        words.push(random_word(rng.random_range(3..12)));
41    }
42    words.join(" ")
43}