gonk_core/
index.rs

1#[derive(Debug, Clone)]
2pub struct Index<T> {
3    pub data: Vec<T>,
4    index: Option<usize>,
5}
6
7impl<T> Index<T> {
8    pub fn new(data: Vec<T>, index: Option<usize>) -> Self {
9        Self { data, index }
10    }
11    pub fn up(&mut self) {
12        if self.data.is_empty() {
13            return;
14        }
15
16        if let Some(index) = &mut self.index {
17            if *index > 0 {
18                *index -= 1;
19            } else {
20                *index = self.data.len() - 1;
21            }
22        }
23    }
24    pub fn down(&mut self) {
25        if self.data.is_empty() {
26            return;
27        }
28
29        if let Some(index) = &mut self.index {
30            if *index + 1 < self.data.len() {
31                *index += 1;
32            } else {
33                *index = 0;
34            }
35        }
36    }
37    pub fn up_with_len(&mut self, len: usize) {
38        if let Some(index) = &mut self.index {
39            if *index > 0 {
40                *index -= 1;
41            } else {
42                *index = len - 1;
43            }
44        }
45    }
46    pub fn down_with_len(&mut self, len: usize) {
47        if let Some(index) = &mut self.index {
48            if *index + 1 < len {
49                *index += 1;
50            } else {
51                *index = 0;
52            }
53        }
54    }
55    pub fn selected(&self) -> Option<&T> {
56        if let Some(index) = self.index {
57            if let Some(item) = self.data.get(index) {
58                return Some(item);
59            }
60        }
61        None
62    }
63    pub fn selection(&self) -> Option<usize> {
64        self.index
65    }
66    pub fn len(&self) -> usize {
67        self.data.len()
68    }
69    pub fn select(&mut self, i: Option<usize>) {
70        self.index = i;
71    }
72    pub fn is_none(&self) -> bool {
73        self.index.is_none()
74    }
75    pub fn is_empty(&self) -> bool {
76        self.data.is_empty()
77    }
78}
79
80impl<T> Default for Index<T> {
81    fn default() -> Self {
82        Self {
83            data: Vec::new(),
84            index: None,
85        }
86    }
87}