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