Skip to content

Commit

Permalink
Use pin macro instead of new_unchecked (#40)
Browse files Browse the repository at this point in the history
Addresses concerns that the variable was not being properly pinned.
  • Loading branch information
notgull authored Apr 30, 2023
1 parent 2232df7 commit f738cfd
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
15 changes: 15 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,21 @@ macro_rules! ready {
}};
}

/// Pins a variable on the stack.
///
/// TODO: Drop in favor of `core::pin::pin`, once MSRV is bumped to 1.68.
macro_rules! pin {
($($x:ident),* $(,)?) => {
$(
let mut $x = $x;
#[allow(unused_mut)]
let mut $x = unsafe {
std::pin::Pin::new_unchecked(&mut $x)
};
)*
}
}

mod barrier;
mod mutex;
mod once_cell;
Expand Down
8 changes: 3 additions & 5 deletions src/once_cell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use std::convert::Infallible;
use std::fmt;
use std::future::Future;
use std::mem::{forget, MaybeUninit};
use std::pin::Pin;
use std::ptr;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
Expand Down Expand Up @@ -750,7 +749,7 @@ impl<T> Drop for OnceCell<T> {
}

/// Either return the result of a future now, or panic.
fn now_or_never<T>(mut f: impl Future<Output = T>) -> T {
fn now_or_never<T>(f: impl Future<Output = T>) -> T {
const NOOP_WAKER: RawWakerVTable = RawWakerVTable::new(clone, wake, wake_by_ref, drop);

unsafe fn wake(_: *const ()) {}
Expand All @@ -760,15 +759,14 @@ fn now_or_never<T>(mut f: impl Future<Output = T>) -> T {
}
unsafe fn drop(_: *const ()) {}

// SAFETY: We don't move the future after we pin it here.
let future = unsafe { Pin::new_unchecked(&mut f) };
pin!(f);

let waker = unsafe { Waker::from_raw(RawWaker::new(ptr::null(), &NOOP_WAKER)) };

// Poll the future exactly once.
let mut cx = Context::from_waker(&waker);

match future.poll(&mut cx) {
match f.poll(&mut cx) {
Poll::Ready(value) => value,
Poll::Pending => unreachable!("future not ready"),
}
Expand Down

0 comments on commit f738cfd

Please sign in to comment.