use std::convert::TryInto;
use std::fmt::Debug;
use std::iter::FromIterator;
use std::sync::atomic::{AtomicUsize, Ordering};
use tokio::sync::{Mutex, Semaphore};
use crate::atomic::Available;
use crate::unlimited::Queue as UnlimitedQueue;
use crate::{Notifier, Receiver};
pub struct Queue<T> {
queue: UnlimitedQueue<T>,
capacity: AtomicUsize,
push_semaphore: Semaphore,
available: Available,
resize_mutex: Mutex<()>,
notifier_full: Notifier,
notifier_empty: Notifier,
}
impl<T> Queue<T> {
pub fn new(max_size: usize) -> Self {
Self {
queue: UnlimitedQueue::new(),
capacity: AtomicUsize::new(max_size),
push_semaphore: Semaphore::new(max_size),
available: Available::new(0),
resize_mutex: Mutex::default(),
notifier_full: crate::new_notifier(),
notifier_empty: crate::new_notifier(),
}
}
pub async fn pop(&self) -> T {
let (txn, new_len) = self.available.sub();
let item = self.queue.pop().await;
txn.commit();
if new_len <= 0 {
self.notify_empty();
}
self.push_semaphore.add_permits(1);
item
}
pub fn try_pop(&self) -> Option<T> {
let (txn, new_len) = self.available.sub();
let item = self.queue.try_pop();
if item.is_some() {
txn.commit();
if new_len <= 0 {
self.notify_empty();
}
self.push_semaphore.add_permits(1);
}
item
}
pub async fn push(&self, item: T) {
let permit = self.push_semaphore.acquire().await.unwrap();
let new_len = self.available.add();
self.queue.push(item);
if new_len >= self.capacity().try_into().unwrap() {
self.notify_full();
}
permit.forget();
}
pub fn try_push(&self, item: T) -> Result<(), T> {
match self.push_semaphore.try_acquire() {
Ok(permit) => {
let new_len = self.available.add();
self.queue.push(item);
if new_len >= self.capacity().try_into().unwrap() {
self.notify_full();
}
permit.forget();
Ok(())
}
Err(_) => Err(item),
}
}
pub fn capacity(&self) -> usize {
self.capacity.load(Ordering::Relaxed)
}
pub fn len(&self) -> usize {
self.queue.len()
}
pub fn is_empty(&self) -> bool {
self.queue.is_empty()
}
pub fn is_full(&self) -> bool {
self.len() >= self.capacity()
}
pub fn available(&self) -> isize {
self.queue.available()
}
fn notify_full(&self) {
self.notifier_full.send_replace(());
}
pub async fn wait_full(&self) {
if self.len() == self.capacity() {
return;
}
self.subscribe_full().changed().await.unwrap();
}
pub fn subscribe_full(&self) -> Receiver {
self.notifier_full.subscribe()
}
fn notify_empty(&self) {
self.notifier_empty.send_replace(());
}
pub async fn wait_empty(&self) {
if self.is_empty() {
return;
}
self.subscribe_empty().changed().await.unwrap();
}
pub fn subscribe_empty(&self) -> Receiver {
self.notifier_empty.subscribe()
}
pub async fn resize(&self, target_capacity: usize) {
let _guard = self.resize_mutex.lock().await;
match target_capacity.cmp(&self.capacity()) {
std::cmp::Ordering::Greater => {
let diff = target_capacity - self.capacity();
self.capacity.fetch_add(diff, Ordering::Relaxed);
self.push_semaphore.add_permits(diff);
}
std::cmp::Ordering::Less => {
for _ in target_capacity..self.capacity() {
tokio::select! {
biased;
push_permit = self.push_semaphore.acquire() => {
push_permit.unwrap().forget();
}
_ = self.queue.pop() => {}
};
self.capacity.fetch_sub(1, Ordering::Relaxed);
}
if self.is_full() {
self.notify_full();
}
}
_ => {}
}
}
}
impl<T> Debug for Queue<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Queue")
.field("queue", &self.queue)
.field("capacity", &self.capacity)
.field("push_semaphore", &self.push_semaphore)
.field("resize_mutex", &self.resize_mutex)
.finish()
}
}
impl<T> FromIterator<T> for Queue<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let queue = UnlimitedQueue::from_iter(iter);
let len = queue.len();
Self {
queue,
capacity: len.into(),
push_semaphore: Semaphore::new(0),
available: Available::new(0),
resize_mutex: Mutex::default(),
notifier_full: crate::new_notifier(),
notifier_empty: crate::new_notifier(),
}
}
}