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.
14 use core::iter::{range_step, Repeat};
18 use {Rng, SeedableRng, Rand};
20 static RAND_SIZE_LEN: u32 = 8;
21 static RAND_SIZE: u32 = 1 << (RAND_SIZE_LEN as uint);
22 static RAND_SIZE_UINT: uint = 1 << (RAND_SIZE_LEN as uint);
24 /// A random number generator that uses the ISAAC algorithm[1].
26 /// The ISAAC algorithm is generally accepted as suitable for
27 /// cryptographic purposes, but this implementation has not be
28 /// verified as such. Prefer a generator like `OsRng` that defers to
29 /// the operating system for cases that need high security.
31 /// [1]: Bob Jenkins, [*ISAAC: A fast cryptographic random number
32 /// generator*](http://www.burtleburtle.net/bob/rand/isaacafa.html)
35 rsl: [u32, ..RAND_SIZE_UINT],
36 mem: [u32, ..RAND_SIZE_UINT],
41 static EMPTY: IsaacRng = IsaacRng {
43 rsl: [0, ..RAND_SIZE_UINT],
44 mem: [0, ..RAND_SIZE_UINT],
49 /// Create an ISAAC random number generator using the default
51 pub fn new_unseeded() -> IsaacRng {
57 /// Initialises `self`. If `use_rsl` is true, then use the current value
58 /// of `rsl` as a seed, otherwise construct one algorithmically (not
60 fn init(&mut self, use_rsl: bool) {
61 let mut a = 0x9e3779b9;
83 for _ in range(0u, 4) {
88 macro_rules! memloop (
90 for i in range_step(0, RAND_SIZE as uint, 8) {
91 a+=$arr[i ]; b+=$arr[i+1];
92 c+=$arr[i+2]; d+=$arr[i+3];
93 e+=$arr[i+4]; f+=$arr[i+5];
94 g+=$arr[i+6]; h+=$arr[i+7];
96 self.mem[i ]=a; self.mem[i+1]=b;
97 self.mem[i+2]=c; self.mem[i+3]=d;
98 self.mem[i+4]=e; self.mem[i+5]=f;
99 self.mem[i+6]=g; self.mem[i+7]=h;
107 for i in range_step(0, RAND_SIZE as uint, 8) {
109 self.mem[i ]=a; self.mem[i+1]=b;
110 self.mem[i+2]=c; self.mem[i+3]=d;
111 self.mem[i+4]=e; self.mem[i+5]=f;
112 self.mem[i+6]=g; self.mem[i+7]=h;
119 /// Refills the output buffer (`self.rsl`)
121 #[allow(unsigned_negate)]
122 fn isaac(&mut self) {
126 let mut b = self.b + self.c;
128 static MIDPOINT: uint = (RAND_SIZE / 2) as uint;
130 macro_rules! ind (($x:expr) => {
131 self.mem[(($x >> 2) as uint & ((RAND_SIZE - 1) as uint))]
133 macro_rules! rngstepp(
134 ($j:expr, $shift:expr) => {{
136 let mix = a << $shift as uint;
138 let x = self.mem[base + mr_offset];
139 a = (a ^ mix) + self.mem[base + m2_offset];
140 let y = ind!(x) + a + b;
141 self.mem[base + mr_offset] = y;
143 b = ind!(y >> RAND_SIZE_LEN as uint) + x;
144 self.rsl[base + mr_offset] = b;
147 macro_rules! rngstepn(
148 ($j:expr, $shift:expr) => {{
150 let mix = a >> $shift as uint;
152 let x = self.mem[base + mr_offset];
153 a = (a ^ mix) + self.mem[base + m2_offset];
154 let y = ind!(x) + a + b;
155 self.mem[base + mr_offset] = y;
157 b = ind!(y >> RAND_SIZE_LEN as uint) + x;
158 self.rsl[base + mr_offset] = b;
162 let r = [(0, MIDPOINT), (MIDPOINT, 0)];
163 for &(mr_offset, m2_offset) in r.iter() {
164 for i in range_step(0u, MIDPOINT, 4) {
165 rngstepp!(i + 0, 13);
168 rngstepn!(i + 3, 16);
174 self.cnt = RAND_SIZE;
178 impl Rng for IsaacRng {
180 fn next_u32(&mut self) -> u32 {
182 // make some more numbers
186 self.rsl[self.cnt as uint]
190 impl<'a> SeedableRng<&'a [u32]> for IsaacRng {
191 fn reseed(&mut self, seed: &'a [u32]) {
192 // make the seed into [seed[0], seed[1], ..., seed[seed.len()
193 // - 1], 0, 0, ...], to fill rng.rsl.
194 let seed_iter = seed.iter().map(|&x| x).chain(Repeat::new(0u32));
196 for (rsl_elem, seed_elem) in self.rsl.mut_iter().zip(seed_iter) {
197 *rsl_elem = seed_elem;
207 /// Create an ISAAC random number generator with a seed. This can
208 /// be any length, although the maximum number of elements used is
209 /// 256 and any more will be silently ignored. A generator
210 /// constructed with a given seed will generate the same sequence
211 /// of values as all other generators constructed with that seed.
212 fn from_seed(seed: &'a [u32]) -> IsaacRng {
219 impl Rand for IsaacRng {
220 fn rand<R: Rng>(other: &mut R) -> IsaacRng {
223 let ptr = ret.rsl.as_mut_ptr();
225 raw::mut_buf_as_slice(ptr as *mut u8,
226 mem::size_of_val(&ret.rsl), |slice| {
227 other.fill_bytes(slice);
240 static RAND_SIZE_64_LEN: uint = 8;
241 static RAND_SIZE_64: uint = 1 << RAND_SIZE_64_LEN;
243 /// A random number generator that uses ISAAC-64[1], the 64-bit
244 /// variant of the ISAAC algorithm.
246 /// The ISAAC algorithm is generally accepted as suitable for
247 /// cryptographic purposes, but this implementation has not be
248 /// verified as such. Prefer a generator like `OsRng` that defers to
249 /// the operating system for cases that need high security.
251 /// [1]: Bob Jenkins, [*ISAAC: A fast cryptographic random number
252 /// generator*](http://www.burtleburtle.net/bob/rand/isaacafa.html)
253 pub struct Isaac64Rng {
255 rsl: [u64, .. RAND_SIZE_64],
256 mem: [u64, .. RAND_SIZE_64],
262 static EMPTY_64: Isaac64Rng = Isaac64Rng {
264 rsl: [0, .. RAND_SIZE_64],
265 mem: [0, .. RAND_SIZE_64],
270 /// Create a 64-bit ISAAC random number generator using the
271 /// default fixed seed.
272 pub fn new_unseeded() -> Isaac64Rng {
273 let mut rng = EMPTY_64;
278 /// Initialises `self`. If `use_rsl` is true, then use the current value
279 /// of `rsl` as a seed, otherwise construct one algorithmically (not
281 fn init(&mut self, use_rsl: bool) {
284 let mut $var = 0x9e3779b97f4a7c13;
287 init!(a); init!(b); init!(c); init!(d);
288 init!(e); init!(f); init!(g); init!(h);
294 c-=g; h^=b>>23; b+=c;
295 d-=h; a^=c<<15; c+=d;
296 e-=a; b^=d>>14; d+=e;
297 f-=b; c^=e<<20; e+=f;
298 g-=c; d^=f>>17; f+=g;
299 h-=d; e^=g<<14; g+=h;
303 for _ in range(0u, 4) {
308 macro_rules! memloop (
310 for i in range(0, RAND_SIZE_64 / 8).map(|i| i * 8) {
311 a+=$arr[i ]; b+=$arr[i+1];
312 c+=$arr[i+2]; d+=$arr[i+3];
313 e+=$arr[i+4]; f+=$arr[i+5];
314 g+=$arr[i+6]; h+=$arr[i+7];
316 self.mem[i ]=a; self.mem[i+1]=b;
317 self.mem[i+2]=c; self.mem[i+3]=d;
318 self.mem[i+4]=e; self.mem[i+5]=f;
319 self.mem[i+6]=g; self.mem[i+7]=h;
327 for i in range(0, RAND_SIZE_64 / 8).map(|i| i * 8) {
329 self.mem[i ]=a; self.mem[i+1]=b;
330 self.mem[i+2]=c; self.mem[i+3]=d;
331 self.mem[i+4]=e; self.mem[i+5]=f;
332 self.mem[i+6]=g; self.mem[i+7]=h;
339 /// Refills the output buffer (`self.rsl`)
340 fn isaac64(&mut self) {
344 let mut b = self.b + self.c;
345 static MIDPOINT: uint = RAND_SIZE_64 / 2;
346 static MP_VEC: [(uint, uint), .. 2] = [(0,MIDPOINT), (MIDPOINT, 0)];
349 *self.mem.unsafe_ref(($x as uint >> 3) & (RAND_SIZE_64 - 1))
352 macro_rules! rngstepp(
353 ($j:expr, $shift:expr) => {{
354 let base = base + $j;
355 let mix = a ^ (a << $shift as uint);
356 let mix = if $j == 0 {!mix} else {mix};
359 let x = *self.mem.unsafe_ref(base + mr_offset);
360 a = mix + *self.mem.unsafe_ref(base + m2_offset);
361 let y = ind!(x) + a + b;
362 self.mem.unsafe_set(base + mr_offset, y);
364 b = ind!(y >> RAND_SIZE_64_LEN) + x;
365 self.rsl.unsafe_set(base + mr_offset, b);
369 macro_rules! rngstepn(
370 ($j:expr, $shift:expr) => {{
371 let base = base + $j;
372 let mix = a ^ (a >> $shift as uint);
373 let mix = if $j == 0 {!mix} else {mix};
376 let x = *self.mem.unsafe_ref(base + mr_offset);
377 a = mix + *self.mem.unsafe_ref(base + m2_offset);
378 let y = ind!(x) + a + b;
379 self.mem.unsafe_set(base + mr_offset, y);
381 b = ind!(y >> RAND_SIZE_64_LEN) + x;
382 self.rsl.unsafe_set(base + mr_offset, b);
387 for &(mr_offset, m2_offset) in MP_VEC.iter() {
388 for base in range(0, MIDPOINT / 4).map(|i| i * 4) {
398 self.cnt = RAND_SIZE_64;
402 impl Rng for Isaac64Rng {
403 // FIXME #7771: having next_u32 like this should be unnecessary
405 fn next_u32(&mut self) -> u32 {
406 self.next_u64() as u32
410 fn next_u64(&mut self) -> u64 {
412 // make some more numbers
416 unsafe { *self.rsl.unsafe_ref(self.cnt) }
420 impl<'a> SeedableRng<&'a [u64]> for Isaac64Rng {
421 fn reseed(&mut self, seed: &'a [u64]) {
422 // make the seed into [seed[0], seed[1], ..., seed[seed.len()
423 // - 1], 0, 0, ...], to fill rng.rsl.
424 let seed_iter = seed.iter().map(|&x| x).chain(Repeat::new(0u64));
426 for (rsl_elem, seed_elem) in self.rsl.mut_iter().zip(seed_iter) {
427 *rsl_elem = seed_elem;
437 /// Create an ISAAC random number generator with a seed. This can
438 /// be any length, although the maximum number of elements used is
439 /// 256 and any more will be silently ignored. A generator
440 /// constructed with a given seed will generate the same sequence
441 /// of values as all other generators constructed with that seed.
442 fn from_seed(seed: &'a [u64]) -> Isaac64Rng {
443 let mut rng = EMPTY_64;
449 impl Rand for Isaac64Rng {
450 fn rand<R: Rng>(other: &mut R) -> Isaac64Rng {
451 let mut ret = EMPTY_64;
453 let ptr = ret.rsl.as_mut_ptr();
455 raw::mut_buf_as_slice(ptr as *mut u8,
456 mem::size_of_val(&ret.rsl), |slice| {
457 other.fill_bytes(slice);
474 use core::iter::order;
475 use {Rng, SeedableRng};
476 use super::{IsaacRng, Isaac64Rng};
479 fn test_rng_32_rand_seeded() {
480 let s = ::test::rng().gen_iter::<u32>().take(256).collect::<Vec<u32>>();
481 let mut ra: IsaacRng = SeedableRng::from_seed(s.as_slice());
482 let mut rb: IsaacRng = SeedableRng::from_seed(s.as_slice());
483 assert!(order::equals(ra.gen_ascii_chars().take(100),
484 rb.gen_ascii_chars().take(100)));
487 fn test_rng_64_rand_seeded() {
488 let s = ::test::rng().gen_iter::<u64>().take(256).collect::<Vec<u64>>();
489 let mut ra: Isaac64Rng = SeedableRng::from_seed(s.as_slice());
490 let mut rb: Isaac64Rng = SeedableRng::from_seed(s.as_slice());
491 assert!(order::equals(ra.gen_ascii_chars().take(100),
492 rb.gen_ascii_chars().take(100)));
496 fn test_rng_32_seeded() {
497 let seed = &[1, 23, 456, 7890, 12345];
498 let mut ra: IsaacRng = SeedableRng::from_seed(seed);
499 let mut rb: IsaacRng = SeedableRng::from_seed(seed);
500 assert!(order::equals(ra.gen_ascii_chars().take(100),
501 rb.gen_ascii_chars().take(100)));
504 fn test_rng_64_seeded() {
505 let seed = &[1, 23, 456, 7890, 12345];
506 let mut ra: Isaac64Rng = SeedableRng::from_seed(seed);
507 let mut rb: Isaac64Rng = SeedableRng::from_seed(seed);
508 assert!(order::equals(ra.gen_ascii_chars().take(100),
509 rb.gen_ascii_chars().take(100)));
513 fn test_rng_32_reseed() {
514 let s = ::test::rng().gen_iter::<u32>().take(256).collect::<Vec<u32>>();
515 let mut r: IsaacRng = SeedableRng::from_seed(s.as_slice());
516 let string1: String = r.gen_ascii_chars().take(100).collect();
518 r.reseed(s.as_slice());
520 let string2: String = r.gen_ascii_chars().take(100).collect();
521 assert_eq!(string1, string2);
524 fn test_rng_64_reseed() {
525 let s = ::test::rng().gen_iter::<u64>().take(256).collect::<Vec<u64>>();
526 let mut r: Isaac64Rng = SeedableRng::from_seed(s.as_slice());
527 let string1: String = r.gen_ascii_chars().take(100).collect();
529 r.reseed(s.as_slice());
531 let string2: String = r.gen_ascii_chars().take(100).collect();
532 assert_eq!(string1, string2);
536 fn test_rng_32_true_values() {
537 let seed = &[1, 23, 456, 7890, 12345];
538 let mut ra: IsaacRng = SeedableRng::from_seed(seed);
539 // Regression test that isaac is actually using the above vector
540 let v = Vec::from_fn(10, |_| ra.next_u32());
542 vec!(2558573138, 873787463, 263499565, 2103644246, 3595684709,
543 4203127393, 264982119, 2765226902, 2737944514, 3900253796));
545 let seed = &[12345, 67890, 54321, 9876];
546 let mut rb: IsaacRng = SeedableRng::from_seed(seed);
547 // skip forward to the 10000th number
548 for _ in range(0u, 10000) { rb.next_u32(); }
550 let v = Vec::from_fn(10, |_| rb.next_u32());
552 vec!(3676831399, 3183332890, 2834741178, 3854698763, 2717568474,
553 1576568959, 3507990155, 179069555, 141456972, 2478885421));
556 fn test_rng_64_true_values() {
557 let seed = &[1, 23, 456, 7890, 12345];
558 let mut ra: Isaac64Rng = SeedableRng::from_seed(seed);
559 // Regression test that isaac is actually using the above vector
560 let v = Vec::from_fn(10, |_| ra.next_u64());
562 vec!(547121783600835980, 14377643087320773276, 17351601304698403469,
563 1238879483818134882, 11952566807690396487, 13970131091560099343,
564 4469761996653280935, 15552757044682284409, 6860251611068737823,
565 13722198873481261842));
567 let seed = &[12345, 67890, 54321, 9876];
568 let mut rb: Isaac64Rng = SeedableRng::from_seed(seed);
569 // skip forward to the 10000th number
570 for _ in range(0u, 10000) { rb.next_u64(); }
572 let v = Vec::from_fn(10, |_| rb.next_u64());
574 vec!(18143823860592706164, 8491801882678285927, 2699425367717515619,
575 17196852593171130876, 2606123525235546165, 15790932315217671084,
576 596345674630742204, 9947027391921273664, 11788097613744130851,
577 10391409374914919106));