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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#![allow(clippy::unreadable_literal)]

pub struct Otp<R>(R);

/** A "random number generator" which reads from a source.

	This is useful for crypto with a one-time-pad or for situations where you want to control the sequence of generated numbers.

	Integers read from this RNG are read little-endian from the underlying source.
*/
impl<R: std::io::Read> Otp<R> {
	pub fn new(source: R) -> Self {
		Self(source)
	}
}

impl<R: std::io::Read> rand::RngCore for Otp<R> {
	fn next_u32(&mut self) -> u32 {
		let mut buf = [0; 4];
		self.0.read_exact(&mut buf).unwrap();
		u32::from_le_bytes(buf)
	}

	fn next_u64(&mut self) -> u64 {
		let mut buf = [0; 8];
		self.0.read_exact(&mut buf).unwrap();
		u64::from_le_bytes(buf)
	}

	fn fill_bytes(&mut self, buf: &mut [u8]) {
		self.0.read_exact(buf).unwrap();
	}

	fn try_fill_bytes(&mut self, buf: &mut [u8]) -> Result<(), rand::Error> {
		self.0.read(buf)
			.and_then(|len| match len {
				0 => Err(std::io::ErrorKind::UnexpectedEof.into()),
				_ => Ok(()),
			})
			.map_err(rand::Error::new)
	}
}

#[test]
fn test_basic() {
	use rand::RngCore;

	let buf = [
		1, 2, 3, 4,
		4, 3, 2, 1,
		8, 9, 10, 11, 12, 13, 14, 15,
		255,
	];

	let mut rng = Otp::new(&buf[..]);
	assert_eq!(rng.next_u32(), 0x04030201);
	assert_eq!(rng.next_u32(), 0x01020304);

	assert_eq!(rng.next_u64(), 0x0F0E0D0C0B0A0908);

	let mut out = [0; 1];
	rng.fill_bytes(&mut out);
	assert_eq!(out, [255]);

	assert!(rng.try_fill_bytes(&mut out).is_err());
}

#[test]
fn test_urandom() {
	use rand::RngCore;

	let f = std::fs::File::open("/dev/urandom").unwrap();

	let mut rng = Otp::new(f);
	rng.next_u32();
	rng.next_u64();
	rng.fill_bytes(&mut [0; 32]);
	assert!(rng.try_fill_bytes(&mut [0; 32]).is_ok());
}

#[test]
#[should_panic(expected = "UnexpectedEof")]
fn test_eof() {
	use rand::RngCore;

	let buf = [
		1, 2, 3, 4,
	];

	Otp::new(&buf[..]).next_u64();
}