rand 0.10.4

Random number generators and other randomness functionality.
Documentation
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
// Copyright 2018-2020 Developers of the Rand project.
// Copyright 2017 The Rust Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! `UniformChar`, `UniformDuration` implementations

use super::{Error, SampleBorrow, SampleUniform, Uniform, UniformInt, UniformSampler};
use crate::Rng;
use crate::distr::Distribution;
use core::time::Duration;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

impl SampleUniform for char {
    type Sampler = UniformChar;
}

/// The back-end implementing [`UniformSampler`] for `char`.
///
/// Unless you are implementing [`UniformSampler`] for your own type, this type
/// should not be used directly, use [`Uniform`] instead.
///
/// This differs from integer range sampling since the range `0xD800..=0xDFFF`
/// are used for surrogate pairs in UCS and UTF-16, and consequently are not
/// valid Unicode code points. We must therefore avoid sampling values in this
/// range.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct UniformChar {
    #[cfg_attr(feature = "serde", serde(deserialize_with = "deser_sampler"))]
    sampler: UniformInt<u32>,
}

#[cfg(feature = "serde")]
fn deser_sampler<'de, D>(d: D) -> Result<UniformInt<u32>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let sampler = <UniformInt<u32> as serde::Deserialize>::deserialize(d)?;
    if sampler.max() > char::MAX as u32 - CHAR_SURROGATE_LEN {
        return Err(serde::de::Error::custom(
            "bad sampler range for UniformChar",
        ));
    }
    Ok(sampler)
}

/// UTF-16 surrogate range start
const CHAR_SURROGATE_START: u32 = 0xD800;
/// UTF-16 surrogate range size
const CHAR_SURROGATE_LEN: u32 = 0xE000 - CHAR_SURROGATE_START;

/// Convert `char` to compressed `u32`
fn char_to_comp_u32(c: char) -> u32 {
    match c as u32 {
        c if c >= CHAR_SURROGATE_START => c - CHAR_SURROGATE_LEN,
        c => c,
    }
}

impl UniformSampler for UniformChar {
    type X = char;

    #[inline] // if the range is constant, this helps LLVM to do the
    // calculations at compile-time.
    fn new<B1, B2>(low_b: B1, high_b: B2) -> Result<Self, Error>
    where
        B1: SampleBorrow<Self::X> + Sized,
        B2: SampleBorrow<Self::X> + Sized,
    {
        let low = char_to_comp_u32(*low_b.borrow());
        let high = char_to_comp_u32(*high_b.borrow());
        let sampler = UniformInt::<u32>::new(low, high);
        sampler.map(|sampler| UniformChar { sampler })
    }

    #[inline] // if the range is constant, this helps LLVM to do the
    // calculations at compile-time.
    fn new_inclusive<B1, B2>(low_b: B1, high_b: B2) -> Result<Self, Error>
    where
        B1: SampleBorrow<Self::X> + Sized,
        B2: SampleBorrow<Self::X> + Sized,
    {
        let low = char_to_comp_u32(*low_b.borrow());
        let high = char_to_comp_u32(*high_b.borrow());
        let sampler = UniformInt::<u32>::new_inclusive(low, high);
        sampler.map(|sampler| UniformChar { sampler })
    }

    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X {
        let mut x = self.sampler.sample(rng);
        if x >= CHAR_SURROGATE_START {
            x += CHAR_SURROGATE_LEN;
        }

        char::from_u32(x)
            .expect("rand::distr::uniform::UniformChar: invalid Unicode scalar value (likely memory corruption)")
    }
}

#[cfg(feature = "alloc")]
impl crate::distr::SampleString for Uniform<char> {
    fn append_string<R: Rng + ?Sized>(
        &self,
        rng: &mut R,
        string: &mut alloc::string::String,
        len: usize,
    ) {
        // Getting the hi value to assume the required length to reserve in string.
        let mut hi = self.0.sampler.low + self.0.sampler.range - 1;
        if hi >= CHAR_SURROGATE_START {
            hi += CHAR_SURROGATE_LEN;
        }
        // Get the utf8 length of hi to minimize extra space.
        let max_char_len = char::from_u32(hi).map(char::len_utf8).unwrap_or(4);
        string.reserve(max_char_len * len);
        string.extend(self.sample_iter(rng).take(len))
    }
}

/// The back-end implementing [`UniformSampler`] for `Duration`.
///
/// Unless you are implementing [`UniformSampler`] for your own types, this type
/// should not be used directly, use [`Uniform`] instead.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct UniformDuration {
    mode: UniformDurationMode,
    offset: u32,
}

/// `sample` feeds the sampler state straight to `Duration::new`, which panics
/// on overflow, so reject any state which cannot have come from `new_inclusive`
/// in the same way `UniformChar` rejects a bad `UniformInt<u32>`.
#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for UniformDuration {
    fn deserialize<D>(d: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        /// Nanoseconds in one second
        const NANOS_PER_SEC: u64 = 1_000_000_000;

        #[derive(Deserialize)]
        #[serde(rename = "UniformDuration")]
        struct Fields {
            mode: UniformDurationMode,
            offset: u32,
        }

        let Fields { mode, offset } = Fields::deserialize(d)?;

        let valid = offset < NANOS_PER_SEC as u32
            && match mode {
                UniformDurationMode::Small { secs, nanos } => {
                    let carry = u64::from(nanos.0.max()) / NANOS_PER_SEC;
                    secs.checked_add(carry).is_some()
                }
                UniformDurationMode::Medium { .. } => true,
                UniformDurationMode::Large {
                    max_secs,
                    max_nanos,
                    secs,
                } => {
                    let carry = (u64::from(max_nanos) + u64::from(offset)) / NANOS_PER_SEC;
                    // `new_inclusive` samples `secs` over at least two values
                    // (`low_s < high_s`), so `sample` rejects at most about
                    // half of its draws. A single-value range with a small
                    // `max_nanos` would make it loop for ~`NANOS_PER_SEC` iterations.
                    secs.max() == max_secs
                        && secs.range != 1
                        && max_secs.checked_add(carry).is_some()
                }
            };

        if !valid {
            return Err(serde::de::Error::custom(
                "bad sampler state for UniformDuration",
            ));
        }

        Ok(UniformDuration { mode, offset })
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
enum UniformDurationMode {
    Small {
        secs: u64,
        nanos: Uniform<u32>,
    },
    Medium {
        nanos: Uniform<u64>,
    },
    Large {
        max_secs: u64,
        max_nanos: u32,
        secs: UniformInt<u64>,
    },
}

impl SampleUniform for Duration {
    type Sampler = UniformDuration;
}

impl UniformSampler for UniformDuration {
    type X = Duration;

    #[inline]
    fn new<B1, B2>(low_b: B1, high_b: B2) -> Result<Self, Error>
    where
        B1: SampleBorrow<Self::X> + Sized,
        B2: SampleBorrow<Self::X> + Sized,
    {
        let low = *low_b.borrow();
        let high = *high_b.borrow();
        if !(low < high) {
            return Err(Error::EmptyRange);
        }
        UniformDuration::new_inclusive(low, high - Duration::new(0, 1))
    }

    #[inline]
    fn new_inclusive<B1, B2>(low_b: B1, high_b: B2) -> Result<Self, Error>
    where
        B1: SampleBorrow<Self::X> + Sized,
        B2: SampleBorrow<Self::X> + Sized,
    {
        let low = *low_b.borrow();
        let high = *high_b.borrow();
        if !(low <= high) {
            return Err(Error::EmptyRange);
        }

        let low_s = low.as_secs();
        let low_n = low.subsec_nanos();
        let mut high_s = high.as_secs();
        let mut high_n = high.subsec_nanos();

        if high_n < low_n {
            high_s -= 1;
            high_n += 1_000_000_000;
        }

        let mode = if low_s == high_s {
            UniformDurationMode::Small {
                secs: low_s,
                nanos: Uniform::new_inclusive(low_n, high_n)?,
            }
        } else {
            let max = high_s
                .checked_mul(1_000_000_000)
                .and_then(|n| n.checked_add(u64::from(high_n)));

            if let Some(higher_bound) = max {
                let lower_bound = low_s * 1_000_000_000 + u64::from(low_n);
                UniformDurationMode::Medium {
                    nanos: Uniform::new_inclusive(lower_bound, higher_bound)?,
                }
            } else {
                // An offset is applied to simplify generation of nanoseconds
                let max_nanos = high_n - low_n;
                UniformDurationMode::Large {
                    max_secs: high_s,
                    max_nanos,
                    secs: UniformInt::new_inclusive(low_s, high_s)?,
                }
            }
        };
        Ok(UniformDuration {
            mode,
            offset: low_n,
        })
    }

    #[inline]
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Duration {
        match self.mode {
            UniformDurationMode::Small { secs, nanos } => {
                let n = nanos.sample(rng);
                Duration::new(secs, n)
            }
            UniformDurationMode::Medium { nanos } => {
                let nanos = nanos.sample(rng);
                Duration::new(nanos / 1_000_000_000, (nanos % 1_000_000_000) as u32)
            }
            UniformDurationMode::Large {
                max_secs,
                max_nanos,
                secs,
            } => {
                // constant folding means this is at least as fast as `Rng::sample(Range)`
                let nano_range = Uniform::new(0, 1_000_000_000).unwrap();
                loop {
                    let s = secs.sample(rng);
                    let n = nano_range.sample(rng);
                    if !(s == max_secs && n > max_nanos) {
                        let sum = n + self.offset;
                        break Duration::new(s, sum);
                    }
                }
            }
        }
    }
}

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

    #[test]
    #[cfg(feature = "serde")]
    fn test_serialization_uniform_duration() {
        let distr = UniformDuration::new(Duration::from_secs(10), Duration::from_secs(60)).unwrap();
        let de_distr: UniformDuration =
            postcard::from_bytes(&postcard::to_allocvec(&distr).unwrap()).unwrap();
        assert_eq!(distr, de_distr);
    }

    #[test]
    #[cfg_attr(miri, ignore)] // Miri is too slow
    fn test_char() {
        let mut rng = crate::test::rng(891);
        let mut max = core::char::from_u32(0).unwrap();
        for _ in 0..100 {
            let c = rng.random_range('A'..='Z');
            assert!(c.is_ascii_uppercase());
            max = max.max(c);
        }
        assert_eq!(max, 'Z');
        let d = Uniform::new(
            core::char::from_u32(0xD7F0).unwrap(),
            core::char::from_u32(0xE010).unwrap(),
        )
        .unwrap();
        for _ in 0..100 {
            let c = d.sample(&mut rng);
            assert!((c as u32) < 0xD800 || (c as u32) > 0xDFFF);
        }
        #[cfg(feature = "alloc")]
        {
            use crate::distr::SampleString;
            let string1 = d.sample_string(&mut rng, 100);
            assert_eq!(string1.capacity(), 300);
            let string2 = Uniform::new(
                core::char::from_u32(0x0000).unwrap(),
                core::char::from_u32(0x0080).unwrap(),
            )
            .unwrap()
            .sample_string(&mut rng, 100);
            assert_eq!(string2.capacity(), 100);
            let string3 = Uniform::new_inclusive(
                core::char::from_u32(0x0000).unwrap(),
                core::char::from_u32(0x0080).unwrap(),
            )
            .unwrap()
            .sample_string(&mut rng, 100);
            assert_eq!(string3.capacity(), 200);
        }
    }

    #[test]
    #[cfg(feature = "serde")]
    fn test_char_bad_deser() {
        fn do_test(json: &str, col: usize) {
            let result = serde_json::from_str::<Uniform<char>>(json);
            assert!(result.is_err());
            let err = result.unwrap_err();
            assert_eq!(err.classify(), serde_json::error::Category::Data);

            #[cfg(feature = "alloc")]
            {
                let msg =
                    alloc::format!("bad sampler range for UniformChar at line 1 column {col}");
                assert_eq!(alloc::string::ToString::to_string(&err), msg);
            }
        }

        do_test(r#"{"sampler":{"low":5,"range":0,"thresh":0}}"#, 42);
        do_test(r#"{"sampler":{"low":4294967200,"range":0,"thresh":0}}"#, 51);
        do_test(
            r#"{"sampler":{"low":4294967280,"range":32,"thresh":0}}"#,
            52,
        );
    }

    #[test]
    #[cfg(feature = "serde")]
    fn test_duration_bad_deser() {
        fn do_test(json: &str) {
            let result = serde_json::from_str::<UniformDuration>(json);
            assert!(result.is_err());
            let err = result.unwrap_err();
            assert_eq!(err.classify(), serde_json::error::Category::Data);

            #[cfg(feature = "alloc")]
            {
                let msg = "bad sampler state for UniformDuration";
                assert!(alloc::string::ToString::to_string(&err).starts_with(msg));
            }
        }

        // Small: sampled nanos carry a second into `secs`, overflowing it
        do_test(
            r#"{"mode":{"Small":{"secs":18446744073709551615,"nanos":{"low":1000000000,"range":1,"thresh":0}}},"offset":0}"#,
        );
        // Large: the seconds sampler can exceed `max_secs`, so the rejection
        // test in `sample` never fires and `secs + 1` overflows
        do_test(
            r#"{"mode":{"Large":{"max_secs":0,"max_nanos":999999999,"secs":{"low":18446744073709551615,"range":0,"thresh":0}}},"offset":999999999}"#,
        );
        // Large: `offset` is not a valid subsecond nanosecond count
        do_test(
            r#"{"mode":{"Large":{"max_secs":10,"max_nanos":999999999,"secs":{"low":0,"range":11,"thresh":0}}},"offset":4294967295}"#,
        );
        // Large: the seconds sampler covers all of `u64`, not `..=max_secs`
        do_test(
            r#"{"mode":{"Large":{"max_secs":0,"max_nanos":0,"secs":{"low":0,"range":0,"thresh":0}}},"offset":0}"#,
        );
        // Large: the seconds sampler's maximum is not `max_secs`
        do_test(
            r#"{"mode":{"Large":{"max_secs":20,"max_nanos":0,"secs":{"low":0,"range":11,"thresh":0}}},"offset":0}"#,
        );
        // Large: a single-value seconds sampler would reject ~every sample
        do_test(
            r#"{"mode":{"Large":{"max_secs":10,"max_nanos":0,"secs":{"low":10,"range":1,"thresh":0}}},"offset":0}"#,
        );
    }

    #[test]
    #[cfg(feature = "serde")]
    fn test_duration_large_narrow_range_roundtrip() {
        // Valid `Large` sampler whose seconds range holds only two values
        let low = Duration::new(u64::MAX - 1, 0);
        let high = Duration::new(u64::MAX, 0);
        let distr = UniformDuration::new_inclusive(low, high).unwrap();
        assert!(matches!(distr.mode, UniformDurationMode::Large { .. }));
        let json = serde_json::to_string(&distr).unwrap();
        let de_distr: UniformDuration = serde_json::from_str(&json).unwrap();
        assert_eq!(distr, de_distr);
    }

    #[test]
    #[cfg_attr(miri, ignore)] // Miri is too slow
    fn test_durations() {
        let mut rng = crate::test::rng(253);

        let v = &[
            (Duration::new(10, 50000), Duration::new(100, 1234)),
            (Duration::new(0, 100), Duration::new(1, 50)),
            (Duration::new(0, 0), Duration::new(u64::MAX, 999_999_999)),
        ];
        for &(low, high) in v.iter() {
            let my_uniform = Uniform::new(low, high).unwrap();
            for _ in 0..1000 {
                let v = rng.sample(my_uniform);
                assert!(low <= v && v < high);
            }
        }
    }
}