Skip to main content

mtorrent_utils/
loop_select.rs

1use std::ops::ControlFlow;
2use std::pin::Pin;
3use std::task::{Context, Poll, ready};
4use tokio::task;
5
6/// Type alias for the poll function signature used in [`loop_select`].
7pub type LoopSelectPollFn<D, O> = fn(&mut D, &mut Context<'_>) -> Poll<ControlFlow<O>>;
8
9/// Future returned by [`loop_select`].
10pub struct LoopSelect<'d, D, O, const N: usize> {
11    data: &'d mut D,
12    poll_fns: [LoopSelectPollFn<D, O>; N],
13}
14
15impl<D, O, const N: usize> Future for LoopSelect<'_, D, O, N> {
16    type Output = O;
17
18    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
19        let this = &mut *self;
20        loop {
21            let coop = ready!(task::coop::poll_proceed(cx));
22            let mut made_progress = false;
23            for poll_fn in &this.poll_fns {
24                match poll_fn(this.data, cx) {
25                    Poll::Ready(ControlFlow::Break(out)) => {
26                        coop.made_progress();
27                        return Poll::Ready(out);
28                    }
29                    Poll::Ready(ControlFlow::Continue(())) => {
30                        made_progress = true;
31                    }
32                    Poll::Pending => {}
33                }
34            }
35            if !made_progress {
36                return Poll::Pending;
37            }
38            coop.made_progress();
39        }
40    }
41}
42
43/// Run multiple poll functions in a loop until one of them returns [`ControlFlow::Break`].
44/// All functions have access to a mutable reference to the same data.
45///
46/// In each round, the functions are polled in the order of `poll_fns`. A poll function must:
47/// - return `Poll::Ready(ControlFlow::Break(output))` to finish the loop with `output`; the
48///   remaining functions are not polled in that round,
49/// - return `Poll::Ready(ControlFlow::Continue(()))` only if it made progress,
50/// - return `Poll::Pending` only after arranging for the waker in `cx` to be woken.
51///
52/// Rounds are repeated as long as at least one function made progress. The loop takes part in
53/// Tokio's cooperative scheduling, so a function that always returns `Continue` doesn't block
54/// the thread, but it keeps the task busy forever.
55///
56/// `poll_fns` must not be empty.
57pub fn loop_select<D, O, const N: usize>(
58    data: &mut D,
59    poll_fns: [LoopSelectPollFn<D, O>; N],
60) -> LoopSelect<'_, D, O, N> {
61    const { assert!(N > 0, "loop_select requires at least one poll function") };
62    LoopSelect { data, poll_fns }
63}
64
65#[cfg(test)]
66mod tests {
67    use super::*;
68    use tokio::sync::mpsc;
69    use tokio_test::task::spawn;
70    use tokio_test::{assert_pending, assert_ready_eq};
71
72    struct Counters {
73        counter1: usize,
74        counter2: usize,
75        target1: usize,
76        target2: usize,
77    }
78
79    impl Counters {
80        fn new(target1: usize, target2: usize) -> Self {
81            Self {
82                counter1: 0,
83                counter2: 0,
84                target1,
85                target2,
86            }
87        }
88    }
89
90    fn count1(ctx: &mut Counters, _cx: &mut Context<'_>) -> Poll<ControlFlow<usize>> {
91        if ctx.counter1 < ctx.target1 {
92            ctx.counter1 += 1;
93            Poll::Ready(ControlFlow::Continue(()))
94        } else {
95            Poll::Ready(ControlFlow::Break(1))
96        }
97    }
98
99    fn count2(ctx: &mut Counters, _cx: &mut Context<'_>) -> Poll<ControlFlow<usize>> {
100        if ctx.counter2 < ctx.target2 {
101            ctx.counter2 += 1;
102            Poll::Ready(ControlFlow::Continue(()))
103        } else {
104            Poll::Ready(ControlFlow::Break(2))
105        }
106    }
107
108    #[test]
109    fn test_polls_in_order_and_stops_at_first_break() {
110        let mut ctx = Counters::new(5, 3);
111        assert_ready_eq!(spawn(loop_select(&mut ctx, [count1, count2])).poll(), 2);
112        assert_eq!(ctx.counter1, 4);
113        assert_eq!(ctx.counter2, 3);
114
115        let mut ctx = Counters::new(5, 3);
116        assert_ready_eq!(spawn(loop_select(&mut ctx, [count2, count1])).poll(), 2);
117        assert_eq!(ctx.counter2, 3);
118        assert_eq!(ctx.counter1, 3);
119    }
120
121    #[test]
122    fn test_break_in_first_round() {
123        let mut ctx = Counters::new(0, 3);
124        assert_ready_eq!(spawn(loop_select(&mut ctx, [count1, count2])).poll(), 1);
125        assert_eq!(ctx.counter1, 0);
126        assert_eq!(ctx.counter2, 0);
127    }
128
129    struct Receivers {
130        rx1: mpsc::UnboundedReceiver<u32>,
131        rx2: mpsc::UnboundedReceiver<u32>,
132        received: Vec<u32>,
133    }
134
135    fn recv_into(
136        rx: &mut mpsc::UnboundedReceiver<u32>,
137        received: &mut Vec<u32>,
138        cx: &mut Context<'_>,
139    ) -> Poll<ControlFlow<Vec<u32>>> {
140        match rx.poll_recv(cx) {
141            Poll::Ready(Some(value)) => {
142                received.push(value);
143                Poll::Ready(ControlFlow::Continue(()))
144            }
145            Poll::Ready(None) => Poll::Ready(ControlFlow::Break(received.clone())),
146            Poll::Pending => Poll::Pending,
147        }
148    }
149
150    fn recv1(ctx: &mut Receivers, cx: &mut Context<'_>) -> Poll<ControlFlow<Vec<u32>>> {
151        recv_into(&mut ctx.rx1, &mut ctx.received, cx)
152    }
153
154    fn recv2(ctx: &mut Receivers, cx: &mut Context<'_>) -> Poll<ControlFlow<Vec<u32>>> {
155        recv_into(&mut ctx.rx2, &mut ctx.received, cx)
156    }
157
158    #[test]
159    fn test_pending_until_woken() {
160        let (tx1, rx1) = mpsc::unbounded_channel();
161        let (tx2, rx2) = mpsc::unbounded_channel();
162        let mut ctx = Receivers {
163            rx1,
164            rx2,
165            received: Vec::new(),
166        };
167        let mut fut = spawn(loop_select(&mut ctx, [recv1, recv2]));
168        assert_pending!(fut.poll());
169
170        tx2.send(1).unwrap();
171        assert!(fut.is_woken());
172        assert_pending!(fut.poll());
173
174        tx1.send(2).unwrap();
175        tx1.send(3).unwrap();
176        assert!(fut.is_woken());
177        assert_pending!(fut.poll());
178
179        drop(tx2);
180        assert!(fut.is_woken());
181        assert_ready_eq!(fut.poll(), vec![1, 2, 3]);
182    }
183
184    #[test]
185    fn test_continues_while_some_functions_pending() {
186        let (tx1, rx1) = mpsc::unbounded_channel();
187        let (_tx2, rx2) = mpsc::unbounded_channel();
188        let mut ctx = Receivers {
189            rx1,
190            rx2,
191            received: Vec::new(),
192        };
193        for value in 0..10 {
194            tx1.send(value).unwrap();
195        }
196        drop(tx1);
197        // rx2 stays pending, but rx1 keeps making progress until its channel is closed
198        assert_ready_eq!(
199            spawn(loop_select(&mut ctx, [recv2, recv1])).poll(),
200            (0..10).collect::<Vec<_>>()
201        );
202    }
203
204    fn always_continue(count: &mut usize, _cx: &mut Context<'_>) -> Poll<ControlFlow<()>> {
205        *count += 1;
206        if *count < 1_000_000 {
207            Poll::Ready(ControlFlow::Continue(()))
208        } else {
209            // Fail instead of hanging if the coop budget is not enforced
210            Poll::Ready(ControlFlow::Break(()))
211        }
212    }
213
214    #[tokio::test]
215    async fn test_yields_when_coop_budget_exhausted() {
216        let mut count = 0;
217        let mut fut = spawn(loop_select(&mut count, [always_continue]));
218        assert_pending!(fut.poll());
219        // Tokio defers the wakeup until the current task yields to the runtime
220        tokio::task::yield_now().await;
221        assert!(fut.is_woken());
222        drop(fut);
223        assert!(count > 0);
224        assert!(count < 1_000_000);
225    }
226}