menmos_std/collections/
concurrent_list.rs

1use std::collections::LinkedList;
2
3use parking_lot::Mutex;
4
5#[derive(Debug)]
6pub struct ConcurrentList<T> {
7    data: Mutex<LinkedList<T>>,
8}
9
10impl<T> Default for ConcurrentList<T> {
11    fn default() -> Self {
12        Self {
13            data: Mutex::new(LinkedList::new()),
14        }
15    }
16}
17
18impl<T> ConcurrentList<T> {
19    pub fn pop_front(&self) -> Option<T> {
20        let mut guard = self.data.lock();
21        guard.pop_front()
22    }
23
24    pub fn pop_back(&self) -> Option<T> {
25        let mut guard = self.data.lock();
26        guard.pop_back()
27    }
28
29    pub fn push_front(&self, v: T) {
30        let mut guard = self.data.lock();
31        guard.push_front(v)
32    }
33
34    pub fn push_back(&self, v: T) {
35        let mut guard = self.data.lock();
36        guard.push_back(v)
37    }
38}
39
40impl<T> ConcurrentList<T>
41where
42    T: Clone,
43{
44    pub fn get_all(&self) -> Vec<T> {
45        let guard = self.data.lock();
46        guard.iter().cloned().collect()
47    }
48
49    /// Fetches the head of the list and swaps it to the back of the list atomically.
50    pub fn fetch_swap(&self) -> Option<T> {
51        let mut guard = self.data.lock();
52        match guard.pop_front() {
53            Some(v) => {
54                let value_copy = v.clone();
55                guard.push_back(v);
56                Some(value_copy)
57            }
58            None => None,
59        }
60    }
61}