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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
use std::convert::TryInto;
use std::iter::FromIterator;
use std::sync::atomic::{AtomicUsize, Ordering};
use tokio::sync::{Mutex, Semaphore};
use crate::unlimited::Queue as UnlimitedQueue;
pub struct Queue<T> {
base: UnlimitedQueue<T>,
capacity: AtomicUsize,
push_semaphore: Semaphore,
resize_mutex: Mutex<()>,
}
impl<T> Queue<T> {
pub fn new(max_size: usize) -> Self {
Self {
base: UnlimitedQueue::new(),
capacity: AtomicUsize::new(max_size),
push_semaphore: Semaphore::new(max_size),
resize_mutex: Mutex::default(),
}
}
pub async fn pop(&self) -> T {
let item = self.base.pop().await;
self.push_semaphore.add_permits(1);
item
}
pub fn try_pop(&self) -> Option<T> {
let item = self.base.try_pop();
if item.is_some() {
self.push_semaphore.add_permits(1);
}
item
}
pub async fn push(&self, item: T) {
let permit = self.push_semaphore.acquire().await;
self.base.push(item);
permit.forget();
}
pub fn try_push(&self, item: T) -> Result<(), T> {
match self.push_semaphore.try_acquire() {
Ok(permit) => {
self.base.push(item);
permit.forget();
Ok(())
}
Err(_) => Err(item),
}
}
pub fn capacity(&self) -> usize {
self.capacity.load(Ordering::Relaxed)
}
pub fn len(&self) -> usize {
self.base.len()
}
pub fn available(&self) -> isize {
self.base.available()
}
pub async fn resize(&mut self, new_max_size: usize) {
let _guard = self.resize_mutex.lock().await;
if new_max_size > self.capacity() {
let diff = new_max_size - self.capacity();
self.capacity.fetch_add(diff, Ordering::Relaxed);
self.push_semaphore.add_permits(diff);
} else if new_max_size < self.capacity() {
for _ in self.capacity()..new_max_size {
let permit = self.push_semaphore.acquire().await;
self.capacity.fetch_sub(1, Ordering::Relaxed);
permit.forget();
self.base.pop().await;
}
}
}
}
impl<T> FromIterator<T> for Queue<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let base = UnlimitedQueue::from_iter(iter);
let len = base.len();
Self {
base,
capacity: len.try_into().unwrap(),
push_semaphore: Semaphore::new(0),
resize_mutex: Mutex::default(),
}
}
}