use std::{cmp::Ordering, collections::BinaryHeap};
use super::Instant;
#[derive(Clone)]
pub struct TimeQueue<T: Eq + PartialEq> {
queue: BinaryHeap<ItemContainer<T>>,
}
#[allow(clippy::new_without_default)]
impl<T: Eq + PartialEq> TimeQueue<T> {
pub fn new() -> Self {
Self {
queue: BinaryHeap::default(),
}
}
}
impl<T: Eq + PartialEq> TimeQueue<T> {
pub fn add_item(&mut self, instant: Instant, item: T) {
self.queue.push(ItemContainer { instant, item });
}
pub fn has_item(&self) -> bool {
if self.queue.is_empty() {
return false;
}
if let Some(item) = self.queue.peek() {
return item.instant <= Instant::now();
}
false
}
pub fn pop_item(&mut self) -> Option<T> {
if self.has_item() {
if let Some(container) = self.queue.pop() {
return Some(container.item);
}
}
None
}
pub fn peek_entry(&self) -> Option<&ItemContainer<T>> {
self.queue.peek()
}
pub fn len(&self) -> usize {
self.queue.len()
}
pub fn is_empty(&self) -> bool {
self.queue.is_empty()
}
}
#[derive(Clone, Eq, PartialEq)]
pub struct ItemContainer<T: Eq + PartialEq> {
pub instant: Instant,
pub item: T,
}
impl<T: Eq + PartialEq> Ord for ItemContainer<T> {
fn cmp(&self, other: &ItemContainer<T>) -> Ordering {
other.instant.cmp(&self.instant)
}
}
impl<T: Eq + PartialEq> PartialOrd for ItemContainer<T> {
fn partial_cmp(&self, other: &ItemContainer<T>) -> Option<Ordering> {
Some(self.cmp(other))
}
}