openlegends_core/
pool.rs

1pub mod cursor;
2
3pub use cursor::Cursor;
4
5use rand::{seq::SliceRandom, thread_rng};
6
7pub struct Pool<T> {
8    cursor: Cursor,
9    vector: Vec<T>,
10}
11
12impl<T> Pool<T> {
13    pub fn new(vector: Vec<T>) -> Self {
14        Self {
15            cursor: Cursor::new(vector.len()),
16            vector,
17        }
18    }
19
20    pub fn back(&self) -> Option<&T> {
21        self.vector.get(self.cursor.back().as_index())
22    }
23
24    pub fn take_back(&mut self) -> Option<T> {
25        self.back()?;
26        Some(self.vector.remove(self.cursor.take_back().as_index()))
27    }
28
29    pub fn to_back(&mut self) -> Option<&T> {
30        self.vector.get(self.cursor.to_back().as_index())
31    }
32
33    pub fn first(&self) -> Option<&T> {
34        self.vector.get(self.cursor.first().as_index())
35    }
36
37    pub fn take_first(&mut self) -> Option<T> {
38        self.first()?;
39        Some(self.vector.remove(self.cursor.take_first().as_index()))
40    }
41
42    pub fn to_first(&mut self) -> Option<&T> {
43        self.vector.get(self.cursor.to_first().as_index())
44    }
45
46    pub fn last(&self) -> Option<&T> {
47        self.vector.get(self.cursor.last().as_index())
48    }
49
50    pub fn take_last(&mut self) -> Option<T> {
51        self.last()?;
52        Some(self.vector.remove(self.cursor.take_last().as_index()))
53    }
54
55    pub fn to_last(&mut self) -> Option<&T> {
56        self.vector.get(self.cursor.to_last().as_index())
57    }
58
59    pub fn next(&self) -> Option<&T> {
60        self.vector.get(self.cursor.next().as_index())
61    }
62
63    pub fn take_next(&mut self) -> Option<T> {
64        self.next()?;
65        Some(self.vector.remove(self.cursor.take_next().as_index()))
66    }
67
68    pub fn to_next(&mut self) -> Option<&T> {
69        self.vector.get(self.cursor.to_next().as_index())
70    }
71
72    pub fn current(&self) -> Option<&T> {
73        self.get(&self.cursor)
74    }
75
76    pub fn random(&self) -> Option<&T> {
77        self.vector.choose(&mut thread_rng())
78    }
79
80    pub fn shuffle(&mut self) {
81        self.vector.shuffle(&mut thread_rng());
82    }
83
84    pub fn get(&self, cursor: &Cursor) -> Option<&T> {
85        self.vector.get(cursor.as_index())
86    }
87
88    pub fn total(&self) -> usize {
89        self.vector.len()
90    }
91}