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
#[derive(Debug, Clone)]
pub struct Index<T> {
    pub data: Vec<T>,
    pub index: Option<usize>,
}

impl<T> Index<T> {
    pub fn new(data: Vec<T>, index: Option<usize>) -> Self {
        Self { data, index }
    }
    pub fn up(&mut self) {
        if self.data.is_empty() {
            return;
        }

        if let Some(index) = &mut self.index {
            if *index > 0 {
                *index -= 1;
            } else {
                *index = self.data.len() - 1;
            }
        }
    }
    pub fn down(&mut self) {
        if self.data.is_empty() {
            return;
        }

        if let Some(index) = &mut self.index {
            if *index + 1 < self.data.len() {
                *index += 1;
            } else {
                *index = 0;
            }
        }
    }
    pub fn up_with_len(&mut self, len: usize) {
        if let Some(index) = &mut self.index {
            if *index > 0 {
                *index -= 1;
            } else {
                *index = len - 1;
            }
        }
    }
    pub fn down_with_len(&mut self, len: usize) {
        if let Some(index) = &mut self.index {
            if *index + 1 < len {
                *index += 1;
            } else {
                *index = 0;
            }
        }
    }
    pub fn selected(&self) -> Option<&T> {
        if let Some(index) = self.index {
            if let Some(item) = self.data.get(index) {
                return Some(item);
            }
        }
        None
    }
    pub fn len(&self) -> usize {
        self.data.len()
    }
    pub fn select(&mut self, i: Option<usize>) {
        //TODO: this will crash
        self.index = i;
    }
    pub fn is_none(&self) -> bool {
        self.index.is_none()
    }
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }
}

impl<T> Default for Index<T> {
    fn default() -> Self {
        Self {
            data: Vec::default(),
            index: Option::default(),
        }
    }
}