nimbusqueue 0.2.7

fifo collection
Documentation
use std::sync::{Arc, Mutex};

/// Queue data structure definition
#[derive(Debug, Clone)]
pub struct Queue<T> {
    queue: Arc<Mutex<Vec<T>>>, // Arc<Mutex> wrapping the Vec for internal locking
}

impl<T> Queue<T> {
    /// Creates a new Queue instance
    pub fn new() -> Self {
        Queue {
            queue: Arc::new(Mutex::new(Vec::new())), // Initialize with empty Vec<T>
        }
    }

    /// Returns the length of the queue (thread-safe)
    pub fn length(&self) -> usize {
        let queue = self.queue.lock().unwrap(); // Lock the mutex to access the queue
        queue.len()
    }

    /// Enqueues an item (thread-safe)
    pub fn enqueue(&self, item: T) {
        let mut queue = self.queue.lock().unwrap(); // Lock the mutex for mutability
        queue.push(item);
    }

    /// Dequeues an item (thread-safe)
    pub fn dequeue(&self) -> Option<T> {
        let mut queue = self.queue.lock().unwrap(); // Lock the mutex for mutability
        if !queue.is_empty() {
            Some(queue.remove(0)) // Remove the first item
        } else {
            None // Return None if the queue is empty
        }
    }

    /// Checks if the queue is empty (thread-safe)
    pub fn is_empty(&self) -> bool {
        let queue = self.queue.lock().unwrap(); // Lock the mutex to access the queue
        queue.is_empty()
    }

    /// Peeks at the first item in the queue (thread-safe)
    pub fn peek(&self) -> Option<T>
    where
        T: Clone, // We need T to implement Clone to return a copy of the value
    {
        let queue = self.queue.lock().unwrap(); // Lock the mutex to access the queue
        queue.first().cloned() // Return a cloned version of the first element
    }

    /// Read-only iteration over the queue (thread-safe)
    pub fn iter(&self) -> Vec<T>
    where
        T: Clone, // T must implement Clone to allow safe copying
    {
        let queue = self.queue.lock().unwrap();
        queue.clone() // Return a clone of the internal Vec for safe iteration
    }
}