time: add #[track_caller] and panic docs to timeout_at() (#8077)

This commit is contained in:
Alice Ryhl
2026-04-20 20:22:36 +02:00
committed by GitHub
parent 1afb391350
commit 16bc4e2e28
2 changed files with 37 additions and 6 deletions
+20 -5
View File
@@ -142,16 +142,31 @@ where
/// }
/// # }
/// ```
///
/// # Panics
///
/// This function panics if there is no current timer set.
///
/// It can be triggered when [`Builder::enable_time`] or
/// [`Builder::enable_all`] are not included in the builder.
///
/// It can also panic whenever a timer is created outside of a
/// Tokio runtime. That is why `rt.block_on(sleep(...))` will panic,
/// since the function is executed outside of the runtime.
/// Whereas `rt.block_on(async {sleep(...).await})` doesn't panic.
/// And this is because wrapping the function on an async makes it lazy,
/// and so gets executed inside the runtime successfully without
/// panicking.
///
/// [`Builder::enable_time`]: crate::runtime::Builder::enable_time
/// [`Builder::enable_all`]: crate::runtime::Builder::enable_all
#[track_caller]
pub fn timeout_at<F>(deadline: Instant, future: F) -> Timeout<F::IntoFuture>
where
F: IntoFuture,
{
let delay = sleep_until(deadline);
Timeout {
value: future.into_future(),
delay,
}
Timeout::new_with_delay(future.into_future(), delay)
}
pin_project! {
+17 -1
View File
@@ -6,7 +6,7 @@ use futures::future;
use std::error::Error;
use std::time::Duration;
use tokio::runtime::{Builder, Runtime};
use tokio::time::{self, interval, interval_at, timeout, Instant};
use tokio::time::{self, interval, interval_at, timeout, timeout_at, Instant};
mod support {
pub mod panic;
@@ -131,6 +131,22 @@ fn timeout_panic_caller() -> Result<(), Box<dyn Error>> {
Ok(())
}
#[test]
fn timeout_at_panic_caller() -> Result<(), Box<dyn Error>> {
let panic_location_file = test_panic(|| {
// Runtime without `enable_time` so it has no current timer set.
let rt = Builder::new_current_thread().build().unwrap();
rt.block_on(async {
let _timeout = timeout_at(Instant::now(), future::pending::<()>());
});
});
// The panic location should be in this file
assert_eq!(&panic_location_file.unwrap(), file!());
Ok(())
}
fn current_thread() -> Runtime {
tokio::runtime::Builder::new_current_thread()
.enable_all()