-
Notifications
You must be signed in to change notification settings - Fork 75
/
random.rs
69 lines (55 loc) · 1.53 KB
/
random.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
use anyhow::Result;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use std::io::Cursor;
//------------------------------------
// A simple linear congruence generator used to create the data to
// go into the thin/cache blocks.
pub struct Generator {
x: u64,
a: u64,
c: u64,
}
impl Generator {
pub fn new() -> Generator {
Generator {
x: 0,
a: 6364136223846793005,
c: 1442695040888963407,
}
}
fn step(&mut self) {
self.x = self.a.wrapping_mul(self.x).wrapping_add(self.c)
}
pub fn fill_buffer(&mut self, seed: u64, bytes: &mut [u8]) -> Result<()> {
self.x = seed;
assert!(bytes.len() % 8 == 0);
let nr_words = bytes.len() / 8;
let mut out = Cursor::new(bytes);
for _ in 0..nr_words {
out.write_u64::<LittleEndian>(self.x)?;
self.step();
}
Ok(())
}
pub fn verify_buffer(&mut self, seed: u64, bytes: &[u8]) -> Result<bool> {
self.x = seed;
assert!(bytes.len() % 8 == 0);
let nr_words = bytes.len() / 8;
let mut input = Cursor::new(bytes);
for _ in 0..nr_words {
let w = input.read_u64::<LittleEndian>()?;
if w != self.x {
eprintln!("{} != {}", w, self.x);
return Ok(false);
}
self.step();
}
Ok(true)
}
}
impl Default for Generator {
fn default() -> Self {
Self::new()
}
}
//------------------------------------