1#[derive(Clone)]
12pub struct Parks {
13 #[cfg(any(test, feature = "test-utils"))]
14 inner: std::sync::Arc<ParkCounts>,
15}
16
17#[cfg(any(test, feature = "test-utils"))]
18struct ParkCounts {
19 polls: std::sync::atomic::AtomicU64,
21 parked: tokio::sync::watch::Sender<u64>,
23 waker: std::sync::Mutex<Option<std::task::Waker>>,
25}
26
27pub struct LoopRunning<'a> {
29 #[cfg(any(test, feature = "test-utils"))]
30 parks: &'a Parks,
31 #[cfg(not(any(test, feature = "test-utils")))]
32 parks: std::marker::PhantomData<&'a Parks>,
33}
34
35impl Drop for LoopRunning<'_> {
36 fn drop(&mut self) {
37 #[cfg(any(test, feature = "test-utils"))]
38 self.parks.inner.parked.send_modify(|parked| *parked = u64::MAX);
39 }
40}
41
42impl Parks {
43 pub fn new() -> Self {
45 Self {
46 #[cfg(any(test, feature = "test-utils"))]
47 inner: std::sync::Arc::new(ParkCounts {
48 polls: std::sync::atomic::AtomicU64::new(0),
49 parked: tokio::sync::watch::channel(0).0,
50 waker: std::sync::Mutex::new(None),
51 }),
52 }
53 }
54
55 pub fn running(&self) -> LoopRunning<'_> {
57 #[cfg(any(test, feature = "test-utils"))]
58 return LoopRunning { parks: self };
59 #[cfg(not(any(test, feature = "test-utils")))]
60 LoopRunning { parks: std::marker::PhantomData }
61 }
62
63 pub fn polling(&self) -> impl std::future::Future<Output = std::convert::Infallible> + '_ {
65 #[cfg(any(test, feature = "test-utils"))]
66 return std::future::poll_fn(|context| {
67 self.inner.polls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
68 let mut waker = coven_foundation::locks::lock_unpoisoned(&self.inner.waker);
69 match &mut *waker {
70 Some(waker) => waker.clone_from(context.waker()),
71 None => *waker = Some(context.waker().clone()),
72 }
73 std::task::Poll::Pending
74 });
75 #[cfg(not(any(test, feature = "test-utils")))]
76 std::future::pending()
77 }
78
79 pub fn parked(&self) -> impl std::future::Future<Output = std::convert::Infallible> + '_ {
82 #[cfg(any(test, feature = "test-utils"))]
83 return std::future::poll_fn(|_| {
84 let poll = self.inner.polls.load(std::sync::atomic::Ordering::SeqCst);
85 self.inner.parked.send_modify(|parked| *parked = (*parked).max(poll));
86 std::task::Poll::Pending
87 });
88 #[cfg(not(any(test, feature = "test-utils")))]
89 std::future::pending()
90 }
91
92 #[cfg(any(test, feature = "test-utils"))]
97 pub fn parked_from_now(&self) -> impl std::future::Future<Output = ()> + Send + 'static {
98 let mut parked = self.inner.parked.subscribe();
99 let now = self.inner.polls.load(std::sync::atomic::Ordering::SeqCst);
100 if let Some(waker) = &*coven_foundation::locks::lock_unpoisoned(&self.inner.waker) {
101 waker.wake_by_ref();
102 }
103 async move {
104 coven_foundation::clock::within(parked.wait_for(|parked| *parked > now))
105 .await
106 .expect("the loop parks")
107 .expect("the loop's parks are kept");
108 }
109 }
110}