Skip to main content

sheetkit_core/workbook/
open_options.rs

1/// Controls how worksheets and auxiliary parts are parsed during open.
2#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3pub enum ReadMode {
4    /// Parse all parts eagerly. Equivalent to the old `Full` mode.
5    Eager,
6    /// Skip auxiliary parts (comments, drawings, charts, images, doc props,
7    /// pivot tables, slicers, threaded comments, VBA, tables, form controls).
8    /// These are stored as raw bytes for on-demand parsing or direct
9    /// round-trip preservation. Equivalent to the old `ReadFast` mode.
10    /// Will evolve into true lazy on-demand hydration in later workstreams.
11    /// This is the default mode.
12    #[default]
13    Lazy,
14    /// Forward-only streaming read mode (reserved for future use).
15    /// Currently behaves the same as `Lazy`.
16    Stream,
17}
18
19/// Controls when auxiliary parts (comments, charts, images, etc.) are parsed.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
21pub enum AuxParts {
22    /// Parse auxiliary parts only when accessed. This is the default.
23    #[default]
24    Deferred,
25    /// Parse all auxiliary parts during open.
26    EagerLoad,
27}
28
29/// Controls how number cells carrying a date-like number format are
30/// returned.
31///
32/// OOXML distinguishes between a cell's value type (`t="n"`, `t="d"`, ...)
33/// and the number format applied to it. Microsoft Excel itself almost
34/// never emits `t="d"`; dates are instead stored as `t="n"` with a date
35/// number format attached. Depending on the caller's needs, sheetkit can
36/// either honor the `t` attribute literally or promote such number cells
37/// to [`CellValue::Date`](crate::cell::CellValue::Date).
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
39pub enum DateInterpretation {
40    /// Follow the cell's `t` attribute strictly. A `t="n"` cell is
41    /// returned as `CellValue::Number` even when its number format is a
42    /// date format; only `t="d"` cells become `CellValue::Date`. Matches
43    /// the OOXML spec literally. Opt in when you want to treat the raw
44    /// cell type as the source of truth.
45    CellType,
46    /// Promote `t="n"` (or untyped) cells whose style references a
47    /// built-in date number format (IDs 14-22, 45-47) or a custom format
48    /// code containing date/time tokens (y, m, d, h, s) to
49    /// `CellValue::Date`. This is the default, and matches how Microsoft
50    /// Excel stores dates in practice.
51    #[default]
52    NumFmt,
53}
54
55/// Options for controlling how a workbook is opened and parsed.
56///
57/// Resource dimensions use finite secure defaults. Read mode defaults to
58/// `Lazy` and auxiliary parts default to `Deferred`.
59/// Use the builder-style setter methods for convenience.
60#[derive(Debug, Clone, Default)]
61pub struct OpenOptions {
62    /// Maximum number of rows to read per sheet. Rows beyond this limit
63    /// are silently discarded during parsing.
64    pub sheet_rows: Option<u32>,
65
66    /// Only parse sheets whose names are in this list. Sheets not listed
67    /// are represented as empty worksheets (their XML is not parsed).
68    /// `None` means parse all sheets.
69    pub sheets: Option<Vec<String>>,
70
71    /// Maximum total decompressed size of all ZIP entries in bytes.
72    /// Compatibility override for aggregate declared and actual ZIP bytes.
73    /// `None` uses the finite values in [`OpenLimits`](super::OpenLimits).
74    pub max_unzip_size: Option<u64>,
75
76    /// Maximum number of ZIP entries allowed.
77    /// Compatibility override for archive entry count.
78    /// `None` uses the finite value in [`OpenLimits`](super::OpenLimits).
79    pub max_zip_entries: Option<usize>,
80
81    /// Independently configurable finite resource limits.
82    pub limits: super::OpenLimits,
83
84    /// Independently configurable finite encryption-container and KDF limits.
85    #[cfg(feature = "encryption")]
86    pub crypt_limits: crate::crypt::CryptLimits,
87
88    /// Independently configurable finite VBA project limits.
89    pub vba_limits: crate::vba::VbaLimits,
90
91    /// Read mode: `Lazy` (default) skips auxiliary parts for faster
92    /// read-only workloads; `Eager` parses everything; `Stream` is
93    /// reserved for future streaming reads.
94    pub read_mode: ReadMode,
95
96    /// Controls when auxiliary parts are parsed.
97    pub aux_parts: AuxParts,
98
99    /// Controls how date-formatted number cells are returned. Defaults to
100    /// [`DateInterpretation::NumFmt`], which matches how Excel authors
101    /// files in practice. Use [`DateInterpretation::CellType`] when you
102    /// want spec-literal behavior.
103    pub date_interpretation: DateInterpretation,
104}
105
106impl OpenOptions {
107    /// Create options with finite secure limits, lazy read, and deferred parts.
108    pub fn new() -> Self {
109        Self::default()
110    }
111
112    /// Set the maximum number of rows to read per sheet.
113    pub fn sheet_rows(mut self, rows: u32) -> Self {
114        self.sheet_rows = Some(rows);
115        self
116    }
117
118    /// Only parse sheets whose names are in this list.
119    pub fn sheets(mut self, names: Vec<String>) -> Self {
120        self.sheets = Some(names);
121        self
122    }
123
124    /// Set the maximum total decompressed size in bytes.
125    pub fn max_unzip_size(mut self, size: u64) -> Self {
126        self.max_unzip_size = Some(size);
127        self
128    }
129
130    /// Set the maximum number of ZIP entries.
131    pub fn max_zip_entries(mut self, count: usize) -> Self {
132        self.max_zip_entries = Some(count);
133        self
134    }
135
136    /// Override the outer input byte limit for this open operation.
137    pub fn max_outer_input_bytes(mut self, bytes: u64) -> Self {
138        self.limits.outer_input_bytes = bytes;
139        self
140    }
141
142    /// Override the declared byte limit for each archive entry.
143    pub fn max_entry_declared_bytes(mut self, bytes: u64) -> Self {
144        self.limits.entry_declared_bytes = bytes;
145        self
146    }
147
148    /// Override the actual byte limit for each archive entry.
149    pub fn max_entry_actual_bytes(mut self, bytes: u64) -> Self {
150        self.limits.entry_actual_bytes = bytes;
151        self
152    }
153
154    /// Override the aggregate declared archive byte limit.
155    pub fn max_aggregate_declared_bytes(mut self, bytes: u64) -> Self {
156        self.limits.aggregate_declared_bytes = bytes;
157        self
158    }
159
160    /// Override the aggregate actual archive byte limit.
161    pub fn max_aggregate_actual_bytes(mut self, bytes: u64) -> Self {
162        self.limits.aggregate_actual_bytes = bytes;
163        self
164    }
165
166    /// Override the per-entry expansion ratio limit.
167    pub fn max_compression_ratio(mut self, ratio: u64) -> Self {
168        self.limits.compression_ratio = ratio;
169        self
170    }
171
172    /// Override the decompressed entry size at or below which the expansion
173    /// ratio is not enforced. `0` enforces the ratio for every entry.
174    pub fn compression_ratio_floor_bytes(mut self, bytes: u64) -> Self {
175        self.limits.compression_ratio_floor_bytes = bytes;
176        self
177    }
178
179    /// Override the actual byte limit for each XML part.
180    pub fn max_xml_part_bytes(mut self, bytes: u64) -> Self {
181        self.limits.xml_bytes = bytes;
182        self
183    }
184
185    /// Override the byte limit for raw package data retained after open.
186    pub fn max_retained_package_bytes(mut self, bytes: u64) -> Self {
187        self.limits.retained_package_bytes = bytes;
188        self
189    }
190
191    /// Override encryption-container and password-derivation limits.
192    #[cfg(feature = "encryption")]
193    pub fn crypt_limits(mut self, limits: crate::crypt::CryptLimits) -> Self {
194        self.crypt_limits = limits;
195        self
196    }
197
198    /// Override VBA project parsing limits.
199    pub fn vba_limits(mut self, limits: crate::vba::VbaLimits) -> Self {
200        self.vba_limits = limits;
201        self
202    }
203
204    pub(crate) fn resolved_limits(&self) -> crate::error::Result<super::OpenLimits> {
205        let mut limits = self.limits;
206        if let Some(entries) = self.max_zip_entries {
207            limits.archive_entries = entries as u64;
208        }
209        if let Some(bytes) = self.max_unzip_size {
210            limits.aggregate_declared_bytes = bytes;
211            limits.aggregate_actual_bytes = bytes;
212        }
213        limits.validate()
214    }
215
216    /// Set the read mode. `Lazy` skips auxiliary parts for faster
217    /// read-only workloads. `Stream` is reserved for future use.
218    pub fn read_mode(mut self, mode: ReadMode) -> Self {
219        self.read_mode = mode;
220        self
221    }
222
223    /// Set the auxiliary parts parsing policy.
224    pub fn aux_parts(mut self, policy: AuxParts) -> Self {
225        self.aux_parts = policy;
226        self
227    }
228
229    /// Set the date interpretation policy. When set to
230    /// [`DateInterpretation::NumFmt`], number cells that carry a date
231    /// number format are returned as `CellValue::Date` instead of
232    /// `CellValue::Number`.
233    pub fn date_interpretation(mut self, interpretation: DateInterpretation) -> Self {
234        self.date_interpretation = interpretation;
235        self
236    }
237
238    /// Returns true when auxiliary parts should be skipped during open.
239    /// Lazy/Stream modes always skip. Eager mode respects `aux_parts`.
240    pub(crate) fn skip_aux_parts(&self) -> bool {
241        match self.read_mode {
242            ReadMode::Eager => self.aux_parts == AuxParts::Deferred,
243            ReadMode::Lazy | ReadMode::Stream => true,
244        }
245    }
246
247    /// Returns true when worksheets are parsed during open (`Eager` mode).
248    pub(crate) fn is_eager(&self) -> bool {
249        self.read_mode == ReadMode::Eager
250    }
251
252    /// Check whether a given sheet name should be parsed based on the `sheets` filter.
253    pub(crate) fn should_parse_sheet(&self, name: &str) -> bool {
254        match &self.sheets {
255            None => true,
256            Some(names) => names.iter().any(|n| n == name),
257        }
258    }
259}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264
265    #[test]
266    fn test_default_options() {
267        let opts = OpenOptions::default();
268        assert!(opts.sheet_rows.is_none());
269        assert!(opts.sheets.is_none());
270        assert!(opts.max_unzip_size.is_none());
271        assert!(opts.max_zip_entries.is_none());
272        assert_eq!(opts.limits, crate::workbook::OpenLimits::default());
273        assert_eq!(opts.read_mode, ReadMode::Lazy);
274        assert!(opts.skip_aux_parts());
275        assert_eq!(opts.date_interpretation, DateInterpretation::NumFmt);
276    }
277
278    #[test]
279    fn test_date_interpretation_default_is_num_fmt() {
280        assert_eq!(DateInterpretation::default(), DateInterpretation::NumFmt);
281    }
282
283    #[test]
284    fn test_date_interpretation_builder() {
285        let opts = OpenOptions::new().date_interpretation(DateInterpretation::CellType);
286        assert_eq!(opts.date_interpretation, DateInterpretation::CellType);
287
288        let opts = opts.date_interpretation(DateInterpretation::NumFmt);
289        assert_eq!(opts.date_interpretation, DateInterpretation::NumFmt);
290    }
291
292    #[test]
293    fn test_builder_methods() {
294        let opts = OpenOptions::new()
295            .sheet_rows(100)
296            .sheets(vec!["Sheet1".to_string()])
297            .max_unzip_size(1_000_000)
298            .max_zip_entries(500);
299        assert_eq!(opts.sheet_rows, Some(100));
300        assert_eq!(opts.sheets, Some(vec!["Sheet1".to_string()]));
301        assert_eq!(opts.max_unzip_size, Some(1_000_000));
302        assert_eq!(opts.max_zip_entries, Some(500));
303    }
304
305    #[test]
306    fn test_read_mode_builder() {
307        let opts = OpenOptions::new().read_mode(ReadMode::Lazy);
308        assert_eq!(opts.read_mode, ReadMode::Lazy);
309        assert!(opts.skip_aux_parts());
310    }
311
312    #[test]
313    fn test_read_mode_default_is_lazy() {
314        let mode = ReadMode::default();
315        assert_eq!(mode, ReadMode::Lazy);
316    }
317
318    #[test]
319    fn test_read_mode_combined_with_other_options() {
320        let opts = OpenOptions::new().sheet_rows(50).read_mode(ReadMode::Lazy);
321        assert_eq!(opts.sheet_rows, Some(50));
322        assert!(opts.skip_aux_parts());
323    }
324
325    #[test]
326    fn test_stream_mode_skips_aux_parts() {
327        let opts = OpenOptions::new().read_mode(ReadMode::Stream);
328        assert!(opts.skip_aux_parts());
329        assert!(!opts.is_eager());
330    }
331
332    #[test]
333    fn test_aux_parts_default_is_deferred() {
334        let opts = OpenOptions::default();
335        assert_eq!(opts.aux_parts, AuxParts::Deferred);
336    }
337
338    #[test]
339    fn test_aux_parts_deferred() {
340        let opts = OpenOptions::new().aux_parts(AuxParts::Deferred);
341        assert_eq!(opts.aux_parts, AuxParts::Deferred);
342    }
343
344    #[test]
345    fn test_eager_mode_with_deferred_aux_skips_aux() {
346        let opts = OpenOptions::new()
347            .read_mode(ReadMode::Eager)
348            .aux_parts(AuxParts::Deferred);
349        assert!(opts.skip_aux_parts());
350    }
351
352    #[test]
353    fn test_eager_mode_with_eager_aux_parses_all() {
354        let opts = OpenOptions::new()
355            .read_mode(ReadMode::Eager)
356            .aux_parts(AuxParts::EagerLoad);
357        assert!(!opts.skip_aux_parts());
358    }
359
360    #[test]
361    fn test_should_parse_sheet_no_filter() {
362        let opts = OpenOptions::default();
363        assert!(opts.should_parse_sheet("Sheet1"));
364        assert!(opts.should_parse_sheet("anything"));
365    }
366
367    #[test]
368    fn test_should_parse_sheet_with_filter() {
369        let opts = OpenOptions::new().sheets(vec!["Sales".to_string(), "Data".to_string()]);
370        assert!(opts.should_parse_sheet("Sales"));
371        assert!(opts.should_parse_sheet("Data"));
372        assert!(!opts.should_parse_sheet("Sheet1"));
373        assert!(!opts.should_parse_sheet("Other"));
374    }
375
376    #[test]
377    fn test_helper_methods() {
378        let eager = OpenOptions::new().read_mode(ReadMode::Eager);
379        assert!(eager.is_eager());
380
381        let lazy = OpenOptions::new().read_mode(ReadMode::Lazy);
382        assert!(!lazy.is_eager());
383
384        let stream = OpenOptions::new().read_mode(ReadMode::Stream);
385        assert!(!stream.is_eager());
386    }
387}