1use std::ops::Range;
2
3#[derive(Debug, Clone)]
4pub struct SelectionVector {
5 pub indices: Vec<u32>,
6 pub size: usize,
7}
8
9impl SelectionVector {
10 pub fn new(capacity: usize) -> Self {
11 Self {
12 indices: Vec::with_capacity(capacity),
13 size: 0,
14 }
15 }
16
17 pub fn from_slice(indices: &[u32]) -> Self {
18 let mut sv = Self::new(indices.len());
19 sv.indices.extend_from_slice(indices);
20 sv.size = indices.len();
21 sv
22 }
23
24 pub fn from_range(len: usize) -> Self {
25 let indices: Vec<u32> = (0..len as u32).collect();
26 Self { size: len, indices }
27 }
28
29 pub fn is_empty(&self) -> bool {
30 self.size == 0
31 }
32
33 pub fn clear(&mut self) {
34 self.indices.clear();
35 self.size = 0;
36 }
37
38 pub fn push(&mut self, idx: u32) {
39 if self.size < self.indices.len() {
40 self.indices[self.size] = idx;
41 } else {
42 self.indices.push(idx);
43 }
44 self.size += 1;
45 }
46
47 pub fn iter(&self) -> SelectionIter<'_> {
48 SelectionIter {
49 indices: &self.indices[..self.size],
50 pos: 0,
51 }
52 }
53
54 pub fn get(&self, pos: usize) -> Option<u32> {
55 if pos < self.size { Some(self.indices[pos]) } else { None }
56 }
57
58 pub fn slice(&self, range: Range<usize>) -> &[u32] {
59 let end = range.end.min(self.size);
60 &self.indices[range.start..end]
61 }
62}
63
64pub struct SelectionIter<'a> {
65 indices: &'a [u32],
66 pos: usize,
67}
68
69impl<'a> Iterator for SelectionIter<'a> {
70 type Item = u32;
71
72 fn next(&mut self) -> Option<Self::Item> {
73 if self.pos < self.indices.len() {
74 let val = self.indices[self.pos];
75 self.pos += 1;
76 Some(val)
77 } else {
78 None
79 }
80 }
81
82 fn size_hint(&self) -> (usize, Option<usize>) {
83 let remaining = self.indices.len() - self.pos;
84 (remaining, Some(remaining))
85 }
86}
87
88impl<'a> ExactSizeIterator for SelectionIter<'a> {}
89
90impl<'a> IntoIterator for &'a SelectionVector {
91 type Item = u32;
92 type IntoIter = SelectionIter<'a>;
93
94 fn into_iter(self) -> Self::IntoIter {
95 self.iter()
96 }
97}