event_queue/
barrier.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use futures::channel::mpsc;
use futures::never::Never;
use futures::task::{Context, Poll};
use futures::{Future, Stream};
use std::pin::Pin;

/// A barrier allows an async task to wait for all blocks to be dropped.
#[derive(Debug)]
pub struct Barrier(mpsc::Receiver<Never>);

/// Any clone of a barrier block prevents the associated [`Barrier`] future from completing.
#[derive(Debug, Clone)]
pub struct BarrierBlock(#[expect(dead_code)] mpsc::Sender<Never>);

impl Barrier {
    /// Creates a new barrier and associated blocker.
    ///
    /// The future that is [`Barrier`] resolves when all clones of [`BarrierBlock`] are dropped.
    pub fn new() -> (Self, BarrierBlock) {
        let (send, recv) = mpsc::channel(0);
        (Self(recv), BarrierBlock(send))
    }
}

impl Future for Barrier {
    type Output = ();

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let recv = Pin::new(&mut self.get_mut().0);
        recv.poll_next(cx).map(|_| ())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use futures::prelude::*;

    #[test]
    fn drop_single_block_unblocks_barrier() {
        let (barrier, _) = Barrier::new();
        assert_eq!(barrier.now_or_never(), Some(()));
    }

    #[test]
    fn single_block_blocks_barrier() {
        let mut executor = fuchsia_async::TestExecutor::new();

        let (mut barrier, block) = Barrier::new();
        assert_eq!(executor.run_until_stalled(&mut barrier), Poll::Pending);

        drop(block);
        assert_eq!(executor.run_until_stalled(&mut barrier), Poll::Ready(()));
    }

    #[test]
    fn block_clone_blocks_barrier() {
        let mut executor = fuchsia_async::TestExecutor::new();

        let (mut barrier, block) = Barrier::new();
        let block_clone = block.clone();
        assert_eq!(executor.run_until_stalled(&mut barrier), Poll::Pending);

        drop(block);
        assert_eq!(executor.run_until_stalled(&mut barrier), Poll::Pending);

        drop(block_clone);
        assert_eq!(executor.run_until_stalled(&mut barrier), Poll::Ready(()));
    }
}