openlegends_core/pool/
cursor.rs

1pub struct Cursor {
2    current: usize,
3    last: usize,
4}
5
6impl Cursor {
7    pub fn new(length: usize) -> Self {
8        Self {
9            current: 0,
10            last: length,
11        }
12    }
13
14    pub fn back(&self) -> Self {
15        Self {
16            current: if self.current > 0 {
17                self.current - 1
18            } else {
19                self.last
20            },
21            last: self.last,
22        }
23    }
24
25    pub fn take_back(&mut self) -> &mut Self {
26        *self = Self {
27            current: if self.current > 0 {
28                self.current - 1
29            } else {
30                self.last
31            },
32            last: if self.last - 1 > 0 { self.last - 1 } else { 0 },
33        };
34        self
35    }
36
37    pub fn to_back(&mut self) -> &mut Self {
38        *self = self.back();
39        self
40    }
41
42    pub fn first(&self) -> Self {
43        Self {
44            current: if self.last > 0 { 1 } else { 0 },
45            last: self.last,
46        }
47    }
48
49    pub fn take_first(&mut self) -> &mut Self {
50        *self = Self {
51            current: if self.last > 0 { 1 } else { 0 },
52            last: if self.last - 1 > 0 { self.last - 1 } else { 0 },
53        };
54        self
55    }
56
57    pub fn to_first(&mut self) -> &mut Self {
58        *self = self.first();
59        self
60    }
61
62    pub fn last(&self) -> Self {
63        Self {
64            current: self.last,
65            last: self.last,
66        }
67    }
68
69    pub fn take_last(&mut self) -> &mut Self {
70        *self = Self {
71            current: self.last,
72            last: if self.last - 1 > 0 { self.last - 1 } else { 0 },
73        };
74        self
75    }
76
77    pub fn to_last(&mut self) -> &mut Self {
78        *self = self.last();
79        self
80    }
81
82    pub fn next(&self) -> Self {
83        Self {
84            current: if self.current < self.last {
85                self.current + 1
86            } else {
87                0
88            },
89            last: self.last,
90        }
91    }
92
93    pub fn take_next(&mut self) -> &mut Self {
94        *self = Self {
95            current: if self.current < self.last {
96                self.current + 1
97            } else {
98                self.last
99            },
100            last: if self.last - 1 > 0 { self.last - 1 } else { 0 },
101        };
102        self
103    }
104
105    pub fn to_next(&mut self) -> &mut Self {
106        *self = self.next();
107        self
108    }
109
110    pub fn as_index(&self) -> usize {
111        if self.current > 0 {
112            self.current - 1
113        } else {
114            0
115        }
116    }
117
118    pub fn as_position(&self) -> Option<usize> {
119        if self.current > 0 {
120            Some(self.current)
121        } else {
122            None
123        }
124    }
125}