]> git.proxmox.com Git - rustc.git/blame - src/librand/isaac.rs
Imported Upstream version 1.0.0~0alpha
[rustc.git] / src / librand / isaac.rs
CommitLineData
1a4d82fc
JJ
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.
4//
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.
10
11//! The ISAAC random number generator.
12
13use core::prelude::*;
14use core::slice;
15use core::iter::{range_step, repeat};
16
17use {Rng, SeedableRng, Rand};
18
19const RAND_SIZE_LEN: u32 = 8;
20const RAND_SIZE: u32 = 1 << (RAND_SIZE_LEN as uint);
21const RAND_SIZE_UINT: uint = 1 << (RAND_SIZE_LEN as uint);
22
23/// A random number generator that uses the ISAAC algorithm[1].
24///
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.
29///
30/// [1]: Bob Jenkins, [*ISAAC: A fast cryptographic random number
31/// generator*](http://www.burtleburtle.net/bob/rand/isaacafa.html)
32#[derive(Copy)]
33pub struct IsaacRng {
34 cnt: u32,
35 rsl: [u32; RAND_SIZE_UINT],
36 mem: [u32; RAND_SIZE_UINT],
37 a: u32,
38 b: u32,
39 c: u32
40}
41
42static EMPTY: IsaacRng = IsaacRng {
43 cnt: 0,
44 rsl: [0; RAND_SIZE_UINT],
45 mem: [0; RAND_SIZE_UINT],
46 a: 0, b: 0, c: 0
47};
48
49impl IsaacRng {
50
51 /// Create an ISAAC random number generator using the default
52 /// fixed seed.
53 pub fn new_unseeded() -> IsaacRng {
54 let mut rng = EMPTY;
55 rng.init(false);
56 rng
57 }
58
59 /// Initialises `self`. If `use_rsl` is true, then use the current value
60 /// of `rsl` as a seed, otherwise construct one algorithmically (not
61 /// randomly).
62 fn init(&mut self, use_rsl: bool) {
63 let mut a = 0x9e3779b9;
64 let mut b = a;
65 let mut c = a;
66 let mut d = a;
67 let mut e = a;
68 let mut f = a;
69 let mut g = a;
70 let mut h = a;
71
72 macro_rules! mix {
73 () => {{
74 a^=b<<11; d+=a; b+=c;
75 b^=c>>2; e+=b; c+=d;
76 c^=d<<8; f+=c; d+=e;
77 d^=e>>16; g+=d; e+=f;
78 e^=f<<10; h+=e; f+=g;
79 f^=g>>4; a+=f; g+=h;
80 g^=h<<8; b+=g; h+=a;
81 h^=a>>9; c+=h; a+=b;
82 }}
83 }
84
85 for _ in range(0u, 4) {
86 mix!();
87 }
88
89 if use_rsl {
90 macro_rules! memloop {
91 ($arr:expr) => {{
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];
97 mix!();
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;
102 }
103 }}
104 }
105
106 memloop!(self.rsl);
107 memloop!(self.mem);
108 } else {
109 for i in range_step(0, RAND_SIZE as uint, 8) {
110 mix!();
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;
115 }
116 }
117
118 self.isaac();
119 }
120
121 /// Refills the output buffer (`self.rsl`)
122 #[inline]
123 #[allow(unsigned_negation)]
124 fn isaac(&mut self) {
125 self.c += 1;
126 // abbreviations
127 let mut a = self.a;
128 let mut b = self.b + self.c;
129
130 static MIDPOINT: uint = (RAND_SIZE / 2) as uint;
131
132 macro_rules! ind {
133 ($x:expr) => ( self.mem[(($x >> 2) as uint & ((RAND_SIZE - 1) as uint))] )
134 }
135
136 let r = [(0, MIDPOINT), (MIDPOINT, 0)];
137 for &(mr_offset, m2_offset) in r.iter() {
138
139 macro_rules! rngstepp {
140 ($j:expr, $shift:expr) => {{
141 let base = $j;
142 let mix = a << $shift as uint;
143
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;
148
149 b = ind!(y >> RAND_SIZE_LEN as uint) + x;
150 self.rsl[base + mr_offset] = b;
151 }}
152 }
153
154 macro_rules! rngstepn {
155 ($j:expr, $shift:expr) => {{
156 let base = $j;
157 let mix = a >> $shift as uint;
158
159 let x = self.mem[base + mr_offset];
160 a = (a ^ mix) + self.mem[base + m2_offset];
161 let y = ind!(x) + a + b;
162 self.mem[base + mr_offset] = y;
163
164 b = ind!(y >> RAND_SIZE_LEN as uint) + x;
165 self.rsl[base + mr_offset] = b;
166 }}
167 }
168
169 for i in range_step(0u, MIDPOINT, 4) {
170 rngstepp!(i + 0, 13);
171 rngstepn!(i + 1, 6);
172 rngstepp!(i + 2, 2);
173 rngstepn!(i + 3, 16);
174 }
175 }
176
177 self.a = a;
178 self.b = b;
179 self.cnt = RAND_SIZE;
180 }
181}
182
183// Cannot be derived because [u32; 256] does not implement Clone
184impl Clone for IsaacRng {
185 fn clone(&self) -> IsaacRng {
186 *self
187 }
188}
189
190impl Rng for IsaacRng {
191 #[inline]
192 fn next_u32(&mut self) -> u32 {
193 if self.cnt == 0 {
194 // make some more numbers
195 self.isaac();
196 }
197 self.cnt -= 1;
198
199 // self.cnt is at most RAND_SIZE, but that is before the
200 // subtraction above. We want to index without bounds
201 // checking, but this could lead to incorrect code if someone
202 // misrefactors, so we check, sometimes.
203 //
204 // (Changes here should be reflected in Isaac64Rng.next_u64.)
205 debug_assert!(self.cnt < RAND_SIZE);
206
207 // (the % is cheaply telling the optimiser that we're always
208 // in bounds, without unsafe. NB. this is a power of two, so
209 // it optimises to a bitwise mask).
210 self.rsl[(self.cnt % RAND_SIZE) as uint]
211 }
212}
213
214impl<'a> SeedableRng<&'a [u32]> for IsaacRng {
215 fn reseed(&mut self, seed: &'a [u32]) {
216 // make the seed into [seed[0], seed[1], ..., seed[seed.len()
217 // - 1], 0, 0, ...], to fill rng.rsl.
218 let seed_iter = seed.iter().map(|&x| x).chain(repeat(0u32));
219
220 for (rsl_elem, seed_elem) in self.rsl.iter_mut().zip(seed_iter) {
221 *rsl_elem = seed_elem;
222 }
223 self.cnt = 0;
224 self.a = 0;
225 self.b = 0;
226 self.c = 0;
227
228 self.init(true);
229 }
230
231 /// Create an ISAAC random number generator with a seed. This can
232 /// be any length, although the maximum number of elements used is
233 /// 256 and any more will be silently ignored. A generator
234 /// constructed with a given seed will generate the same sequence
235 /// of values as all other generators constructed with that seed.
236 fn from_seed(seed: &'a [u32]) -> IsaacRng {
237 let mut rng = EMPTY;
238 rng.reseed(seed);
239 rng
240 }
241}
242
243impl Rand for IsaacRng {
244 fn rand<R: Rng>(other: &mut R) -> IsaacRng {
245 let mut ret = EMPTY;
246 unsafe {
247 let ptr = ret.rsl.as_mut_ptr() as *mut u8;
248
249 let slice = slice::from_raw_mut_buf(&ptr, (RAND_SIZE * 4) as uint);
250 other.fill_bytes(slice);
251 }
252 ret.cnt = 0;
253 ret.a = 0;
254 ret.b = 0;
255 ret.c = 0;
256
257 ret.init(true);
258 return ret;
259 }
260}
261
262const RAND_SIZE_64_LEN: uint = 8;
263const RAND_SIZE_64: uint = 1 << RAND_SIZE_64_LEN;
264
265/// A random number generator that uses ISAAC-64[1], the 64-bit
266/// variant of the ISAAC algorithm.
267///
268/// The ISAAC algorithm is generally accepted as suitable for
269/// cryptographic purposes, but this implementation has not be
270/// verified as such. Prefer a generator like `OsRng` that defers to
271/// the operating system for cases that need high security.
272///
273/// [1]: Bob Jenkins, [*ISAAC: A fast cryptographic random number
274/// generator*](http://www.burtleburtle.net/bob/rand/isaacafa.html)
275#[derive(Copy)]
276pub struct Isaac64Rng {
277 cnt: uint,
278 rsl: [u64; RAND_SIZE_64],
279 mem: [u64; RAND_SIZE_64],
280 a: u64,
281 b: u64,
282 c: u64,
283}
284
285static EMPTY_64: Isaac64Rng = Isaac64Rng {
286 cnt: 0,
287 rsl: [0; RAND_SIZE_64],
288 mem: [0; RAND_SIZE_64],
289 a: 0, b: 0, c: 0,
290};
291
292impl Isaac64Rng {
293 /// Create a 64-bit ISAAC random number generator using the
294 /// default fixed seed.
295 pub fn new_unseeded() -> Isaac64Rng {
296 let mut rng = EMPTY_64;
297 rng.init(false);
298 rng
299 }
300
301 /// Initialises `self`. If `use_rsl` is true, then use the current value
302 /// of `rsl` as a seed, otherwise construct one algorithmically (not
303 /// randomly).
304 fn init(&mut self, use_rsl: bool) {
305 macro_rules! init {
306 ($var:ident) => (
307 let mut $var = 0x9e3779b97f4a7c13;
308 )
309 }
310 init!(a); init!(b); init!(c); init!(d);
311 init!(e); init!(f); init!(g); init!(h);
312
313 macro_rules! mix {
314 () => {{
315 a-=e; f^=h>>9; h+=a;
316 b-=f; g^=a<<9; a+=b;
317 c-=g; h^=b>>23; b+=c;
318 d-=h; a^=c<<15; c+=d;
319 e-=a; b^=d>>14; d+=e;
320 f-=b; c^=e<<20; e+=f;
321 g-=c; d^=f>>17; f+=g;
322 h-=d; e^=g<<14; g+=h;
323 }}
324 }
325
326 for _ in range(0u, 4) {
327 mix!();
328 }
329
330 if use_rsl {
331 macro_rules! memloop {
332 ($arr:expr) => {{
333 for i in range(0, RAND_SIZE_64 / 8).map(|i| i * 8) {
334 a+=$arr[i ]; b+=$arr[i+1];
335 c+=$arr[i+2]; d+=$arr[i+3];
336 e+=$arr[i+4]; f+=$arr[i+5];
337 g+=$arr[i+6]; h+=$arr[i+7];
338 mix!();
339 self.mem[i ]=a; self.mem[i+1]=b;
340 self.mem[i+2]=c; self.mem[i+3]=d;
341 self.mem[i+4]=e; self.mem[i+5]=f;
342 self.mem[i+6]=g; self.mem[i+7]=h;
343 }
344 }}
345 }
346
347 memloop!(self.rsl);
348 memloop!(self.mem);
349 } else {
350 for i in range(0, RAND_SIZE_64 / 8).map(|i| i * 8) {
351 mix!();
352 self.mem[i ]=a; self.mem[i+1]=b;
353 self.mem[i+2]=c; self.mem[i+3]=d;
354 self.mem[i+4]=e; self.mem[i+5]=f;
355 self.mem[i+6]=g; self.mem[i+7]=h;
356 }
357 }
358
359 self.isaac64();
360 }
361
362 /// Refills the output buffer (`self.rsl`)
363 fn isaac64(&mut self) {
364 self.c += 1;
365 // abbreviations
366 let mut a = self.a;
367 let mut b = self.b + self.c;
368 const MIDPOINT: uint = RAND_SIZE_64 / 2;
369 const MP_VEC: [(uint, uint); 2] = [(0,MIDPOINT), (MIDPOINT, 0)];
370 macro_rules! ind {
371 ($x:expr) => {
372 *self.mem.get_unchecked(($x as uint >> 3) & (RAND_SIZE_64 - 1))
373 }
374 }
375
376 for &(mr_offset, m2_offset) in MP_VEC.iter() {
377 for base in range(0, MIDPOINT / 4).map(|i| i * 4) {
378
379 macro_rules! rngstepp {
380 ($j:expr, $shift:expr) => {{
381 let base = base + $j;
382 let mix = a ^ (a << $shift as uint);
383 let mix = if $j == 0 {!mix} else {mix};
384
385 unsafe {
386 let x = *self.mem.get_unchecked(base + mr_offset);
387 a = mix + *self.mem.get_unchecked(base + m2_offset);
388 let y = ind!(x) + a + b;
389 *self.mem.get_unchecked_mut(base + mr_offset) = y;
390
391 b = ind!(y >> RAND_SIZE_64_LEN) + x;
392 *self.rsl.get_unchecked_mut(base + mr_offset) = b;
393 }
394 }}
395 }
396
397 macro_rules! rngstepn {
398 ($j:expr, $shift:expr) => {{
399 let base = base + $j;
400 let mix = a ^ (a >> $shift as uint);
401 let mix = if $j == 0 {!mix} else {mix};
402
403 unsafe {
404 let x = *self.mem.get_unchecked(base + mr_offset);
405 a = mix + *self.mem.get_unchecked(base + m2_offset);
406 let y = ind!(x) + a + b;
407 *self.mem.get_unchecked_mut(base + mr_offset) = y;
408
409 b = ind!(y >> RAND_SIZE_64_LEN) + x;
410 *self.rsl.get_unchecked_mut(base + mr_offset) = b;
411 }
412 }}
413 }
414
415 rngstepp!(0u, 21);
416 rngstepn!(1u, 5);
417 rngstepp!(2u, 12);
418 rngstepn!(3u, 33);
419 }
420 }
421
422 self.a = a;
423 self.b = b;
424 self.cnt = RAND_SIZE_64;
425 }
426}
427
428// Cannot be derived because [u32; 256] does not implement Clone
429impl Clone for Isaac64Rng {
430 fn clone(&self) -> Isaac64Rng {
431 *self
432 }
433}
434
435impl Rng for Isaac64Rng {
436 // FIXME #7771: having next_u32 like this should be unnecessary
437 #[inline]
438 fn next_u32(&mut self) -> u32 {
439 self.next_u64() as u32
440 }
441
442 #[inline]
443 fn next_u64(&mut self) -> u64 {
444 if self.cnt == 0 {
445 // make some more numbers
446 self.isaac64();
447 }
448 self.cnt -= 1;
449
450 // See corresponding location in IsaacRng.next_u32 for
451 // explanation.
452 debug_assert!(self.cnt < RAND_SIZE_64);
453 self.rsl[(self.cnt % RAND_SIZE_64) as uint]
454 }
455}
456
457impl<'a> SeedableRng<&'a [u64]> for Isaac64Rng {
458 fn reseed(&mut self, seed: &'a [u64]) {
459 // make the seed into [seed[0], seed[1], ..., seed[seed.len()
460 // - 1], 0, 0, ...], to fill rng.rsl.
461 let seed_iter = seed.iter().map(|&x| x).chain(repeat(0u64));
462
463 for (rsl_elem, seed_elem) in self.rsl.iter_mut().zip(seed_iter) {
464 *rsl_elem = seed_elem;
465 }
466 self.cnt = 0;
467 self.a = 0;
468 self.b = 0;
469 self.c = 0;
470
471 self.init(true);
472 }
473
474 /// Create an ISAAC random number generator with a seed. This can
475 /// be any length, although the maximum number of elements used is
476 /// 256 and any more will be silently ignored. A generator
477 /// constructed with a given seed will generate the same sequence
478 /// of values as all other generators constructed with that seed.
479 fn from_seed(seed: &'a [u64]) -> Isaac64Rng {
480 let mut rng = EMPTY_64;
481 rng.reseed(seed);
482 rng
483 }
484}
485
486impl Rand for Isaac64Rng {
487 fn rand<R: Rng>(other: &mut R) -> Isaac64Rng {
488 let mut ret = EMPTY_64;
489 unsafe {
490 let ptr = ret.rsl.as_mut_ptr() as *mut u8;
491
492 let slice = slice::from_raw_mut_buf(&ptr, (RAND_SIZE_64 * 8) as uint);
493 other.fill_bytes(slice);
494 }
495 ret.cnt = 0;
496 ret.a = 0;
497 ret.b = 0;
498 ret.c = 0;
499
500 ret.init(true);
501 return ret;
502 }
503}
504
505
506#[cfg(test)]
507mod test {
508 use std::prelude::v1::*;
509
510 use core::iter::order;
511 use {Rng, SeedableRng};
512 use super::{IsaacRng, Isaac64Rng};
513
514 #[test]
515 fn test_rng_32_rand_seeded() {
516 let s = ::test::rng().gen_iter::<u32>().take(256).collect::<Vec<u32>>();
517 let mut ra: IsaacRng = SeedableRng::from_seed(s.as_slice());
518 let mut rb: IsaacRng = SeedableRng::from_seed(s.as_slice());
519 assert!(order::equals(ra.gen_ascii_chars().take(100),
520 rb.gen_ascii_chars().take(100)));
521 }
522 #[test]
523 fn test_rng_64_rand_seeded() {
524 let s = ::test::rng().gen_iter::<u64>().take(256).collect::<Vec<u64>>();
525 let mut ra: Isaac64Rng = SeedableRng::from_seed(s.as_slice());
526 let mut rb: Isaac64Rng = SeedableRng::from_seed(s.as_slice());
527 assert!(order::equals(ra.gen_ascii_chars().take(100),
528 rb.gen_ascii_chars().take(100)));
529 }
530
531 #[test]
532 fn test_rng_32_seeded() {
533 let seed: &[_] = &[1, 23, 456, 7890, 12345];
534 let mut ra: IsaacRng = SeedableRng::from_seed(seed);
535 let mut rb: IsaacRng = SeedableRng::from_seed(seed);
536 assert!(order::equals(ra.gen_ascii_chars().take(100),
537 rb.gen_ascii_chars().take(100)));
538 }
539 #[test]
540 fn test_rng_64_seeded() {
541 let seed: &[_] = &[1, 23, 456, 7890, 12345];
542 let mut ra: Isaac64Rng = SeedableRng::from_seed(seed);
543 let mut rb: Isaac64Rng = SeedableRng::from_seed(seed);
544 assert!(order::equals(ra.gen_ascii_chars().take(100),
545 rb.gen_ascii_chars().take(100)));
546 }
547
548 #[test]
549 fn test_rng_32_reseed() {
550 let s = ::test::rng().gen_iter::<u32>().take(256).collect::<Vec<u32>>();
551 let mut r: IsaacRng = SeedableRng::from_seed(s.as_slice());
552 let string1: String = r.gen_ascii_chars().take(100).collect();
553
554 r.reseed(s.as_slice());
555
556 let string2: String = r.gen_ascii_chars().take(100).collect();
557 assert_eq!(string1, string2);
558 }
559 #[test]
560 fn test_rng_64_reseed() {
561 let s = ::test::rng().gen_iter::<u64>().take(256).collect::<Vec<u64>>();
562 let mut r: Isaac64Rng = SeedableRng::from_seed(s.as_slice());
563 let string1: String = r.gen_ascii_chars().take(100).collect();
564
565 r.reseed(s.as_slice());
566
567 let string2: String = r.gen_ascii_chars().take(100).collect();
568 assert_eq!(string1, string2);
569 }
570
571 #[test]
572 fn test_rng_32_true_values() {
573 let seed: &[_] = &[1, 23, 456, 7890, 12345];
574 let mut ra: IsaacRng = SeedableRng::from_seed(seed);
575 // Regression test that isaac is actually using the above vector
576 let v = range(0, 10).map(|_| ra.next_u32()).collect::<Vec<_>>();
577 assert_eq!(v,
578 vec!(2558573138, 873787463, 263499565, 2103644246, 3595684709,
579 4203127393, 264982119, 2765226902, 2737944514, 3900253796));
580
581 let seed: &[_] = &[12345, 67890, 54321, 9876];
582 let mut rb: IsaacRng = SeedableRng::from_seed(seed);
583 // skip forward to the 10000th number
584 for _ in range(0u, 10000) { rb.next_u32(); }
585
586 let v = range(0, 10).map(|_| rb.next_u32()).collect::<Vec<_>>();
587 assert_eq!(v,
588 vec!(3676831399, 3183332890, 2834741178, 3854698763, 2717568474,
589 1576568959, 3507990155, 179069555, 141456972, 2478885421));
590 }
591 #[test]
592 fn test_rng_64_true_values() {
593 let seed: &[_] = &[1, 23, 456, 7890, 12345];
594 let mut ra: Isaac64Rng = SeedableRng::from_seed(seed);
595 // Regression test that isaac is actually using the above vector
596 let v = range(0, 10).map(|_| ra.next_u64()).collect::<Vec<_>>();
597 assert_eq!(v,
598 vec!(547121783600835980, 14377643087320773276, 17351601304698403469,
599 1238879483818134882, 11952566807690396487, 13970131091560099343,
600 4469761996653280935, 15552757044682284409, 6860251611068737823,
601 13722198873481261842));
602
603 let seed: &[_] = &[12345, 67890, 54321, 9876];
604 let mut rb: Isaac64Rng = SeedableRng::from_seed(seed);
605 // skip forward to the 10000th number
606 for _ in range(0u, 10000) { rb.next_u64(); }
607
608 let v = range(0, 10).map(|_| rb.next_u64()).collect::<Vec<_>>();
609 assert_eq!(v,
610 vec!(18143823860592706164, 8491801882678285927, 2699425367717515619,
611 17196852593171130876, 2606123525235546165, 15790932315217671084,
612 596345674630742204, 9947027391921273664, 11788097613744130851,
613 10391409374914919106));
614 }
615
616 #[test]
617 fn test_rng_clone() {
618 let seed: &[_] = &[1, 23, 456, 7890, 12345];
619 let mut rng: Isaac64Rng = SeedableRng::from_seed(seed);
620 let mut clone = rng.clone();
621 for _ in range(0u, 16) {
622 assert_eq!(rng.next_u64(), clone.next_u64());
623 }
624 }
625}