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
#![cfg_attr(not(feature="std"), no_std)]

//! A simple and super slim random crate, gifted from the sun God!
//!
//! If you need decent random numbers pretty speedily, and hate
//! to wait for compile-times, this is the crate for you!
//! No dependencies, no worries!
//!
//! A basic usage would look like this:
//! ```
//! use sungod::Ra;
//! fn main() {
//!     let mut ra = Ra::default();
//!     assert_ne!(ra.sample::<u64>(), ra.sample::<u64>());
//! }
//! ```
//!
//! This is an implementation of xorwow, in a nice slim package,
//! with some extra type safety. If you want to support randomizing
//! more exotic types, you'll have to implement it yourself. No
//! fancy traits or anything in this crate.
//!
//!
//! NOTE: This create is not at all suitable for cryptographic use.


/// The struct that holds all the random state. Can be instanced
/// as many times as you want!
#[derive(Copy, Clone, Debug)]
pub struct Ra {
    state: [u64; 4],
    counter: u64,
}

/// The sexiest of seeds.
pub const DEFAULT_RANDOM_SEED: u64 = 0xCAFEBABEDEADBEEF;

#[cfg(feature="std")]
static mut RA: Ra = Ra {
    state: [0, 0, 0, 0],
    counter: 0,
};

impl Default for Ra {
    fn default() -> Self {
        Self::new_with(DEFAULT_RANDOM_SEED)
    }
}

/// How to make a random of whatever from
/// random [u64]s.
pub trait Sample {
    fn sample(ra: &mut Ra) -> Self;
}

impl Ra {
    /// Initalizes with the time since UNIX_EPOCH.
    #[cfg(feature="std")]
    pub fn new_random() -> Self {
        use std::time::{SystemTime, UNIX_EPOCH};
        Self::new_with(SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap().as_nanos() as u64)
    }

    /// This function is kinda "unsafe", race conditions
    /// might corrupt the random state. I'd personally write
    /// this off as a "feature" since it's just more noise!
    ///
    /// It might be annoying if you're trying to reproduce bugs
    /// tough, so beware.
    #[cfg(feature="std")]
    pub fn global<'t>() -> &'t mut Ra {
        if unsafe { RA.state[0] == 0 && RA.state[1] == 0 } {
            unsafe { RA = Ra::default(); }
        }
        unsafe { &mut RA }
    }

    pub fn new_with(seed: u64) -> Self {
        let mut inst = Self {
            state: [0, 0, 0, 0],
            counter: 0,
        };
        inst.seed(seed);
        inst
    }

    pub fn seed(&mut self, seed: u64) {
        *self = Self {
            state: [0x70A7A712EAF07AA2 ^ seed,
                    0xE96A320D4BC6BDDB ^ seed,
                    0xBC78C1658C9333BF ^ seed,
                    0xBE5B64076E942A9E ^ seed],
            counter: 100,
        };
    }

    /// The random source, spits out random [u64]s
    pub fn xorwow(&mut self) -> u64 {
        let mut t = self.state[3];
        let s = self.state[0];
        self.state[3] = self.state[2];
        self.state[2] = self.state[1];
        self.state[1] = s;

        t ^= t >> 2;
        t ^= t << 2;
        t ^= s ^ (s << 4);
        self.state[0] = t;

        self.counter = self.counter.wrapping_add(362437);
        return t.wrapping_add(self.counter);
    }

    #[allow(dead_code)]
    /// Spits out a random of whatever.
    pub fn sample<T: Sample>(&mut self) -> T {
        T::sample(self)
    }

    /// Spits out a random of whatever.
    /// Same as sample, but makes it easier to port from Rand.
    pub fn gen<T: Sample>(&mut self) -> T {
        self.sample::<T>()
    }
}

// Boring boilerplate bellow here!

macro_rules! impl_sample {
    ( $ty:tt ) => {
        impl Sample for $ty {
            fn sample(ra: &mut Ra) -> Self {
                ra.xorwow() as Self
            }
        }
    };

    ( large $ty:tt ) => {
        impl Sample for $ty {
            fn sample(ra: &mut Ra) -> Self {
                ((ra.xorwow() as u128) << 64 | (ra.xorwow() as u128)) as Self
            }
        }
    };

    ( float $ty:tt ) => {
        impl Sample for $ty {
            fn sample(ra: &mut Ra) -> Self {
                (ra.xorwow() as Self) / (u64::MAX as Self)
            }
        }
    };
}

impl Sample for bool {
    fn sample(ra: &mut Ra) -> Self {
        ra.xorwow() & 0b100000 == 0
    }
}

impl_sample!(u8);
impl_sample!(i8);
impl_sample!(u16);
impl_sample!(i16);
impl_sample!(u32);
impl_sample!(i32);
impl_sample!(u64);
impl_sample!(i64);
impl_sample!(usize);
impl_sample!(isize);
impl_sample!(large u128);
impl_sample!(large i128);
impl_sample!(float f32);
impl_sample!(float f64);

#[cfg(test)]
mod tests {

    use crate::Ra;

    #[cfg(std)]
    fn new() -> Ra {
        Ra::new_random()
    }
    #[cfg(not(std))]
    fn new() -> Ra {
        Ra::default()
    }

    #[test]
    fn something_random() {
        let mut ra = new();
        assert_ne!(ra.sample::<u64>(), ra.sample::<u64>());
    }

    #[test]
    fn negative_random() {
        let mut ra = new();
        for _ in 0..10 {
            if ra.sample::<i64>() < 0 {
                return;
            }
        }
        assert!(false);
    }

    #[test]
    fn valid_float_range() {
        let mut ra = new();
        for _ in 0..1000000 {
            let sample = ra.sample::<f64>();
            assert!(sample >= 0.0);
            assert!(sample < 1.0);
        }
    }

    #[test]
    #[should_panic]
    fn edge_coverage() {
        let mut ra = new();
        let mut count = 0;
        const NUM_SAMPLES: u32 = 1000000;
        for _ in 0..NUM_SAMPLES {
            let sample = ra.sample::<f64>();
            if sample < 0.05 || 0.95 < sample {
                count += 1;
            }
        }
        assert!(count > NUM_SAMPLES / 100 / 2);
        assert!(count < 2 * NUM_SAMPLES / 100);
    }

    #[test]
    #[should_panic]
    fn split() {
        let mut ra = new();
        let mut count = 0;
        const NUM_SAMPLES: u32 = 1000000;
        for _ in 0..NUM_SAMPLES {
            if ra.sample::<f64>() <= 0.5 {
                count += 1;
            }
        }
        assert!(count < NUM_SAMPLES / 4);
        assert!(count < 3 * NUM_SAMPLES / 4);
    }


    #[test]
    fn random_enough() {
        let mut ra = new();
        let mut histogram = [0_u64; u8::MAX as usize + 1];
        const NUM_SAMPLES: u32 = 1000000;
        for _ in 0..NUM_SAMPLES {
            histogram[ra.sample::<u8>() as usize] += 1;
        }

        /// mu  = n * p
        /// var = n * p * (1 - p)
        /// 5sd is a lot, of variation, but it's good enough.
        const SAMPLES: f64 = NUM_SAMPLES as f64;
        const MEAN: f64 = SAMPLES / 256.0;
        const VAR: f64 = MEAN * (1.0 - 1.0 / 256.0);
        for v in &histogram {
            assert!(*v > (MEAN - VAR.sqrt() * 5.0) as u64);
        }
    }
}