Debian Codegraph @

tests/uutests/src/lib/random.rs

raw
1 // This file is part of the uutils coreutils package.
2 //
3 // For the full copyright and license information, please view the LICENSE
4 // file that was distributed with this source code.
5
6 #![allow(clippy::naive_bytecount)]
7
8 use rand::{
9 Rng, RngExt as _,
10 distr::{Distribution, Uniform},
11 rng,
12 };
13
14 /// Samples alphanumeric characters `[A-Za-z0-9]` including newline `\n`
15 ///
16 /// # Examples
17 ///
18 /// ```rust,ignore
19 /// use rand::{Rng, rng};
20 ///
21 /// let vec = rng()
22 /// .sample_iter(AlphanumericNewline)
23 /// .take(10)
24 /// .collect::<Vec<u8>>();
25 /// println!("Random chars: {}", String::from_utf8(vec).unwrap());
26 /// ```
27 #[derive(Clone, Copy, Debug)]
28 pub struct AlphanumericNewline;
29
30 impl AlphanumericNewline {
31 /// The charset to act upon
32 const CHARSET: &'static [u8] =
33 b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\n";
34
35 /// Generate a random byte from [`Self::CHARSET`] and return it as `u8`.
36 ///
37 /// # Arguments
38 ///
39 /// * `rng`: A [`rand::Rng`]
40 ///
41 /// returns: u8
42 fn random<R>(rng: &mut R) -> u8
43 where
44 R: Rng + ?Sized,
45 {
46 let idx = rng.random_range(0..Self::CHARSET.len());
47 Self::CHARSET[idx]
48 }
49 }
50
51 impl Distribution<u8> for AlphanumericNewline {
52 fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> u8 {
53 Self::random(rng)
54 }
55 }
56
57 /// Generate a random string from a [`Distribution`]
58 ///
59 /// # Examples
60 ///
61 /// ```rust,ignore
62 /// use crate::common::random::{AlphanumericNewline, RandomizedString};
63 /// use rand::distributions::Alphanumeric;
64 ///
65 /// // generates a 100 byte string with characters from AlphanumericNewline
66 /// let random_string = RandomizedString::generate(AlphanumericNewline, 100);
67 /// assert_eq!(100, random_string.len());
68 ///
69 /// // generates a 100 byte string with 10 newline characters not ending with a newline
70 /// let string = RandomizedString::generate_with_delimiter(Alphanumeric, b'\n', 10, false, 100);
71 /// assert_eq!(100, random_string.len());
72 /// ```
73 pub struct RandomizedString;
74
75 impl RandomizedString {
76 /// Generate a random string from the given [`Distribution`] with the given `length` in bytes.
77 ///
78 /// # Arguments
79 ///
80 /// * `dist`: A u8 [`Distribution`]
81 /// * `length`: the length of the resulting string in bytes
82 ///
83 /// returns: String
84 pub fn generate<D>(dist: D, length: usize) -> String
85 where
86 D: Distribution<u8>,
87 {
88 rng()
89 .sample_iter(dist)
90 .take(length)
91 .map(|b| b as char)
92 .collect()
93 }
94
95 /// Generate a random string from the [`Distribution`] with the given `length` in bytes. The
96 /// function takes a `delimiter`, which is randomly distributed in the string, such that exactly
97 /// `num_delimiter` amount of `delimiter`s occur. If `end_with_delimiter` is set, then the
98 /// string ends with the delimiter, else the string does not end with the delimiter.
99 ///
100 /// # Arguments
101 ///
102 /// * `dist`: A `u8` [`Distribution`]
103 /// * `delimiter`: A `u8` delimiter, which does not need to be included in the `Distribution`
104 /// * `num_delimiter`: The number of `delimiter`s contained in the resulting string
105 /// * `end_with_delimiter`: If the string shall end with the given delimiter
106 /// * `length`: the length of the resulting string in bytes
107 ///
108 /// returns: String
109 ///
110 /// # Examples
111 ///
112 /// ```rust,ignore
113 /// use crate::common::random::{AlphanumericNewline, RandomizedString};
114 ///
115 /// // generates a 100 byte string with 10 '\0' byte characters not ending with a '\0' byte
116 /// let string = RandomizedString::generate_with_delimiter(AlphanumericNewline, 0, 10, false, 100);
117 /// assert_eq!(100, random_string.len());
118 /// assert_eq!(
119 /// 10,
120 /// random_string.as_bytes().iter().filter(|p| **p == 0).count()
121 /// );
122 /// assert!(!random_string.as_bytes().ends_with(&[0]));
123 /// ```
124 pub fn generate_with_delimiter<D>(
125 dist: D,
126 delimiter: u8,
127 num_delimiter: usize,
128 end_with_delimiter: bool,
129 length: usize,
130 ) -> String
131 where
132 D: Distribution<u8>,
133 {
134 if length == 0 {
135 return String::new();
136 } else if length == 1 {
137 return if num_delimiter > 0 {
138 String::from(delimiter as char)
139 } else {
140 String::from(rng().sample(&dist) as char)
141 };
142 }
143
144 let samples = length - 1;
145 let mut result: Vec<u8> = rng().sample_iter(&dist).take(samples).collect();
146
147 if num_delimiter == 0 {
148 result.push(rng().sample(&dist));
149 return String::from_utf8(result).unwrap();
150 }
151
152 let num_delimiter = if end_with_delimiter {
153 num_delimiter - 1
154 } else {
155 num_delimiter
156 };
157
158 // it's safe to unwrap because samples is always > 0, thus low < high
159 let between = Uniform::new(0, samples).unwrap();
160 for _ in 0..num_delimiter {
161 let mut pos = between.sample(&mut rng());
162 let turn = pos;
163 while result[pos] == delimiter {
164 pos += 1;
165 if pos >= samples {
166 pos = 0;
167 }
168 if pos == turn {
169 break;
170 }
171 }
172 result[pos] = delimiter;
173 }
174
175 if end_with_delimiter {
176 result.push(delimiter);
177 } else {
178 result.push(rng().sample(&dist));
179 }
180
181 String::from_utf8(result).unwrap()
182 }
183 }
184
185 #[cfg(test)]
186 mod tests {
187 use super::*;
188 use rand::distr::Alphanumeric;
189
190 #[test]
191 fn test_random_string_generate() {
192 let random_string = RandomizedString::generate(AlphanumericNewline, 0);
193 assert_eq!(0, random_string.len());
194
195 let random_string = RandomizedString::generate(AlphanumericNewline, 1);
196 assert_eq!(1, random_string.len());
197
198 let random_string = RandomizedString::generate(AlphanumericNewline, 100);
199 assert_eq!(100, random_string.len());
200 }
201
202 #[test]
203 fn test_random_string_generate_with_delimiter_when_length_is_zero() {
204 let random_string = RandomizedString::generate_with_delimiter(Alphanumeric, 0, 0, false, 0);
205 assert_eq!(0, random_string.len());
206 }
207
208 #[test]
209 fn test_random_string_generate_with_delimiter_when_num_delimiter_is_greater_than_length() {
210 let random_string = RandomizedString::generate_with_delimiter(Alphanumeric, 0, 2, false, 1);
211 assert_eq!(1, random_string.len());
212 assert!(random_string.as_bytes().contains(&0));
213 assert!(random_string.as_bytes().ends_with(&[0]));
214 }
215
216 #[test]
217 #[allow(clippy::cognitive_complexity)] // Ignore clippy lint of too long function sign
218 fn test_random_string_generate_with_delimiter_should_end_with_delimiter() {
219 let random_string = RandomizedString::generate_with_delimiter(Alphanumeric, 0, 1, true, 1);
220 assert_eq!(1, random_string.len());
221 assert_eq!(
222 1,
223 random_string.as_bytes().iter().filter(|p| **p == 0).count()
224 );
225 assert!(random_string.as_bytes().ends_with(&[0]));
226
227 let random_string = RandomizedString::generate_with_delimiter(Alphanumeric, 0, 1, false, 1);
228 assert_eq!(1, random_string.len());
229 assert_eq!(
230 1,
231 random_string.as_bytes().iter().filter(|p| **p == 0).count()
232 );
233 assert!(random_string.as_bytes().ends_with(&[0]));
234
235 let random_string = RandomizedString::generate_with_delimiter(Alphanumeric, 0, 1, true, 2);
236 assert_eq!(2, random_string.len());
237 assert_eq!(
238 1,
239 random_string.as_bytes().iter().filter(|p| **p == 0).count()
240 );
241 assert!(random_string.as_bytes().ends_with(&[0]));
242
243 let random_string = RandomizedString::generate_with_delimiter(Alphanumeric, 0, 2, true, 2);
244 assert_eq!(2, random_string.len());
245 assert_eq!(
246 2,
247 random_string.as_bytes().iter().filter(|p| **p == 0).count()
248 );
249 assert!(random_string.as_bytes().ends_with(&[0]));
250
251 let random_string = RandomizedString::generate_with_delimiter(Alphanumeric, 0, 1, true, 3);
252 assert_eq!(3, random_string.len());
253 assert_eq!(
254 1,
255 random_string.as_bytes().iter().filter(|p| **p == 0).count()
256 );
257 assert!(random_string.as_bytes().ends_with(&[0]));
258 }
259
260 #[test]
261 #[allow(clippy::cognitive_complexity)] // Ignore clippy lint of too long function sign
262 fn test_random_string_generate_with_delimiter_should_not_end_with_delimiter() {
263 let random_string = RandomizedString::generate_with_delimiter(Alphanumeric, 0, 0, false, 1);
264 assert_eq!(1, random_string.len());
265 assert_eq!(
266 0,
267 random_string.as_bytes().iter().filter(|p| **p == 0).count()
268 );
269
270 let random_string = RandomizedString::generate_with_delimiter(Alphanumeric, 0, 0, true, 1);
271 assert_eq!(1, random_string.len());
272 assert_eq!(
273 0,
274 random_string.as_bytes().iter().filter(|p| **p == 0).count()
275 );
276
277 let random_string = RandomizedString::generate_with_delimiter(Alphanumeric, 0, 1, false, 2);
278 assert_eq!(2, random_string.len());
279 assert_eq!(
280 1,
281 random_string.as_bytes().iter().filter(|p| **p == 0).count()
282 );
283 assert!(!random_string.as_bytes().ends_with(&[0]));
284
285 let random_string = RandomizedString::generate_with_delimiter(Alphanumeric, 0, 1, false, 3);
286 assert_eq!(3, random_string.len());
287 assert_eq!(
288 1,
289 random_string.as_bytes().iter().filter(|p| **p == 0).count()
290 );
291 assert!(!random_string.as_bytes().ends_with(&[0]));
292
293 let random_string = RandomizedString::generate_with_delimiter(Alphanumeric, 0, 2, false, 3);
294 assert_eq!(3, random_string.len());
295 assert_eq!(
296 2,
297 random_string.as_bytes().iter().filter(|p| **p == 0).count()
298 );
299 assert!(!random_string.as_bytes().ends_with(&[0]));
300 }
301
302 #[test]
303 fn test_generate_with_delimiter_with_greater_length() {
304 let random_string =
305 RandomizedString::generate_with_delimiter(Alphanumeric, 0, 100, false, 1000);
306 assert_eq!(1000, random_string.len());
307 assert_eq!(
308 100,
309 random_string.as_bytes().iter().filter(|p| **p == 0).count()
310 );
311 assert!(!random_string.as_bytes().ends_with(&[0]));
312
313 let random_string =
314 RandomizedString::generate_with_delimiter(Alphanumeric, 0, 100, true, 1000);
315 assert_eq!(1000, random_string.len());
316 assert_eq!(
317 100,
318 random_string.as_bytes().iter().filter(|p| **p == 0).count()
319 );
320 assert!(random_string.as_bytes().ends_with(&[0]));
321 }
322
323 /// Originally used to exclude an error within the `random` module. The two
324 /// affected tests timed out on windows, but only in the ci. These tests are
325 /// also the source for the concrete numbers. The timed out tests are
326 /// `test_tail.rs::test_pipe_when_lines_option_given_input_size_has_multiple_size_of_buffer_size`
327 /// `test_tail.rs::test_pipe_when_bytes_option_given_input_size_has_multiple_size_of_buffer_size`.
328 #[test]
329 fn test_generate_random_strings_when_length_is_around_critical_buffer_sizes() {
330 let length = 8192 * 3;
331 let random_string = RandomizedString::generate(AlphanumericNewline, length);
332 assert_eq!(length, random_string.len());
333
334 let length = 8192 * 3 + 1;
335 let random_string =
336 RandomizedString::generate_with_delimiter(Alphanumeric, b'\n', 100, true, length);
337 assert_eq!(length, random_string.len());
338 assert_eq!(
339 100,
340 random_string
341 .as_bytes()
342 .iter()
343 .filter(|p| **p == b'\n')
344 .count()
345 );
346 assert!(!random_string.as_bytes().ends_with(&[0]));
347 }
348 }