Skip to content

Commit

Permalink
Make racey futures use an internal RNG
Browse files Browse the repository at this point in the history
This commit prevents these functions from needed to make calls into
thread-local storage for every poll.

Signed-off-by: John Nunley <dev@notgull.net>
  • Loading branch information
notgull committed Aug 24, 2023
1 parent 7896fcc commit 074c0ca
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
13 changes: 11 additions & 2 deletions src/future.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ use std::{
panic::{catch_unwind, AssertUnwindSafe, UnwindSafe},
};

#[cfg(feature = "std")]
use fastrand::Rng;

#[cfg(feature = "alloc")]
use alloc::boxed::Box;
use core::task::{Context, Poll};
Expand Down Expand Up @@ -480,7 +483,11 @@ where
F1: Future<Output = T>,
F2: Future<Output = T>,
{
Race { future1, future2 }
Race {
future1,
future2,
rng: Rng::new(),
}
}

#[cfg(feature = "std")]
Expand All @@ -493,6 +500,7 @@ pin_project! {
future1: F1,
#[pin]
future2: F2,
rng: Rng,
}
}

Expand All @@ -507,7 +515,7 @@ where
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();

if fastrand::bool() {
if this.rng.bool() {
if let Poll::Ready(t) = this.future1.poll(cx) {
return Poll::Ready(t);
}
Expand Down Expand Up @@ -644,6 +652,7 @@ pub trait FutureExt: Future {
Race {
future1: self,
future2: other,
rng: Rng::new(),
}
}

Expand Down
13 changes: 11 additions & 2 deletions src/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ use core::mem;
use core::pin::Pin;
use core::task::{Context, Poll};

#[cfg(feature = "std")]
use fastrand::Rng;

use pin_project_lite::pin_project;

use crate::ready;
Expand Down Expand Up @@ -1756,6 +1759,7 @@ pub trait StreamExt: Stream {
Race {
stream1: self,
stream2: other,
rng: Rng::new(),
}
}

Expand Down Expand Up @@ -2377,7 +2381,11 @@ where
S1: Stream<Item = T>,
S2: Stream<Item = T>,
{
Race { stream1, stream2 }
Race {
stream1,
stream2,
rng: Rng::new(),
}
}

#[cfg(feature = "std")]
Expand All @@ -2390,6 +2398,7 @@ pin_project! {
stream1: S1,
#[pin]
stream2: S2,
rng: Rng,
}
}

Expand All @@ -2404,7 +2413,7 @@ where
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut this = self.project();

if fastrand::bool() {
if this.rng.bool() {
if let Poll::Ready(Some(t)) = this.stream1.as_mut().poll_next(cx) {
return Poll::Ready(Some(t));
}
Expand Down

0 comments on commit 074c0ca

Please sign in to comment.