aboutsummaryrefslogtreecommitdiffstats
path: root/src/wireguard/queue.rs
blob: eea1ccf5db6b1b6751578d6fde6ed6444e698d11 (plain) (blame)
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
use std::sync::Mutex;

use crossbeam_channel::{bounded, Receiver, Sender};

pub struct ParallelQueue<T> {
    queue: Mutex<Option<Sender<T>>>,
}

impl<T> ParallelQueue<T> {
    /// Create a new ParallelQueue instance
    ///
    /// # Arguments
    ///
    /// - `queues`: number of readers
    /// - `capacity`: capacity of each internal queue
    ///
    pub fn new(queues: usize, capacity: usize) -> (Self, Vec<Receiver<T>>) {
        let mut receivers = Vec::with_capacity(queues);
        let (tx, rx) = bounded(capacity);
        for _ in 0..queues {
            receivers.push(rx.clone());
        }
        (
            ParallelQueue {
                queue: Mutex::new(Some(tx)),
            },
            receivers,
        )
    }

    pub fn send(&self, v: T) {
        self.queue.lock().unwrap().as_ref().map(|s| {
            let _ = s.send(v);
        });
    }

    pub fn close(&self) {
        *self.queue.lock().unwrap() = None;
    }
}