1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! The ISAAC random number generator.
15 use core::iter::{range_step, repeat};
17 use {Rng, SeedableRng, Rand};
19 const RAND_SIZE_LEN: u32 = 8;
20 const RAND_SIZE: u32 = 1 << (RAND_SIZE_LEN as uint);
21 const RAND_SIZE_UINT: uint = 1 << (RAND_SIZE_LEN as uint);
23 /// A random number generator that uses the ISAAC algorithm[1].
25 /// The ISAAC algorithm is generally accepted as suitable for
26 /// cryptographic purposes, but this implementation has not be
27 /// verified as such. Prefer a generator like `OsRng` that defers to
28 /// the operating system for cases that need high security.
30 /// [1]: Bob Jenkins, [*ISAAC: A fast cryptographic random number
31 /// generator*](http://www.burtleburtle.net/bob/rand/isaacafa.html)
35 rsl: [u32; RAND_SIZE_UINT],
36 mem: [u32; RAND_SIZE_UINT],
42 static EMPTY: IsaacRng = IsaacRng {
44 rsl: [0; RAND_SIZE_UINT],
45 mem: [0; RAND_SIZE_UINT],
51 /// Create an ISAAC random number generator using the default
53 pub fn new_unseeded() -> IsaacRng {
59 /// Initialises `self`. If `use_rsl` is true, then use the current value
60 /// of `rsl` as a seed, otherwise construct one algorithmically (not
62 fn init(&mut self, use_rsl: bool) {
63 let mut a = 0x9e3779b9;
85 for _ in range(0u, 4) {
90 macro_rules! memloop (
92 for i in range_step(0, RAND_SIZE as uint, 8) {
93 a+=$arr[i ]; b+=$arr[i+1];
94 c+=$arr[i+2]; d+=$arr[i+3];
95 e+=$arr[i+4]; f+=$arr[i+5];
96 g+=$arr[i+6]; h+=$arr[i+7];
98 self.mem[i ]=a; self.mem[i+1]=b;
99 self.mem[i+2]=c; self.mem[i+3]=d;
100 self.mem[i+4]=e; self.mem[i+5]=f;
101 self.mem[i+6]=g; self.mem[i+7]=h;
109 for i in range_step(0, RAND_SIZE as uint, 8) {
111 self.mem[i ]=a; self.mem[i+1]=b;
112 self.mem[i+2]=c; self.mem[i+3]=d;
113 self.mem[i+4]=e; self.mem[i+5]=f;
114 self.mem[i+6]=g; self.mem[i+7]=h;
121 /// Refills the output buffer (`self.rsl`)
123 #[allow(unsigned_negation)]
124 fn isaac(&mut self) {
128 let mut b = self.b + self.c;
130 static MIDPOINT: uint = (RAND_SIZE / 2) as uint;
132 macro_rules! ind (($x:expr) => {
133 self.mem[(($x >> 2) as uint & ((RAND_SIZE - 1) as uint))]
136 let r = [(0, MIDPOINT), (MIDPOINT, 0)];
137 for &(mr_offset, m2_offset) in r.iter() {
139 macro_rules! rngstepp(
140 ($j:expr, $shift:expr) => {{
142 let mix = a << $shift as uint;
144 let x = self.mem[base + mr_offset];
145 a = (a ^ mix) + self.mem[base + m2_offset];
146 let y = ind!(x) + a + b;
147 self.mem[base + mr_offset] = y;
149 b = ind!(y >> RAND_SIZE_LEN as uint) + x;
150 self.rsl[base + mr_offset] = b;
153 macro_rules! rngstepn(
154 ($j:expr, $shift:expr) => {{
156 let mix = a >> $shift as uint;
158 let x = self.mem[base + mr_offset];
159 a = (a ^ mix) + self.mem[base + m2_offset];
160 let y = ind!(x) + a + b;
161 self.mem[base + mr_offset] = y;
163 b = ind!(y >> RAND_SIZE_LEN as uint) + x;
164 self.rsl[base + mr_offset] = b;
168 for i in range_step(0u, MIDPOINT, 4) {
169 rngstepp!(i + 0, 13);
172 rngstepn!(i + 3, 16);
178 self.cnt = RAND_SIZE;
182 impl Rng for IsaacRng {
184 fn next_u32(&mut self) -> u32 {
186 // make some more numbers
191 // self.cnt is at most RAND_SIZE, but that is before the
192 // subtraction above. We want to index without bounds
193 // checking, but this could lead to incorrect code if someone
194 // misrefactors, so we check, sometimes.
196 // (Changes here should be reflected in Isaac64Rng.next_u64.)
197 debug_assert!(self.cnt < RAND_SIZE);
199 // (the % is cheaply telling the optimiser that we're always
200 // in bounds, without unsafe. NB. this is a power of two, so
201 // it optimises to a bitwise mask).
202 self.rsl[(self.cnt % RAND_SIZE) as uint]
206 impl<'a> SeedableRng<&'a [u32]> for IsaacRng {
207 fn reseed(&mut self, seed: &'a [u32]) {
208 // make the seed into [seed[0], seed[1], ..., seed[seed.len()
209 // - 1], 0, 0, ...], to fill rng.rsl.
210 let seed_iter = seed.iter().map(|&x| x).chain(repeat(0u32));
212 for (rsl_elem, seed_elem) in self.rsl.iter_mut().zip(seed_iter) {
213 *rsl_elem = seed_elem;
223 /// Create an ISAAC random number generator with a seed. This can
224 /// be any length, although the maximum number of elements used is
225 /// 256 and any more will be silently ignored. A generator
226 /// constructed with a given seed will generate the same sequence
227 /// of values as all other generators constructed with that seed.
228 fn from_seed(seed: &'a [u32]) -> IsaacRng {
235 impl Rand for IsaacRng {
236 fn rand<R: Rng>(other: &mut R) -> IsaacRng {
239 let ptr = ret.rsl.as_mut_ptr() as *mut u8;
241 let slice = slice::from_raw_mut_buf(&ptr, (RAND_SIZE * 4) as uint);
242 other.fill_bytes(slice);
254 const RAND_SIZE_64_LEN: uint = 8;
255 const RAND_SIZE_64: uint = 1 << RAND_SIZE_64_LEN;
257 /// A random number generator that uses ISAAC-64[1], the 64-bit
258 /// variant of the ISAAC algorithm.
260 /// The ISAAC algorithm is generally accepted as suitable for
261 /// cryptographic purposes, but this implementation has not be
262 /// verified as such. Prefer a generator like `OsRng` that defers to
263 /// the operating system for cases that need high security.
265 /// [1]: Bob Jenkins, [*ISAAC: A fast cryptographic random number
266 /// generator*](http://www.burtleburtle.net/bob/rand/isaacafa.html)
268 pub struct Isaac64Rng {
270 rsl: [u64; RAND_SIZE_64],
271 mem: [u64; RAND_SIZE_64],
277 static EMPTY_64: Isaac64Rng = Isaac64Rng {
279 rsl: [0; RAND_SIZE_64],
280 mem: [0; RAND_SIZE_64],
285 /// Create a 64-bit ISAAC random number generator using the
286 /// default fixed seed.
287 pub fn new_unseeded() -> Isaac64Rng {
288 let mut rng = EMPTY_64;
293 /// Initialises `self`. If `use_rsl` is true, then use the current value
294 /// of `rsl` as a seed, otherwise construct one algorithmically (not
296 fn init(&mut self, use_rsl: bool) {
299 let mut $var = 0x9e3779b97f4a7c13;
302 init!(a); init!(b); init!(c); init!(d);
303 init!(e); init!(f); init!(g); init!(h);
309 c-=g; h^=b>>23; b+=c;
310 d-=h; a^=c<<15; c+=d;
311 e-=a; b^=d>>14; d+=e;
312 f-=b; c^=e<<20; e+=f;
313 g-=c; d^=f>>17; f+=g;
314 h-=d; e^=g<<14; g+=h;
318 for _ in range(0u, 4) {
323 macro_rules! memloop (
325 for i in range(0, RAND_SIZE_64 / 8).map(|i| i * 8) {
326 a+=$arr[i ]; b+=$arr[i+1];
327 c+=$arr[i+2]; d+=$arr[i+3];
328 e+=$arr[i+4]; f+=$arr[i+5];
329 g+=$arr[i+6]; h+=$arr[i+7];
331 self.mem[i ]=a; self.mem[i+1]=b;
332 self.mem[i+2]=c; self.mem[i+3]=d;
333 self.mem[i+4]=e; self.mem[i+5]=f;
334 self.mem[i+6]=g; self.mem[i+7]=h;
342 for i in range(0, RAND_SIZE_64 / 8).map(|i| i * 8) {
344 self.mem[i ]=a; self.mem[i+1]=b;
345 self.mem[i+2]=c; self.mem[i+3]=d;
346 self.mem[i+4]=e; self.mem[i+5]=f;
347 self.mem[i+6]=g; self.mem[i+7]=h;
354 /// Refills the output buffer (`self.rsl`)
355 fn isaac64(&mut self) {
359 let mut b = self.b + self.c;
360 const MIDPOINT: uint = RAND_SIZE_64 / 2;
361 const MP_VEC: [(uint, uint); 2] = [(0,MIDPOINT), (MIDPOINT, 0)];
364 *self.mem.get_unchecked(($x as uint >> 3) & (RAND_SIZE_64 - 1))
368 for &(mr_offset, m2_offset) in MP_VEC.iter() {
369 for base in range(0, MIDPOINT / 4).map(|i| i * 4) {
371 macro_rules! rngstepp(
372 ($j:expr, $shift:expr) => {{
373 let base = base + $j;
374 let mix = a ^ (a << $shift as uint);
375 let mix = if $j == 0 {!mix} else {mix};
378 let x = *self.mem.get_unchecked(base + mr_offset);
379 a = mix + *self.mem.get_unchecked(base + m2_offset);
380 let y = ind!(x) + a + b;
381 *self.mem.get_unchecked_mut(base + mr_offset) = y;
383 b = ind!(y >> RAND_SIZE_64_LEN) + x;
384 *self.rsl.get_unchecked_mut(base + mr_offset) = b;
388 macro_rules! rngstepn(
389 ($j:expr, $shift:expr) => {{
390 let base = base + $j;
391 let mix = a ^ (a >> $shift as uint);
392 let mix = if $j == 0 {!mix} else {mix};
395 let x = *self.mem.get_unchecked(base + mr_offset);
396 a = mix + *self.mem.get_unchecked(base + m2_offset);
397 let y = ind!(x) + a + b;
398 *self.mem.get_unchecked_mut(base + mr_offset) = y;
400 b = ind!(y >> RAND_SIZE_64_LEN) + x;
401 *self.rsl.get_unchecked_mut(base + mr_offset) = b;
414 self.cnt = RAND_SIZE_64;
418 impl Rng for Isaac64Rng {
419 // FIXME #7771: having next_u32 like this should be unnecessary
421 fn next_u32(&mut self) -> u32 {
422 self.next_u64() as u32
426 fn next_u64(&mut self) -> u64 {
428 // make some more numbers
433 // See corresponding location in IsaacRng.next_u32 for
435 debug_assert!(self.cnt < RAND_SIZE_64);
436 self.rsl[(self.cnt % RAND_SIZE_64) as uint]
440 impl<'a> SeedableRng<&'a [u64]> for Isaac64Rng {
441 fn reseed(&mut self, seed: &'a [u64]) {
442 // make the seed into [seed[0], seed[1], ..., seed[seed.len()
443 // - 1], 0, 0, ...], to fill rng.rsl.
444 let seed_iter = seed.iter().map(|&x| x).chain(repeat(0u64));
446 for (rsl_elem, seed_elem) in self.rsl.iter_mut().zip(seed_iter) {
447 *rsl_elem = seed_elem;
457 /// Create an ISAAC random number generator with a seed. This can
458 /// be any length, although the maximum number of elements used is
459 /// 256 and any more will be silently ignored. A generator
460 /// constructed with a given seed will generate the same sequence
461 /// of values as all other generators constructed with that seed.
462 fn from_seed(seed: &'a [u64]) -> Isaac64Rng {
463 let mut rng = EMPTY_64;
469 impl Rand for Isaac64Rng {
470 fn rand<R: Rng>(other: &mut R) -> Isaac64Rng {
471 let mut ret = EMPTY_64;
473 let ptr = ret.rsl.as_mut_ptr() as *mut u8;
475 let slice = slice::from_raw_mut_buf(&ptr, (RAND_SIZE_64 * 8) as uint);
476 other.fill_bytes(slice);
490 use std::prelude::v1::*;
492 use core::iter::order;
493 use {Rng, SeedableRng};
494 use super::{IsaacRng, Isaac64Rng};
497 fn test_rng_32_rand_seeded() {
498 let s = ::test::rng().gen_iter::<u32>().take(256).collect::<Vec<u32>>();
499 let mut ra: IsaacRng = SeedableRng::from_seed(s.as_slice());
500 let mut rb: IsaacRng = SeedableRng::from_seed(s.as_slice());
501 assert!(order::equals(ra.gen_ascii_chars().take(100),
502 rb.gen_ascii_chars().take(100)));
505 fn test_rng_64_rand_seeded() {
506 let s = ::test::rng().gen_iter::<u64>().take(256).collect::<Vec<u64>>();
507 let mut ra: Isaac64Rng = SeedableRng::from_seed(s.as_slice());
508 let mut rb: Isaac64Rng = SeedableRng::from_seed(s.as_slice());
509 assert!(order::equals(ra.gen_ascii_chars().take(100),
510 rb.gen_ascii_chars().take(100)));
514 fn test_rng_32_seeded() {
515 let seed: &[_] = &[1, 23, 456, 7890, 12345];
516 let mut ra: IsaacRng = SeedableRng::from_seed(seed);
517 let mut rb: IsaacRng = SeedableRng::from_seed(seed);
518 assert!(order::equals(ra.gen_ascii_chars().take(100),
519 rb.gen_ascii_chars().take(100)));
522 fn test_rng_64_seeded() {
523 let seed: &[_] = &[1, 23, 456, 7890, 12345];
524 let mut ra: Isaac64Rng = SeedableRng::from_seed(seed);
525 let mut rb: Isaac64Rng = SeedableRng::from_seed(seed);
526 assert!(order::equals(ra.gen_ascii_chars().take(100),
527 rb.gen_ascii_chars().take(100)));
531 fn test_rng_32_reseed() {
532 let s = ::test::rng().gen_iter::<u32>().take(256).collect::<Vec<u32>>();
533 let mut r: IsaacRng = SeedableRng::from_seed(s.as_slice());
534 let string1: String = r.gen_ascii_chars().take(100).collect();
536 r.reseed(s.as_slice());
538 let string2: String = r.gen_ascii_chars().take(100).collect();
539 assert_eq!(string1, string2);
542 fn test_rng_64_reseed() {
543 let s = ::test::rng().gen_iter::<u64>().take(256).collect::<Vec<u64>>();
544 let mut r: Isaac64Rng = SeedableRng::from_seed(s.as_slice());
545 let string1: String = r.gen_ascii_chars().take(100).collect();
547 r.reseed(s.as_slice());
549 let string2: String = r.gen_ascii_chars().take(100).collect();
550 assert_eq!(string1, string2);
554 fn test_rng_32_true_values() {
555 let seed: &[_] = &[1, 23, 456, 7890, 12345];
556 let mut ra: IsaacRng = SeedableRng::from_seed(seed);
557 // Regression test that isaac is actually using the above vector
558 let v = range(0, 10).map(|_| ra.next_u32()).collect::<Vec<_>>();
560 vec!(2558573138, 873787463, 263499565, 2103644246, 3595684709,
561 4203127393, 264982119, 2765226902, 2737944514, 3900253796));
563 let seed: &[_] = &[12345, 67890, 54321, 9876];
564 let mut rb: IsaacRng = SeedableRng::from_seed(seed);
565 // skip forward to the 10000th number
566 for _ in range(0u, 10000) { rb.next_u32(); }
568 let v = range(0, 10).map(|_| rb.next_u32()).collect::<Vec<_>>();
570 vec!(3676831399, 3183332890, 2834741178, 3854698763, 2717568474,
571 1576568959, 3507990155, 179069555, 141456972, 2478885421));
574 fn test_rng_64_true_values() {
575 let seed: &[_] = &[1, 23, 456, 7890, 12345];
576 let mut ra: Isaac64Rng = SeedableRng::from_seed(seed);
577 // Regression test that isaac is actually using the above vector
578 let v = range(0, 10).map(|_| ra.next_u64()).collect::<Vec<_>>();
580 vec!(547121783600835980, 14377643087320773276, 17351601304698403469,
581 1238879483818134882, 11952566807690396487, 13970131091560099343,
582 4469761996653280935, 15552757044682284409, 6860251611068737823,
583 13722198873481261842));
585 let seed: &[_] = &[12345, 67890, 54321, 9876];
586 let mut rb: Isaac64Rng = SeedableRng::from_seed(seed);
587 // skip forward to the 10000th number
588 for _ in range(0u, 10000) { rb.next_u64(); }
590 let v = range(0, 10).map(|_| rb.next_u64()).collect::<Vec<_>>();
592 vec!(18143823860592706164, 8491801882678285927, 2699425367717515619,
593 17196852593171130876, 2606123525235546165, 15790932315217671084,
594 596345674630742204, 9947027391921273664, 11788097613744130851,
595 10391409374914919106));