devela/num/rand/xorshift/u128.rs
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
// devela::num::rand::xorshift::u128
//
//! 128-bit versions of XorShift generators.
//
#[cfg(any(feature = "join", feature = "split"))]
use crate::Cast;
use crate::{ConstDefault, Own};
/// The `XorShift128` pseudo-random number generator.
///
/// It has a 128-bit state and generates 64-bit numbers.
#[must_use]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct XorShift128([u32; 4]);
impl Default for XorShift128 {
fn default() -> Self {
Self::DEFAULT
}
}
impl ConstDefault for XorShift128 {
const DEFAULT: Self = Self::new_unchecked(Self::DEFAULT_SEED);
}
// private associated items
impl XorShift128 {
const DEFAULT_SEED: [u32; 4] = [0xDEFA_0017; 4];
#[cold] #[rustfmt::skip]
const fn cold_path_result() -> Option<Self> { None }
#[cold] #[allow(dead_code)] #[rustfmt::skip]
const fn cold_path_default() -> Self { Self::new_unchecked(Self::DEFAULT_SEED) }
}
impl XorShift128 {
/// Returns a seeded `XorShift128` generator from the given 4 × 32-bit seeds.
///
/// Returns `None` if all given seeds are `0`.
#[must_use]
pub const fn new(seeds: [u32; 4]) -> Option<Self> {
if (seeds[0] | seeds[1] | seeds[2] | seeds[3]) == 0 {
Self::cold_path_result()
} else {
Some(Self([seeds[0], seeds[1], seeds[2], seeds[3]]))
}
}
/// Returns a seeded `XorShift128` generator from the given 8-bit seed,
/// unchecked.
///
/// The seeds must not be all `0`, otherwise every result will also be `0`.
///
/// # Panics
/// Panics in debug if the seeds are all `0`.
pub const fn new_unchecked(seeds: [u32; 4]) -> Self {
debug_assert![(seeds[0] | seeds[1] | seeds[2] | seeds[3]) != 0, "Seeds must be non-zero"];
Self(seeds)
}
/// Returns the current random `u64`.
#[must_use]
pub const fn current_u64(&self) -> u64 {
((self.0[0] as u64) << 32) | (self.0[1] as u64)
}
/// Returns the next random `u64`.
// Note how the output of the RNG is computed before updating the state,
// unlike on Xoroshiro128pp, for example.
#[must_use]
pub fn next_u64(&mut self) -> u64 {
let t = self.0[3];
let mut s = self.0[0];
self.0[3] = self.0[2];
self.0[2] = self.0[1];
self.0[1] = s;
s ^= s << 11;
s ^= s >> 8;
self.0[0] = s ^ t ^ (t >> 19);
((self.0[0] as u64) << 32) | (self.0[1] as u64)
}
/// Returns a copy of the next new random state.
pub const fn next_state(&self) -> Self {
let mut x = self.0;
let t = x[3];
let mut s = x[0];
x[3] = x[2];
x[2] = x[1];
x[1] = s;
s ^= s << 11;
s ^= s >> 8;
x[0] = s ^ t ^ (t >> 19);
Self(x)
}
/// Returns both the next random state and the `u64` value.
pub const fn own_next_u64(self) -> Own<Self, u64> {
let s = self.next_state();
let v = s.current_u64();
Own::new(s, v)
}
}
/// # Extra constructors
impl XorShift128 {
/// Returns a seeded `XorShift128` generator from the given 128-bit seed.
///
/// The seeds will be split in little endian order.
#[cfg(feature = "split")]
#[cfg_attr(feature = "nightly_doc", doc(cfg(feature = "split")))]
pub const fn new1_u128(seed: u128) -> Option<Self> {
Self::new(Cast(seed).into_u32_le())
}
/// Returns a seeded `XorShift128` generator from the given 2 × 64-bit seeds.
///
/// The seeds will be split in little endian order.
#[cfg(feature = "split")]
#[cfg_attr(feature = "nightly_doc", doc(cfg(feature = "split")))]
pub const fn new2_u64(seeds: [u64; 2]) -> Option<Self> {
let [x, y] = Cast(seeds[0]).into_u32_le();
let [z, a] = Cast(seeds[1]).into_u32_le();
Self::new([x, y, z, a])
}
/// Returns a seeded `XorShift128` generator from the given 4 × 32-bit seeds.
///
/// This is an alias of [`new`][Self#method.new].
pub const fn new4_u32(seeds: [u32; 4]) -> Option<Self> {
Self::new(seeds)
}
/// Returns a seeded `XorShift128` generator from the given 8 × 16-bit seeds.
///
/// The seeds will be joined in little endian order.
#[cfg(feature = "join")]
#[cfg_attr(feature = "nightly_doc", doc(cfg(feature = "join")))]
pub const fn new8_u16(seeds: [u16; 8]) -> Option<Self> {
Self::new([
Cast::<u32>::from_u16_le([seeds[0], seeds[1]]),
Cast::<u32>::from_u16_le([seeds[2], seeds[3]]),
Cast::<u32>::from_u16_le([seeds[4], seeds[5]]),
Cast::<u32>::from_u16_le([seeds[6], seeds[7]]),
])
}
/// Returns a seeded `XorShift128` generator from the given 16 × 8-bit seeds.
///
/// The seeds will be joined in little endian order.
pub const fn new16_u8(seeds: [u8; 16]) -> Option<Self> {
Self::new([
u32::from_le_bytes([seeds[0], seeds[1], seeds[2], seeds[3]]),
u32::from_le_bytes([seeds[4], seeds[5], seeds[6], seeds[7]]),
u32::from_le_bytes([seeds[8], seeds[9], seeds[10], seeds[11]]),
u32::from_le_bytes([seeds[12], seeds[13], seeds[14], seeds[15]]),
])
}
}
/// The `XorShift128+` pseudo-random number generator.
///
/// It has a 128-bit state and generates 64-bit numbers.
///
/// It is generally considered to have better statistical properties than
/// [`XorShift128`].
#[must_use]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct XorShift128p([u64; 2]);
impl Default for XorShift128p {
fn default() -> Self {
Self::DEFAULT
}
}
impl ConstDefault for XorShift128p {
const DEFAULT: Self = Self::new_unchecked(Self::DEFAULT_SEED);
}
// private associated items
impl XorShift128p {
const DEFAULT_SEED: [u64; 2] = [0xDEFA_0017_DEFA_0017; 2];
#[cold] #[rustfmt::skip]
const fn cold_path_result() -> Option<Self> { None }
#[cold] #[allow(dead_code)] #[rustfmt::skip]
const fn cold_path_default() -> Self { Self::new_unchecked(Self::DEFAULT_SEED) }
}
impl XorShift128p {
/// Returns a seeded `XorShift128+` generator from the given 2 × 64-bit seeds.
///
/// Returns `None` if all given seeds are `0`.
#[must_use]
pub const fn new(seeds: [u64; 2]) -> Option<Self> {
if (seeds[0] | seeds[1]) == 0 {
Self::cold_path_result()
} else {
Some(Self(seeds))
}
}
/// Returns a seeded `XorShift128p` generator from the given 8-bit seed,
/// unchecked.
///
/// The seeds must not be all `0`, otherwise every result will also be `0`.
///
/// # Panics
/// Panics in debug if the seeds are all `0`.
pub const fn new_unchecked(seeds: [u64; 2]) -> Self {
debug_assert![(seeds[0] | seeds[1]) != 0, "Seeds must be non-zero"];
Self(seeds)
}
/// Returns the current random `u64`.
#[must_use]
pub const fn current_u64(&self) -> u64 {
self.0[0].wrapping_add(self.0[1])
}
/// Returns the next random `u64`.
#[must_use]
pub fn next_u64(&mut self) -> u64 {
let [s0, mut s1] = [self.0[0], self.0[1]];
let result = s0.wrapping_add(s1);
s1 ^= s0;
self.0[0] = s0.rotate_left(55) ^ s1 ^ (s1 << 14); // a, b
self.0[1] = s1.rotate_left(36); // c
result
}
/// Returns a copy of the next new random state.
pub const fn next_state(&self) -> Self {
let mut x = self.0;
let [s0, mut s1] = [x[0], x[1]];
s1 ^= s0;
x[0] = s0.rotate_left(55) ^ s1 ^ (s1 << 14); // a, b
x[1] = s1.rotate_left(36); // c
Self(x)
}
/// Returns both the next random state and the `u64` value.
pub const fn own_next_u64(self) -> Own<Self, u64> {
let s = self.next_state();
let v = s.current_u64();
Own::new(s, v)
}
}
/// # Extra constructors
impl XorShift128p {
/// Returns a seeded `XorShift128+` generator from the given 128-bit seed.
///
/// The seeds will be split in little endian order.
#[cfg(feature = "split")]
#[cfg_attr(feature = "nightly_doc", doc(cfg(feature = "split")))]
pub const fn new1_u128(seed: u128) -> Option<Self> {
Self::new(Cast(seed).into_u64_le())
}
/// Returns a seeded `XorShift128+` generator from the given 2 × 64-bit seeds.
///
/// This is an alias of [`new`][Self#method.new].
pub const fn new2_u64(seeds: [u64; 2]) -> Option<Self> {
Self::new(seeds)
}
/// Returns a seeded `XorShift128+` generator from the given 4 × 32-bit seeds.
///
/// The seeds will be joined in little endian order.
#[cfg(feature = "join")]
#[cfg_attr(feature = "nightly_doc", doc(cfg(feature = "join")))]
pub const fn new4_u32(seeds: [u32; 4]) -> Option<Self> {
Self::new([
Cast::<u64>::from_u32_le([seeds[0], seeds[1]]),
Cast::<u64>::from_u32_le([seeds[2], seeds[3]]),
])
}
/// Returns a seeded `XorShift128+` generator from the given 8 × 16-bit seeds.
///
/// The seeds will be joined in little endian order.
#[cfg(feature = "join")]
#[cfg_attr(feature = "nightly_doc", doc(cfg(feature = "join")))]
pub const fn new8_u16(seeds: [u16; 8]) -> Option<Self> {
Self::new([
Cast::<u64>::from_u16_le([seeds[0], seeds[1], seeds[2], seeds[3]]),
Cast::<u64>::from_u16_le([seeds[4], seeds[5], seeds[6], seeds[7]]),
])
}
/// Returns a seeded `XorShift128` generator from the given 4 × 8-bit seeds.
///
/// The seeds will be joined in little endian order.
pub const fn new16_u8(seeds: [u8; 16]) -> Option<Self> {
let s = seeds;
Self::new([
u64::from_le_bytes([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]]),
u64::from_le_bytes([s[8], s[9], s[10], s[11], s[12], s[13], s[14], s[15]]),
])
}
}
#[cfg(feature = "dep_rand_core")]
#[cfg_attr(feature = "nightly_doc", doc(cfg(feature = "dep_rand_core")))]
mod impl_rand {
use super::{XorShift128, XorShift128p};
use crate::_dep::rand_core::{Error, RngCore, SeedableRng};
impl RngCore for XorShift128 {
/// Returns the next random `u32`,
/// from the first 32-bits of `next_u64`.
fn next_u32(&mut self) -> u32 {
(self.next_u64() & 0xFFFF_FFFF) as u32
}
/// Returns the next random `u64`.
fn next_u64(&mut self) -> u64 {
self.next_u64()
}
fn fill_bytes(&mut self, dest: &mut [u8]) {
let mut i = 0;
while i < dest.len() {
let random_u64 = self.next_u64();
let bytes = random_u64.to_le_bytes();
let remaining = dest.len() - i;
if remaining >= 8 {
dest[i..i + 8].copy_from_slice(&bytes);
i += 8;
} else {
dest[i..].copy_from_slice(&bytes[..remaining]);
break;
}
}
}
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
self.fill_bytes(dest);
Ok(())
}
}
impl SeedableRng for XorShift128 {
type Seed = [u8; 16];
/// When seeded with zero this implementation uses the default seed
/// value as the cold path.
fn from_seed(seed: Self::Seed) -> Self {
let mut seed_u32s = [0u32; 4];
if seed == [0; 16] {
Self::cold_path_default()
} else {
for i in 0..4 {
seed_u32s[i] = u32::from_le_bytes([
seed[i * 4],
seed[i * 4 + 1],
seed[i * 4 + 2],
seed[i * 4 + 3],
]);
}
Self::new_unchecked(seed_u32s)
}
}
}
impl RngCore for XorShift128p {
/// Returns the next random `u32`,
/// from the first 32-bits of `next_u64`.
fn next_u32(&mut self) -> u32 {
(self.next_u64() & 0xFFFF_FFFF) as u32
}
/// Returns the next random `u64`.
fn next_u64(&mut self) -> u64 {
self.next_u64()
}
fn fill_bytes(&mut self, dest: &mut [u8]) {
let mut i = 0;
while i < dest.len() {
let random_u64 = self.next_u64();
let bytes = random_u64.to_le_bytes();
let remaining = dest.len() - i;
if remaining >= 8 {
dest[i..i + 8].copy_from_slice(&bytes);
i += 8;
} else {
dest[i..].copy_from_slice(&bytes[..remaining]);
break;
}
}
}
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
self.fill_bytes(dest);
Ok(())
}
}
impl SeedableRng for XorShift128p {
type Seed = [u8; 16];
/// When seeded with zero this implementation uses the default seed
/// value as the cold path.
fn from_seed(seed: Self::Seed) -> Self {
let mut seed_u64s = [0u64; 2];
if seed == [0; 16] {
Self::cold_path_default()
} else {
for i in 0..2 {
seed_u64s[i] = u64::from_le_bytes([
seed[i * 8],
seed[i * 8 + 1],
seed[i * 8 + 2],
seed[i * 8 + 3],
seed[i * 8 + 4],
seed[i * 8 + 5],
seed[i * 8 + 6],
seed[i * 8 + 7],
]);
}
Self::new_unchecked(seed_u64s)
}
}
}
}