File: xorshift.rs

package info (click to toggle)
rust-interprocess 2.2.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,016 kB
  • sloc: makefile: 2
file content (30 lines) | stat: -rw-r--r-- 891 bytes parent folder | download
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
use std::{
    collections::hash_map::DefaultHasher,
    hash::{Hash, Hasher},
};

/// The 32-bit variant of the Xorshift PRNG algorithm.
///
/// Didn't feel like pulling in the `rand` crate, so have this here beauty instead.
#[repr(transparent)]
#[derive(Copy, Clone, Debug)]
pub struct Xorshift32(pub u32);
impl Xorshift32 {
    pub fn from_id(id: &str) -> Self {
        let mut hasher = DefaultHasher::new();
        id.hash(&mut hasher);
        let hash64 = hasher.finish();
        let hash32 = ((hash64 & 0xFFFF_FFFF_0000_0000) >> 32) ^ (hash64 & 0xFFFF_FFFF);
        Self(hash32.try_into().unwrap())
    }
    pub fn next(&mut self) -> u32 {
        self.0 ^= self.0 << 13;
        self.0 ^= self.0 >> 17;
        self.0 ^= self.0 << 5;
        self.0
    }
}
impl Iterator for Xorshift32 {
    type Item = u32;
    fn next(&mut self) -> Option<Self::Item> { Some(self.next()) }
}