devela/data/collections/traits/
stacks.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
// devela::data::collections::traits::stacks
//
//! DataStack and DataDesta abstract data types
//
// TOC
// - define traits DataStack, DataDesta
// - impl for
//   - VecDeque

use crate::{DataCollection, NotEnoughElements, NotEnoughSpace};

/// An abstract *stack* data type.
pub trait DataStack: DataCollection {
    /// Remove an element from the (back of the) stack.
    fn stack_pop(&mut self) -> Result<<Self as DataCollection>::Element, NotEnoughElements>;
    /// Add an element to the (back of the) stack.
    fn stack_push(
        &mut self,
        element: <Self as DataCollection>::Element,
    ) -> Result<(), NotEnoughSpace>;
}

/// An abstract *double-ended stack* data type.
pub trait DataDesta: DataStack {
    /// Remove an element from the front of the stack.
    fn stack_pop_front(&mut self) -> Result<<Self as DataCollection>::Element, NotEnoughElements>;
    /// Add an element to the front of the stack.
    fn stack_push_front(
        &mut self,
        element: <Self as DataCollection>::Element,
    ) -> Result<(), NotEnoughSpace>;

    /// Remove an element from the back of the stack (calls [`DataStack::stack_pop`]).
    fn stack_pop_back(&mut self) -> Result<<Self as DataCollection>::Element, NotEnoughElements> {
        self.stack_pop()
    }
    /// Remove an element from the back of the stack (calls [`DataStack::stack_push`]).
    ///
    fn stack_push_back(
        &mut self,
        element: <Self as DataCollection>::Element,
    ) -> Result<(), NotEnoughSpace> {
        self.stack_push(element)
    }
}

/* impl for VecDeque */

#[rustfmt::skip]
#[cfg(feature = "alloc")]
impl<T> DataStack for crate::VecDeque<T> {
    fn stack_pop(&mut self) -> Result<<Self as DataCollection>::Element, NotEnoughElements> {
        self.pop_back().ok_or(NotEnoughElements(Some(1)))
    }
    fn stack_push(&mut self, element: <Self as DataCollection>::Element) -> Result<(), NotEnoughSpace> {
        self.push_back(element); Ok(())
    }
}
#[rustfmt::skip]
#[cfg(feature = "alloc")]
impl<T> DataDesta for crate::VecDeque<T> {
    fn stack_pop_front(&mut self) -> Result<<Self as DataCollection>::Element, NotEnoughElements> {
        self.pop_front().ok_or(NotEnoughElements(Some(1)))
    }
    fn stack_push_front(&mut self, element: <Self as DataCollection>::Element) -> Result<(), NotEnoughSpace> {
        self.push_front(element); Ok(())
    }
}