Skip to main content

simu/
timeout.rs

1// SPDX-FileCopyrightText: Copyright (c) Siemens 2026 contributed by Christoph Kuhmuench christoph.kuhmuench@gmail.com
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5use std::future::Future;
6use std::pin::Pin;
7use std::task::{Context, Poll};
8
9use crate::env::EnvHandle;
10
11/// A `Future` that resolves once simulated time reaches `deadline`.
12///
13/// On first poll it registers a wakeup in the event queue and returns
14/// `Pending`. The executor wakes it when the event fires, and the next
15/// poll returns `Ready`.
16#[derive(Debug)]
17pub struct Timeout {
18    deadline: f64,
19    scheduled: bool,
20    env: EnvHandle,
21}
22
23impl Timeout {
24    pub(crate) fn new(deadline: f64, env: EnvHandle) -> Self {
25        Timeout {
26            deadline,
27            scheduled: false,
28            env,
29        }
30    }
31}
32
33impl Future for Timeout {
34    type Output = ();
35
36    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
37        // Return Ready only when the deadline has actually been reached.
38        // Checking both flags guards against spurious re-polls that arrive
39        // before our deadline — for example when AllOf re-polls all sub-futures
40        // after one of its other futures fires.
41        if self.scheduled && self.env.now() >= self.deadline {
42            return Poll::Ready(());
43        }
44        if !self.scheduled {
45            self.env.schedule_wakeup(self.deadline, cx.waker().clone());
46            self.scheduled = true;
47        }
48        Poll::Pending
49    }
50}