//! A queue that can be extended while iterating over it. use std::{ collections::VecDeque, sync::{Arc, RwLock, Weak}, }; /// A queue that can be extended while iterating over it. #[derive(Debug, Clone)] pub struct ExtendableQueue { queue: Arc>>, } impl Default for ExtendableQueue { fn default() -> Self { Self { queue: Arc::new(RwLock::new(VecDeque::new())), } } } impl From for ExtendableQueue where V: Into>, { fn from(value: V) -> Self { Self { queue: Arc::new(RwLock::new(value.into())), } } } impl ExtendableQueue { /// Add an element to the queue. pub fn push(&self, value: T) { self.queue.write().unwrap().push_back(value); } /// Get the queue. #[must_use] pub fn get(&self) -> &Arc>> { &self.queue } /// Get a weak reference to the queue. #[must_use] pub fn get_weak(&self) -> Weak>> { Arc::downgrade(&self.queue) } /// Clear the queue. pub fn clear(&self) { self.queue.write().unwrap().clear(); } /// Get the length of the queue. #[must_use] pub fn len(&self) -> usize { self.queue.read().unwrap().len() } /// Check if the queue is empty. #[must_use] pub fn is_empty(&self) -> bool { self.queue.read().unwrap().is_empty() } /// Get and remove the next item without needing mutable access. #[must_use] pub fn pop_front(&self) -> Option { self.queue.write().unwrap().pop_front() } } impl Extend for ExtendableQueue { fn extend>(&mut self, iter: T) { self.queue.write().unwrap().extend(iter); } } impl Iterator for ExtendableQueue { type Item = T; fn next(&mut self) -> Option { self.queue.write().unwrap().pop_front() } }