Skip to main content

sheet_core/
cell.rs

1//! Cell model — values, style indices, and the XLSX error literals.
2//!
3//! A [`Cell`] is a [`CellValue`] plus an optional style index. Values cover
4//! everything a spreadsheet grid can hold: numbers, text, booleans, the
5//! eight-plus XLSX error literals ([`ExcelError`]), formula text, and the
6//! explicit blank.
7//!
8//! Coordinates live one level up ([`crate::Sheet`]): a cell never knows its
9//! own address, so cells are freely movable and the sparse map stays the
10//! single source of truth for occupancy.
11
12use core::fmt;
13use core::str::FromStr;
14
15/// The XLSX error literals — what a cell evaluates to when a formula fails.
16///
17/// The `Display` implementation renders the canonical spreadsheet spelling
18/// (`#DIV/0!`, …) and [`FromStr`] parses that spelling back, so the type
19/// round-trips through the text-oriented file formats losslessly.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub enum ExcelError {
22    /// `#DIV/0!` — division by zero (or by an empty cell).
23    Div0,
24    /// `#N/A` — a lookup found nothing (`NA()`, failed `VLOOKUP`).
25    Na,
26    /// `#NAME?` — an unknown function or named range.
27    Name,
28    /// `#NULL!` — a range intersection operator found no intersection.
29    Null,
30    /// `#NUM!` — a numeric argument or result is out of domain
31    /// (`SQRT(-1)`, overflow).
32    Num,
33    /// `#REF!` — a reference points at a deleted or invalid cell.
34    Ref,
35    /// `#VALUE!` — an argument has the wrong type (text where a number
36    /// belongs).
37    Value,
38    /// `#SPILL!` — a dynamic-array result is blocked by occupied cells.
39    Spill,
40    /// `#CALC!` — a calc-engine failure with no more specific literal.
41    Calc,
42}
43
44impl ExcelError {
45    /// The canonical XLSX spelling of this error, e.g. `#DIV/0!`.
46    #[must_use]
47    pub const fn as_str(self) -> &'static str {
48        match self {
49            ExcelError::Div0 => "#DIV/0!",
50            ExcelError::Na => "#N/A",
51            ExcelError::Name => "#NAME?",
52            ExcelError::Null => "#NULL!",
53            ExcelError::Num => "#NUM!",
54            ExcelError::Ref => "#REF!",
55            ExcelError::Value => "#VALUE!",
56            ExcelError::Spill => "#SPILL!",
57            ExcelError::Calc => "#CALC!",
58        }
59    }
60}
61
62impl fmt::Display for ExcelError {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        f.write_str(self.as_str())
65    }
66}
67
68impl FromStr for ExcelError {
69    type Err = ();
70
71    /// Parses a canonical XLSX error literal (`#REF!`) into an
72    /// [`ExcelError`]. Matching is exact and case-sensitive, mirroring the
73    /// file format. Unknown literals parse to `Err(())`.
74    fn from_str(s: &str) -> Result<Self, Self::Err> {
75        match s {
76            "#DIV/0!" => Ok(ExcelError::Div0),
77            "#N/A" => Ok(ExcelError::Na),
78            "#NAME?" => Ok(ExcelError::Name),
79            "#NULL!" => Ok(ExcelError::Null),
80            "#NUM!" => Ok(ExcelError::Num),
81            "#REF!" => Ok(ExcelError::Ref),
82            "#VALUE!" => Ok(ExcelError::Value),
83            "#SPILL!" => Ok(ExcelError::Spill),
84            "#CALC!" => Ok(ExcelError::Calc),
85            _ => Err(()),
86        }
87    }
88}
89
90/// Everything a grid cell can hold.
91///
92/// `Formula` carries the formula **text** verbatim as written (typically
93/// with its leading `=`) — `sheet-core` does not evaluate formulas. The
94/// dependency graph over formula text lives in
95/// [`crate::DependencyGraph`].
96#[derive(Debug, Clone, PartialEq)]
97pub enum CellValue {
98    /// A floating-point number — the universal numeric storage of every
99    /// mainstream spreadsheet (dates included: they are numbers plus style).
100    Number(f64),
101    /// Text. Empty text is distinct from [`CellValue::Blank`]: the cell
102    /// exists and holds a zero-length string.
103    Text(alloc::string::String),
104    /// A boolean.
105    Boolean(bool),
106    /// A formula error result.
107    Error(ExcelError),
108    /// Formula text, stored verbatim (usually including the leading `=`).
109    /// A cell whose value is a formula has no cached result in this model;
110    /// engines that cache results layer that on top.
111    Formula(alloc::string::String),
112    /// The explicit blank: the cell exists (and may carry a style) but holds
113    /// no value. Absence from the sheet map is the *implicit* blank.
114    Blank,
115}
116
117impl CellValue {
118    /// Convenience constructor: `CellValue::Number(n)`.
119    #[must_use]
120    pub const fn number(n: f64) -> Self {
121        CellValue::Number(n)
122    }
123
124    /// Convenience constructor: `CellValue::Text(s)`.
125    #[must_use]
126    pub fn text(s: impl Into<alloc::string::String>) -> Self {
127        CellValue::Text(s.into())
128    }
129
130    /// Convenience constructor: `CellValue::Boolean(b)`.
131    #[must_use]
132    pub const fn boolean(b: bool) -> Self {
133        CellValue::Boolean(b)
134    }
135
136    /// Convenience constructor: `CellValue::Error(e)`.
137    #[must_use]
138    pub const fn error(e: ExcelError) -> Self {
139        CellValue::Error(e)
140    }
141
142    /// Convenience constructor: `CellValue::Formula(text)`.
143    #[must_use]
144    pub fn formula(text: impl Into<alloc::string::String>) -> Self {
145        CellValue::Formula(text.into())
146    }
147
148    /// `true` when this value is a [`CellValue::Formula`].
149    #[must_use]
150    pub const fn is_formula(&self) -> bool {
151        matches!(self, CellValue::Formula(_))
152    }
153}
154
155/// One grid cell: a value and an optional style index.
156///
157/// `style` is an index into the workbook's style table (the `cellXfs` list
158/// in XLSX terms). `sheet-core` stores only the index — style *definitions*
159/// (fonts, fills, number formats) belong to the format codec.
160#[derive(Debug, Clone, PartialEq)]
161pub struct Cell {
162    /// The cell's value.
163    pub value: CellValue,
164    /// Index into the workbook's style table, if the cell is styled.
165    pub style: Option<u32>,
166}
167
168impl Cell {
169    /// A cell holding `value` with no style.
170    #[must_use]
171    pub const fn new(value: CellValue) -> Self {
172        Cell { value, style: None }
173    }
174
175    /// Convenience constructor: a number cell.
176    #[must_use]
177    pub const fn number(n: f64) -> Self {
178        Cell::new(CellValue::Number(n))
179    }
180
181    /// Convenience constructor: a text cell.
182    #[must_use]
183    pub fn text(s: impl Into<alloc::string::String>) -> Self {
184        Cell::new(CellValue::Text(s.into()))
185    }
186
187    /// Convenience constructor: a boolean cell.
188    #[must_use]
189    pub const fn boolean(b: bool) -> Self {
190        Cell::new(CellValue::Boolean(b))
191    }
192
193    /// Convenience constructor: a formula-error cell.
194    #[must_use]
195    pub const fn error(e: ExcelError) -> Self {
196        Cell::new(CellValue::Error(e))
197    }
198
199    /// Convenience constructor: a formula cell.
200    #[must_use]
201    pub fn formula(text: impl Into<alloc::string::String>) -> Self {
202        Cell::new(CellValue::Formula(text.into()))
203    }
204
205    /// Convenience constructor: the explicit blank.
206    #[must_use]
207    pub const fn blank() -> Self {
208        Cell::new(CellValue::Blank)
209    }
210
211    /// Builder: attaches style index `style`.
212    #[must_use]
213    pub const fn with_style(mut self, style: u32) -> Self {
214        self.style = Some(style);
215        self
216    }
217}
218
219#[cfg(test)]
220mod tests {
221    #![allow(
222        clippy::unwrap_used,
223        clippy::expect_used,
224        clippy::panic,
225        clippy::indexing_slicing
226    )]
227
228    use super::{Cell, CellValue, ExcelError};
229    use alloc::format;
230    use alloc::string::ToString;
231    use core::str::FromStr;
232
233    #[test]
234    fn error_literals_round_trip_through_display_and_from_str() {
235        let all = [
236            ExcelError::Div0,
237            ExcelError::Na,
238            ExcelError::Name,
239            ExcelError::Null,
240            ExcelError::Num,
241            ExcelError::Ref,
242            ExcelError::Value,
243            ExcelError::Spill,
244            ExcelError::Calc,
245        ];
246        for e in all {
247            let rendered = format!("{e}");
248            assert_eq!(rendered, e.as_str(), "{e:?} Display/as_str mismatch");
249            assert_eq!(ExcelError::from_str(&rendered), Ok(e), "{e:?} round trip");
250        }
251    }
252
253    #[test]
254    fn unknown_error_literal_is_rejected() {
255        assert_eq!(ExcelError::from_str("#NOPE!"), Err(()));
256        assert_eq!(ExcelError::from_str("#ref!"), Err(())); // case-sensitive
257        assert_eq!(ExcelError::from_str(""), Err(()));
258    }
259
260    #[test]
261    fn cell_constructors_and_style_builder() {
262        let styled = Cell::number(1.5).with_style(7);
263        assert_eq!(
264            styled,
265            Cell {
266                value: CellValue::Number(1.5),
267                style: Some(7)
268            }
269        );
270        assert_eq!(Cell::text("hi").style, None);
271        assert_eq!(Cell::boolean(true).value, CellValue::Boolean(true));
272        assert_eq!(
273            Cell::formula("=A1").value,
274            CellValue::Formula("=A1".to_string())
275        );
276        assert_eq!(Cell::blank().value, CellValue::Blank);
277        assert_eq!(Cell::new(CellValue::Blank).style, None);
278    }
279
280    #[test]
281    fn value_helpers() {
282        assert!(CellValue::formula("=A1").is_formula());
283        assert!(!CellValue::number(0.0).is_formula());
284        assert!(!CellValue::Blank.is_formula());
285        assert_eq!(CellValue::text("x"), CellValue::Text("x".to_string()));
286        assert_eq!(CellValue::boolean(false), CellValue::Boolean(false));
287        assert_eq!(CellValue::number(2.0), CellValue::Number(2.0));
288    }
289}