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
/// # Usage
/// ```
/// let lorem = lorem_rustum::LoremRustum::new(42);
/// println!("{}", lorem.to_string());
/// ```
///
/// ## Rusty Phrases:
/// ```
/// pub static RUSTY_PHRASES: [&str; 132] = [
///     "rust", "borrowing", "tokio", "async", "unsafe", "thread", "trait", "&str",
///     "rust-analyzer", "scope", "await", "ryan", "ownership", "safety", "nightly",
///     "allocated", "rustlings", "stack", "heap", "no garbage collector", "runtime",
///     "macros", "code execution", "fmt", "clippy", "memory safe", "cargo", "built-in",
///     "performance", "golang sucks", "better than c++", "friendly community",
///     "loved by developers", "wasm", "webassembly", "actix", "axum", "rocket", "yew",
///     "diesel", "sqlx", "pub", "mod", "enum", "static", "missing lifetime", "rusty",
///     "the most admired language", "a safer alternative to C and C++", "cargo package manager",
///     "performance-critical services", "Ferris mascot", "fast and reliable", "control over memory allocation",
///     "deallocation", "deref", "derive", "impl", "implement trait for", "to_owned()",
///     "i'm not looking for a job", "<'static>", "mut", "&mut", "efficient and organized development workflows",
///     "concurrency", "multiple threads can work on shared data without introducing memory-related issues",
///     "low-level tools and kernels", "type checking", "unwrap", "please gouge out my eyes",
///     "Sync + Send", "thread safety", "spawn concurrent task", "non-blocking i/o",
///     "smart pointer", "<'a>", "cargo test", "async-std", "println!", "dbg!", "dyn",
///     "stderr", "mpsc", "async move", "Arc", "Rc", "RefCell", "Box", "||", "expect",
///     "map", "making", "building", "produce", "consume", "out of scope", "rustc",
///     "rustup", "panic", "generics", "<T>", "impl fmt::Display for", "macro",
///     "#[derive()]", "multiple bounds", "traits", "macro_rules!", "Some()", "Option<&T>",
///     "None", "RAII", "drop", "destructor", "mutability of data", "ref", "as",
///     "closures", "HOF", "Higher Order Functions", "lazy loading", "err", "error",
///     "Result<T, Error>", "()", "Err(_)", "std", "#[cfg(test)]", "assert!",
///     "cargo run", "publish crate", "code blocks below"
/// ];
/// ```
use rand::prelude::*;

mod data;

#[derive(PartialEq, Debug, Clone)]
pub struct LoremRustum {
    pub body: Vec<&'static str>,
    pub length: usize,
}

impl LoremRustum {
    /// Build `LoremRustum` struct with specified length
    /// by choosing random elements from `RUSTY_PHRASES` using `rand::thread_rng()`.
    ///
    /// # Examples
    /// ```
    /// let lorem = lorem_rustum::LoremRustum::new(42);
    /// println!("{}", lorem.to_string());
    /// ```
    ///
    /// ### Rusty Phrases:
    /// ```
    /// pub static RUSTY_PHRASES: [&str; 132] = [
    ///     "rust", "borrowing", "tokio", "async", "unsafe", "thread", "trait", "&str",
    ///     "rust-analyzer", "scope", "await", "ryan", "ownership", "safety", "nightly",
    ///     "allocated", "rustlings", "stack", "heap", "no garbage collector", "runtime",
    ///     "macros", "code execution", "fmt", "clippy", "memory safe", "cargo", "built-in",
    ///     "performance", "golang sucks", "better than c++", "friendly community",
    ///     "loved by developers", "wasm", "webassembly", "actix", "axum", "rocket", "yew",
    ///     "diesel", "sqlx", "pub", "mod", "enum", "static", "missing lifetime", "rusty",
    ///     "the most admired language", "a safer alternative to C and C++", "cargo package manager",
    ///     "performance-critical services", "Ferris mascot", "fast and reliable", "control over memory allocation",
    ///     "deallocation", "deref", "derive", "impl", "implement trait for", "to_owned()",
    ///     "i'm not looking for a job", "<'static>", "mut", "&mut", "efficient and organized development workflows",
    ///     "concurrency", "multiple threads can work on shared data without introducing memory-related issues",
    ///     "low-level tools and kernels", "type checking", "unwrap", "please gouge out my eyes",
    ///     "Sync + Send", "thread safety", "spawn concurrent task", "non-blocking i/o",
    ///     "smart pointer", "<'a>", "cargo test", "async-std", "println!", "dbg!", "dyn",
    ///     "stderr", "mpsc", "async move", "Arc", "Rc", "RefCell", "Box", "||", "expect",
    ///     "map", "making", "building", "produce", "consume", "out of scope", "rustc",
    ///     "rustup", "panic", "generics", "<T>", "impl fmt::Display for", "macro",
    ///     "#[derive()]", "multiple bounds", "traits", "macro_rules!", "Some()", "Option<&T>",
    ///     "None", "RAII", "drop", "destructor", "mutability of data", "ref", "as",
    ///     "closures", "HOF", "Higher Order Functions", "lazy loading", "err", "error",
    ///     "Result<T, Error>", "()", "Err(_)", "std", "#[cfg(test)]", "assert!",
    ///     "cargo run", "publish crate", "code blocks below"
    /// ];
    /// ```
    pub fn new(length: usize) -> LoremRustum {
        let mut rng = rand::thread_rng();
        let body = LoremRustum::get_body(&mut rng, length);
        LoremRustum { body, length }
    }

    fn get_body(rng: &mut ThreadRng, length: usize) -> Vec<&'static str> {
        if length > data::RUSTY_PHRASES.len() {
            return LoremRustum::get_bigger_body(rng, length);
        }
        let mut rusty_words: Vec<&str> = data::RUSTY_PHRASES.to_vec();
        rusty_words.shuffle(rng);
        rusty_words.drain(0..length).collect()
    }

    fn get_bigger_body(rng: &mut ThreadRng, length: usize) -> Vec<&'static str> {
        let mut body = vec![];
        for _ in 0..length {
            body.push(data::RUSTY_PHRASES.choose(rng).unwrap().to_owned())
        }
        body
    }

    /// Shuffle body of `LoremRustum` in place using `shuffle()` from `rand` crate.
    ///
    /// # Examples
    /// ```
    /// let mut lorem = lorem_rustum::LoremRustum::default();
    /// let text = lorem.to_string();
    ///
    /// lorem.shuffle();
    /// let new_text = lorem.to_string();
    ///
    /// assert_ne!(text, new_text);
    /// ```
    pub fn shuffle(&mut self) {
        let mut rng = rand::thread_rng();
        self.body.shuffle(&mut rng);
    }
}

impl ToString for LoremRustum {
    fn to_string(&self) -> String {
        self.body.join(" ")
    }
}

impl Default for LoremRustum {
    /// Build `LoremRustum` with all `RUSTY_PHRASES` (contains 132 phrases).
    ///
    /// # Examples
    /// ```
    /// let lorem = lorem_rustum::LoremRustum::default();
    /// println!("{}", lorem.to_string());
    /// ```
    fn default() -> Self {
        let length = data::RUSTY_PHRASES.len();
        LoremRustum::new(length)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_new() {
        let length = data::RUSTY_PHRASES.len();
        let full_text = String::from_iter(data::RUSTY_PHRASES);
        let result = LoremRustum::new(length);

        assert!(result.body.len() == length);
        for i in 0..length {
            assert!(full_text.contains(result.body[i]))
        }
    }

    #[test]
    fn test_default() {
        let length = data::RUSTY_PHRASES.len();
        let lorem_rustum = LoremRustum::new(length);
        let result = LoremRustum::default();

        assert_eq!(result.body.len(), lorem_rustum.body.len());
    }

    #[test]
    fn test_length() {
        let rusty_words_len = data::RUSTY_PHRASES.len();
        let length = rusty_words_len / 2;
        let result = LoremRustum::new(length);

        assert_eq!(result.body.len(), length);

        let length = rusty_words_len * 4;
        let result = LoremRustum::new(length);

        assert_eq!(result.body.len(), length);
    }

    #[test]
    fn test_to_string() {
        let result = LoremRustum::new(5);
        let string = result.body.join(" ");

        assert_eq!(string, result.to_string());
    }

    #[test]
    fn test_random() {
        let length = 25;
        let result = LoremRustum::new(length);
        let body: Vec<&str> = data::RUSTY_PHRASES
            .into_iter()
            .enumerate()
            .filter(|&(i, _)| i < length)
            .map(|(_, e)| e)
            .collect();
        let lorem = LoremRustum { body, length };

        assert_ne!(result, lorem);
    }

    #[test]
    fn test_get_body() {
        let length = data::RUSTY_PHRASES.len() / 2;
        let mut rng = rand::thread_rng();
        let result = LoremRustum::get_body(&mut rng, length);
        let body: Vec<&str> = data::RUSTY_PHRASES
            .into_iter()
            .enumerate()
            .filter(|&(i, _)| i < length)
            .map(|(_, e)| e)
            .collect();

        assert!(result.len() == length);
        assert_eq!(result.len(), body.len());
    }

    #[test]
    fn test_get_bigger_body() {
        use rand::prelude::*;
        let length = data::RUSTY_PHRASES.len() * 2;
        let mut rng = rand::thread_rng();

        let result = LoremRustum::get_bigger_body(&mut rng, length);
        let mut body = vec![];
        for _ in 0..length {
            body.push(data::RUSTY_PHRASES.choose(&mut rng).unwrap().to_owned())
        }

        assert!(result.len() == length);
        assert_eq!(result.len(), body.len())
    }

    #[test]
    fn test_shuffle() {
        let mut lorem = LoremRustum::default();
        let text = lorem.to_string();
        lorem.shuffle();
        let new_text = lorem.to_string();

        assert_eq!(text.len(), new_text.len());
        assert_ne!(text, new_text);
    }
}