Created
August 24, 2018 07:41
-
-
Save mikeando/3ff947e20bb1a6bd415761d17f7e2860 to your computer and use it in GitHub Desktop.
Rust Circular Queue Implementation from https://www.reddit.com/r/learnrust/comments/99ctqv/how_to_reference_struct_elements/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pub struct CircularQueue<T> { | |
queue: Vec<Option<T>>, | |
head: usize, | |
tail: usize, | |
max_capacity: usize, | |
count: usize, | |
} | |
impl<T> CircularQueue<T> { | |
pub fn new(size: usize) -> CircularQueue<T> { | |
CircularQueue { | |
queue: Vec::with_capacity(size), | |
head: 0, | |
tail: 0, | |
max_capacity: size, | |
count: 0 | |
} | |
} | |
fn is_full(&self) -> bool { | |
self.count == self.max_capacity | |
} | |
fn is_empty(&self) -> bool { | |
self.count == 0 | |
} | |
pub fn enqueue(&mut self, item: T) -> Result<(), String>{ | |
if self.is_full() { | |
return Err("Queue is full!".to_owned()) | |
} | |
self.queue.insert(self.tail, Some(item)); | |
self.tail = (self.tail + 1) % self.max_capacity; | |
self.count += 1; | |
Ok(()) | |
} | |
pub fn dequeue(&mut self) -> Result<T, String> { | |
if self.is_empty() { | |
return Err("Queue is empty!".to_owned()) | |
} | |
let item = std::mem::replace(&mut self.queue[self.head], None); | |
self.head = (self.head + 1) % self.max_capacity; | |
self.count -= 1; | |
Ok(item.unwrap()) | |
} | |
} | |
fn main() { | |
let mut q = CircularQueue::<usize>::new(2); | |
q.enqueue(123).expect("Item 123 should be added"); | |
println!("q.dequeue() == {}", q.dequeue().expect("Could not dequeue item")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment