async_time_mock_core/
timeout.rs1use crate::TimeHandlerGuard;
2use pin_project_lite::pin_project;
3use std::fmt::{Debug, Display, Formatter};
4use std::future::Future;
5use std::pin::Pin;
6use std::task::{Context, Poll};
7
8pin_project! {
9 pub struct Timeout<F> {
10 #[pin]
11 future: F,
12 sleep: Pin<Box<dyn Future<Output = TimeHandlerGuard> + Send>>,
13 }
14}
15
16impl<F> Timeout<F> {
17 pub(crate) fn new(future: F, sleep: impl Future<Output = TimeHandlerGuard> + Send + 'static) -> Self {
18 let sleep = Box::pin(sleep);
19 Self { sleep, future }
20 }
21
22 pub fn get_ref(&self) -> &F {
23 &self.future
24 }
25
26 pub fn get_mut(&mut self) -> &mut F {
27 &mut self.future
28 }
29
30 pub fn into_inner(self) -> F {
31 self.future
32 }
33}
34
35impl<F> Future for Timeout<F>
36where
37 F: Future,
38{
39 type Output = Result<F::Output, Elapsed>;
40
41 fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
42 let this = self.project();
43 use Poll::*;
44 if let Ready(guard) = this.sleep.as_mut().poll(context) {
45 return Ready(Err(Elapsed(guard)));
46 };
47
48 this.future.poll(context).map(Ok)
49 }
50}
51
52#[must_use = "Elapsed must be kept until the timer has performed it's side-effects"]
53pub struct Elapsed(pub TimeHandlerGuard);
54
55impl Display for Elapsed {
56 fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
57 formatter.write_str("Timeout elapsed.")
58 }
59}
60
61impl Debug for Elapsed {
62 fn fmt(&self, format: &mut Formatter<'_>) -> std::fmt::Result {
63 format.debug_tuple("Elapsed").finish()
64 }
65}