devela/data/collections/traits/queues.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
// devela::data::collections::traits::queues
//
//! DataQueue, DataDeque abstract data type
//
// TOC
// - define traits DataQueue, DataDeque
// - impl for:
// - VecDeque
use crate::{DataCollection, NotEnoughElements, NotEnoughSpace};
/// An abstract *queue* data type.
pub trait DataQueue: DataCollection {
/// Remove an element from the (front of the) queue.
/// # Errors
/// Returns [`NotEnoughElements`] if there are not enough elements in the queue.
fn queue_pop(&mut self) -> Result<<Self as DataCollection>::Element, NotEnoughElements>;
/// Add an element to the (back of the) queue.
/// # Errors
/// Returns [`NotEnoughSpace`] if there is not enough free space in the queue.
fn queue_push(
&mut self,
element: <Self as DataCollection>::Element,
) -> Result<(), NotEnoughSpace>;
}
/// An abstract *double-ended queue* data type.
pub trait DataDeque: DataQueue {
/// Remove an element from the back of the queue.
/// # Errors
/// Returns [`NotEnoughElements`] if there are not enough elements in the queue.
fn queue_pop_back(&mut self) -> Result<<Self as DataCollection>::Element, NotEnoughElements>;
/// Add an element to the front of the queue.
/// # Errors
/// Returns [`NotEnoughSpace`] if there is not enough free space in the queue.
fn queue_push_front(
&mut self,
element: <Self as DataCollection>::Element,
) -> Result<(), NotEnoughSpace>;
/// Remove an element from the front of the queue (calls [`queue_pop`][DataQueue::queue_pop]).
/// # Errors
/// Returns [`NotEnoughElements`] if there are not enough elements in the queue.
fn queue_pop_front(&mut self) -> Result<<Self as DataCollection>::Element, NotEnoughElements> {
self.queue_pop()
}
/// Remove an element from the back of the queue (calls [`queue_push`][DataQueue::queue_push]).
/// # Errors
/// Returns [`NotEnoughSpace`] if there is not enough free space in the queue.
fn queue_push_back(
&mut self,
element: <Self as DataCollection>::Element,
) -> Result<(), NotEnoughSpace> {
self.queue_push(element)
}
}
/* impls */
#[cfg(feature = "alloc")]
impl<T> DataQueue for crate::VecDeque<T> {
fn queue_pop(&mut self) -> Result<<Self as DataCollection>::Element, NotEnoughElements> {
self.pop_front().ok_or(NotEnoughElements(Some(1)))
}
fn queue_push(
&mut self,
element: <Self as DataCollection>::Element,
) -> Result<(), NotEnoughSpace> {
self.push_back(element);
Ok(())
}
}
#[cfg(feature = "alloc")]
impl<T> DataDeque for crate::VecDeque<T> {
fn queue_pop_back(&mut self) -> Result<<Self as DataCollection>::Element, NotEnoughElements> {
self.pop_back().ok_or(NotEnoughElements(Some(1)))
}
fn queue_push_front(
&mut self,
element: <Self as DataCollection>::Element,
) -> Result<(), NotEnoughSpace> {
self.push_front(element);
Ok(())
}
}