Skip to content

Commit

Permalink
Rollup merge of rust-lang#58442 - cuviper:unix-weak, r=alexcrichton
Browse files Browse the repository at this point in the history
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`.
  • Loading branch information
Centril authored Feb 24, 2019
2 parents 4b755c1 + 33d80bf commit 2699132
Showing 1 changed file with 7 additions and 8 deletions.
15 changes: 7 additions & 8 deletions src/libstd/sys/unix/weak.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,15 @@
use libc;

use ffi::CString;
use ffi::CStr;
use marker;
use mem;
use sync::atomic::{AtomicUsize, Ordering};

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'));
)
}

Expand All @@ -45,23 +45,22 @@ impl<F> 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,
};
Expand Down

0 comments on commit 2699132

Please sign in to comment.