Path: blob/main/crates/wasi-common/src/tokio/sched/unix.rs
2465 views
use crate::{1Error,2sched::{3Poll,4subscription::{RwEventFlags, Subscription},5},6};7use std::future::Future;8use std::pin::Pin;9use std::task::{Context, Poll as FPoll};1011struct FirstReady<'a, T>(Vec<Pin<Box<dyn Future<Output = T> + Send + 'a>>>);1213impl<'a, T> FirstReady<'a, T> {14fn new() -> Self {15FirstReady(Vec::new())16}17fn push(&mut self, f: impl Future<Output = T> + Send + 'a) {18self.0.push(Box::pin(f));19}20}2122impl<'a, T> Future for FirstReady<'a, T> {23type Output = T;24fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> FPoll<T> {25let mut result = FPoll::Pending;26for f in self.as_mut().0.iter_mut() {27match f.as_mut().poll(cx) {28FPoll::Ready(r) => match result {29// First ready gets to set the result. But, continue the loop so all futures30// which are ready simultaneously (often on first poll) get to report their31// readiness.32FPoll::Pending => {33result = FPoll::Ready(r);34}35_ => {}36},37_ => continue,38}39}40return result;41}42}4344pub async fn poll_oneoff<'a>(poll: &mut Poll<'a>) -> Result<(), Error> {45if poll.is_empty() {46return Ok(());47}4849let duration = poll50.earliest_clock_deadline()51.map(|sub| sub.duration_until());5253let mut futures = FirstReady::new();54for s in poll.rw_subscriptions() {55match s {56Subscription::Read(f) => {57futures.push(async move {58f.file59.readable()60.await61.map_err(|e| e.context("readable future"))?;62f.complete(63f.file64.num_ready_bytes()65.map_err(|e| e.context("read num_ready_bytes"))?,66RwEventFlags::empty(),67);68Ok::<(), Error>(())69});70}7172Subscription::Write(f) => {73futures.push(async move {74f.file75.writable()76.await77.map_err(|e| e.context("writable future"))?;78f.complete(0, RwEventFlags::empty());79Ok(())80});81}82Subscription::MonotonicClock { .. } => unreachable!(),83}84}85if let Some(Some(remaining_duration)) = duration {86match tokio::time::timeout(remaining_duration, futures).await {87Ok(r) => r?,88Err(_deadline_elapsed) => {}89}90} else {91futures.await?;92}9394Ok(())95}969798