urng 0.10.0

Universal Random Number Generator
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
#[cfg(feature = "simd")]
use std::arch::x86_64::*;

use wrapn::Wrap;

#[cfg(feature = "simd")]
use crate::_internal::FSCALE32;
use crate::{rng::Rng32, rng32::SplitMix32};

/// A SFC32 pseudo-random number generator.
///
/// # Examples
///
/// ```
/// use urng::*;
///
/// let mut rng = Sfc32::new(1);
/// let _ = rng.nextu();
/// ```
///
/// A time-seeded instance can also be created via `Default`:
///
/// ```
/// use urng::*;
///
/// let mut rng = Sfc32::default();
/// let _ = rng.nextu();
/// ```
#[repr(C, align(64))]
pub struct Sfc32 {
    pub a: Wrap<u32>,
    pub b: Wrap<u32>,
    pub c: Wrap<u32>,
    pub counter: Wrap<u32>,
}

impl Sfc32 {
    pub fn new(seed: u32) -> Self {
        let mut seedgen = SplitMix32::new(seed);
        Self {
            a: seedgen.nextu().into(),
            b: seedgen.nextu().into(),
            c: seedgen.nextu().into(),
            counter: 1.into(),
        }
    }
}

impl Rng32 for Sfc32 {
    #[inline(always)]
    fn nextu(&mut self) -> u32 {
        let tmp = self.a + self.b + self.counter;
        self.counter += 1;
        self.a = self.b ^ (self.b >> 9);
        self.b = self.c + (self.c << 3);
        self.c = self.c.rotate_right(11);
        self.c += tmp;
        tmp.value()
    }
}

#[cfg(feature = "simd")]
pub(crate) const SFC32X4: usize = 4;

/// A SFC32 pseudo-random number generator.
///
/// # Examples
///
/// ```
/// use urng::rng32::sfc::Sfc32x4;
///
/// let mut rng = Sfc32x4::new(1);
/// let _ = rng.nextu();
/// ```
#[cfg(feature = "simd")]
#[repr(C, align(64))]
pub struct Sfc32x4 {
    pub(crate) a: __m128i,
    pub(crate) b: __m128i,
    pub(crate) c: __m128i,
    pub(crate) counter: __m128i,
}

#[cfg(feature = "simd")]
impl Sfc32x4 {
    pub fn new(seed: u32) -> Self {
        let mut seedgen = SplitMix32::new(seed);
        let mut a = [0u32; SFC32X4];
        let mut b = [0u32; SFC32X4];
        let mut c = [0u32; SFC32X4];
        for i in 0..SFC32X4 {
            a[i] = seedgen.nextu();
            b[i] = seedgen.nextu();
            c[i] = seedgen.nextu();
        }

        unsafe {
            Self {
                a: _mm_loadu_si128(a.as_ptr() as *const _),
                b: _mm_loadu_si128(b.as_ptr() as *const _),
                c: _mm_loadu_si128(c.as_ptr() as *const _),
                counter: _mm_set1_epi32(1),
            }
        }
    }

    #[inline(always)]
    pub(crate) fn nextuv(&mut self) -> __m128i {
        unsafe {
            let tmp = _mm_add_epi32(_mm_add_epi32(self.a, self.b), self.counter);
            self.counter = _mm_add_epi32(self.counter, _mm_set1_epi32(1));
            self.a = _mm_xor_si128(self.b, _mm_srli_epi32(self.b, 9));
            self.b = _mm_add_epi32(self.c, _mm_slli_epi32(self.c, 3));
            self.c = _mm_add_epi32(
                _mm_or_si128(_mm_slli_epi32(self.c, 21), _mm_srli_epi32(self.c, 11)),
                tmp,
            );
            tmp
        }
    }

    #[inline(always)]
    fn u32x4_to_ps(v: __m128i) -> __m128 {
        unsafe {
            let lo = _mm_and_si128(v, _mm_set1_epi32(0xffff));
            let hi = _mm_srli_epi32(v, 16);
            _mm_add_ps(
                _mm_mul_ps(_mm_cvtepi32_ps(hi), _mm_set1_ps(65536.0)),
                _mm_cvtepi32_ps(lo),
            )
        }
    }

    #[inline(always)]
    pub(crate) fn nextfv(&mut self, scale: __m128) -> __m128 {
        unsafe { _mm_mul_ps(Self::u32x4_to_ps(self.nextuv()), scale) }
    }

    #[inline(always)]
    pub(crate) fn randiv(&mut self, v_range: __m128i, v_min: __m128i) -> __m128i {
        unsafe {
            let uv = self.nextuv();
            let hi = _mm_set1_epi64x((0xffff_ffffu64 << 32) as i64);
            let res_even = _mm_srli_epi64(_mm_mul_epu32(uv, v_range), 32);
            let prod_odd = _mm_and_si128(
                _mm_mul_epu32(_mm_srli_epi64(uv, 32), _mm_srli_epi64(v_range, 32)),
                hi,
            );
            _mm_add_epi32(_mm_or_si128(res_even, prod_odd), v_min)
        }
    }

    #[inline(always)]
    pub(crate) fn randfv(&mut self, v_mult: __m128, v_min: __m128) -> __m128 {
        unsafe { _mm_add_ps(_mm_mul_ps(Self::u32x4_to_ps(self.nextuv()), v_mult), v_min) }
    }

    #[inline(always)]
    pub fn nextu(&mut self) -> [u32; SFC32X4] {
        unsafe { std::mem::transmute(self.nextuv()) }
    }

    #[inline(always)]
    pub fn nextf(&mut self) -> [f32; SFC32X4] {
        self.nextu().map(|x| x as f32 * FSCALE32)
    }
}

#[cfg(feature = "simd")]
pub(crate) const SFC32X8: usize = 8;

/// A SFC32 pseudo-random number generator.
///
/// # Examples
///
/// ```no_run
/// use urng::rng32::sfc::Sfc32x8;
///
/// let mut rng = unsafe { Sfc32x8::new(1) };
/// let _ = rng.nextu();
/// ```
#[cfg(feature = "simd")]
#[repr(C, align(64))]
pub struct Sfc32x8 {
    pub(crate) a: __m256i,
    pub(crate) b: __m256i,
    pub(crate) c: __m256i,
    pub(crate) counter: __m256i,
}

#[cfg(feature = "simd")]
#[allow(dead_code)]
impl Sfc32x8 {
    ///
    /// # Safety
    ///
    /// The caller must ensure the CPU supports the `avx2` target feature.
    #[target_feature(enable = "avx2")]
    pub unsafe fn new(seed: u32) -> Self {
        let mut seedgen = SplitMix32::new(seed);
        let mut a = [0u32; SFC32X8];
        let mut b = [0u32; SFC32X8];
        let mut c = [0u32; SFC32X8];
        for i in 0..SFC32X8 {
            a[i] = seedgen.nextu();
            b[i] = seedgen.nextu();
            c[i] = seedgen.nextu();
        }
        unsafe {
            Self {
                a: _mm256_loadu_si256(a.as_ptr() as *const _),
                b: _mm256_loadu_si256(b.as_ptr() as *const _),
                c: _mm256_loadu_si256(c.as_ptr() as *const _),
                counter: _mm256_set1_epi32(1),
            }
        }
    }

    #[inline]
    #[target_feature(enable = "avx2")]
    pub(crate) unsafe fn nextuv(&mut self) -> __m256i {
        let tmp = _mm256_add_epi32(_mm256_add_epi32(self.a, self.b), self.counter);
        self.counter = _mm256_add_epi32(self.counter, _mm256_set1_epi32(1));
        self.a = _mm256_xor_si256(self.b, _mm256_srli_epi32(self.b, 9));
        self.b = _mm256_add_epi32(self.c, _mm256_slli_epi32(self.c, 3));
        self.c = _mm256_add_epi32(unsafe { _mm256_rol_epi32(self.c, 21) }, tmp);
        tmp
    }

    #[inline]
    #[target_feature(enable = "avx2")]
    pub(crate) unsafe fn nextfv(&mut self, scale: __m256) -> __m256 {
        let v_f32 = _mm256_cvtepi32_ps(unsafe { self.nextuv() });
        _mm256_mul_ps(v_f32, scale)
    }

    #[inline]
    #[target_feature(enable = "avx2")]
    pub(crate) unsafe fn randiv(&mut self, v_range: __m256i, v_min: __m256i) -> __m256i {
        const MERGE_MASK: u8 = 0xAA;
        let v_u32 = unsafe { self.nextuv() };
        let res_even = _mm256_srli_epi64(_mm256_mul_epu32(v_u32, v_range), 32);
        let prod_odd = _mm256_mul_epu32(_mm256_srli_epi64(v_u32, 32), v_range);
        let merged = unsafe { _mm256_mask_blend_epi32(MERGE_MASK, res_even, prod_odd) };
        _mm256_add_epi32(merged, v_min)
    }

    #[inline]
    #[target_feature(enable = "avx2")]
    pub(crate) unsafe fn randfv(&mut self, v_mult: __m256, v_min: __m256) -> __m256 {
        let v_f32 = _mm256_cvtepi32_ps(unsafe { self.nextuv() });
        _mm256_add_ps(_mm256_mul_ps(v_f32, v_mult), v_min)
    }

    #[inline(always)]
    pub fn nextu(&mut self) -> [u32; SFC32X8] {
        unsafe { std::mem::transmute(self.nextuv()) }
    }

    #[inline(always)]
    pub fn nextf(&mut self) -> [f32; SFC32X8] {
        self.nextu().map(|x| x as f32 * FSCALE32)
    }
}

#[cfg(feature = "simd")]
pub(crate) const SFC32X16: usize = 16;

/// A SFC32 pseudo-random number generator.
///
/// # Examples
///
/// ```no_run
/// use urng::rng32::sfc::Sfc32x16;
///
/// let mut rng = unsafe { Sfc32x16::new(1) };
/// let _ = rng.nextu();
/// ```
#[cfg(feature = "simd")]
#[repr(C, align(64))]
pub struct Sfc32x16 {
    pub(crate) a: __m512i,
    pub(crate) b: __m512i,
    pub(crate) c: __m512i,
    pub(crate) counter: __m512i,
}

#[cfg(feature = "simd")]
#[allow(dead_code)]
impl Sfc32x16 {
    ///
    /// # Safety
    ///
    /// The caller must ensure the CPU supports the `avx512f` target feature.
    #[target_feature(enable = "avx512f")]
    pub unsafe fn new(seed: u32) -> Self {
        let mut seedgen = SplitMix32::new(seed);
        let mut a = [0u32; SFC32X16];
        let mut b = [0u32; SFC32X16];
        let mut c = [0u32; SFC32X16];
        for i in 0..SFC32X16 {
            a[i] = seedgen.nextu();
            b[i] = seedgen.nextu();
            c[i] = seedgen.nextu();
        }
        unsafe {
            Self {
                a: _mm512_loadu_si512(a.as_ptr() as *const _),
                b: _mm512_loadu_si512(b.as_ptr() as *const _),
                c: _mm512_loadu_si512(c.as_ptr() as *const _),
                counter: _mm512_set1_epi32(1),
            }
        }
    }

    #[inline]
    #[target_feature(enable = "avx512f")]
    pub(crate) unsafe fn nextuv(&mut self) -> __m512i {
        let tmp = _mm512_add_epi32(_mm512_add_epi32(self.a, self.b), self.counter);
        self.counter = _mm512_add_epi32(self.counter, _mm512_set1_epi32(1));
        self.a = _mm512_xor_si512(self.b, _mm512_srli_epi32(self.b, 9));
        self.b = _mm512_add_epi32(self.c, _mm512_slli_epi32(self.c, 3));
        self.c = _mm512_add_epi32(_mm512_rol_epi32(self.c, 21), tmp);
        tmp
    }

    #[inline]
    #[target_feature(enable = "avx512f")]
    pub(crate) unsafe fn nextfv(&mut self, scale: __m512) -> __m512 {
        let v_u32 = unsafe { self.nextuv() };
        let v_f32 = _mm512_cvtepu32_ps(v_u32);
        _mm512_mul_ps(v_f32, scale)
    }

    #[inline]
    #[target_feature(enable = "avx512f")]
    pub(crate) unsafe fn randiv(&mut self, v_range: __m512i, v_min: __m512i) -> __m512i {
        const MERGE_MASK: u16 = 0xAAAA;
        let v_u32 = unsafe { self.nextuv() };
        let prod_even = _mm512_mul_epu32(v_u32, v_range);
        let res_even = _mm512_srli_epi64(prod_even, 32);
        let v_u32_shifted = _mm512_srli_epi64(v_u32, 32);
        let prod_odd = _mm512_mul_epu32(v_u32_shifted, v_range);
        let merged = _mm512_mask_blend_epi32(MERGE_MASK, res_even, prod_odd);
        _mm512_add_epi32(merged, v_min)
    }

    #[inline]
    #[target_feature(enable = "avx512f")]
    pub(crate) unsafe fn randfv(&mut self, v_mult: __m512, v_min: __m512) -> __m512 {
        let v_u32 = unsafe { self.nextuv() };
        let v_f32 = _mm512_cvtepu32_ps(v_u32);
        _mm512_add_ps(_mm512_mul_ps(v_f32, v_mult), v_min)
    }

    #[inline(always)]
    pub fn nextu(&mut self) -> [u32; SFC32X16] {
        unsafe { std::mem::transmute(self.nextuv()) }
    }

    pub fn nextf(&mut self) -> [f32; SFC32X16] {
        self.nextu().map(|x| x as f32 * FSCALE32)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::safe_test;
    #[cfg(any(target_feature = "avx2", target_feature = "avx512f"))]
    use crate::unsafe_test;

    safe_test!(Sfc32);
    #[cfg(feature = "simd")]
    safe_test!(Sfc32x4);
    #[cfg(all(feature = "simd", target_feature = "avx2"))]
    unsafe_test!(Sfc32x8);
    #[cfg(all(feature = "simd", target_feature = "avx512f"))]
    unsafe_test!(Sfc32x16);

    #[cfg(feature = "simd")]
    fn scalar_lanes(seed: u32) -> [Sfc32; SFC32X4] {
        let mut seedgen = SplitMix32::new(seed);
        std::array::from_fn(|_| Sfc32 {
            a: seedgen.nextu().into(),
            b: seedgen.nextu().into(),
            c: seedgen.nextu().into(),
            counter: 1.into(),
        })
    }

    #[cfg(feature = "simd")]
    #[test]
    fn sfc32x4_lanes_match_scalar() {
        let mut vector = Sfc32x4::new(0);
        let mut scalars = scalar_lanes(0);

        for _ in 0..8 {
            let got = vector.nextu();
            let want: [u32; SFC32X4] = std::array::from_fn(|i| scalars[i].nextu());
            assert_eq!(got, want);
        }
    }

    #[cfg(feature = "simd")]
    #[test]
    fn sfc32x4_randiv_randfv_match_scalar() {
        let (min_i, max_i) = (-5i32, 7i32);
        let (min_f, max_f) = (-2.0f32, 3.0f32);
        let v_range = unsafe { _mm_set1_epi32((max_i as i64 - min_i as i64 + 1) as u32 as i32) };
        let v_min = unsafe { _mm_set1_epi32(min_i) };
        let v_mult = unsafe { _mm_set1_ps((max_f - min_f) * FSCALE32) };
        let v_minf = unsafe { _mm_set1_ps(min_f) };
        let scale = unsafe { _mm_set1_ps(FSCALE32) };

        let mut vector = Sfc32x4::new(1);
        let mut scalars = scalar_lanes(1);
        for _ in 0..8 {
            let got: [i32; SFC32X4] = unsafe { std::mem::transmute(vector.randiv(v_range, v_min)) };
            let want: [i32; SFC32X4] = std::array::from_fn(|i| scalars[i].randi(min_i, max_i));
            assert_eq!(got, want);
        }

        let mut vector = Sfc32x4::new(2);
        let mut scalars = scalar_lanes(2);
        for _ in 0..8 {
            let got: [f32; SFC32X4] = unsafe { std::mem::transmute(vector.randfv(v_mult, v_minf)) };
            let want: [f32; SFC32X4] = std::array::from_fn(|i| scalars[i].randf(min_f, max_f));
            assert_eq!(got, want);
        }

        let mut vector = Sfc32x4::new(3);
        let mut scalars = scalar_lanes(3);
        for _ in 0..8 {
            let got: [f32; SFC32X4] = unsafe { std::mem::transmute(vector.nextfv(scale)) };
            let want: [f32; SFC32X4] = std::array::from_fn(|i| scalars[i].nextf());
            assert_eq!(got, want);
        }
    }
}