Skip to main content

ratio_reactor/
skip.rs

1//! # Skip-waiting queue implementation
2//!
3//! ## License
4//!
5//! This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
6//! If a copy of the MPL was not distributed with this file,
7//! You can obtain one at <https://mozilla.org/MPL/2.0/>.
8//!
9//! **Code examples both in the docstrings and rendered documentation are free to use.**
10
11use std::collections::BTreeMap;
12
13use futures::Future;
14use futures::future::{Fuse, FusedFuture};
15
16use crate::key::KeyedData;
17use crate::reactor::Queue;
18
19/// Skip-waiting queue implementation.
20/// All arriving jobs replace the currently waiting job.
21/// Currently running jobs are left alone.
22pub struct SkipQueue<I> {
23    /// Waiting job.
24    pub job: Option<I>,
25}
26impl<I> Default for SkipQueue<I> {
27    fn default() -> Self {
28        Self { job: None }
29    }
30}
31impl<I> Queue<I> for SkipQueue<I> {
32    fn enqueue(&mut self, input: I) {
33        // Replace any waiting job with te input.
34        self.job = Some(input);
35    }
36    fn next<F, O>(&mut self, handle: &Fuse<F>) -> Option<I>
37    where
38        F: Future<Output = O>,
39    {
40        // Release new input if current handle is terminated.
41        if handle.is_terminated() {
42            self.job.take()
43        } else {
44            None
45        }
46    }
47}
48
49/// Keyed skip queue implementation.
50/// Only the last arrived job is queued for each key, replacing any other waiting job for that key.
51/// Keys are ordered, such that jobs with an earlier key have higher priority.
52#[derive(Clone, Debug)]
53pub struct KeySkipQueue<K: Ord, D> {
54    /// Waiting jobs.
55    pub waiting: BTreeMap<K, D>,
56}
57impl<K: Ord, D> Default for KeySkipQueue<K, D> {
58    fn default() -> Self {
59        Self {
60            waiting: BTreeMap::new(),
61        }
62    }
63}
64impl<K: Ord + Clone, D> Queue<KeyedData<K, D>> for KeySkipQueue<K, D> {
65    fn enqueue(&mut self, input: KeyedData<K, D>) {
66        let KeyedData { key, data } = input;
67        self.waiting.insert(key, data);
68    }
69
70    fn next<F, O>(&mut self, handle: &Fuse<F>) -> Option<KeyedData<K, D>>
71    where
72        F: Future<Output = O>,
73    {
74        // Release new input if current handle is terminated.
75        if handle.is_terminated() {
76            self.waiting
77                .pop_first()
78                .map(|(key, data)| KeyedData { key, data })
79        } else {
80            None
81        }
82    }
83}