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