Skip to content

Commit 618c6af

Browse files
committed
std::rand::os: use the externfn! macro for the Windows RNG.
1 parent d86de18 commit 618c6af

File tree

1 file changed

+16
-22
lines changed

1 file changed

+16
-22
lines changed

src/libstd/rand/os.rs

Lines changed: 16 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,13 @@ use rt::io::{file, Open, Read};
2121

2222
#[cfg(windows)]
2323
use cast;
24+
#[cfg(windows)]
25+
use libc::{c_long, DWORD, BYTE};
26+
#[cfg(windows)]
27+
type HCRYPTPROV = c_long;
28+
// the extern functions imported from the runtime on Windows are
29+
// implemented so that they either succeed or abort(), so we can just
30+
// assume they work when we call them.
2431

2532
/// A random number generator that retrieves randomness straight from
2633
/// the operating system. On Unix-like systems this reads from
@@ -38,7 +45,7 @@ pub struct OSRng {
3845
/// This does not block.
3946
#[cfg(windows)]
4047
pub struct OSRng {
41-
priv hcryptprov: raw::HCRYPTPROV
48+
priv hcryptprov: HCRYPTPROV
4249
}
4350

4451
impl OSRng {
@@ -53,10 +60,11 @@ impl OSRng {
5360

5461
/// Create a new `OSRng`.
5562
#[cfg(windows)]
56-
#[fixed_stack_segment] #[inline(never)]
5763
pub fn new() -> OSRng {
64+
externfn!(fn rust_win32_rand_acquire(phProv: *mut HCRYPTPROV))
65+
5866
let mut hcp = 0;
59-
unsafe {raw::rust_win32_rand_acquire(&mut hcp)};
67+
unsafe {rust_win32_rand_acquire(&mut hcp)};
6068

6169
OSRng { hcryptprov: hcp }
6270
}
@@ -87,12 +95,11 @@ impl Rng for OSRng {
8795
self.fill_bytes(v);
8896
unsafe { cast::transmute(v) }
8997
}
90-
#[fixed_stack_segment] #[inline(never)]
9198
fn fill_bytes(&mut self, v: &mut [u8]) {
92-
use libc::DWORD;
99+
externfn!(fn rust_win32_rand_gen(hProv: HCRYPTPROV, dwLen: DWORD, pbBuffer: *mut BYTE))
93100

94101
do v.as_mut_buf |ptr, len| {
95-
unsafe {raw::rust_win32_rand_gen(self.hcryptprov, len as DWORD, ptr)}
102+
unsafe {rust_win32_rand_gen(self.hcryptprov, len as DWORD, ptr)}
96103
}
97104
}
98105
}
@@ -105,27 +112,14 @@ impl Drop for OSRng {
105112
}
106113

107114
#[cfg(windows)]
108-
#[fixed_stack_segment] #[inline(never)]
109115
fn drop(&mut self) {
110-
unsafe {raw::rust_win32_rand_release(self.hcryptprov)}
111-
}
112-
}
116+
externfn!(fn rust_win32_rand_release(hProv: HCRYPTPROV))
113117

114-
#[cfg(windows)]
115-
mod raw {
116-
use libc::{c_long, DWORD, BYTE};
117-
118-
pub type HCRYPTPROV = c_long;
119-
120-
// these functions are implemented so that they either succeed or
121-
// abort(), so we can just assume they work when we call them.
122-
extern {
123-
pub fn rust_win32_rand_acquire(phProv: *mut HCRYPTPROV);
124-
pub fn rust_win32_rand_gen(hProv: HCRYPTPROV, dwLen: DWORD, pbBuffer: *mut BYTE);
125-
pub fn rust_win32_rand_release(hProv: HCRYPTPROV);
118+
unsafe {rust_win32_rand_release(self.hcryptprov)}
126119
}
127120
}
128121

122+
129123
#[cfg(test)]
130124
mod test {
131125
use super::*;

0 commit comments

Comments
 (0)