Skip to content

Commit d80f5c1

Browse files
committed
Minimize unsafe regions
1 parent bc0c8da commit d80f5c1

File tree

1 file changed

+14
-16
lines changed

1 file changed

+14
-16
lines changed

rand_os/src/solarish.rs

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -126,33 +126,31 @@ type GetRandomFn = unsafe extern fn(*mut u8, libc::size_t, libc::c_uint)
126126
// Instead the stable APIs are exposed via libc. Cache the result of the
127127
// lookup for future calls. This is loosely modeled after the
128128
// libstd::sys::unix::weak macro which unfortunately is not exported.
129-
fn fetch() -> Option<&'static GetRandomFn> {
129+
fn fetch() -> Option<GetRandomFn> {
130130
static FPTR: AtomicUsize = AtomicUsize::new(1);
131131

132+
if FPTR.load(Ordering::SeqCst) == 1 {
133+
let name = "getrandom\0";
134+
let addr = unsafe {
135+
libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr() as *const _) as usize
136+
};
137+
FPTR.store(addr, Ordering::SeqCst);
138+
}
139+
140+
let ptr = FPTR.load(Ordering::SeqCst);
132141
unsafe {
133-
if FPTR.load(Ordering::SeqCst) == 1 {
134-
let name = "getrandom\0";
135-
let addr = libc::dlsym(libc::RTLD_DEFAULT,
136-
name.as_ptr() as *const _) as usize;
137-
FPTR.store(addr, Ordering::SeqCst);
138-
}
139-
140-
if FPTR.load(Ordering::SeqCst) == 0 {
141-
return None;
142-
} else {
143-
mem::transmute::<&AtomicUsize, Option<&GetRandomFn>>(&FPTR)
144-
}
145-
}
142+
mem::transmute::<usize, Option<GetRandomFn>>(ptr)
143+
}
146144
}
147145

148146
fn getrandom(buf: &mut [u8], blocking: bool) -> libc::ssize_t {
149147
const GRND_NONBLOCK: libc::c_uint = 0x0001;
150148
const GRND_RANDOM: libc::c_uint = 0x0002;
151149

152150
if let Some(rand) = fetch() {
151+
let flag = if blocking { 0 } else { GRND_NONBLOCK } | GRND_RANDOM;
153152
unsafe {
154-
rand(buf.as_mut_ptr(), buf.len(),
155-
if blocking { 0 } else { GRND_NONBLOCK } | GRND_RANDOM) as libc::ssize_t
153+
rand(buf.as_mut_ptr(), buf.len(), flag) as libc::ssize_t
156154
}
157155
} else {
158156
-1

0 commit comments

Comments
 (0)