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:
Mazdak Farrokhzad 2019-02-24 05:55:58 +01:00 committed by GitHub
commit b78e9f4fe3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -18,7 +18,7 @@
use libc; use libc;
use ffi::CString; use ffi::CStr;
use marker; use marker;
use mem; use mem;
use sync::atomic::{AtomicUsize, Ordering}; use sync::atomic::{AtomicUsize, Ordering};
@ -26,7 +26,7 @@
macro_rules! weak { macro_rules! weak {
(fn $name:ident($($t:ty),*) -> $ret:ty) => ( (fn $name:ident($($t:ty),*) -> $ret:ty) => (
static $name: ::sys::weak::Weak<unsafe extern fn($($t),*) -> $ret> = 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>()); assert_eq!(mem::size_of::<F>(), mem::size_of::<usize>());
unsafe { unsafe {
if self.addr.load(Ordering::SeqCst) == 1 { if self.addr.load(Ordering::SeqCst) == 1 {
self.addr.store(fetch(self.name), Ordering::SeqCst); self.addr.store(fetch(self.name), Ordering::SeqCst);
} }
if self.addr.load(Ordering::SeqCst) == 0 { match self.addr.load(Ordering::SeqCst) {
None 0 => None,
} else { addr => Some(mem::transmute_copy::<usize, F>(&addr)),
mem::transmute::<&AtomicUsize, Option<&F>>(&self.addr)
} }
} }
} }
} }
unsafe fn fetch(name: &str) -> usize { 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, Ok(cstr) => cstr,
Err(..) => return 0, Err(..) => return 0,
}; };