Rollup merge of #58442 - cuviper:unix-weak, r=alexcrichton
Simplify the unix `Weak` functionality - We can avoid allocation by adding a NUL to the function name. - We can get `Option<F>` directly, rather than aliasing the inner `AtomicUsize`.
This commit is contained in:
commit
b78e9f4fe3
@ -18,7 +18,7 @@
|
||||
|
||||
use libc;
|
||||
|
||||
use ffi::CString;
|
||||
use ffi::CStr;
|
||||
use marker;
|
||||
use mem;
|
||||
use sync::atomic::{AtomicUsize, Ordering};
|
||||
@ -26,7 +26,7 @@
|
||||
macro_rules! weak {
|
||||
(fn $name:ident($($t:ty),*) -> $ret:ty) => (
|
||||
static $name: ::sys::weak::Weak<unsafe extern fn($($t),*) -> $ret> =
|
||||
::sys::weak::Weak::new(stringify!($name));
|
||||
::sys::weak::Weak::new(concat!(stringify!($name), '\0'));
|
||||
)
|
||||
}
|
||||
|
||||
@ -45,23 +45,22 @@ pub const fn new(name: &'static str) -> Weak<F> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get(&self) -> Option<&F> {
|
||||
pub fn get(&self) -> Option<F> {
|
||||
assert_eq!(mem::size_of::<F>(), mem::size_of::<usize>());
|
||||
unsafe {
|
||||
if self.addr.load(Ordering::SeqCst) == 1 {
|
||||
self.addr.store(fetch(self.name), Ordering::SeqCst);
|
||||
}
|
||||
if self.addr.load(Ordering::SeqCst) == 0 {
|
||||
None
|
||||
} else {
|
||||
mem::transmute::<&AtomicUsize, Option<&F>>(&self.addr)
|
||||
match self.addr.load(Ordering::SeqCst) {
|
||||
0 => None,
|
||||
addr => Some(mem::transmute_copy::<usize, F>(&addr)),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn fetch(name: &str) -> usize {
|
||||
let name = match CString::new(name) {
|
||||
let name = match CStr::from_bytes_with_nul(name.as_bytes()) {
|
||||
Ok(cstr) => cstr,
|
||||
Err(..) => return 0,
|
||||
};
|
||||
|
Loading…
Reference in New Issue
Block a user