Skip to main content

sheet_core/
sheet.rs

1//! Sparse worksheet storage — `BTreeMap<(row, col), Cell>` plus tracked
2//! bounds.
3//!
4//! Absence *is* the blank: a coordinate not in the map holds nothing, so
5//! memory scales with filled cells, not with the bounding rectangle. The
6//! map also gives deterministic iteration order (row-major) for free —
7//! golden tests and serialized output come out in a stable order.
8
9use crate::cell::Cell;
10use alloc::vec::Vec;
11use core::ops::RangeInclusive;
12
13/// One worksheet's cells: sparse, row-major-ordered, unbounded up to the
14/// `u32 × u32` coordinate space.
15#[derive(Debug, Clone, Default, PartialEq)]
16pub struct Sheet {
17    cells: alloc::collections::BTreeMap<(u32, u32), Cell>,
18    max_row: u32,
19    max_col: u32,
20}
21
22impl Sheet {
23    /// An empty sheet.
24    #[must_use]
25    pub const fn new() -> Self {
26        Sheet {
27            cells: alloc::collections::BTreeMap::new(),
28            max_row: 0,
29            max_col: 0,
30        }
31    }
32
33    /// Sets (inserts or overwrites) the cell at `row`, `col`.
34    pub fn set(&mut self, row: u32, col: u32, cell: Cell) {
35        self.cells.insert((row, col), cell);
36        self.max_row = self.max_row.max(row);
37        self.max_col = self.max_col.max(col);
38    }
39
40    /// Returns the cell at `row`, `col`, or `None` when the coordinate is
41    /// blank (absent).
42    #[must_use]
43    pub fn get(&self, row: u32, col: u32) -> Option<&Cell> {
44        self.cells.get(&(row, col))
45    }
46
47    /// Removes the cell at `row`, `col` (making it blank). Removing an
48    /// absent coordinate is a no-op.
49    pub fn remove(&mut self, row: u32, col: u32) {
50        if self.cells.remove(&(row, col)).is_some() && (row == self.max_row || col == self.max_col)
51        {
52            self.recompute_bounds();
53        }
54    }
55
56    /// The used range — `((min_row, min_col), (max_row, max_col))` over all
57    /// present cells — or `None` when the sheet is empty. The spreadsheet
58    /// equivalent of the `dimension` element: the bounding box of occupied
59    /// coordinates.
60    #[must_use]
61    pub fn used_range(&self) -> Option<((u32, u32), (u32, u32))> {
62        if self.cells.is_empty() {
63            return None;
64        }
65        let mut min = (u32::MAX, u32::MAX);
66        for &(r, c) in self.cells.keys() {
67            min = (min.0.min(r), min.1.min(c));
68        }
69        Some((min, (self.max_row, self.max_col)))
70    }
71
72    /// Iterates present cells in row-major (deterministic) order.
73    pub fn iter(&self) -> alloc::collections::btree_map::Iter<'_, (u32, u32), Cell> {
74        self.cells.iter()
75    }
76    /// Number of present (non-blank-by-absence) cells.
77    #[must_use]
78    pub fn len(&self) -> usize {
79        self.cells.len()
80    }
81
82    /// `true` when no cell is present.
83    #[must_use]
84    pub fn is_empty(&self) -> bool {
85        self.cells.is_empty()
86    }
87
88    /// Collects the present cells in the given (row, col) range, in
89    /// row-major order. Range-bounded scans back the file formats' row
90    /// streaming without materializing blank coordinates.
91    #[must_use]
92    pub fn cells_in(
93        &self,
94        rows: RangeInclusive<u32>,
95        cols: RangeInclusive<u32>,
96    ) -> Vec<((u32, u32), &Cell)> {
97        self.cells
98            .range((*rows.start(), *cols.start())..=(*rows.end(), *cols.end()))
99            .map(|(k, v)| (*k, v))
100            .collect()
101    }
102
103    /// Recomputes the tracked max bounds after a boundary removal. O(n) in
104    /// present cells — only paid when the removed cell sat on the max row
105    /// or column.
106    fn recompute_bounds(&mut self) {
107        self.max_row = self.cells.keys().next_back().map_or(0, |&(r, _)| r);
108        self.max_col = self.cells.keys().fold(0, |acc, &(_, c)| acc.max(c));
109    }
110}
111
112impl<'a> IntoIterator for &'a Sheet {
113    type Item = ((u32, u32), &'a Cell);
114    type IntoIter = alloc::boxed::Box<dyn Iterator<Item = ((u32, u32), &'a Cell)> + 'a>;
115
116    /// Iterates present cells in row-major (deterministic) order — same as
117    /// [`Sheet::iter`], so `for (coord, cell) in &sheet` works.
118    fn into_iter(self) -> Self::IntoIter {
119        alloc::boxed::Box::new(self.cells.iter().map(|(k, v)| (*k, v)))
120    }
121}
122
123#[cfg(test)]
124mod tests {
125    #![allow(
126        clippy::unwrap_used,
127        clippy::expect_used,
128        clippy::panic,
129        clippy::indexing_slicing
130    )]
131
132    use super::Sheet;
133    use crate::cell::{Cell, CellValue};
134    use alloc::string::ToString;
135    use alloc::{vec, vec::Vec};
136
137    #[test]
138    fn set_get_overwrite_and_absence() {
139        let mut sheet = Sheet::new();
140        assert!(sheet.is_empty());
141        assert_eq!(sheet.len(), 0);
142        assert_eq!(sheet.get(0, 0), None);
143
144        sheet.set(3, 2, Cell::number(1.0));
145        assert_eq!(sheet.get(3, 2), Some(&Cell::number(1.0)));
146        assert_eq!(sheet.get(2, 3), None); // transposed: absent
147        assert!(!sheet.is_empty());
148        assert_eq!(sheet.len(), 1);
149
150        sheet.set(3, 2, Cell::text("replaced"));
151        assert_eq!(sheet.len(), 1); // overwrite, not insert
152        assert_eq!(
153            sheet.get(3, 2).map(|c| &c.value),
154            Some(&CellValue::Text("replaced".to_string()))
155        );
156    }
157
158    #[test]
159    fn used_range_is_the_bounding_box() {
160        let mut sheet = Sheet::new();
161        assert_eq!(sheet.used_range(), None);
162
163        // Deliberately non-corner shapes: (1,5) and (2,0).
164        sheet.set(1, 5, Cell::number(1.0));
165        sheet.set(2, 0, Cell::number(2.0));
166        assert_eq!(sheet.used_range(), Some(((1, 0), (2, 5))));
167
168        sheet.set(0, 7, Cell::number(3.0));
169        assert_eq!(sheet.used_range(), Some(((0, 0), (2, 7))));
170    }
171
172    #[test]
173    fn remove_shrinks_bounds_only_when_needed() {
174        let mut sheet = Sheet::new();
175        sheet.set(0, 0, Cell::number(1.0));
176        sheet.set(5, 7, Cell::number(2.0));
177        sheet.remove(0, 0); // interior for cols, boundary row? no: (0,0) row != max
178        assert_eq!(sheet.used_range(), Some(((5, 7), (5, 7))));
179
180        sheet.remove(5, 7); // boundary corner: bounds recompute to empty
181        assert_eq!(sheet.used_range(), None);
182        assert!(sheet.is_empty());
183
184        // Removing an absent cell never panics nor corrupts bounds.
185        sheet.remove(9, 9);
186        assert_eq!(sheet.used_range(), None);
187
188        sheet.set(2, 4, Cell::blank());
189        sheet.remove(2, 4);
190        assert_eq!(sheet.used_range(), None);
191    }
192
193    #[test]
194    fn iteration_is_row_major_and_cells_in_bounds_correctly() {
195        let mut sheet = Sheet::new();
196        sheet.set(1, 0, Cell::number(1.0));
197        sheet.set(0, 1, Cell::number(2.0));
198        sheet.set(1, 1, Cell::number(3.0));
199
200        let order: Vec<_> = sheet.iter().map(|(k, _)| *k).collect();
201        assert_eq!(order, vec![(0, 1), (1, 0), (1, 1)]);
202
203        let sliced: Vec<_> = sheet
204            .cells_in(1..=1, 0..=1)
205            .iter()
206            .map(|(k, _)| *k)
207            .collect();
208        assert_eq!(sliced, vec![(1, 0), (1, 1)]);
209        assert!(sheet.cells_in(5..=9, 5..=9).is_empty());
210    }
211
212    #[test]
213    fn sheet_is_default_and_cloneable() {
214        let sheet = Sheet::default();
215        assert!(sheet.is_empty());
216        let mut clone = sheet.clone();
217        clone.set(0, 0, Cell::number(9.0));
218        assert!(sheet.is_empty()); // deep copy
219        assert_eq!(clone.used_range(), Some(((0, 0), (0, 0))));
220    }
221}