synchronous_queue/
queue.rs

1use std::sync::{Arc, Mutex};
2
3/// Queue data structure definition
4#[derive(Debug, Clone)]
5pub struct Queue<T> {
6    queue: Arc<Mutex<Vec<T>>>, // Arc<Mutex> wrapping the Vec for internal locking
7}
8
9impl<T> Queue<T> {
10    /// Creates a new Queue instance
11    pub fn new() -> Self {
12        Queue {
13            queue: Arc::new(Mutex::new(Vec::new())), // Initialize with empty Vec<T>
14        }
15    }
16
17    /// Returns the length of the queue (thread-safe)
18    pub fn length(&self) -> usize {
19        let queue = self.queue.lock().unwrap(); // Lock the mutex to access the queue
20        queue.len()
21    }
22
23    /// Enqueues an item (thread-safe)
24    pub fn enqueue(&self, item: T) {
25        let mut queue = self.queue.lock().unwrap(); // Lock the mutex for mutability
26        queue.push(item);
27    }
28
29    /// Dequeues an item (thread-safe)
30    pub fn dequeue(&self) -> Option<T> {
31        let mut queue = self.queue.lock().unwrap(); // Lock the mutex for mutability
32        if !queue.is_empty() {
33            Some(queue.remove(0)) // Remove the first item
34        } else {
35            None // Return None if the queue is empty
36        }
37    }
38
39    /// Checks if the queue is empty (thread-safe)
40    pub fn is_empty(&self) -> bool {
41        let queue = self.queue.lock().unwrap(); // Lock the mutex to access the queue
42        queue.is_empty()
43    }
44
45    /// Peeks at the first item in the queue (thread-safe)
46    pub fn peek(&self) -> Option<T>
47    where
48        T: Clone, // We need T to implement Clone to return a copy of the value
49    {
50        let queue = self.queue.lock().unwrap(); // Lock the mutex to access the queue
51        queue.first().cloned() // Return a cloned version of the first element
52    }
53
54    /// Read-only iteration over the queue (thread-safe)
55    pub fn iter(&self) -> Vec<T>
56    where
57        T: Clone, // T must implement Clone to allow safe copying
58    {
59        let queue = self.queue.lock().unwrap();
60        queue.clone() // Return a clone of the internal Vec for safe iteration
61    }
62}