Skip to main content

mkutils/
active_vec.rs

1use crate::utils::Utils;
2
3pub struct ActiveVec<T> {
4    active_index: usize,
5    vec: Vec<T>,
6}
7
8impl<T> ActiveVec<T> {
9    const INITIAL_ACTIVE_INDEX: usize = 0;
10
11    pub fn new(item: T) -> Self {
12        let active_index = Self::INITIAL_ACTIVE_INDEX;
13        let vec = std::vec![item];
14
15        Self { active_index, vec }
16    }
17
18    #[must_use]
19    pub const fn active_index(&self) -> usize {
20        self.active_index
21    }
22
23    #[must_use]
24    pub fn as_slice(&self) -> &[T] {
25        &self.vec
26    }
27
28    pub fn as_slice_mut(&mut self) -> &mut [T] {
29        &mut self.vec
30    }
31
32    #[must_use]
33    pub fn active(&self) -> &T {
34        &self.vec[self.active_index]
35    }
36
37    pub fn active_mut(&mut self) -> &mut T {
38        &mut self.vec[self.active_index]
39    }
40
41    pub fn remove_active(&mut self) -> Option<T> {
42        if self.vec.len() < 2 {
43            return None;
44        }
45
46        let element = self.vec.remove(self.active_index);
47
48        self.active_index = self.active_index.saturating_sub(1);
49
50        element.some()
51    }
52
53    pub fn push(&mut self, item: T) -> (usize, &mut T) {
54        let index = self.vec.len();
55        let item = self.vec.mut_push(item);
56
57        (index, item)
58    }
59
60    pub const fn set_active_index(&mut self, active_index: usize) {
61        if active_index < self.vec.len() {
62            self.active_index = active_index;
63        }
64    }
65
66    pub fn cycle(&mut self, amount: isize) -> &mut Self {
67        self.active_index.cycle_in_place(amount, self.vec.len());
68
69        self
70    }
71
72    pub fn cycle_next(&mut self) -> &mut Self {
73        self.cycle(1)
74    }
75
76    pub fn cycle_prev(&mut self) -> &mut Self {
77        self.cycle(-1)
78    }
79}