cros_async/
queue.rs

1// Copyright 2020 The ChromiumOS Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use std::collections::VecDeque;
6
7use async_task::Runnable;
8use sync::Mutex;
9
10/// A queue of `Runnables`. Intended to be used by executors to keep track of futures that have been
11/// scheduled to run.
12pub struct RunnableQueue {
13    runnables: Mutex<VecDeque<Runnable>>,
14}
15
16impl RunnableQueue {
17    /// Create a new, empty `RunnableQueue`.
18    pub fn new() -> RunnableQueue {
19        RunnableQueue {
20            runnables: Mutex::new(VecDeque::new()),
21        }
22    }
23
24    /// Schedule `runnable` to run in the future by adding it to this `RunnableQueue`.
25    pub fn push_back(&self, runnable: Runnable) {
26        self.runnables.lock().push_back(runnable);
27    }
28
29    /// Remove and return the first `Runnable` in this `RunnableQueue` or `None` if it is empty.
30    pub fn pop_front(&self) -> Option<Runnable> {
31        self.runnables.lock().pop_front()
32    }
33
34    /// Create an iterator over this `RunnableQueue` that repeatedly calls `pop_front()` until it is
35    /// empty.
36    pub fn iter(&self) -> RunnableQueueIter {
37        self.into_iter()
38    }
39}
40
41impl Default for RunnableQueue {
42    fn default() -> Self {
43        Self::new()
44    }
45}
46
47impl<'q> IntoIterator for &'q RunnableQueue {
48    type Item = Runnable;
49    type IntoIter = RunnableQueueIter<'q>;
50
51    fn into_iter(self) -> Self::IntoIter {
52        RunnableQueueIter { queue: self }
53    }
54}
55
56/// An iterator over a `RunnableQueue`.
57pub struct RunnableQueueIter<'q> {
58    queue: &'q RunnableQueue,
59}
60
61impl Iterator for RunnableQueueIter<'_> {
62    type Item = Runnable;
63    fn next(&mut self) -> Option<Self::Item> {
64        self.queue.pop_front()
65    }
66}