Skip to content

Commit 3eff0fc

Browse files
committed
Add LazyFd
1 parent 2e3e8eb commit 3eff0fc

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

src/lib.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -142,11 +142,11 @@ extern crate std;
142142

143143
mod error;
144144
pub use crate::error::Error;
145+
145146
#[allow(dead_code)]
146147
mod util;
147-
148-
// These targets need weak linkage to libc randomness functions.
149-
#[cfg(any(target_os = "macos", target_os = "solaris", target_os = "illumos"))]
148+
#[cfg(any(unix, target_os = "redox"))]
149+
#[allow(dead_code)]
150150
mod util_libc;
151151

152152
// System-specific implementations.

src/util_libc.rs

+24
Original file line numberDiff line numberDiff line change
@@ -36,3 +36,27 @@ impl Weak {
3636
NonNull::new(addr as *mut _)
3737
}
3838
}
39+
40+
pub struct LazyFd(LazyUsize);
41+
42+
impl LazyFd {
43+
pub const fn new() -> Self {
44+
Self(LazyUsize::new())
45+
}
46+
47+
pub fn init(&self, init: impl FnOnce() -> Option<libc::c_int>) -> Option<libc::c_int> {
48+
let fd = self.0.sync_init(
49+
|| match init() {
50+
Some(val) => val as usize,
51+
None => LazyUsize::UNINIT,
52+
},
53+
|| unsafe {
54+
libc::usleep(1000);
55+
},
56+
);
57+
match fd {
58+
LazyUsize::UNINIT => None,
59+
val => Some(val as libc::c_int),
60+
}
61+
}
62+
}

0 commit comments

Comments
 (0)