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