Skip to main content

rand_xorshift/
lib.rs

1// Copyright 2018-2023 Developers of the Rand project.
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9//! The xorshift random number generator.
10//!
11//! # Example
12//!
13//! To initialize a generator, use the [`SeedableRng`] trait:
14//!
15//! ```
16//! use rand_core::{SeedableRng, Rng};
17//! use rand_xorshift::XorShiftRng;
18//!
19//! let mut rng = XorShiftRng::seed_from_u64(0);
20//! let x = rng.next_u32();
21//! ```
22
23#![doc(
24    html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
25    html_favicon_url = "https://www.rust-lang.org/favicon.ico"
26)]
27#![forbid(unsafe_code)]
28#![deny(missing_docs)]
29#![deny(missing_debug_implementations)]
30#![no_std]
31
32use core::num::Wrapping as w;
33use core::{convert::Infallible, fmt};
34use rand_core::{Rng, SeedableRng, TryRng, utils};
35#[cfg(feature = "serde")]
36use serde::{Deserialize, Serialize};
37
38/// An Xorshift random number generator.
39///
40/// The Xorshift[^1] algorithm is not suitable for cryptographic purposes
41/// but is very fast. If you do not know for sure that it fits your
42/// requirements, use a more secure one such as `StdRng` or `OsRng`.
43///
44/// When seeded with zero (i.e. `XorShiftRng::from_seed(0)` is called), this implementation
45/// actually uses `0xBAD_5EED_0BAD_5EED_0BAD_5EED_0BAD_5EED` for the seed. This arbitrary value is
46/// used because the underlying algorithm can't escape from an all-zero state, and the function is
47/// infallible so it can't signal this by returning an error.
48///
49/// [^1]: Marsaglia, George (July 2003).
50///       ["Xorshift RNGs"](https://www.jstatsoft.org/v08/i14/paper).
51///       *Journal of Statistical Software*. Vol. 8 (Issue 14).
52#[derive(Clone, PartialEq, Eq)]
53#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
54pub struct XorShiftRng {
55    x: w<u32>,
56    y: w<u32>,
57    z: w<u32>,
58    w: w<u32>,
59}
60
61// Custom Debug implementation that does not expose the internal state
62impl fmt::Debug for XorShiftRng {
63    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
64        write!(f, "XorShiftRng {{}}")
65    }
66}
67
68impl TryRng for XorShiftRng {
69    type Error = Infallible;
70    #[inline]
71    fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
72        // These shifts are taken from the example in the Summary section of
73        // the paper 'Xorshift RNGs'. (On the bottom of page 5.)
74        let x = self.x;
75        let t = x ^ (x << 11);
76        self.x = self.y;
77        self.y = self.z;
78        self.z = self.w;
79        let w_ = self.w;
80        self.w = w_ ^ (w_ >> 19) ^ (t ^ (t >> 8));
81        Ok(self.w.0)
82    }
83
84    #[inline]
85    fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
86        utils::next_u64_via_u32(self)
87    }
88
89    #[inline]
90    fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Self::Error> {
91        utils::fill_bytes_via_next_word(dest, || self.try_next_u32())
92    }
93}
94
95impl SeedableRng for XorShiftRng {
96    type Seed = [u8; 16];
97
98    fn from_seed(seed: Self::Seed) -> Self {
99        let mut seed_u32: [u32; 4] = utils::read_words(&seed);
100
101        // Xorshift cannot be seeded with 0 and we cannot return an Error, but
102        // also do not wish to panic (because a random seed can legitimately be
103        // 0); our only option is therefore to use a preset value.
104        if seed_u32 == [0; 4] {
105            seed_u32 = [0xBAD_5EED, 0xBAD_5EED, 0xBAD_5EED, 0xBAD_5EED];
106        }
107
108        XorShiftRng {
109            x: w(seed_u32[0]),
110            y: w(seed_u32[1]),
111            z: w(seed_u32[2]),
112            w: w(seed_u32[3]),
113        }
114    }
115
116    fn from_rng<R>(rng: &mut R) -> Self
117    where
118        R: Rng + ?Sized,
119    {
120        let mut b = [0u8; 16];
121        loop {
122            rng.fill_bytes(b.as_mut());
123            if b != [0; 16] {
124                break;
125            }
126        }
127
128        XorShiftRng {
129            x: w(u32::from_le_bytes([b[0], b[1], b[2], b[3]])),
130            y: w(u32::from_le_bytes([b[4], b[5], b[6], b[7]])),
131            z: w(u32::from_le_bytes([b[8], b[9], b[10], b[11]])),
132            w: w(u32::from_le_bytes([b[12], b[13], b[14], b[15]])),
133        }
134    }
135
136    fn try_from_rng<R>(rng: &mut R) -> Result<Self, R::Error>
137    where
138        R: TryRng + ?Sized,
139    {
140        let mut b = [0u8; 16];
141        loop {
142            rng.try_fill_bytes(b.as_mut())?;
143            if b != [0; 16] {
144                break;
145            }
146        }
147
148        Ok(XorShiftRng {
149            x: w(u32::from_le_bytes([b[0], b[1], b[2], b[3]])),
150            y: w(u32::from_le_bytes([b[4], b[5], b[6], b[7]])),
151            z: w(u32::from_le_bytes([b[8], b[9], b[10], b[11]])),
152            w: w(u32::from_le_bytes([b[12], b[13], b[14], b[15]])),
153        })
154    }
155}