File: random.rs

package info (click to toggle)
rust-coreutils 0.0.30-3~exp1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 17,388 kB
  • sloc: sh: 1,088; python: 407; javascript: 72; makefile: 51
file content (344 lines) | stat: -rw-r--r-- 12,176 bytes parent folder | download | duplicates (2)
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
// This file is part of the uutils coreutils package.
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
#![allow(clippy::naive_bytecount)]

use rand::distr::{Distribution, Uniform};
use rand::{rng, Rng};

/// Samples alphanumeric characters `[A-Za-z0-9]` including newline `\n`
///
/// # Examples
///
/// ```rust,ignore
/// use rand::{Rng, rng};
///
/// let vec = rng()
///     .sample_iter(AlphanumericNewline)
///     .take(10)
///     .collect::<Vec<u8>>();
/// println!("Random chars: {}", String::from_utf8(vec).unwrap());
/// ```
#[derive(Clone, Copy, Debug)]
pub struct AlphanumericNewline;

impl AlphanumericNewline {
    /// The charset to act upon
    const CHARSET: &'static [u8] =
        b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\n";

    /// Generate a random byte from [`Self::CHARSET`] and return it as `u8`.
    ///
    /// # Arguments
    ///
    /// * `rng`: A [`rand::Rng`]
    ///
    /// returns: u8
    fn random<R>(rng: &mut R) -> u8
    where
        R: Rng + ?Sized,
    {
        let idx = rng.random_range(0..Self::CHARSET.len());
        Self::CHARSET[idx]
    }
}

impl Distribution<u8> for AlphanumericNewline {
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> u8 {
        Self::random(rng)
    }
}

/// Generate a random string from a [`Distribution`]
///
/// # Examples
///
/// ```rust,ignore
/// use crate::common::random::{AlphanumericNewline, RandomizedString};
/// use rand::distributions::Alphanumeric;
///
/// // generates a 100 byte string with characters from AlphanumericNewline
/// let random_string = RandomizedString::generate(AlphanumericNewline, 100);
/// assert_eq!(100, random_string.len());
///
/// // generates a 100 byte string with 10 newline characters not ending with a newline
/// let string = RandomizedString::generate_with_delimiter(Alphanumeric, b'\n', 10, false, 100);
/// assert_eq!(100, random_string.len());
/// ```
pub struct RandomizedString;

impl RandomizedString {
    /// Generate a random string from the given [`Distribution`] with the given `length` in bytes.
    ///
    /// # Arguments
    ///
    /// * `dist`: A u8 [`Distribution`]
    /// * `length`: the length of the resulting string in bytes
    ///
    /// returns: String
    pub fn generate<D>(dist: D, length: usize) -> String
    where
        D: Distribution<u8>,
    {
        rng()
            .sample_iter(dist)
            .take(length)
            .map(|b| b as char)
            .collect()
    }

    /// Generate a random string from the [`Distribution`] with the given `length` in bytes. The
    /// function takes a `delimiter`, which is randomly distributed in the string, such that exactly
    /// `num_delimiter` amount of `delimiter`s occur. If `end_with_delimiter` is set, then the
    /// string ends with the delimiter, else the string does not end with the delimiter.
    ///
    /// # Arguments
    ///
    /// * `dist`: A `u8` [`Distribution`]
    /// * `delimiter`: A `u8` delimiter, which does not need to be included in the `Distribution`
    /// * `num_delimiter`: The number of `delimiter`s contained in the resulting string
    /// * `end_with_delimiter`: If the string shall end with the given delimiter
    /// * `length`: the length of the resulting string in bytes
    ///
    /// returns: String
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use crate::common::random::{AlphanumericNewline, RandomizedString};
    ///
    /// // generates a 100 byte string with 10 '\0' byte characters not ending with a '\0' byte
    /// let string = RandomizedString::generate_with_delimiter(AlphanumericNewline, 0, 10, false, 100);
    /// assert_eq!(100, random_string.len());
    /// assert_eq!(
    ///     10,
    ///     random_string.as_bytes().iter().filter(|p| **p == 0).count()
    /// );
    /// assert!(!random_string.as_bytes().ends_with(&[0]));
    /// ```
    pub fn generate_with_delimiter<D>(
        dist: D,
        delimiter: u8,
        num_delimiter: usize,
        end_with_delimiter: bool,
        length: usize,
    ) -> String
    where
        D: Distribution<u8>,
    {
        if length == 0 {
            return String::new();
        } else if length == 1 {
            return if num_delimiter > 0 {
                String::from(delimiter as char)
            } else {
                String::from(rng().sample(&dist) as char)
            };
        }

        let samples = length - 1;
        let mut result: Vec<u8> = rng().sample_iter(&dist).take(samples).collect();

        if num_delimiter == 0 {
            result.push(rng().sample(&dist));
            return String::from_utf8(result).unwrap();
        }

        let num_delimiter = if end_with_delimiter {
            num_delimiter - 1
        } else {
            num_delimiter
        };

        // it's safe to unwrap because samples is always > 0, thus low < high
        let between = Uniform::new(0, samples).unwrap();
        for _ in 0..num_delimiter {
            let mut pos = between.sample(&mut rng());
            let turn = pos;
            while result[pos] == delimiter {
                pos += 1;
                if pos >= samples {
                    pos = 0;
                }
                if pos == turn {
                    break;
                }
            }
            result[pos] = delimiter;
        }

        if end_with_delimiter {
            result.push(delimiter);
        } else {
            result.push(rng().sample(&dist));
        }

        String::from_utf8(result).unwrap()
    }
}

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

    #[test]
    fn test_random_string_generate() {
        let random_string = RandomizedString::generate(AlphanumericNewline, 0);
        assert_eq!(0, random_string.len());

        let random_string = RandomizedString::generate(AlphanumericNewline, 1);
        assert_eq!(1, random_string.len());

        let random_string = RandomizedString::generate(AlphanumericNewline, 100);
        assert_eq!(100, random_string.len());
    }

    #[test]
    fn test_random_string_generate_with_delimiter_when_length_is_zero() {
        let random_string = RandomizedString::generate_with_delimiter(Alphanumeric, 0, 0, false, 0);
        assert_eq!(0, random_string.len());
    }

    #[test]
    fn test_random_string_generate_with_delimiter_when_num_delimiter_is_greater_than_length() {
        let random_string = RandomizedString::generate_with_delimiter(Alphanumeric, 0, 2, false, 1);
        assert_eq!(1, random_string.len());
        assert!(random_string.as_bytes().contains(&0));
        assert!(random_string.as_bytes().ends_with(&[0]));
    }

    #[test]
    #[allow(clippy::cognitive_complexity)] // Ignore clippy lint of too long function sign
    fn test_random_string_generate_with_delimiter_should_end_with_delimiter() {
        let random_string = RandomizedString::generate_with_delimiter(Alphanumeric, 0, 1, true, 1);
        assert_eq!(1, random_string.len());
        assert_eq!(
            1,
            random_string.as_bytes().iter().filter(|p| **p == 0).count()
        );
        assert!(random_string.as_bytes().ends_with(&[0]));

        let random_string = RandomizedString::generate_with_delimiter(Alphanumeric, 0, 1, false, 1);
        assert_eq!(1, random_string.len());
        assert_eq!(
            1,
            random_string.as_bytes().iter().filter(|p| **p == 0).count()
        );
        assert!(random_string.as_bytes().ends_with(&[0]));

        let random_string = RandomizedString::generate_with_delimiter(Alphanumeric, 0, 1, true, 2);
        assert_eq!(2, random_string.len());
        assert_eq!(
            1,
            random_string.as_bytes().iter().filter(|p| **p == 0).count()
        );
        assert!(random_string.as_bytes().ends_with(&[0]));

        let random_string = RandomizedString::generate_with_delimiter(Alphanumeric, 0, 2, true, 2);
        assert_eq!(2, random_string.len());
        assert_eq!(
            2,
            random_string.as_bytes().iter().filter(|p| **p == 0).count()
        );
        assert!(random_string.as_bytes().ends_with(&[0]));

        let random_string = RandomizedString::generate_with_delimiter(Alphanumeric, 0, 1, true, 3);
        assert_eq!(3, random_string.len());
        assert_eq!(
            1,
            random_string.as_bytes().iter().filter(|p| **p == 0).count()
        );
        assert!(random_string.as_bytes().ends_with(&[0]));
    }

    #[test]
    #[allow(clippy::cognitive_complexity)] // Ignore clippy lint of too long function sign
    fn test_random_string_generate_with_delimiter_should_not_end_with_delimiter() {
        let random_string = RandomizedString::generate_with_delimiter(Alphanumeric, 0, 0, false, 1);
        assert_eq!(1, random_string.len());
        assert_eq!(
            0,
            random_string.as_bytes().iter().filter(|p| **p == 0).count()
        );

        let random_string = RandomizedString::generate_with_delimiter(Alphanumeric, 0, 0, true, 1);
        assert_eq!(1, random_string.len());
        assert_eq!(
            0,
            random_string.as_bytes().iter().filter(|p| **p == 0).count()
        );

        let random_string = RandomizedString::generate_with_delimiter(Alphanumeric, 0, 1, false, 2);
        assert_eq!(2, random_string.len());
        assert_eq!(
            1,
            random_string.as_bytes().iter().filter(|p| **p == 0).count()
        );
        assert!(!random_string.as_bytes().ends_with(&[0]));

        let random_string = RandomizedString::generate_with_delimiter(Alphanumeric, 0, 1, false, 3);
        assert_eq!(3, random_string.len());
        assert_eq!(
            1,
            random_string.as_bytes().iter().filter(|p| **p == 0).count()
        );
        assert!(!random_string.as_bytes().ends_with(&[0]));

        let random_string = RandomizedString::generate_with_delimiter(Alphanumeric, 0, 2, false, 3);
        assert_eq!(3, random_string.len());
        assert_eq!(
            2,
            random_string.as_bytes().iter().filter(|p| **p == 0).count()
        );
        assert!(!random_string.as_bytes().ends_with(&[0]));
    }

    #[test]
    fn test_generate_with_delimiter_with_greater_length() {
        let random_string =
            RandomizedString::generate_with_delimiter(Alphanumeric, 0, 100, false, 1000);
        assert_eq!(1000, random_string.len());
        assert_eq!(
            100,
            random_string.as_bytes().iter().filter(|p| **p == 0).count()
        );
        assert!(!random_string.as_bytes().ends_with(&[0]));

        let random_string =
            RandomizedString::generate_with_delimiter(Alphanumeric, 0, 100, true, 1000);
        assert_eq!(1000, random_string.len());
        assert_eq!(
            100,
            random_string.as_bytes().iter().filter(|p| **p == 0).count()
        );
        assert!(random_string.as_bytes().ends_with(&[0]));
    }

    /// Originally used to exclude an error within the `random` module. The two
    /// affected tests timed out on windows, but only in the ci. These tests are
    /// also the source for the concrete numbers. The timed out tests are
    /// `test_tail.rs::test_pipe_when_lines_option_given_input_size_has_multiple_size_of_buffer_size`
    /// `test_tail.rs::test_pipe_when_bytes_option_given_input_size_has_multiple_size_of_buffer_size`.
    #[test]
    fn test_generate_random_strings_when_length_is_around_critical_buffer_sizes() {
        let length = 8192 * 3;
        let random_string = RandomizedString::generate(AlphanumericNewline, length);
        assert_eq!(length, random_string.len());

        let length = 8192 * 3 + 1;
        let random_string =
            RandomizedString::generate_with_delimiter(Alphanumeric, b'\n', 100, true, length);
        assert_eq!(length, random_string.len());
        assert_eq!(
            100,
            random_string
                .as_bytes()
                .iter()
                .filter(|p| **p == b'\n')
                .count()
        );
        assert!(!random_string.as_bytes().ends_with(&[0]));
    }
}