xref: /aosp_15_r20/external/crosvm/cros_async/src/queue.rs (revision bb4ee6a4ae7042d18b07a98463b9c8b875e44b39)
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 
5 use std::collections::VecDeque;
6 
7 use async_task::Runnable;
8 use 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.
12 pub struct RunnableQueue {
13     runnables: Mutex<VecDeque<Runnable>>,
14 }
15 
16 impl RunnableQueue {
17     /// Create a new, empty `RunnableQueue`.
new() -> RunnableQueue18     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`.
push_back(&self, runnable: Runnable)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.
pop_front(&self) -> Option<Runnable>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.
iter(&self) -> RunnableQueueIter36     pub fn iter(&self) -> RunnableQueueIter {
37         self.into_iter()
38     }
39 }
40 
41 impl Default for RunnableQueue {
default() -> Self42     fn default() -> Self {
43         Self::new()
44     }
45 }
46 
47 impl<'q> IntoIterator for &'q RunnableQueue {
48     type Item = Runnable;
49     type IntoIter = RunnableQueueIter<'q>;
50 
into_iter(self) -> Self::IntoIter51     fn into_iter(self) -> Self::IntoIter {
52         RunnableQueueIter { queue: self }
53     }
54 }
55 
56 /// An iterator over a `RunnableQueue`.
57 pub struct RunnableQueueIter<'q> {
58     queue: &'q RunnableQueue,
59 }
60 
61 impl<'q> Iterator for RunnableQueueIter<'q> {
62     type Item = Runnable;
next(&mut self) -> Option<Self::Item>63     fn next(&mut self) -> Option<Self::Item> {
64         self.queue.pop_front()
65     }
66 }
67