1#[cfg(any(
2 all(any(feature = "client", feature = "server"), feature = "http2"),
3 all(feature = "server", feature = "http1"),
4))]
5use std::time::Duration;
6use std::{fmt, sync::Arc};
7use std::{pin::Pin, time::Instant};
8
9use crate::rt::Sleep;
10use crate::rt::Timer;
11
12#[derive(Clone)]
14pub(crate) enum Time {
15 Timer(Arc<dyn Timer + Send + Sync>),
16 Empty,
17}
18
19#[cfg(all(feature = "server", feature = "http1"))]
20#[derive(Clone, Copy, Debug)]
21pub(crate) enum Dur {
22 Default(Option<Duration>),
23 Configured(Option<Duration>),
24}
25
26impl fmt::Debug for Time {
27 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28 f.debug_struct("Time").finish()
29 }
30}
31
32impl Time {
33 #[cfg(all(any(feature = "client", feature = "server"), feature = "http2"))]
34 pub(crate) fn sleep(&self, duration: Duration) -> Pin<Box<dyn Sleep>> {
35 match &self {
36 #[allow(clippy::panic)]
37 Time::Empty => {
38 panic!("You must supply a timer.")
39 }
40 Time::Timer(t) => t.sleep(duration),
41 }
42 }
43
44 #[cfg(all(feature = "server", feature = "http1"))]
45 pub(crate) fn sleep_until(&self, deadline: Instant) -> Pin<Box<dyn Sleep>> {
46 match &self {
47 #[allow(clippy::panic)]
48 Time::Empty => {
49 panic!("You must supply a timer.")
50 }
51 Time::Timer(t) => t.sleep_until(deadline),
52 }
53 }
54
55 pub(crate) fn now(&self) -> Instant {
56 match &self {
57 Time::Empty => Instant::now(),
58 Time::Timer(t) => t.now(),
59 }
60 }
61
62 pub(crate) fn reset(&self, sleep: &mut Pin<Box<dyn Sleep>>, new_deadline: Instant) {
63 match &self {
64 #[allow(clippy::panic)]
65 Time::Empty => {
66 panic!("You must supply a timer.")
67 }
68 Time::Timer(t) => t.reset(sleep, new_deadline),
69 }
70 }
71
72 #[cfg(all(feature = "server", feature = "http1"))]
73 pub(crate) fn check(&self, dur: Dur, name: &'static str) -> Option<Duration> {
74 match dur {
75 Dur::Default(Some(dur)) => match self {
76 Time::Empty => {
77 warn!("timeout `{}` has default, but no timer set", name,);
78 None
79 }
80 Time::Timer(..) => Some(dur),
81 },
82 Dur::Configured(Some(dur)) => match self {
83 #[allow(clippy::panic)]
84 Time::Empty => panic!("timeout `{name}` set, but no timer set"),
85 Time::Timer(..) => Some(dur),
86 },
87 Dur::Default(None) | Dur::Configured(None) => None,
88 }
89 }
90}