]> git.proxmox.com Git - rustc.git/blame - src/librand/reseeding.rs
Imported Upstream version 1.6.0+dfsg1
[rustc.git] / src / librand / reseeding.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//! A wrapper around another RNG that reseeds it after it
12//! generates a certain number of random bytes.
13
1a4d82fc 14use {Rng, SeedableRng};
1a4d82fc
JJ
15
16/// How many bytes of entropy the underling RNG is allowed to generate
17/// before it is reseeded.
c34b1796 18const DEFAULT_GENERATION_THRESHOLD: usize = 32 * 1024;
1a4d82fc
JJ
19
20/// A wrapper around any RNG which reseeds the underlying RNG after it
21/// has generated a certain number of random bytes.
22pub struct ReseedingRng<R, Rsdr> {
23 rng: R,
c34b1796
AL
24 generation_threshold: usize,
25 bytes_generated: usize,
1a4d82fc
JJ
26 /// Controls the behaviour when reseeding the RNG.
27 pub reseeder: Rsdr,
28}
29
30impl<R: Rng, Rsdr: Reseeder<R>> ReseedingRng<R, Rsdr> {
31 /// Create a new `ReseedingRng` with the given parameters.
32 ///
33 /// # Arguments
34 ///
35 /// * `rng`: the random number generator to use.
36 /// * `generation_threshold`: the number of bytes of entropy at which to reseed the RNG.
37 /// * `reseeder`: the reseeding object to use.
b039eaaf 38 pub fn new(rng: R, generation_threshold: usize, reseeder: Rsdr) -> ReseedingRng<R, Rsdr> {
1a4d82fc
JJ
39 ReseedingRng {
40 rng: rng,
41 generation_threshold: generation_threshold,
42 bytes_generated: 0,
b039eaaf 43 reseeder: reseeder,
1a4d82fc
JJ
44 }
45 }
46
47 /// Reseed the internal RNG if the number of bytes that have been
48 /// generated exceed the threshold.
49 pub fn reseed_if_necessary(&mut self) {
50 if self.bytes_generated >= self.generation_threshold {
51 self.reseeder.reseed(&mut self.rng);
52 self.bytes_generated = 0;
53 }
54 }
55}
56
57
58impl<R: Rng, Rsdr: Reseeder<R>> Rng for ReseedingRng<R, Rsdr> {
59 fn next_u32(&mut self) -> u32 {
60 self.reseed_if_necessary();
61 self.bytes_generated += 4;
62 self.rng.next_u32()
63 }
64
65 fn next_u64(&mut self) -> u64 {
66 self.reseed_if_necessary();
67 self.bytes_generated += 8;
68 self.rng.next_u64()
69 }
70
71 fn fill_bytes(&mut self, dest: &mut [u8]) {
72 self.reseed_if_necessary();
73 self.bytes_generated += dest.len();
74 self.rng.fill_bytes(dest)
75 }
76}
77
78impl<S, R: SeedableRng<S>, Rsdr: Reseeder<R> + Default>
79 SeedableRng<(Rsdr, S)> for ReseedingRng<R, Rsdr> {
80 fn reseed(&mut self, (rsdr, seed): (Rsdr, S)) {
81 self.rng.reseed(seed);
82 self.reseeder = rsdr;
83 self.bytes_generated = 0;
84 }
85
86 /// Create a new `ReseedingRng` from the given reseeder and
87 /// seed. This uses a default value for `generation_threshold`.
88 fn from_seed((rsdr, seed): (Rsdr, S)) -> ReseedingRng<R, Rsdr> {
89 ReseedingRng {
90 rng: SeedableRng::from_seed(seed),
91 generation_threshold: DEFAULT_GENERATION_THRESHOLD,
92 bytes_generated: 0,
b039eaaf 93 reseeder: rsdr,
1a4d82fc
JJ
94 }
95 }
96}
97
98/// Something that can be used to reseed an RNG via `ReseedingRng`.
1a4d82fc
JJ
99pub trait Reseeder<R> {
100 /// Reseed the given RNG.
101 fn reseed(&mut self, rng: &mut R);
102}
103
104/// Reseed an RNG using a `Default` instance. This reseeds by
105/// replacing the RNG with the result of a `Default::default` call.
c34b1796
AL
106#[derive(Copy, Clone)]
107pub struct ReseedWithDefault;
1a4d82fc
JJ
108
109impl<R: Rng + Default> Reseeder<R> for ReseedWithDefault {
110 fn reseed(&mut self, rng: &mut R) {
111 *rng = Default::default();
112 }
113}
85aaf69f 114#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 115impl Default for ReseedWithDefault {
b039eaaf
SL
116 fn default() -> ReseedWithDefault {
117 ReseedWithDefault
118 }
1a4d82fc
JJ
119}
120
121#[cfg(test)]
d9579d0f 122mod tests {
1a4d82fc
JJ
123 use std::prelude::v1::*;
124
b039eaaf 125 use core::iter::order;
1a4d82fc 126 use super::{ReseedingRng, ReseedWithDefault};
1a4d82fc
JJ
127 use {SeedableRng, Rng};
128
129 struct Counter {
b039eaaf 130 i: u32,
1a4d82fc
JJ
131 }
132
133 impl Rng for Counter {
134 fn next_u32(&mut self) -> u32 {
135 self.i += 1;
136 // very random
137 self.i - 1
138 }
139 }
140 impl Default for Counter {
141 fn default() -> Counter {
142 Counter { i: 0 }
143 }
144 }
145 impl SeedableRng<u32> for Counter {
146 fn reseed(&mut self, seed: u32) {
147 self.i = seed;
148 }
149 fn from_seed(seed: u32) -> Counter {
150 Counter { i: seed }
151 }
152 }
153 type MyRng = ReseedingRng<Counter, ReseedWithDefault>;
154
155 #[test]
156 fn test_reseeding() {
b039eaaf 157 let mut rs = ReseedingRng::new(Counter { i: 0 }, 400, ReseedWithDefault);
1a4d82fc
JJ
158
159 let mut i = 0;
85aaf69f 160 for _ in 0..1000 {
1a4d82fc
JJ
161 assert_eq!(rs.next_u32(), i % 100);
162 i += 1;
163 }
164 }
165
166 #[test]
167 fn test_rng_seeded() {
168 let mut ra: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2));
169 let mut rb: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2));
170 assert!(order::equals(ra.gen_ascii_chars().take(100),
171 rb.gen_ascii_chars().take(100)));
172 }
173
174 #[test]
175 fn test_rng_reseed() {
176 let mut r: MyRng = SeedableRng::from_seed((ReseedWithDefault, 3));
177 let string1: String = r.gen_ascii_chars().take(100).collect();
178
179 r.reseed((ReseedWithDefault, 3));
180
181 let string2: String = r.gen_ascii_chars().take(100).collect();
182 assert_eq!(string1, string2);
183 }
184
c34b1796 185 const FILL_BYTES_V_LEN: usize = 13579;
1a4d82fc
JJ
186 #[test]
187 fn test_rng_fill_bytes() {
c1a9b12d 188 let mut v = vec![0; FILL_BYTES_V_LEN];
85aaf69f 189 ::test::rng().fill_bytes(&mut v);
1a4d82fc
JJ
190
191 // Sanity test: if we've gotten here, `fill_bytes` has not infinitely
192 // recursed.
193 assert_eq!(v.len(), FILL_BYTES_V_LEN);
194
195 // To test that `fill_bytes` actually did something, check that the
196 // average of `v` is not 0.
197 let mut sum = 0.0;
85aaf69f 198 for &x in &v {
1a4d82fc
JJ
199 sum += x as f64;
200 }
201 assert!(sum / v.len() as f64 != 0.0);
202 }
203}