logisheets_controller/navigator/
id_manager.rs

1use im::{hashset::HashSet, Vector};
2use logisheets_base::{BlockId, ColId, RowId};
3
4#[derive(Clone, Debug)]
5pub struct IdManager {
6    next_avail_row: RowId,
7    next_avail_col: ColId,
8    preserved_row: HashSet<RowId>,
9    preserved_col: HashSet<ColId>,
10    has_allocated: HashSet<(RowId, ColId)>,
11    next_avail_block: BlockId,
12}
13
14impl IdManager {
15    pub fn new(next_avail_row: RowId, next_avail_col: ColId, next_avail_block: BlockId) -> Self {
16        IdManager {
17            next_avail_row,
18            next_avail_col,
19            next_avail_block,
20            preserved_col: HashSet::new(),
21            preserved_row: HashSet::new(),
22            has_allocated: HashSet::new(),
23        }
24    }
25
26    pub fn get_block_id(&mut self) -> BlockId {
27        let res = self.next_avail_block;
28        self.next_avail_block += 1;
29        res
30    }
31
32    pub fn get_row_ids(&mut self, cnt: u32) -> Vector<RowId> {
33        let ids = (0..cnt)
34            .map(|cnt| cnt + self.next_avail_row)
35            .collect::<Vector<_>>();
36        self.next_avail_row += cnt;
37        ids
38    }
39
40    pub fn get_col_ids(&mut self, cnt: u32) -> Vector<ColId> {
41        let ids = (0..cnt)
42            .map(|cnt| cnt + self.next_avail_col)
43            .collect::<Vector<_>>();
44        self.next_avail_col += cnt;
45        ids
46    }
47
48    pub fn get_preserved_row_ids(&mut self, row_ids: Vector<ColId>) -> RowId {
49        let result_id = self
50            .preserved_row
51            .iter()
52            .find(|p| {
53                !row_ids
54                    .iter()
55                    .any(|c| self.has_allocated.contains(&(**p, c.clone())))
56            })
57            .map_or(
58                {
59                    let r = self.next_avail_row;
60                    self.next_avail_row += 1;
61                    r
62                },
63                |id| id.clone(),
64            );
65        row_ids.iter().for_each(|c| {
66            self.has_allocated.insert((result_id, c.clone()));
67        });
68        result_id
69    }
70
71    pub fn get_preserved_col_ids(&mut self, row_ids: Vector<RowId>) -> ColId {
72        let result_id = self
73            .preserved_col
74            .iter()
75            .find(|p| {
76                !row_ids
77                    .iter()
78                    .any(|r| self.has_allocated.contains(&(r.clone(), **p)))
79            })
80            .map_or(
81                {
82                    let r = self.next_avail_col;
83                    self.next_avail_col += 1;
84                    r
85                },
86                |id| id.clone(),
87            );
88        row_ids.iter().for_each(|r| {
89            self.has_allocated.insert((r.clone(), result_id));
90        });
91        result_id
92    }
93}