Skip to main content

sheetkit_core/
stream_reader.rs

1//! Forward-only streaming worksheet reader.
2//!
3//! [`SheetStreamReader`] reads worksheet XML row-by-row using event-driven
4//! parsing (`quick_xml::Reader`) without materializing the full DOM. This
5//! enables processing large worksheets with bounded memory by reading rows
6//! in batches.
7//!
8//! Shared string indices are resolved through a reference to the workbook's
9//! [`SharedStringTable`]. Cell types (string, number, boolean, date, formula,
10//! error, inline string) are handled according to the OOXML specification.
11
12use std::fs::File;
13use std::io::{BufRead, Read};
14
15use quick_xml::events::Event;
16use quick_xml::name::QName;
17
18use crate::cell::CellValue;
19use crate::error::{Error, Result};
20use crate::resource::{
21    ResourceCategory, ResourceDimension, ResourceLimitError, ResourceOperation, ResourceStage,
22};
23use crate::sst::SharedStringTable;
24use crate::utils::cell_ref::cell_name_to_coordinates;
25use crate::utils::constants::{MAX_COLUMNS, MAX_ROWS};
26use crate::workbook::open_options::DateInterpretation;
27
28/// Maximum number of rows returned by one streaming-reader batch.
29pub const MAX_STREAM_BATCH_ROWS: usize = 100_000;
30
31/// Workbook-owned input used by [`crate::workbook::Workbook::open_sheet_reader`].
32///
33/// Clean in-memory XML is borrowed directly. Package-backed or dirty XML is
34/// read through an anonymous disk spool so reader construction never needs a
35/// second sheet-sized allocation.
36#[doc(hidden)]
37pub enum SheetReaderInput<'a> {
38    Borrowed(std::io::Cursor<&'a [u8]>),
39    Spool(std::io::BufReader<File>),
40}
41
42impl Read for SheetReaderInput<'_> {
43    fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {
44        match self {
45            Self::Borrowed(reader) => reader.read(buffer),
46            Self::Spool(reader) => reader.read(buffer),
47        }
48    }
49}
50
51impl BufRead for SheetReaderInput<'_> {
52    fn fill_buf(&mut self) -> std::io::Result<&[u8]> {
53        match self {
54            Self::Borrowed(reader) => reader.fill_buf(),
55            Self::Spool(reader) => reader.fill_buf(),
56        }
57    }
58
59    fn consume(&mut self, amount: usize) {
60        match self {
61            Self::Borrowed(reader) => reader.consume(amount),
62            Self::Spool(reader) => reader.consume(amount),
63        }
64    }
65}
66
67enum OwnedSheetReaderInput {
68    Spool(std::io::BufReader<File>),
69}
70
71impl Read for OwnedSheetReaderInput {
72    fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {
73        match self {
74            Self::Spool(reader) => reader.read(buffer),
75        }
76    }
77}
78
79impl BufRead for OwnedSheetReaderInput {
80    fn fill_buf(&mut self) -> std::io::Result<&[u8]> {
81        match self {
82            Self::Spool(reader) => reader.fill_buf(),
83        }
84    }
85
86    fn consume(&mut self, amount: usize) {
87        match self {
88            Self::Spool(reader) => reader.consume(amount),
89        }
90    }
91}
92
93/// A single row produced by the streaming reader.
94#[derive(Debug, Clone, PartialEq)]
95pub struct StreamRow {
96    /// 1-based row number.
97    pub row_number: u32,
98    /// Cells in this row as (1-based column index, value) pairs.
99    pub cells: Vec<(u32, CellValue)>,
100}
101
102/// Forward-only streaming reader for worksheet XML.
103///
104/// Reads rows in batches without deserializing the entire worksheet into
105/// memory. The reader borrows the shared string table for resolving string
106/// cell references.
107pub struct SheetStreamReader<'a, R: BufRead> {
108    reader: quick_xml::Reader<R>,
109    sst: &'a SharedStringTable,
110    done: bool,
111    row_limit: Option<u32>,
112    rows_emitted: u32,
113    date_interpretation: DateInterpretation,
114    style_is_date: Vec<bool>,
115    last_row_number: u32,
116}
117
118impl<'a, R: BufRead> SheetStreamReader<'a, R> {
119    /// Create a new streaming reader over the given `BufRead` source.
120    ///
121    /// `sst` is a reference to the shared string table for resolving
122    /// shared string cell values. Optional configuration (row limit, date
123    /// interpretation) is applied via the builder methods.
124    pub fn new(source: R, sst: &'a SharedStringTable) -> Self {
125        let mut reader = quick_xml::Reader::from_reader(source);
126        reader.config_mut().trim_text(false);
127        Self {
128            reader,
129            sst,
130            done: false,
131            row_limit: None,
132            rows_emitted: 0,
133            date_interpretation: DateInterpretation::default(),
134            style_is_date: Vec::new(),
135            last_row_number: 0,
136        }
137    }
138
139    /// Cap the number of rows produced by this reader. `None` means no
140    /// limit (the default).
141    pub fn row_limit(mut self, limit: Option<u32>) -> Self {
142        self.row_limit = limit;
143        self
144    }
145
146    /// Configure how date-formatted number cells are interpreted.
147    ///
148    /// `style_is_date` is a per-style boolean produced by
149    /// [`crate::style::compute_style_is_date`]; it is indexed by each
150    /// cell's `s` attribute. Empty vectors are equivalent to "no style
151    /// was a date format", which is the safe default.
152    pub fn date_promotion(
153        mut self,
154        interpretation: DateInterpretation,
155        style_is_date: Vec<bool>,
156    ) -> Self {
157        self.date_interpretation = interpretation;
158        self.style_is_date = style_is_date;
159        self
160    }
161
162    /// Returns `true` when `style_idx` refers to a style whose number
163    /// format is a date format and the reader is configured with
164    /// [`DateInterpretation::NumFmt`].
165    fn should_promote_to_date(&self, style_idx: Option<u32>) -> bool {
166        if !matches!(self.date_interpretation, DateInterpretation::NumFmt) {
167            return false;
168        }
169        let idx = match style_idx {
170            Some(i) => i as usize,
171            None => return false,
172        };
173        self.style_is_date.get(idx).copied().unwrap_or(false)
174    }
175
176    /// Read the next batch of rows. Returns an empty `Vec` when there are no
177    /// more rows to read.
178    pub fn next_batch(&mut self, batch_size: usize) -> Result<Vec<StreamRow>> {
179        let mut rows = prepare_batch(batch_size)?;
180        if self.done {
181            return Ok(rows);
182        }
183
184        let mut buf = Vec::with_capacity(4096);
185
186        loop {
187            if rows.len() >= batch_size {
188                break;
189            }
190            if let Some(limit) = self.row_limit {
191                if self.rows_emitted >= limit {
192                    self.done = true;
193                    break;
194                }
195            }
196
197            buf.clear();
198            match self
199                .reader
200                .read_event_into(&mut buf)
201                .map_err(|e| Error::XmlParse(e.to_string()))?
202            {
203                Event::Start(ref e) if is_element(e.name(), b"row") => {
204                    let row_number =
205                        resolve_row_number(extract_row_number(e)?, self.last_row_number)?;
206                    let row = self.parse_row_body(row_number)?;
207                    self.last_row_number = row_number;
208                    self.rows_emitted += 1;
209                    if !row.cells.is_empty() {
210                        rows.push(row);
211                    }
212                }
213                Event::Eof => {
214                    self.done = true;
215                    break;
216                }
217                _ => {}
218            }
219        }
220
221        Ok(rows)
222    }
223
224    /// Returns `true` if there are potentially more rows to read.
225    pub fn has_more(&self) -> bool {
226        !self.done
227    }
228
229    /// Close the reader and release resources.
230    pub fn close(self) {
231        drop(self);
232    }
233
234    /// Parse the body of a `<row>` element (its child `<c>` elements) after
235    /// the row number has been extracted from the opening tag.
236    fn parse_row_body(&mut self, row_number: u32) -> Result<StreamRow> {
237        let mut cells = Vec::new();
238        let mut last_col = 0;
239        let mut buf = Vec::with_capacity(1024);
240
241        loop {
242            buf.clear();
243            match self
244                .reader
245                .read_event_into(&mut buf)
246                .map_err(|e| Error::XmlParse(e.to_string()))?
247            {
248                Event::Start(ref e) if is_element(e.name(), b"c") => {
249                    let (explicit_col, cell_type, style_idx) = extract_cell_attrs(e)?;
250                    let col = resolve_cell_column(explicit_col, last_col)?;
251                    let promote = self.should_promote_to_date(style_idx);
252                    let cv = self.parse_cell_body(cell_type.as_deref(), promote)?;
253                    last_col = col;
254                    cells.push((col, cv));
255                }
256                Event::Empty(ref e) if is_element(e.name(), b"c") => {
257                    let (explicit_col, cell_type, style_idx) = extract_cell_attrs(e)?;
258                    let col = resolve_cell_column(explicit_col, last_col)?;
259                    let promote = self.should_promote_to_date(style_idx);
260                    let cv = resolve_cell_value(
261                        self.sst,
262                        cell_type.as_deref(),
263                        None,
264                        None,
265                        None,
266                        promote,
267                    )?;
268                    last_col = col;
269                    cells.push((col, cv));
270                }
271                Event::End(ref e) if is_element(e.name(), b"row") => break,
272                Event::Eof => {
273                    self.done = true;
274                    return Err(unexpected_eof("row"));
275                }
276                _ => {}
277            }
278        }
279
280        Ok(StreamRow { row_number, cells })
281    }
282
283    /// Parse the body of a `<c>` element (its child `<v>`, `<f>`, `<is>`
284    /// elements) after the cell attributes have been extracted.
285    fn parse_cell_body(
286        &mut self,
287        cell_type: Option<&str>,
288        promote_to_date: bool,
289    ) -> Result<CellValue> {
290        let mut value_text: Option<String> = None;
291        let mut formula_text: Option<String> = None;
292        let mut inline_string: Option<String> = None;
293        let mut buf = Vec::with_capacity(512);
294        let mut in_is = false;
295        let mut in_phonetic = false;
296
297        loop {
298            buf.clear();
299            match self
300                .reader
301                .read_event_into(&mut buf)
302                .map_err(|e| Error::XmlParse(e.to_string()))?
303            {
304                Event::Start(ref e) => {
305                    let local = e.local_name();
306                    if local.as_ref() == b"v" {
307                        value_text = Some(self.read_text_content(b"v")?);
308                    } else if local.as_ref() == b"f" {
309                        formula_text = Some(self.read_text_content(b"f")?);
310                    } else if local.as_ref() == b"is" {
311                        in_is = true;
312                        inline_string = Some(String::new());
313                    } else if local.as_ref() == b"rPh" && in_is {
314                        in_phonetic = true;
315                    } else if local.as_ref() == b"t" && in_is && !in_phonetic {
316                        let t = self.read_text_content(b"t")?;
317                        if let Some(ref mut is) = inline_string {
318                            is.push_str(&t);
319                        }
320                    }
321                }
322                Event::End(ref e) => {
323                    let local = e.local_name();
324                    if local.as_ref() == b"c" {
325                        break;
326                    }
327                    if local.as_ref() == b"is" {
328                        in_is = false;
329                    } else if local.as_ref() == b"rPh" {
330                        in_phonetic = false;
331                    }
332                }
333                Event::Eof => {
334                    self.done = true;
335                    return Err(unexpected_eof("cell"));
336                }
337                _ => {}
338            }
339        }
340
341        resolve_cell_value(
342            self.sst,
343            cell_type,
344            value_text.as_deref(),
345            formula_text,
346            inline_string,
347            promote_to_date,
348        )
349    }
350
351    /// Read text content between an opening tag and its matching closing tag.
352    fn read_text_content(&mut self, end_tag: &[u8]) -> Result<String> {
353        let mut text = String::new();
354        let mut buf = Vec::with_capacity(256);
355        loop {
356            buf.clear();
357            match self
358                .reader
359                .read_event_into(&mut buf)
360                .map_err(|e| Error::XmlParse(e.to_string()))?
361            {
362                Event::Text(ref e) => {
363                    let decoded = e.unescape().map_err(|e| Error::XmlParse(e.to_string()))?;
364                    text.push_str(&decoded);
365                }
366                Event::End(ref e) if e.local_name().as_ref() == end_tag => break,
367                Event::Eof => {
368                    self.done = true;
369                    return Err(unexpected_eof("element"));
370                }
371                _ => {}
372            }
373        }
374        Ok(text)
375    }
376}
377
378/// Owning variant of [`SheetStreamReader`] for use in FFI contexts where
379/// lifetime parameters are not supported (e.g., napi classes).
380///
381/// Stores its own copy of the shared string table and the XML byte source,
382/// avoiding any borrowed references. The parsing logic delegates to the same
383/// free functions used by the borrowed reader.
384pub struct OwnedSheetStreamReader {
385    reader: quick_xml::Reader<OwnedSheetReaderInput>,
386    sst: SharedStringTable,
387    done: bool,
388    row_limit: Option<u32>,
389    rows_emitted: u32,
390    date_interpretation: DateInterpretation,
391    style_is_date: Vec<bool>,
392    last_row_number: u32,
393}
394
395impl OwnedSheetStreamReader {
396    pub(crate) fn from_spool(file: File, sst: SharedStringTable) -> Self {
397        Self::from_input(
398            OwnedSheetReaderInput::Spool(std::io::BufReader::new(file)),
399            sst,
400        )
401    }
402
403    fn from_input(source: OwnedSheetReaderInput, sst: SharedStringTable) -> Self {
404        let mut reader = quick_xml::Reader::from_reader(source);
405        reader.config_mut().trim_text(false);
406        Self {
407            reader,
408            sst,
409            done: false,
410            row_limit: None,
411            rows_emitted: 0,
412            date_interpretation: DateInterpretation::default(),
413            style_is_date: Vec::new(),
414            last_row_number: 0,
415        }
416    }
417
418    /// Cap the number of rows produced by this reader. `None` means no
419    /// limit (the default).
420    pub fn row_limit(mut self, limit: Option<u32>) -> Self {
421        self.row_limit = limit;
422        self
423    }
424
425    /// Configure how date-formatted number cells are interpreted.
426    /// See [`SheetStreamReader::date_promotion`] for details.
427    pub fn date_promotion(
428        mut self,
429        interpretation: DateInterpretation,
430        style_is_date: Vec<bool>,
431    ) -> Self {
432        self.date_interpretation = interpretation;
433        self.style_is_date = style_is_date;
434        self
435    }
436
437    fn should_promote_to_date(&self, style_idx: Option<u32>) -> bool {
438        if !matches!(self.date_interpretation, DateInterpretation::NumFmt) {
439            return false;
440        }
441        let idx = match style_idx {
442            Some(i) => i as usize,
443            None => return false,
444        };
445        self.style_is_date.get(idx).copied().unwrap_or(false)
446    }
447
448    /// Read the next batch of rows. Returns an empty `Vec` when there are no
449    /// more rows to read.
450    pub fn next_batch(&mut self, batch_size: usize) -> Result<Vec<StreamRow>> {
451        let mut rows = prepare_batch(batch_size)?;
452        if self.done {
453            return Ok(rows);
454        }
455
456        let mut buf = Vec::with_capacity(4096);
457
458        loop {
459            if rows.len() >= batch_size {
460                break;
461            }
462            if let Some(limit) = self.row_limit {
463                if self.rows_emitted >= limit {
464                    self.done = true;
465                    break;
466                }
467            }
468
469            buf.clear();
470            match self
471                .reader
472                .read_event_into(&mut buf)
473                .map_err(|e| Error::XmlParse(e.to_string()))?
474            {
475                Event::Start(ref e) if is_element(e.name(), b"row") => {
476                    let row_number =
477                        resolve_row_number(extract_row_number(e)?, self.last_row_number)?;
478                    let row = self.parse_row_body(row_number)?;
479                    self.last_row_number = row_number;
480                    self.rows_emitted += 1;
481                    if !row.cells.is_empty() {
482                        rows.push(row);
483                    }
484                }
485                Event::Eof => {
486                    self.done = true;
487                    break;
488                }
489                _ => {}
490            }
491        }
492
493        Ok(rows)
494    }
495
496    /// Returns `true` if there are potentially more rows to read.
497    pub fn has_more(&self) -> bool {
498        !self.done
499    }
500
501    /// Close the reader and release resources.
502    pub fn close(self) {
503        drop(self);
504    }
505
506    fn parse_row_body(&mut self, row_number: u32) -> Result<StreamRow> {
507        let mut cells = Vec::new();
508        let mut last_col = 0;
509        let mut buf = Vec::with_capacity(1024);
510
511        loop {
512            buf.clear();
513            match self
514                .reader
515                .read_event_into(&mut buf)
516                .map_err(|e| Error::XmlParse(e.to_string()))?
517            {
518                Event::Start(ref e) if is_element(e.name(), b"c") => {
519                    let (explicit_col, cell_type, style_idx) = extract_cell_attrs(e)?;
520                    let col = resolve_cell_column(explicit_col, last_col)?;
521                    let promote = self.should_promote_to_date(style_idx);
522                    let cv = self.parse_cell_body(cell_type.as_deref(), promote)?;
523                    last_col = col;
524                    cells.push((col, cv));
525                }
526                Event::Empty(ref e) if is_element(e.name(), b"c") => {
527                    let (explicit_col, cell_type, style_idx) = extract_cell_attrs(e)?;
528                    let col = resolve_cell_column(explicit_col, last_col)?;
529                    let promote = self.should_promote_to_date(style_idx);
530                    let cv = resolve_cell_value(
531                        &self.sst,
532                        cell_type.as_deref(),
533                        None,
534                        None,
535                        None,
536                        promote,
537                    )?;
538                    last_col = col;
539                    cells.push((col, cv));
540                }
541                Event::End(ref e) if is_element(e.name(), b"row") => break,
542                Event::Eof => {
543                    self.done = true;
544                    return Err(unexpected_eof("row"));
545                }
546                _ => {}
547            }
548        }
549
550        Ok(StreamRow { row_number, cells })
551    }
552
553    fn parse_cell_body(
554        &mut self,
555        cell_type: Option<&str>,
556        promote_to_date: bool,
557    ) -> Result<CellValue> {
558        let mut value_text: Option<String> = None;
559        let mut formula_text: Option<String> = None;
560        let mut inline_string: Option<String> = None;
561        let mut buf = Vec::with_capacity(512);
562        let mut in_is = false;
563        let mut in_phonetic = false;
564
565        loop {
566            buf.clear();
567            match self
568                .reader
569                .read_event_into(&mut buf)
570                .map_err(|e| Error::XmlParse(e.to_string()))?
571            {
572                Event::Start(ref e) => {
573                    let local = e.local_name();
574                    if local.as_ref() == b"v" {
575                        value_text = Some(self.read_text_content(b"v")?);
576                    } else if local.as_ref() == b"f" {
577                        formula_text = Some(self.read_text_content(b"f")?);
578                    } else if local.as_ref() == b"is" {
579                        in_is = true;
580                        inline_string = Some(String::new());
581                    } else if local.as_ref() == b"rPh" && in_is {
582                        in_phonetic = true;
583                    } else if local.as_ref() == b"t" && in_is && !in_phonetic {
584                        let t = self.read_text_content(b"t")?;
585                        if let Some(ref mut is) = inline_string {
586                            is.push_str(&t);
587                        }
588                    }
589                }
590                Event::End(ref e) => {
591                    let local = e.local_name();
592                    if local.as_ref() == b"c" {
593                        break;
594                    }
595                    if local.as_ref() == b"is" {
596                        in_is = false;
597                    } else if local.as_ref() == b"rPh" {
598                        in_phonetic = false;
599                    }
600                }
601                Event::Eof => {
602                    self.done = true;
603                    return Err(unexpected_eof("cell"));
604                }
605                _ => {}
606            }
607        }
608
609        resolve_cell_value(
610            &self.sst,
611            cell_type,
612            value_text.as_deref(),
613            formula_text,
614            inline_string,
615            promote_to_date,
616        )
617    }
618
619    fn read_text_content(&mut self, end_tag: &[u8]) -> Result<String> {
620        let mut text = String::new();
621        let mut buf = Vec::with_capacity(256);
622        loop {
623            buf.clear();
624            match self
625                .reader
626                .read_event_into(&mut buf)
627                .map_err(|e| Error::XmlParse(e.to_string()))?
628            {
629                Event::Text(ref e) => {
630                    let decoded = e.unescape().map_err(|e| Error::XmlParse(e.to_string()))?;
631                    text.push_str(&decoded);
632                }
633                Event::End(ref e) if e.local_name().as_ref() == end_tag => break,
634                Event::Eof => {
635                    self.done = true;
636                    return Err(unexpected_eof("element"));
637                }
638                _ => {}
639            }
640        }
641        Ok(text)
642    }
643}
644
645fn prepare_batch(batch_size: usize) -> Result<Vec<StreamRow>> {
646    let batch_size = validate_stream_batch_size(batch_size)?;
647    let mut rows = Vec::new();
648    rows.try_reserve_exact(batch_size)
649        .map_err(|_| Error::Internal("stream batch allocation failed".to_string()))?;
650    Ok(rows)
651}
652
653/// Validate one requested stream batch size against the shared finite policy.
654///
655/// Language bindings should call this before workbook lookup or reader state
656/// changes so the exact same zero and upper boundaries apply everywhere.
657pub fn validate_stream_batch_size(batch_size: usize) -> Result<usize> {
658    if batch_size == 0 {
659        return Err(Error::InvalidArgument(
660            "stream batch size must be greater than zero".to_string(),
661        ));
662    }
663
664    let observed = u64::try_from(batch_size).unwrap_or(u64::MAX);
665    let limit = MAX_STREAM_BATCH_ROWS as u64;
666    if observed > limit {
667        let Some(metadata) = ResourceLimitError::exceeded(
668            ResourceOperation::StreamRead,
669            ResourceCategory::Streaming,
670            ResourceDimension::RowCount,
671            limit,
672            observed,
673            Some(ResourceStage::Validate),
674        ) else {
675            return Err(Error::Internal(
676                "invalid stream batch resource-limit state".to_string(),
677            ));
678        };
679        return Err(Error::ResourceLimitExceeded(metadata));
680    }
681    Ok(batch_size)
682}
683
684/// Return `true` when `name` has local part `local`, matching
685/// `QName::local_name() == local` without scanning unprefixed names.
686///
687/// `local` must not contain `:`. The unprefixed form is a plain slice
688/// comparison; only a name that ends with `:local` is scanned for an
689/// earlier `:` so the first-colon split rule of `local_name()` is kept.
690#[inline]
691fn is_element(name: QName<'_>, local: &[u8]) -> bool {
692    let name = name.as_ref();
693    if name == local {
694        return true;
695    }
696    let Some(prefix_len) = name.len().checked_sub(local.len() + 1) else {
697        return false;
698    };
699    name[prefix_len] == b':'
700        && &name[prefix_len + 1..] == local
701        && !name[..prefix_len].contains(&b':')
702}
703
704/// Build the error returned when the worksheet XML ends inside an open
705/// `<row>`, `<c>`, or value element.
706fn unexpected_eof(context: &str) -> Error {
707    Error::XmlParse(format!(
708        "unexpected end of worksheet XML inside an open {context}"
709    ))
710}
711
712/// Extract the `r` (row number) attribute from a `<row>` element.
713fn extract_row_number(start: &quick_xml::events::BytesStart<'_>) -> Result<Option<u32>> {
714    for attr in start.attributes().flatten() {
715        if attr.key == QName(b"r") {
716            let val =
717                std::str::from_utf8(&attr.value).map_err(|e| Error::XmlParse(e.to_string()))?;
718            return val
719                .parse::<u32>()
720                .map(Some)
721                .map_err(|e| Error::XmlParse(format!("invalid row number: {e}")));
722        }
723    }
724    Ok(None)
725}
726
727fn resolve_row_number(explicit: Option<u32>, previous: u32) -> Result<u32> {
728    let row = explicit.unwrap_or_else(|| previous.saturating_add(1));
729    if row == 0 || row > MAX_ROWS || row <= previous {
730        return Err(Error::XmlParse(format!(
731            "invalid or out-of-order row number: {row}"
732        )));
733    }
734    Ok(row)
735}
736
737fn resolve_cell_column(explicit: Option<u32>, previous: u32) -> Result<u32> {
738    let col = explicit.unwrap_or_else(|| previous.saturating_add(1));
739    if col == 0 || col > MAX_COLUMNS || col <= previous {
740        return Err(Error::XmlParse(format!(
741            "invalid or out-of-order column number: {col}"
742        )));
743    }
744    Ok(col)
745}
746
747/// Extract the cell reference (column index), type attribute, and style
748/// index from a `<c>` element.
749fn extract_cell_attrs(
750    start: &quick_xml::events::BytesStart<'_>,
751) -> Result<(Option<u32>, Option<String>, Option<u32>)> {
752    let mut cell_ref: Option<String> = None;
753    let mut cell_type: Option<String> = None;
754    let mut style_idx: Option<u32> = None;
755
756    for attr in start.attributes().flatten() {
757        match attr.key {
758            QName(b"r") => {
759                cell_ref = Some(
760                    std::str::from_utf8(&attr.value)
761                        .map_err(|e| Error::XmlParse(e.to_string()))?
762                        .to_string(),
763                );
764            }
765            QName(b"t") => {
766                cell_type = Some(
767                    std::str::from_utf8(&attr.value)
768                        .map_err(|e| Error::XmlParse(e.to_string()))?
769                        .to_string(),
770                );
771            }
772            QName(b"s") => {
773                let raw =
774                    std::str::from_utf8(&attr.value).map_err(|e| Error::XmlParse(e.to_string()))?;
775                style_idx = raw.parse::<u32>().ok();
776            }
777            _ => {}
778        }
779    }
780
781    let col = match &cell_ref {
782        Some(r) => Some(cell_name_to_coordinates(r)?.0),
783        None => None,
784    };
785
786    Ok((col, cell_type, style_idx))
787}
788
789/// Resolve cell type, value text, formula, and inline string into a `CellValue`.
790///
791/// `promote_to_date` is honored only for non-formula numeric cells (`t="n"`
792/// or untyped). When true, such cells are returned as [`CellValue::Date`]
793/// instead of [`CellValue::Number`], used by the
794/// [`DateInterpretation::NumFmt`] path of the streaming reader.
795fn resolve_cell_value(
796    sst: &SharedStringTable,
797    cell_type: Option<&str>,
798    value_text: Option<&str>,
799    formula_text: Option<String>,
800    inline_string: Option<String>,
801    promote_to_date: bool,
802) -> Result<CellValue> {
803    if let Some(formula) = formula_text {
804        let cached = match (cell_type, value_text) {
805            (Some("b"), Some(v)) => Some(Box::new(CellValue::Bool(v == "1"))),
806            (Some("e"), Some(v)) => Some(Box::new(CellValue::Error(v.to_string()))),
807            (Some("str"), Some(v)) => Some(Box::new(CellValue::String(v.to_string()))),
808            (_, Some(v)) => v
809                .parse::<f64>()
810                .ok()
811                .map(|n| Box::new(CellValue::Number(n))),
812            _ => None,
813        };
814        return Ok(CellValue::Formula {
815            expr: formula,
816            result: cached,
817        });
818    }
819
820    match (cell_type, value_text) {
821        (Some("s"), Some(v)) => {
822            let idx: usize = v
823                .parse()
824                .map_err(|_| Error::Internal(format!("invalid SST index: {v}")))?;
825            let s = sst
826                .get(idx)
827                .ok_or_else(|| Error::Internal(format!("SST index {idx} out of bounds")))?;
828            Ok(CellValue::String(s.to_string()))
829        }
830        (Some("b"), Some(v)) => Ok(CellValue::Bool(v == "1")),
831        (Some("e"), Some(v)) => Ok(CellValue::Error(v.to_string())),
832        (Some("inlineStr"), _) => Ok(CellValue::String(inline_string.unwrap_or_default())),
833        (Some("str"), Some(v)) => Ok(CellValue::String(v.to_string())),
834        (Some("d"), Some(v)) => {
835            let n: f64 = v
836                .parse()
837                .map_err(|_| Error::Internal(format!("invalid date value: {v}")))?;
838            Ok(CellValue::Date(n))
839        }
840        (Some("n") | None, Some(v)) => {
841            let n: f64 = v
842                .parse()
843                .map_err(|_| Error::Internal(format!("invalid number: {v}")))?;
844            if promote_to_date {
845                Ok(CellValue::Date(n))
846            } else {
847                Ok(CellValue::Number(n))
848            }
849        }
850        _ => Ok(CellValue::Empty),
851    }
852}
853
854#[cfg(test)]
855mod tests {
856    use super::*;
857    use std::io::Cursor;
858
859    fn make_sst(strings: &[&str]) -> SharedStringTable {
860        let mut sst = SharedStringTable::new();
861        for s in strings {
862            sst.add(s);
863        }
864        sst
865    }
866
867    fn worksheet_xml(sheet_data: &str) -> String {
868        format!(
869            r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
870<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
871<sheetData>
872{sheet_data}
873</sheetData>
874</worksheet>"#
875        )
876    }
877
878    fn read_all(xml: &str, sst: &SharedStringTable, row_limit: Option<u32>) -> Vec<StreamRow> {
879        let cursor = Cursor::new(xml.as_bytes().to_vec());
880        let mut reader = SheetStreamReader::new(cursor, sst).row_limit(row_limit);
881        let mut all = Vec::new();
882        loop {
883            let batch = reader.next_batch(100).unwrap();
884            if batch.is_empty() {
885                break;
886            }
887            all.extend(batch);
888        }
889        all
890    }
891
892    #[test]
893    fn test_basic_batch_reading() {
894        let sst = make_sst(&["Name", "Age"]);
895        let xml = worksheet_xml(
896            r#"
897<row r="1"><c r="A1" t="s"><v>0</v></c><c r="B1" t="s"><v>1</v></c></row>
898<row r="2"><c r="A2" t="s"><v>0</v></c><c r="B2"><v>30</v></c></row>
899<row r="3"><c r="A3" t="s"><v>0</v></c><c r="B3"><v>25</v></c></row>
900"#,
901        );
902
903        let cursor = Cursor::new(xml.as_bytes().to_vec());
904        let mut reader = SheetStreamReader::new(cursor, &sst);
905
906        let batch1 = reader.next_batch(2).unwrap();
907        assert_eq!(batch1.len(), 2);
908        assert!(reader.has_more());
909
910        let batch2 = reader.next_batch(2).unwrap();
911        assert_eq!(batch2.len(), 1);
912
913        let batch3 = reader.next_batch(2).unwrap();
914        assert!(batch3.is_empty());
915        assert!(!reader.has_more());
916    }
917
918    #[test]
919    fn test_sparse_rows() {
920        let sst = SharedStringTable::new();
921        let xml = worksheet_xml(
922            r#"
923<row r="1"><c r="A1"><v>1</v></c></row>
924<row r="5"><c r="C5"><v>5</v></c></row>
925<row r="100"><c r="A100"><v>100</v></c></row>
926"#,
927        );
928
929        let rows = read_all(&xml, &sst, None);
930        assert_eq!(rows.len(), 3);
931        assert_eq!(rows[0].row_number, 1);
932        assert_eq!(rows[1].row_number, 5);
933        assert_eq!(rows[1].cells[0].0, 3);
934        assert_eq!(rows[2].row_number, 100);
935    }
936
937    #[test]
938    fn test_all_cell_types() {
939        let sst = make_sst(&["Hello"]);
940        let xml = worksheet_xml(
941            r#"
942<row r="1">
943  <c r="A1" t="s"><v>0</v></c>
944  <c r="B1"><v>42.5</v></c>
945  <c r="C1" t="b"><v>1</v></c>
946  <c r="D1" t="e"><v>#DIV/0!</v></c>
947  <c r="E1" t="inlineStr"><is><t>Inline</t></is></c>
948  <c r="F1" t="n"><v>99</v></c>
949  <c r="G1" t="d"><v>45000</v></c>
950</row>
951"#,
952        );
953
954        let rows = read_all(&xml, &sst, None);
955        assert_eq!(rows.len(), 1);
956        let cells = &rows[0].cells;
957
958        assert_eq!(cells[0], (1, CellValue::String("Hello".to_string())));
959        assert_eq!(cells[1], (2, CellValue::Number(42.5)));
960        assert_eq!(cells[2], (3, CellValue::Bool(true)));
961        assert_eq!(cells[3], (4, CellValue::Error("#DIV/0!".to_string())));
962        assert_eq!(cells[4], (5, CellValue::String("Inline".to_string())));
963        assert_eq!(cells[5], (6, CellValue::Number(99.0)));
964        assert_eq!(cells[6], (7, CellValue::Date(45000.0)));
965    }
966
967    #[test]
968    fn test_boolean_false() {
969        let sst = SharedStringTable::new();
970        let xml = worksheet_xml(r#"<row r="1"><c r="A1" t="b"><v>0</v></c></row>"#);
971        let rows = read_all(&xml, &sst, None);
972        assert_eq!(rows[0].cells[0].1, CellValue::Bool(false));
973    }
974
975    #[test]
976    fn test_shared_string_resolution() {
977        let sst = make_sst(&["First", "Second", "Third"]);
978        let xml = worksheet_xml(
979            r#"
980<row r="1">
981  <c r="A1" t="s"><v>0</v></c>
982  <c r="B1" t="s"><v>1</v></c>
983  <c r="C1" t="s"><v>2</v></c>
984</row>
985"#,
986        );
987
988        let rows = read_all(&xml, &sst, None);
989        assert_eq!(rows[0].cells[0].1, CellValue::String("First".to_string()));
990        assert_eq!(rows[0].cells[1].1, CellValue::String("Second".to_string()));
991        assert_eq!(rows[0].cells[2].1, CellValue::String("Third".to_string()));
992    }
993
994    #[test]
995    fn test_shared_string_out_of_bounds() {
996        let sst = make_sst(&["Only"]);
997        let xml = worksheet_xml(r#"<row r="1"><c r="A1" t="s"><v>999</v></c></row>"#);
998
999        let cursor = Cursor::new(xml.as_bytes().to_vec());
1000        let mut reader = SheetStreamReader::new(cursor, &sst);
1001        let result = reader.next_batch(10);
1002        assert!(result.is_err());
1003    }
1004
1005    #[test]
1006    fn test_row_limit() {
1007        let sst = SharedStringTable::new();
1008        let xml = worksheet_xml(
1009            r#"
1010<row r="1"><c r="A1"><v>1</v></c></row>
1011<row r="2"><c r="A2"><v>2</v></c></row>
1012<row r="3"><c r="A3"><v>3</v></c></row>
1013<row r="4"><c r="A4"><v>4</v></c></row>
1014<row r="5"><c r="A5"><v>5</v></c></row>
1015"#,
1016        );
1017
1018        let rows = read_all(&xml, &sst, Some(3));
1019        assert_eq!(rows.len(), 3);
1020        assert_eq!(rows[0].row_number, 1);
1021        assert_eq!(rows[2].row_number, 3);
1022    }
1023
1024    #[test]
1025    fn test_row_limit_zero() {
1026        let sst = SharedStringTable::new();
1027        let xml = worksheet_xml(r#"<row r="1"><c r="A1"><v>1</v></c></row>"#);
1028
1029        let rows = read_all(&xml, &sst, Some(0));
1030        assert!(rows.is_empty());
1031    }
1032
1033    #[test]
1034    fn test_empty_sheet() {
1035        let sst = SharedStringTable::new();
1036        let xml = worksheet_xml("");
1037
1038        let rows = read_all(&xml, &sst, None);
1039        assert!(rows.is_empty());
1040    }
1041
1042    #[test]
1043    fn test_empty_rows_are_skipped() {
1044        let sst = SharedStringTable::new();
1045        let xml = worksheet_xml(
1046            r#"
1047<row r="1"></row>
1048<row r="2"><c r="A2"><v>42</v></c></row>
1049<row r="3"></row>
1050"#,
1051        );
1052
1053        let rows = read_all(&xml, &sst, None);
1054        assert_eq!(rows.len(), 1);
1055        assert_eq!(rows[0].row_number, 2);
1056    }
1057
1058    #[test]
1059    fn test_empty_rows_count_against_limit() {
1060        let sst = SharedStringTable::new();
1061        let xml = worksheet_xml(
1062            r#"
1063<row r="1"></row>
1064<row r="2"></row>
1065<row r="3"><c r="A3"><v>3</v></c></row>
1066<row r="4"><c r="A4"><v>4</v></c></row>
1067"#,
1068        );
1069
1070        let rows = read_all(&xml, &sst, Some(2));
1071        assert!(
1072            rows.is_empty(),
1073            "with limit=2 and 2 empty rows, no data rows should be returned"
1074        );
1075
1076        let rows2 = read_all(&xml, &sst, Some(3));
1077        assert_eq!(rows2.len(), 1);
1078        assert_eq!(rows2[0].row_number, 3);
1079    }
1080
1081    #[test]
1082    fn test_formula_with_cached_number() {
1083        let sst = SharedStringTable::new();
1084        let xml = worksheet_xml(r#"<row r="1"><c r="A1"><f>SUM(B1:B10)</f><v>42</v></c></row>"#);
1085
1086        let rows = read_all(&xml, &sst, None);
1087        match &rows[0].cells[0].1 {
1088            CellValue::Formula { expr, result } => {
1089                assert_eq!(expr, "SUM(B1:B10)");
1090                assert_eq!(result.as_deref(), Some(&CellValue::Number(42.0)));
1091            }
1092            other => panic!("expected Formula, got {:?}", other),
1093        }
1094    }
1095
1096    #[test]
1097    fn test_formula_with_cached_string() {
1098        let sst = SharedStringTable::new();
1099        let xml = worksheet_xml(
1100            r#"<row r="1"><c r="A1" t="str"><f>CONCAT("a","b")</f><v>ab</v></c></row>"#,
1101        );
1102
1103        let rows = read_all(&xml, &sst, None);
1104        match &rows[0].cells[0].1 {
1105            CellValue::Formula { expr, result } => {
1106                assert_eq!(expr, r#"CONCAT("a","b")"#);
1107                assert_eq!(
1108                    result.as_deref(),
1109                    Some(&CellValue::String("ab".to_string()))
1110                );
1111            }
1112            other => panic!("expected Formula, got {:?}", other),
1113        }
1114    }
1115
1116    #[test]
1117    fn test_formula_with_cached_boolean() {
1118        let sst = SharedStringTable::new();
1119        let xml = worksheet_xml(r#"<row r="1"><c r="A1" t="b"><f>TRUE()</f><v>1</v></c></row>"#);
1120
1121        let rows = read_all(&xml, &sst, None);
1122        match &rows[0].cells[0].1 {
1123            CellValue::Formula { expr, result } => {
1124                assert_eq!(expr, "TRUE()");
1125                assert_eq!(result.as_deref(), Some(&CellValue::Bool(true)));
1126            }
1127            other => panic!("expected Formula, got {:?}", other),
1128        }
1129    }
1130
1131    #[test]
1132    fn test_formula_with_cached_error() {
1133        let sst = SharedStringTable::new();
1134        let xml = worksheet_xml(r#"<row r="1"><c r="A1" t="e"><f>1/0</f><v>#DIV/0!</v></c></row>"#);
1135
1136        let rows = read_all(&xml, &sst, None);
1137        match &rows[0].cells[0].1 {
1138            CellValue::Formula { expr, result } => {
1139                assert_eq!(expr, "1/0");
1140                assert_eq!(
1141                    result.as_deref(),
1142                    Some(&CellValue::Error("#DIV/0!".to_string()))
1143                );
1144            }
1145            other => panic!("expected Formula, got {:?}", other),
1146        }
1147    }
1148
1149    #[test]
1150    fn test_formula_without_cached_value() {
1151        let sst = SharedStringTable::new();
1152        let xml = worksheet_xml(r#"<row r="1"><c r="A1"><f>A2+A3</f></c></row>"#);
1153
1154        let rows = read_all(&xml, &sst, None);
1155        match &rows[0].cells[0].1 {
1156            CellValue::Formula { expr, result } => {
1157                assert_eq!(expr, "A2+A3");
1158                assert!(result.is_none());
1159            }
1160            other => panic!("expected Formula, got {:?}", other),
1161        }
1162    }
1163
1164    #[test]
1165    fn test_inline_string_with_rich_text_runs() {
1166        let sst = SharedStringTable::new();
1167        let xml = worksheet_xml(
1168            r#"<row r="1"><c r="A1" t="inlineStr"><is><r><t>Bold</t></r><r><t> Normal</t></r></is></c></row>"#,
1169        );
1170
1171        let rows = read_all(&xml, &sst, None);
1172        assert_eq!(
1173            rows[0].cells[0].1,
1174            CellValue::String("Bold Normal".to_string())
1175        );
1176    }
1177
1178    #[test]
1179    fn test_reader_close() {
1180        let sst = SharedStringTable::new();
1181        let xml = worksheet_xml(r#"<row r="1"><c r="A1"><v>1</v></c></row>"#);
1182        let cursor = Cursor::new(xml.as_bytes().to_vec());
1183        let reader = SheetStreamReader::new(cursor, &sst);
1184        reader.close();
1185    }
1186
1187    #[test]
1188    fn test_reader_drop_without_reading_all() {
1189        let sst = SharedStringTable::new();
1190        let xml = worksheet_xml(
1191            r#"
1192<row r="1"><c r="A1"><v>1</v></c></row>
1193<row r="2"><c r="A2"><v>2</v></c></row>
1194"#,
1195        );
1196        let cursor = Cursor::new(xml.as_bytes().to_vec());
1197        let mut reader = SheetStreamReader::new(cursor, &sst);
1198        let batch = reader.next_batch(1).unwrap();
1199        assert_eq!(batch.len(), 1);
1200        drop(reader);
1201    }
1202
1203    #[test]
1204    fn test_has_more_transitions() {
1205        let sst = SharedStringTable::new();
1206        let xml = worksheet_xml(r#"<row r="1"><c r="A1"><v>1</v></c></row>"#);
1207
1208        let cursor = Cursor::new(xml.as_bytes().to_vec());
1209        let mut reader = SheetStreamReader::new(cursor, &sst);
1210        assert!(reader.has_more());
1211
1212        let batch = reader.next_batch(100).unwrap();
1213        assert_eq!(batch.len(), 1);
1214
1215        let batch2 = reader.next_batch(100).unwrap();
1216        assert!(batch2.is_empty());
1217        assert!(!reader.has_more());
1218    }
1219
1220    #[test]
1221    fn test_batch_size_one() {
1222        let sst = SharedStringTable::new();
1223        let xml = worksheet_xml(
1224            r#"
1225<row r="1"><c r="A1"><v>1</v></c></row>
1226<row r="2"><c r="A2"><v>2</v></c></row>
1227<row r="3"><c r="A3"><v>3</v></c></row>
1228"#,
1229        );
1230
1231        let cursor = Cursor::new(xml.as_bytes().to_vec());
1232        let mut reader = SheetStreamReader::new(cursor, &sst);
1233
1234        for expected_row in 1..=3 {
1235            let batch = reader.next_batch(1).unwrap();
1236            assert_eq!(batch.len(), 1);
1237            assert_eq!(batch[0].row_number, expected_row);
1238        }
1239
1240        let batch = reader.next_batch(1).unwrap();
1241        assert!(batch.is_empty());
1242    }
1243
1244    #[test]
1245    fn test_cell_with_no_value() {
1246        let sst = SharedStringTable::new();
1247        let xml = worksheet_xml(r#"<row r="1"><c r="A1"></c><c r="B1"><v>42</v></c></row>"#);
1248
1249        let rows = read_all(&xml, &sst, None);
1250        assert_eq!(rows[0].cells.len(), 2);
1251        assert_eq!(rows[0].cells[0].1, CellValue::Empty);
1252        assert_eq!(rows[0].cells[1].1, CellValue::Number(42.0));
1253    }
1254
1255    #[test]
1256    fn test_self_closing_cell_element() {
1257        let sst = SharedStringTable::new();
1258        let xml = worksheet_xml(
1259            r#"<row r="1"><c r="A1"/><c r="B1"><v>42</v></c><c r="C1" t="b"/></row>"#,
1260        );
1261
1262        let rows = read_all(&xml, &sst, None);
1263        assert_eq!(rows[0].cells.len(), 3);
1264        assert_eq!(rows[0].cells[0], (1, CellValue::Empty));
1265        assert_eq!(rows[0].cells[1], (2, CellValue::Number(42.0)));
1266        assert_eq!(rows[0].cells[2], (3, CellValue::Empty));
1267    }
1268
1269    #[test]
1270    fn test_integration_with_saved_workbook() {
1271        let mut wb = crate::workbook::Workbook::new();
1272        wb.set_cell_value("Sheet1", "A1", "Name").unwrap();
1273        wb.set_cell_value("Sheet1", "B1", "Score").unwrap();
1274        wb.set_cell_value("Sheet1", "A2", "Alice").unwrap();
1275        wb.set_cell_value("Sheet1", "B2", 95.5f64).unwrap();
1276        wb.set_cell_value("Sheet1", "A3", "Bob").unwrap();
1277        wb.set_cell_value("Sheet1", "B3", 87.0f64).unwrap();
1278
1279        let dir = tempfile::TempDir::new().unwrap();
1280        let path = dir.path().join("stream_reader_test.xlsx");
1281        wb.save(&path).unwrap();
1282
1283        let wb2 = crate::workbook::Workbook::open_with_options(
1284            &path,
1285            &crate::workbook::OpenOptions::new().read_mode(crate::workbook::ReadMode::Lazy),
1286        )
1287        .unwrap();
1288
1289        let mut reader = wb2.open_sheet_reader("Sheet1").unwrap();
1290        let rows = reader.next_batch(100).unwrap();
1291
1292        assert_eq!(rows.len(), 3);
1293        assert_eq!(rows[0].row_number, 1);
1294        assert_eq!(rows[0].cells[0].1, CellValue::String("Name".to_string()));
1295        assert_eq!(rows[0].cells[1].1, CellValue::String("Score".to_string()));
1296        assert_eq!(rows[1].cells[0].1, CellValue::String("Alice".to_string()));
1297        assert_eq!(rows[1].cells[1].1, CellValue::Number(95.5));
1298        assert_eq!(rows[2].cells[0].1, CellValue::String("Bob".to_string()));
1299        assert_eq!(rows[2].cells[1].1, CellValue::Number(87.0));
1300    }
1301
1302    #[test]
1303    fn test_integration_with_row_limit() {
1304        let mut wb = crate::workbook::Workbook::new();
1305        for i in 1..=10 {
1306            let cell = format!("A{i}");
1307            wb.set_cell_value("Sheet1", &cell, i as f64).unwrap();
1308        }
1309
1310        let dir = tempfile::TempDir::new().unwrap();
1311        let path = dir.path().join("stream_limit_test.xlsx");
1312        wb.save(&path).unwrap();
1313
1314        let wb2 = crate::workbook::Workbook::open_with_options(
1315            &path,
1316            &crate::workbook::OpenOptions::new()
1317                .read_mode(crate::workbook::ReadMode::Lazy)
1318                .sheet_rows(5),
1319        )
1320        .unwrap();
1321
1322        let mut reader = wb2.open_sheet_reader("Sheet1").unwrap();
1323        let mut all_rows = Vec::new();
1324        loop {
1325            let batch = reader.next_batch(3).unwrap();
1326            if batch.is_empty() {
1327                break;
1328            }
1329            all_rows.extend(batch);
1330        }
1331
1332        assert_eq!(all_rows.len(), 5);
1333        assert_eq!(all_rows[4].row_number, 5);
1334    }
1335
1336    #[test]
1337    fn test_integration_sheet_not_found() {
1338        let wb = crate::workbook::Workbook::new();
1339        let result = wb.open_sheet_reader("NonExistent");
1340        assert!(result.is_err());
1341    }
1342
1343    /// End-to-end date interpretation test harness. Builds a workbook with
1344    /// mixed styled cells, saves it, reopens under both policies, and lets
1345    /// the caller assert on the returned cell values.
1346    fn write_mixed_style_workbook(path: &std::path::Path) {
1347        use crate::style::{builtin_num_fmts, NumFmtStyle, Style};
1348        let mut wb = crate::workbook::Workbook::new();
1349        let builtin_date_style = wb
1350            .add_style(&Style {
1351                num_fmt: Some(NumFmtStyle::Builtin(builtin_num_fmts::DATE_MDY)),
1352                ..Style::default()
1353            })
1354            .unwrap();
1355        let custom_date_style = wb
1356            .add_style(&Style {
1357                num_fmt: Some(NumFmtStyle::Custom("yyyy-mm-dd hh:mm".to_string())),
1358                ..Style::default()
1359            })
1360            .unwrap();
1361        let decimal_style = wb
1362            .add_style(&Style {
1363                num_fmt: Some(NumFmtStyle::Builtin(builtin_num_fmts::DECIMAL_2)),
1364                ..Style::default()
1365            })
1366            .unwrap();
1367
1368        // A1: number + built-in date format.
1369        wb.set_cell_value("Sheet1", "A1", 46127.0_f64).unwrap();
1370        wb.set_cell_style("Sheet1", "A1", builtin_date_style)
1371            .unwrap();
1372        // B1: number + custom date-like format.
1373        wb.set_cell_value("Sheet1", "B1", 46127.9993_f64).unwrap();
1374        wb.set_cell_style("Sheet1", "B1", custom_date_style)
1375            .unwrap();
1376        // C1: number + non-date format (decimal 2).
1377        wb.set_cell_value("Sheet1", "C1", 2.5_f64).unwrap();
1378        wb.set_cell_style("Sheet1", "C1", decimal_style).unwrap();
1379        // D1: number with no explicit style.
1380        wb.set_cell_value("Sheet1", "D1", 42.0_f64).unwrap();
1381
1382        wb.save(path).unwrap();
1383    }
1384
1385    #[test]
1386    fn test_integration_date_interpretation_cell_type_opt_in() {
1387        let dir = tempfile::TempDir::new().unwrap();
1388        let path = dir.path().join("dates_cell_type.xlsx");
1389        write_mixed_style_workbook(&path);
1390
1391        // Explicitly opt into spec-literal interpretation; the default is
1392        // `NumFmt` so this has to be requested by the caller.
1393        let wb = crate::workbook::Workbook::open_with_options(
1394            &path,
1395            &crate::workbook::OpenOptions::new()
1396                .read_mode(crate::workbook::ReadMode::Lazy)
1397                .date_interpretation(crate::workbook::DateInterpretation::CellType),
1398        )
1399        .unwrap();
1400        let mut reader = wb.open_sheet_reader("Sheet1").unwrap();
1401        let rows = reader.next_batch(10).unwrap();
1402
1403        // All number cells remain Number when CellType is requested, regardless
1404        // of whether their style references a date format.
1405        assert_eq!(rows[0].cells[0].1, CellValue::Number(46127.0));
1406        match &rows[0].cells[1].1 {
1407            CellValue::Number(v) => assert!((*v - 46127.9993).abs() < 1e-9),
1408            other => panic!("expected Number, got {:?}", other),
1409        }
1410        assert_eq!(rows[0].cells[2].1, CellValue::Number(2.5));
1411        assert_eq!(rows[0].cells[3].1, CellValue::Number(42.0));
1412    }
1413
1414    #[test]
1415    fn test_integration_date_interpretation_num_fmt_promotes_date_styles() {
1416        let dir = tempfile::TempDir::new().unwrap();
1417        let path = dir.path().join("dates_num_fmt.xlsx");
1418        write_mixed_style_workbook(&path);
1419
1420        let wb = crate::workbook::Workbook::open_with_options(
1421            &path,
1422            &crate::workbook::OpenOptions::new()
1423                .read_mode(crate::workbook::ReadMode::Lazy)
1424                .date_interpretation(crate::workbook::DateInterpretation::NumFmt),
1425        )
1426        .unwrap();
1427        let mut reader = wb.open_sheet_reader("Sheet1").unwrap();
1428        let rows = reader.next_batch(10).unwrap();
1429
1430        // A1: built-in date format → promoted to Date.
1431        assert_eq!(rows[0].cells[0].1, CellValue::Date(46127.0));
1432        // B1: custom date format code → promoted to Date.
1433        match &rows[0].cells[1].1 {
1434            CellValue::Date(v) => assert!((*v - 46127.9993).abs() < 1e-9),
1435            other => panic!("expected Date, got {:?}", other),
1436        }
1437        // C1: non-date format → stays Number.
1438        assert_eq!(rows[0].cells[2].1, CellValue::Number(2.5));
1439        // D1: no style → stays Number.
1440        assert_eq!(rows[0].cells[3].1, CellValue::Number(42.0));
1441    }
1442
1443    #[test]
1444    fn test_infers_missing_row_and_cell_references() {
1445        let xml = worksheet_xml(
1446            r#"<row><c t="n"><v>1</v></c><c t="n"><v>2</v></c></row>
1447<row r="3"><c r="C3" t="n"><v>3</v></c><c t="n"><v>4</v></c></row>"#,
1448        );
1449        let rows = read_all(&xml, &make_sst(&[]), None);
1450        assert_eq!(rows[0].row_number, 1);
1451        assert_eq!(
1452            rows[0].cells,
1453            vec![(1, CellValue::Number(1.0)), (2, CellValue::Number(2.0))]
1454        );
1455        assert_eq!(rows[1].row_number, 3);
1456        assert_eq!(
1457            rows[1].cells,
1458            vec![(3, CellValue::Number(3.0)), (4, CellValue::Number(4.0))]
1459        );
1460    }
1461
1462    #[test]
1463    fn test_rejects_out_of_order_or_out_of_bounds_inferred_positions() {
1464        let xml = worksheet_xml(r#"<row r="2"><c r="B2"/><c r="A2"/></row>"#);
1465        let cursor = Cursor::new(xml.into_bytes());
1466        let sst = make_sst(&[]);
1467        let mut reader = SheetStreamReader::new(cursor, &sst);
1468        assert!(matches!(reader.next_batch(1), Err(Error::XmlParse(_))));
1469
1470        let xml = worksheet_xml(r#"<row r="1048577"><c r="A1048577"/></row>"#);
1471        let cursor = Cursor::new(xml.into_bytes());
1472        let sst = make_sst(&[]);
1473        let mut reader = SheetStreamReader::new(cursor, &sst);
1474        assert!(matches!(reader.next_batch(1), Err(Error::XmlParse(_))));
1475    }
1476
1477    #[test]
1478    fn test_inline_strings_exclude_phonetic_runs() {
1479        let xml = worksheet_xml(
1480            r#"<row r="1"><c r="A1" t="inlineStr"><is><r><t>Base</t></r><rPh sb="0" eb="4"><t>phonetic</t></rPh><r><t> Text</t></r></is></c></row>"#,
1481        );
1482        let rows = read_all(&xml, &make_sst(&[]), None);
1483        assert_eq!(
1484            rows[0].cells[0],
1485            (1, CellValue::String("Base Text".to_string()))
1486        );
1487    }
1488
1489    const PREFIXED_SHEET: &str = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
1490<x:worksheet xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
1491<x:sheetData>
1492<x:row r="1"><x:c r="A1" t="n"><x:v>1</x:v></x:c><x:c r="B1" t="inlineStr"><x:is><x:t>Hi</x:t></x:is></x:c><x:c r="C1"/></x:row>
1493<x:row r="2"><x:c r="A2"><x:v>2</x:v></x:c></x:row>
1494</x:sheetData>
1495</x:worksheet>"#;
1496
1497    fn owned_reader_for(xml: &str) -> OwnedSheetStreamReader {
1498        use std::io::{Seek, Write};
1499        let mut file = tempfile::tempfile().unwrap();
1500        file.write_all(xml.as_bytes()).unwrap();
1501        file.seek(std::io::SeekFrom::Start(0)).unwrap();
1502        OwnedSheetStreamReader::from_spool(file, make_sst(&[]))
1503    }
1504
1505    fn assert_prefixed_rows(rows: &[StreamRow]) {
1506        assert_eq!(rows.len(), 2);
1507        assert_eq!(rows[0].row_number, 1);
1508        assert_eq!(
1509            rows[0].cells,
1510            vec![
1511                (1, CellValue::Number(1.0)),
1512                (2, CellValue::String("Hi".to_string())),
1513                (3, CellValue::Empty),
1514            ]
1515        );
1516        assert_eq!(rows[1].cells, vec![(1, CellValue::Number(2.0))]);
1517    }
1518
1519    #[test]
1520    fn is_element_matches_local_name_semantics() {
1521        let names: [&[u8]; 10] = [
1522            b"c", b"x:c", b"cc", b"xc", b":c", b"a:b:c", b"row", b"x:row", b"r", b"",
1523        ];
1524        for name in names {
1525            for local in [&b"c"[..], b"row"] {
1526                let qname = QName(name);
1527                assert_eq!(
1528                    is_element(qname, local),
1529                    qname.local_name().as_ref() == local,
1530                    "name {:?} local {:?}",
1531                    String::from_utf8_lossy(name),
1532                    String::from_utf8_lossy(local)
1533                );
1534            }
1535        }
1536    }
1537
1538    #[test]
1539    fn reads_namespace_prefixed_worksheet() {
1540        let rows = read_all(PREFIXED_SHEET, &make_sst(&[]), None);
1541        assert_prefixed_rows(&rows);
1542    }
1543
1544    #[test]
1545    fn owned_reader_reads_namespace_prefixed_worksheet() {
1546        let mut reader = owned_reader_for(PREFIXED_SHEET);
1547        let rows = reader.next_batch(100).unwrap();
1548        assert_prefixed_rows(&rows);
1549    }
1550
1551    #[test]
1552    fn truncated_xml_inside_elements_is_an_error() {
1553        let truncations = [
1554            r#"<worksheet><sheetData><row r="1"><c r="A1"><v>1</v></c>"#,
1555            r#"<worksheet><sheetData><row r="1"><c r="A1"><v>1</v>"#,
1556            r#"<worksheet><sheetData><row r="1"><c r="A1"><v>1"#,
1557            r#"<worksheet><sheetData><row r="1"><c r="A1" t="inlineStr"><is><t>ab"#,
1558        ];
1559        for xml in truncations {
1560            let sst = make_sst(&[]);
1561            let mut reader = SheetStreamReader::new(Cursor::new(xml.as_bytes()), &sst);
1562            let result = reader.next_batch(100);
1563            assert!(
1564                matches!(result, Err(Error::XmlParse(_))),
1565                "borrowed reader accepted truncated XML {xml:?}: {result:?}"
1566            );
1567
1568            let mut owned = owned_reader_for(xml);
1569            let result = owned.next_batch(100);
1570            assert!(
1571                matches!(result, Err(Error::XmlParse(_))),
1572                "owned reader accepted truncated XML {xml:?}: {result:?}"
1573            );
1574        }
1575    }
1576}