Skip to main content

sheetkit_core/workbook/
io.rs

1use super::*;
2use crate::workbook::budget::OpenBudget;
3use crate::workbook::open_options::OpenOptions;
4use crate::workbook::package_reader::{ArchiveAccess, PackageReader};
5use crate::workbook::source::{open_package_archive, PackageInput};
6
7/// VBA project relationship type URI.
8const VBA_PROJECT_REL_TYPE: &str =
9    "http://schemas.microsoft.com/office/2006/relationships/vbaProject";
10
11/// VBA project content type.
12const VBA_PROJECT_CONTENT_TYPE: &str = "application/vnd.ms-office.vbaProject";
13
14fn is_canonical_vba_package_path(path: &str) -> bool {
15    path.trim_start_matches('/')
16        .eq_ignore_ascii_case("xl/vbaProject.bin")
17}
18
19impl Workbook {
20    /// Create a new empty workbook containing a single empty sheet named "Sheet1".
21    pub fn new() -> Self {
22        let workbook_xml = WorkbookXml {
23            // Excel-like workbook.xml defaults for interoperability.
24            file_version: Some(sheetkit_xml::workbook::FileVersion {
25                app_name: Some("xl".to_string()),
26                last_edited: Some("7".to_string()),
27                lowest_edited: Some("7".to_string()),
28                rup_build: Some("27425".to_string()),
29            }),
30            // Excel-like workbookPr default.
31            workbook_pr: Some(sheetkit_xml::workbook::WorkbookPr {
32                date1904: None,
33                date_compatibility: None,
34                filter_privacy: None,
35                default_theme_version: Some(166925),
36                show_objects: None,
37                backup_file: None,
38                code_name: None,
39                check_compatibility: None,
40                auto_compress_pictures: None,
41                refresh_all_connections: None,
42                save_external_link_values: None,
43                update_links: None,
44                hide_pivot_field_list: None,
45                show_pivot_chart_filter: None,
46                allow_refresh_query: None,
47                publish_items: None,
48                show_border_unselected_tables: None,
49                prompted_solutions: None,
50                show_ink_annotation: None,
51            }),
52            // Minimal book view default (active tab only).
53            book_views: Some(sheetkit_xml::workbook::BookViews {
54                workbook_views: vec![sheetkit_xml::workbook::WorkbookView {
55                    x_window: None,
56                    y_window: None,
57                    window_width: None,
58                    window_height: None,
59                    active_tab: Some(0),
60                }],
61            }),
62            ..WorkbookXml::default()
63        };
64
65        let sst_runtime = SharedStringTable::new();
66        let mut sheet_name_index = HashMap::new();
67        sheet_name_index.insert("Sheet1".to_string(), 0);
68        Self {
69            format: WorkbookFormat::default(),
70            content_types: ContentTypes::default(),
71            package_rels: relationships::package_rels(),
72            workbook_xml,
73            raw_workbook_xml: None,
74            workbook_xml_baseline: None,
75            workbook_rels: relationships::workbook_rels(),
76            worksheets: vec![(
77                "Sheet1".to_string(),
78                initialized_lock(WorksheetXml::default()),
79            )],
80            stylesheet: StyleSheet::default(),
81            sst_runtime,
82            sheet_comments: vec![None],
83            charts: vec![],
84            raw_charts: vec![],
85            drawings: vec![],
86            raw_graph_parts: HashMap::new(),
87            dirty_graph_parts: HashSet::new(),
88            images: vec![],
89            worksheet_drawings: HashMap::new(),
90            worksheet_rels: HashMap::new(),
91            drawing_rels: HashMap::new(),
92            core_properties: None,
93            app_properties: None,
94            custom_properties: None,
95            raw_doc_props: HashMap::new(),
96            dirty_doc_props: HashSet::new(),
97            pivot_tables: vec![],
98            pivot_cache_defs: vec![],
99            pivot_cache_records: vec![],
100            theme_xml: None,
101            theme_colors: crate::theme::default_theme_colors(),
102            sheet_name_index,
103            sheet_sparklines: vec![vec![]],
104            sheet_sparklines_hydrated: vec![true],
105            sheet_vml: vec![None],
106            unknown_parts: vec![],
107            deferred_parts: crate::workbook::aux::DeferredAuxParts::new(),
108            vba_blob: None,
109            tables: vec![],
110            raw_sheet_xml: vec![None],
111            raw_sheet_extensions: vec![None],
112            sheet_dirty: vec![true],
113            sheet_included: vec![true],
114            sheet_materialized: vec![true],
115            sheet_package_backed: vec![false],
116            slicer_defs: vec![],
117            slicer_caches: vec![],
118            sheet_threaded_comments: vec![None],
119            person_list: sheetkit_xml::threaded_comment::PersonList::default(),
120            sheet_form_controls: vec![vec![]],
121            sheet_controls_dirty: vec![false],
122            streamed_sheets: HashMap::new(),
123            package_source: None,
124            read_mode: ReadMode::default(),
125            sheet_rows_limit: None,
126            worksheet_spool_limit: OpenLimits::default()
127                .xml_bytes
128                .min(OpenLimits::default().entry_actual_bytes),
129            date_interpretation: super::DateInterpretation::default(),
130        }
131    }
132
133    /// Open an existing `.xlsx` file from disk.
134    ///
135    /// If the file is encrypted (CFB container), returns
136    /// [`Error::FileEncrypted`]. Use [`Workbook::open_with_password`] instead.
137    pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
138        Self::open_with_options(path, &OpenOptions::default())
139    }
140
141    /// Open an existing `.xlsx` file with custom parsing options.
142    ///
143    /// See [`OpenOptions`] for available options including row limits,
144    /// sheet filtering, and ZIP safety limits.
145    ///
146    /// The file is opened directly via `std::fs::File` and the ZIP archive
147    /// is read from the file handle, avoiding a full `std::fs::read` copy.
148    pub fn open_with_options<P: AsRef<Path>>(path: P, options: &OpenOptions) -> Result<Self> {
149        let file_path = path.as_ref();
150
151        // Detect encrypted files (CFB container) by reading the magic bytes.
152        #[cfg(feature = "encryption")]
153        {
154            let mut header = [0u8; 8];
155            if let Ok(mut f) = std::fs::File::open(file_path) {
156                use std::io::Read as _;
157                if f.read_exact(&mut header).is_ok() {
158                    if let Ok(crate::crypt::ContainerFormat::Cfb) =
159                        crate::crypt::detect_container_format(&header)
160                    {
161                        return Err(Error::FileEncrypted);
162                    }
163                }
164            }
165        }
166
167        let file = std::fs::File::open(file_path)?;
168        let outer_size = file.metadata()?.len();
169        let limits = options.resolved_limits()?;
170        let mut budget = OpenBudget::new(limits)?;
171        budget.check_outer_input(outer_size)?;
172        // One central-directory parse serves both open and later lazy reads.
173        let package = open_package_archive(PackageInput::file(file), limits)?;
174        let mut archive = PackageReader::from_archive(package.clone(), &mut budget)?;
175        let mut wb = Self::from_archive(&mut archive, options)?;
176        wb.package_source = Some(PackageSource::new(package, limits));
177        wb.read_mode = options.read_mode;
178        Ok(wb)
179    }
180
181    /// Build a Workbook from an already-opened ZIP archive.
182    fn from_archive<A: ArchiveAccess>(archive: &mut A, options: &OpenOptions) -> Result<Self> {
183        let resolved_limits = options.resolved_limits()?;
184        // Track all ZIP entry paths that are explicitly handled so that the
185        // remaining entries can be preserved as unknown parts.
186        let mut known_paths: HashSet<String> = HashSet::new();
187
188        // Parse [Content_Types].xml
189        let content_types: ContentTypes = read_xml_part(archive, "[Content_Types].xml")?;
190        known_paths.insert("[Content_Types].xml".to_string());
191
192        // Infer the workbook format from the content type of xl/workbook.xml.
193        let format = content_types
194            .overrides
195            .iter()
196            .find(|o| o.part_name == "/xl/workbook.xml")
197            .and_then(|o| WorkbookFormat::from_content_type(&o.content_type))
198            .unwrap_or_default();
199
200        // Parse _rels/.rels
201        let package_rels: Relationships = read_xml_part(archive, "_rels/.rels")?;
202        known_paths.insert("_rels/.rels".to_string());
203
204        // Parse xl/workbook.xml while retaining exact source bytes for
205        // passthrough when its typed owner remains unchanged.
206        let raw_workbook_xml = read_bytes_part(archive, "xl/workbook.xml")?;
207        let workbook_xml: WorkbookXml = deserialize_xml_bytes(&raw_workbook_xml)?;
208        let workbook_xml_baseline = workbook_xml.clone();
209        known_paths.insert("xl/workbook.xml".to_string());
210
211        // Parse xl/_rels/workbook.xml.rels
212        let workbook_rels: Relationships = read_xml_part(archive, "xl/_rels/workbook.xml.rels")?;
213        known_paths.insert("xl/_rels/workbook.xml.rels".to_string());
214
215        let package_paths: HashSet<String> = archive.entry_names().into_iter().collect();
216        validate_package_part_names(&package_paths)?;
217
218        // Every worksheet must own a distinct internal package part in every
219        // read mode, so lazy saves cannot alias or escape the package.
220        let sheet_count = workbook_xml.sheets.sheets.len();
221        let worksheet_paths = resolve_worksheet_paths(
222            &workbook_xml,
223            &workbook_rels,
224            &content_types,
225            &package_paths,
226        )?;
227
228        // Parse per-sheet worksheet relationship files (optional).
229        // Always loaded: needed for hyperlinks, on-demand comment loading, etc.
230        let mut worksheet_rels: HashMap<usize, Relationships> = HashMap::with_capacity(sheet_count);
231        for (i, sheet_path) in worksheet_paths.iter().enumerate() {
232            let rels_path = relationship_part_path(sheet_path);
233            if let Some(rels) = read_optional_xml_part::<Relationships, _>(archive, &rels_path)? {
234                worksheet_rels.insert(i, rels);
235                known_paths.insert(rels_path);
236            }
237        }
238        validate_table_relationship_ownership(
239            &worksheet_paths,
240            &worksheet_rels,
241            &content_types,
242            &package_paths,
243        )?;
244
245        let skip_aux = options.skip_aux_parts();
246        let mut worksheets: Vec<(String, OnceLock<WorksheetXml>)> = Vec::with_capacity(sheet_count);
247        let mut raw_sheet_xml: Vec<Option<Vec<u8>>> = Vec::with_capacity(sheet_count);
248        let mut sheet_included: Vec<bool> = Vec::with_capacity(sheet_count);
249        let mut sheet_materialized: Vec<bool> = Vec::with_capacity(sheet_count);
250        let mut eager_sparklines: Vec<Vec<crate::sparkline::SparklineConfig>> =
251            vec![vec![]; sheet_count];
252
253        let defer_sheets = !options.is_eager();
254
255        for (sheet_idx, sheet_entry) in workbook_xml.sheets.sheets.iter().enumerate() {
256            let sheet_path = &worksheet_paths[sheet_idx];
257            let should_parse = options.should_parse_sheet(&sheet_entry.name);
258            sheet_included.push(should_parse);
259
260            if should_parse && !defer_sheets {
261                // Eager mode + selected: parse immediately. Clean save
262                // passthrough uses the pinned package source, so no second
263                // sheet-sized raw allocation is retained. Table and sparkline
264                // checks reuse a spool captured by the same decompression.
265                let table_ids = table_relationship_ids(worksheet_rels.get(&sheet_idx));
266                let capture = !skip_aux || !table_ids.is_empty();
267                let (ws, spool) =
268                    read_eager_worksheet(archive, sheet_path, options.sheet_rows, capture)?;
269                if let Some(mut spool) = spool {
270                    if !table_ids.is_empty() {
271                        validate_worksheet_table_part_stream(
272                            std::io::BufReader::with_capacity(LARGE_BUF_CAPACITY, &mut spool),
273                            &table_ids,
274                            sheet_path,
275                        )?;
276                    }
277                    if !skip_aux {
278                        use std::io::Seek as _;
279                        spool.seek(std::io::SeekFrom::Start(0))?;
280                        if let Some(fragment) =
281                            crate::workbook::source::extract_worksheet_extension_fragment(
282                                std::io::BufReader::new(spool),
283                            )?
284                        {
285                            eager_sparklines[sheet_idx] =
286                                parse_sparklines_from_xml(&String::from_utf8_lossy(&fragment));
287                        }
288                    }
289                }
290                worksheets.push((sheet_entry.name.clone(), initialized_lock(ws)));
291                sheet_materialized.push(true);
292                raw_sheet_xml.push(None);
293            } else if !should_parse {
294                // Filtered out (any mode): do not decompress or retain the
295                // worksheet. Keep an empty typed placeholder for queries; a
296                // clean save raw-copies the original compressed entry.
297                worksheets.push((
298                    sheet_entry.name.clone(),
299                    initialized_lock(WorksheetXml::default()),
300                ));
301                sheet_materialized.push(false);
302                raw_sheet_xml.push(None);
303            } else {
304                // Lazy/Stream mode + selected: keep the sheet package-backed
305                // until first access. OnceLock is left empty.
306                worksheets.push((sheet_entry.name.clone(), OnceLock::new()));
307                sheet_materialized.push(false);
308                raw_sheet_xml.push(None);
309            }
310            known_paths.insert(sheet_path.clone());
311        }
312
313        // Deferred sheets are validated directly from the archive; eagerly
314        // parsed sheets were validated from their capture spool above.
315        let archive_table_checks: Vec<bool> = sheet_included
316            .iter()
317            .map(|included| *included && defer_sheets)
318            .collect();
319        validate_worksheet_table_parts(
320            archive,
321            &worksheet_paths,
322            &worksheet_rels,
323            &archive_table_checks,
324        )?;
325
326        // Parse xl/styles.xml
327        let stylesheet: StyleSheet = read_xml_part(archive, "xl/styles.xml")?;
328        known_paths.insert("xl/styles.xml".to_string());
329
330        // Parse xl/sharedStrings.xml (optional -- may not exist for workbooks with no strings).
331        let shared_strings = match read_shared_strings_part(archive, "xl/sharedStrings.xml")? {
332            Some(sst) => {
333                known_paths.insert("xl/sharedStrings.xml".to_string());
334                sst
335            }
336            None => Sst::default(),
337        };
338
339        let sst_runtime = SharedStringTable::from_sst(shared_strings);
340
341        // Parse xl/theme/theme1.xml (optional -- preserved as raw bytes for round-trip).
342        let (theme_xml, theme_colors) =
343            match read_optional_bytes_part(archive, "xl/theme/theme1.xml")? {
344                Some(bytes) => {
345                    let colors = sheetkit_xml::theme::parse_theme_colors(&bytes);
346                    (Some(bytes), colors)
347                }
348                None => (None, crate::theme::default_theme_colors()),
349            };
350        known_paths.insert("xl/theme/theme1.xml".to_string());
351
352        // Auxiliary part parsing: skipped in Lazy/Stream mode.
353        let mut sheet_comments: Vec<Option<Comments>> = vec![None; worksheets.len()];
354        let mut sheet_vml: Vec<Option<Vec<u8>>> = vec![None; worksheets.len()];
355        let mut drawings: Vec<(String, WsDr)> = Vec::new();
356        let mut worksheet_drawings: HashMap<usize, usize> = HashMap::new();
357        let mut drawing_rels: HashMap<usize, Relationships> = HashMap::new();
358        let mut charts: Vec<(String, ChartSpace)> = Vec::new();
359        let mut raw_charts: Vec<(String, Vec<u8>)> = Vec::new();
360        let mut raw_graph_parts: HashMap<String, Vec<u8>> = HashMap::new();
361        let mut images: Vec<(String, Vec<u8>)> = Vec::new();
362        let mut core_properties: Option<sheetkit_xml::doc_props::CoreProperties> = None;
363        let mut app_properties: Option<sheetkit_xml::doc_props::ExtendedProperties> = None;
364        let mut custom_properties: Option<sheetkit_xml::doc_props::CustomProperties> = None;
365        let mut raw_doc_props: HashMap<String, Vec<u8>> = HashMap::new();
366        let mut pivot_cache_defs = Vec::new();
367        let mut pivot_tables = Vec::new();
368        let mut pivot_cache_records = Vec::new();
369        let mut slicer_defs = Vec::new();
370        let mut slicer_caches = Vec::new();
371        let mut sheet_threaded_comments: Vec<
372            Option<sheetkit_xml::threaded_comment::ThreadedComments>,
373        > = vec![None; worksheets.len()];
374        let mut person_list = sheetkit_xml::threaded_comment::PersonList::default();
375        let sheet_sparklines = eager_sparklines;
376        let sheet_sparklines_hydrated = vec![!skip_aux; worksheets.len()];
377        let mut vba_blob: Option<Vec<u8>> = None;
378        let mut tables: Vec<(String, sheetkit_xml::table::TableXml, usize)> = Vec::new();
379
380        if !skip_aux {
381            let mut drawing_path_to_idx: HashMap<String, usize> = HashMap::new();
382            let mut drawing_paths: HashSet<String> = HashSet::new();
383
384            for (sheet_idx, sheet_path) in worksheet_paths.iter().enumerate() {
385                let Some(rels) = worksheet_rels.get(&sheet_idx) else {
386                    continue;
387                };
388
389                if let Some(comment_rel) = rels
390                    .relationships
391                    .iter()
392                    .find(|r| r.rel_type == rel_types::COMMENTS)
393                {
394                    let comment_path = resolve_relationship_target(sheet_path, &comment_rel.target);
395                    if let Some(comments) =
396                        read_optional_xml_part::<Comments, _>(archive, &comment_path)?
397                    {
398                        sheet_comments[sheet_idx] = Some(comments);
399                        known_paths.insert(comment_path);
400                    }
401                }
402
403                if let Some(vml_rel) = rels
404                    .relationships
405                    .iter()
406                    .find(|r| r.rel_type == rel_types::VML_DRAWING)
407                {
408                    let vml_path = resolve_relationship_target(sheet_path, &vml_rel.target);
409                    if let Some(bytes) = read_optional_bytes_part(archive, &vml_path)? {
410                        sheet_vml[sheet_idx] = Some(bytes);
411                        known_paths.insert(vml_path);
412                    }
413                }
414
415                if let Some(drawing_rel) = rels
416                    .relationships
417                    .iter()
418                    .find(|r| r.rel_type == rel_types::DRAWING)
419                {
420                    let drawing_path = resolve_relationship_target(sheet_path, &drawing_rel.target);
421                    drawing_paths.insert(drawing_path.clone());
422                    let drawing_idx = if let Some(idx) = drawing_path_to_idx.get(&drawing_path) {
423                        *idx
424                    } else {
425                        let Some(bytes) = read_optional_bytes_part(archive, &drawing_path)? else {
426                            continue;
427                        };
428                        known_paths.insert(drawing_path.clone());
429                        raw_graph_parts.insert(drawing_path.clone(), bytes.clone());
430                        let Ok(drawing) = deserialize_xml_bytes::<WsDr>(&bytes) else {
431                            continue;
432                        };
433                        let idx = drawings.len();
434                        drawings.push((drawing_path.clone(), drawing));
435                        drawing_path_to_idx.insert(drawing_path, idx);
436                        idx
437                    };
438                    worksheet_drawings.insert(sheet_idx, drawing_idx);
439                }
440            }
441
442            // Fallback: load drawing parts listed in content types even when they
443            // are not discoverable via worksheet rel parsing.
444            for ovr in &content_types.overrides {
445                if ovr.content_type != mime_types::DRAWING {
446                    continue;
447                }
448                let drawing_path = ovr.part_name.trim_start_matches('/').to_string();
449                if !drawing_paths.insert(drawing_path.clone()) {
450                    continue;
451                }
452                if let Some(bytes) = read_optional_bytes_part(archive, &drawing_path)? {
453                    known_paths.insert(drawing_path.clone());
454                    raw_graph_parts.insert(drawing_path.clone(), bytes.clone());
455                    let Ok(drawing) = deserialize_xml_bytes::<WsDr>(&bytes) else {
456                        continue;
457                    };
458                    let idx = drawings.len();
459                    drawings.push((drawing_path.clone(), drawing));
460                    drawing_path_to_idx.insert(drawing_path, idx);
461                }
462            }
463
464            let mut seen_chart_paths: HashSet<String> = HashSet::new();
465            let mut seen_image_paths: HashSet<String> = HashSet::new();
466
467            for drawing_path in drawing_paths {
468                let drawing_rels_path = relationship_part_path(&drawing_path);
469                let Some(rels_bytes) = read_optional_bytes_part(archive, &drawing_rels_path)?
470                else {
471                    continue;
472                };
473                known_paths.insert(drawing_rels_path.clone());
474                raw_graph_parts.insert(drawing_rels_path, rels_bytes.clone());
475                let Ok(rels) = deserialize_xml_bytes::<Relationships>(&rels_bytes) else {
476                    continue;
477                };
478                let Some(&drawing_idx) = drawing_path_to_idx.get(&drawing_path) else {
479                    continue;
480                };
481
482                for rel in &rels.relationships {
483                    if rel.rel_type == rel_types::CHART {
484                        let chart_path = resolve_relationship_target(&drawing_path, &rel.target);
485                        if seen_chart_paths.insert(chart_path.clone()) {
486                            let Some(bytes) = read_optional_bytes_part(archive, &chart_path)?
487                            else {
488                                continue;
489                            };
490                            known_paths.insert(chart_path.clone());
491                            match deserialize_xml_bytes::<ChartSpace>(&bytes) {
492                                Ok(chart) => {
493                                    raw_graph_parts.insert(chart_path.clone(), bytes);
494                                    charts.push((chart_path, chart));
495                                }
496                                Err(_) => {
497                                    raw_charts.push((chart_path, bytes));
498                                }
499                            }
500                        }
501                    } else if rel.rel_type == rel_types::IMAGE {
502                        let image_path = resolve_relationship_target(&drawing_path, &rel.target);
503                        if seen_image_paths.insert(image_path.clone()) {
504                            if let Some(bytes) = read_optional_bytes_part(archive, &image_path)? {
505                                known_paths.insert(image_path.clone());
506                                images.push((image_path, bytes));
507                            }
508                        }
509                    }
510                }
511
512                drawing_rels.insert(drawing_idx, rels);
513            }
514
515            // Fallback: load chart parts listed in content types even when no
516            // drawing relationship was read.
517            for ovr in &content_types.overrides {
518                if ovr.content_type != mime_types::CHART {
519                    continue;
520                }
521                let chart_path = ovr.part_name.trim_start_matches('/').to_string();
522                if seen_chart_paths.insert(chart_path.clone()) {
523                    let Some(bytes) = read_optional_bytes_part(archive, &chart_path)? else {
524                        continue;
525                    };
526                    known_paths.insert(chart_path.clone());
527                    match deserialize_xml_bytes::<ChartSpace>(&bytes) {
528                        Ok(chart) => {
529                            raw_graph_parts.insert(chart_path.clone(), bytes);
530                            charts.push((chart_path, chart));
531                        }
532                        Err(_) => {
533                            raw_charts.push((chart_path, bytes));
534                        }
535                    }
536                }
537            }
538
539            // Parse each document-property part independently while retaining
540            // its original bytes, including malformed or unsupported content.
541            if let Some(bytes) = read_optional_bytes_part(archive, "docProps/core.xml")? {
542                let xml = String::from_utf8_lossy(&bytes);
543                core_properties = sheetkit_xml::doc_props::deserialize_core_properties(&xml).ok();
544                raw_doc_props.insert("docProps/core.xml".to_string(), bytes);
545                known_paths.insert("docProps/core.xml".to_string());
546            }
547            if let Some(bytes) = read_optional_bytes_part(archive, "docProps/app.xml")? {
548                app_properties = deserialize_xml_bytes(&bytes).ok();
549                raw_doc_props.insert("docProps/app.xml".to_string(), bytes);
550                known_paths.insert("docProps/app.xml".to_string());
551            }
552            if let Some(bytes) = read_optional_bytes_part(archive, "docProps/custom.xml")? {
553                let xml = String::from_utf8_lossy(&bytes);
554                custom_properties =
555                    sheetkit_xml::doc_props::deserialize_custom_properties(&xml).ok();
556                raw_doc_props.insert("docProps/custom.xml".to_string(), bytes);
557                known_paths.insert("docProps/custom.xml".to_string());
558            }
559
560            // Parse pivot cache definitions, pivot tables, and pivot cache records.
561            for ovr in &content_types.overrides {
562                let path = ovr.part_name.trim_start_matches('/');
563                if ovr.content_type == mime_types::PIVOT_CACHE_DEFINITION {
564                    if let Some(pcd) = read_optional_xml_part::<
565                        sheetkit_xml::pivot_cache::PivotCacheDefinition,
566                        _,
567                    >(archive, path)?
568                    {
569                        known_paths.insert(path.to_string());
570                        pivot_cache_defs.push((path.to_string(), pcd));
571                    }
572                } else if ovr.content_type == mime_types::PIVOT_TABLE {
573                    if let Some(pt) = read_optional_xml_part::<
574                        sheetkit_xml::pivot_table::PivotTableDefinition,
575                        _,
576                    >(archive, path)?
577                    {
578                        known_paths.insert(path.to_string());
579                        pivot_tables.push((path.to_string(), pt));
580                    }
581                } else if ovr.content_type == mime_types::PIVOT_CACHE_RECORDS {
582                    if let Some(pcr) = read_optional_xml_part::<
583                        sheetkit_xml::pivot_cache::PivotCacheRecords,
584                        _,
585                    >(archive, path)?
586                    {
587                        known_paths.insert(path.to_string());
588                        pivot_cache_records.push((path.to_string(), pcr));
589                    }
590                }
591            }
592
593            // Parse slicer definitions and slicer cache definitions.
594            for ovr in &content_types.overrides {
595                let path = ovr.part_name.trim_start_matches('/');
596                if ovr.content_type == mime_types::SLICER {
597                    if let Some(sd) = read_optional_xml_part::<
598                        sheetkit_xml::slicer::SlicerDefinitions,
599                        _,
600                    >(archive, path)?
601                    {
602                        known_paths.insert(path.to_string());
603                        slicer_defs.push((path.to_string(), sd));
604                    }
605                } else if ovr.content_type == mime_types::SLICER_CACHE {
606                    if let Some(raw) = read_optional_part(archive, path, true, false)? {
607                        if let Some(scd) = std::str::from_utf8(&raw)
608                            .ok()
609                            .and_then(sheetkit_xml::slicer::parse_slicer_cache)
610                        {
611                            known_paths.insert(path.to_string());
612                            slicer_caches.push((path.to_string(), scd));
613                        }
614                    }
615                }
616            }
617
618            // Parse threaded comments per-sheet and the workbook-level person list.
619            for (sheet_idx, sheet_path) in worksheet_paths.iter().enumerate() {
620                let Some(rels) = worksheet_rels.get(&sheet_idx) else {
621                    continue;
622                };
623                if let Some(tc_rel) = rels.relationships.iter().find(|r| {
624                    r.rel_type == sheetkit_xml::threaded_comment::REL_TYPE_THREADED_COMMENT
625                }) {
626                    let tc_path = resolve_relationship_target(sheet_path, &tc_rel.target);
627                    if let Some(tc) = read_optional_xml_part::<
628                        sheetkit_xml::threaded_comment::ThreadedComments,
629                        _,
630                    >(archive, &tc_path)?
631                    {
632                        sheet_threaded_comments[sheet_idx] = Some(tc);
633                        known_paths.insert(tc_path);
634                    }
635                }
636            }
637
638            // Parse person list (workbook-level).
639            person_list = {
640                let mut found = None;
641                if let Some(person_rel) = workbook_rels
642                    .relationships
643                    .iter()
644                    .find(|r| r.rel_type == sheetkit_xml::threaded_comment::REL_TYPE_PERSON)
645                {
646                    let person_path =
647                        resolve_relationship_target("xl/workbook.xml", &person_rel.target);
648                    if let Some(pl) = read_optional_xml_part::<
649                        sheetkit_xml::threaded_comment::PersonList,
650                        _,
651                    >(archive, &person_path)?
652                    {
653                        known_paths.insert(person_path);
654                        found = Some(pl);
655                    }
656                }
657                if found.is_none() {
658                    if let Some(pl) = read_optional_xml_part::<
659                        sheetkit_xml::threaded_comment::PersonList,
660                        _,
661                    >(archive, "xl/persons/person.xml")?
662                    {
663                        known_paths.insert("xl/persons/person.xml".to_string());
664                        found = Some(pl);
665                    }
666                }
667                found.unwrap_or_default()
668            };
669
670            // Parse table parts referenced from worksheet relationships.
671            for (sheet_idx, sheet_path) in worksheet_paths.iter().enumerate() {
672                let Some(rels) = worksheet_rels.get(&sheet_idx) else {
673                    continue;
674                };
675                for rel in &rels.relationships {
676                    if rel.rel_type != rel_types::TABLE {
677                        continue;
678                    }
679                    let table_path = resolve_relationship_target(sheet_path, &rel.target);
680                    // parse_table_xml keeps extLst/sortState and the source
681                    // snapshot used for byte-identical passthrough.
682                    let parsed = read_optional_part(archive, &table_path, true, false)?
683                        .and_then(|bytes| String::from_utf8(bytes).ok())
684                        .and_then(|xml| sheetkit_xml::table::parse_table_xml(&xml).ok());
685                    if let Some(table_xml) = parsed {
686                        known_paths.insert(table_path.clone());
687                        tables.push((table_path, table_xml, sheet_idx));
688                    }
689                }
690            }
691        }
692
693        // VBA access and preservation must not depend on eager/lazy auxiliary
694        // parsing. Apply the independent VBA input limit before retaining it.
695        let mut vba_candidates: Vec<String> = workbook_rels
696            .relationships
697            .iter()
698            .filter(|relationship| relationship.rel_type == VBA_PROJECT_REL_TYPE)
699            .map(|relationship| {
700                resolve_relationship_target("xl/workbook.xml", &relationship.target)
701            })
702            .collect();
703        if !vba_candidates
704            .iter()
705            .any(|path| is_canonical_vba_package_path(path))
706        {
707            vba_candidates.push("xl/vbaProject.bin".to_string());
708        }
709        for path in vba_candidates {
710            if let Some(bytes) = read_optional_part(archive, &path, false, true)? {
711                crate::vba::validate_vba_input(&bytes, options.vba_limits)?;
712                known_paths.insert(path);
713                vba_blob = Some(bytes);
714                break;
715            }
716        }
717
718        let sheet_form_controls: Vec<Vec<crate::control::FormControlConfig>> =
719            vec![vec![]; worksheets.len()];
720        let sheet_controls_dirty = vec![false; worksheets.len()];
721
722        // Build sheet name -> index lookup.
723        let mut sheet_name_index = HashMap::with_capacity(worksheets.len());
724        for (i, (name, _)) in worksheets.iter().enumerate() {
725            sheet_name_index.insert(name.clone(), i);
726        }
727
728        // Collect remaining ZIP entries. In Lazy/Stream mode, unhandled entries
729        // go into deferred_parts (typed index); in Eager mode, they go into
730        // unknown_parts for round-trip preservation.
731        let mut unknown_parts: Vec<(String, Vec<u8>)> = Vec::new();
732        let mut deferred_parts = crate::workbook::aux::DeferredAuxParts::new();
733        for name in archive.entry_names() {
734            if !known_paths.contains(&name) {
735                // Every remaining entry is preserved, so a corrupt one must
736                // fail the open instead of disappearing on the next save.
737                let bytes = read_bytes_part(archive, &name)?;
738                if skip_aux && crate::workbook::aux::classify_deferred_path(&name).is_some() {
739                    deferred_parts.insert(name, bytes);
740                } else {
741                    unknown_parts.push((name, bytes));
742                }
743            }
744        }
745
746        // Eagerly parsed sheets were validated and indexed by
747        // `deserialize_worksheet_xml_with_row_limit`; filtered sheets hold
748        // empty placeholders. Deferred sheets (empty OnceLock) are skipped
749        // here; they are post-processed on demand when hydrated.
750        for (_name, ws_lock) in &mut worksheets {
751            let Some(ws) = ws_lock.get_mut() else {
752                continue;
753            };
754
755            // Apply sheet_rows limit: keep only the first N rows.
756            if let Some(max_rows) = options.sheet_rows {
757                ws.sheet_data.rows.truncate(max_rows as usize);
758            }
759        }
760
761        if let Some(error) = archive.pending_error() {
762            return Err(error);
763        }
764
765        Ok(Self {
766            format,
767            content_types,
768            package_rels,
769            workbook_xml,
770            raw_workbook_xml: Some(raw_workbook_xml),
771            workbook_xml_baseline: Some(workbook_xml_baseline),
772            workbook_rels,
773            worksheets,
774            stylesheet,
775            sst_runtime,
776            sheet_comments,
777            charts,
778            raw_charts,
779            drawings,
780            raw_graph_parts,
781            dirty_graph_parts: HashSet::new(),
782            images,
783            worksheet_drawings,
784            worksheet_rels,
785            drawing_rels,
786            core_properties,
787            app_properties,
788            custom_properties,
789            raw_doc_props,
790            dirty_doc_props: HashSet::new(),
791            pivot_tables,
792            pivot_cache_defs,
793            pivot_cache_records,
794            theme_xml,
795            theme_colors,
796            sheet_name_index,
797            sheet_sparklines,
798            sheet_sparklines_hydrated,
799            sheet_vml,
800            unknown_parts,
801            deferred_parts,
802            vba_blob,
803            tables,
804            // Every opened sheet retains raw bytes and starts clean. A later
805            // owner mutation marks only its sheet dirty.
806            sheet_dirty: vec![false; raw_sheet_xml.len()],
807            sheet_included,
808            sheet_materialized,
809            sheet_package_backed: vec![true; sheet_count],
810            raw_sheet_xml,
811            raw_sheet_extensions: vec![None; sheet_count],
812            slicer_defs,
813            slicer_caches,
814            sheet_threaded_comments,
815            person_list,
816            sheet_form_controls,
817            sheet_controls_dirty,
818            streamed_sheets: HashMap::new(),
819            package_source: None,
820            read_mode: options.read_mode,
821            sheet_rows_limit: options.sheet_rows,
822            worksheet_spool_limit: resolved_limits
823                .xml_bytes
824                .min(resolved_limits.entry_actual_bytes),
825            date_interpretation: options.date_interpretation,
826        })
827    }
828
829    fn validate_save_model(&self, limits: crate::save::SaveLimits) -> Result<()> {
830        let limits = limits.validate()?;
831        let mut rows = 0u64;
832        let mut cells = 0u64;
833
834        for (index, (_, worksheet)) in self.worksheets.iter().enumerate() {
835            if let Some(streamed) = self.streamed_sheets.get(&index) {
836                rows = rows.saturating_add(streamed.row_count);
837                cells = cells.saturating_add(streamed.cell_count);
838                let xml_bytes = streamed_worksheet_xml_bytes(streamed);
839                reject_save_metric(
840                    crate::resource::ResourceDimension::XmlBytes,
841                    xml_bytes,
842                    limits.xml_part_bytes,
843                )?;
844            } else if self
845                .sheet_package_backed
846                .get(index)
847                .copied()
848                .unwrap_or(false)
849                && (!self.sheet_dirty.get(index).copied().unwrap_or(true)
850                    || (!self.sheet_included.get(index).copied().unwrap_or(true)
851                        && !self.sheet_materialized.get(index).copied().unwrap_or(true)))
852            {
853                let source = self.package_source.as_ref().ok_or_else(|| {
854                    Error::Internal("package-backed sheet has no source".to_string())
855                })?;
856                let (_, raw_rows, raw_cells) = source
857                    .worksheet_save_metrics(&self.sheet_part_path(index), limits.xml_part_bytes)?;
858                rows = rows.saturating_add(raw_rows);
859                cells = cells.saturating_add(raw_cells);
860            } else if !self.sheet_dirty.get(index).copied().unwrap_or(true) {
861                if let Some(Some(raw)) = self.raw_sheet_xml.get(index) {
862                    let (raw_rows, raw_cells) = worksheet_xml_metrics(raw, limits.xml_part_bytes)?;
863                    rows = rows.saturating_add(raw_rows);
864                    cells = cells.saturating_add(raw_cells);
865                } else if let Some(worksheet) = worksheet.get() {
866                    rows = rows.saturating_add(
867                        u64::try_from(worksheet.sheet_data.rows.len()).unwrap_or(u64::MAX),
868                    );
869                    for row in &worksheet.sheet_data.rows {
870                        cells = cells
871                            .saturating_add(u64::try_from(row.cells.len()).unwrap_or(u64::MAX));
872                    }
873                }
874            } else if let Some(worksheet) = worksheet.get() {
875                rows = rows.saturating_add(
876                    u64::try_from(worksheet.sheet_data.rows.len()).unwrap_or(u64::MAX),
877                );
878                for row in &worksheet.sheet_data.rows {
879                    cells =
880                        cells.saturating_add(u64::try_from(row.cells.len()).unwrap_or(u64::MAX));
881                }
882            }
883
884            reject_save_metric(
885                crate::resource::ResourceDimension::RowCount,
886                rows,
887                limits.row_count,
888            )?;
889            reject_save_metric(
890                crate::resource::ResourceDimension::CellCount,
891                cells,
892                limits.cell_count,
893            )?;
894        }
895        Ok(())
896    }
897
898    fn write_zip_archive_with_limits<W: std::io::Write + std::io::Seek>(
899        &self,
900        writer: W,
901        options: SimpleFileOptions,
902        format_override: Option<WorkbookFormat>,
903        limits: crate::save::SaveLimits,
904    ) -> Result<W> {
905        let limits = limits.validate()?;
906        self.validate_save_model(limits)?;
907        let mut output = SaveOutputWriter::new(writer, limits.output_bytes);
908        let result = {
909            let mut zip = zip::ZipWriter::new(&mut output);
910            let contents = self.write_zip_contents(&mut zip, options, format_override, limits);
911            let finish = zip
912                .finish()
913                .map(|_| ())
914                .map_err(|error| Error::Zip(error.to_string()));
915            contents.and(finish)
916        };
917        if let Some(metadata) = output.resource_error() {
918            return Err(metadata.into());
919        }
920        result?;
921        Ok(output.into_inner())
922    }
923
924    /// Save the workbook to a file at the given path.
925    ///
926    /// The target format is inferred from the file extension. Supported
927    /// extensions are `.xlsx`, `.xlsm`, `.xltx`, `.xltm`, and `.xlam`.
928    /// An unsupported extension returns [`Error::UnsupportedFileExtension`].
929    ///
930    /// The inferred format overrides the workbook's stored format so that
931    /// the content type in the output always matches the extension.
932    pub fn save<P: AsRef<Path>>(&self, path: P) -> Result<()> {
933        self.save_with_limits(path, crate::save::SaveLimits::default())
934    }
935
936    /// Save the workbook to a file with explicit finite output limits.
937    pub fn save_with_limits<P: AsRef<Path>>(
938        &self,
939        path: P,
940        limits: crate::save::SaveLimits,
941    ) -> Result<()> {
942        self.save_with_options(path, limits, crate::save::SaveOptions::default())
943    }
944
945    /// Save the workbook to a file with explicit output limits and
946    /// durability options. See [`SaveOptions`](crate::save::SaveOptions) for
947    /// the guarantees of each mode.
948    pub fn save_with_options<P: AsRef<Path>>(
949        &self,
950        path: P,
951        limits: crate::save::SaveLimits,
952        options: crate::save::SaveOptions,
953    ) -> Result<()> {
954        let path = path.as_ref();
955        let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
956        let target_format = WorkbookFormat::from_extension(ext)
957            .ok_or_else(|| Error::UnsupportedFileExtension(ext.to_string()))?;
958
959        atomic_write_file(path, options, |file| {
960            let zip_options = SimpleFileOptions::default()
961                .compression_method(CompressionMethod::Deflated)
962                .compression_level(Some(1));
963            self.write_zip_archive_with_limits(file, zip_options, Some(target_format), limits)?;
964            Ok(())
965        })
966    }
967
968    /// Serialize the workbook to an in-memory buffer using the stored format.
969    pub fn save_to_buffer(&self) -> Result<Vec<u8>> {
970        self.save_to_buffer_with_limits(crate::save::SaveLimits::default())
971    }
972
973    /// Serialize the workbook to a buffer with explicit finite output limits.
974    pub fn save_to_buffer_with_limits(&self, limits: crate::save::SaveLimits) -> Result<Vec<u8>> {
975        let cursor = std::io::Cursor::new(Vec::new());
976        let options = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated);
977        let cursor = self.write_zip_archive_with_limits(cursor, options, None, limits)?;
978        Ok(cursor.into_inner())
979    }
980
981    /// Open a workbook from an in-memory `.xlsx` buffer.
982    pub fn open_from_buffer(data: &[u8]) -> Result<Self> {
983        Self::open_from_buffer_with_options(data, &OpenOptions::default())
984    }
985
986    /// Open a workbook from an in-memory buffer with custom parsing options.
987    pub fn open_from_buffer_with_options(data: &[u8], options: &OpenOptions) -> Result<Self> {
988        // Detect encrypted files (CFB container)
989        #[cfg(feature = "encryption")]
990        if data.len() >= 8 {
991            if let Ok(crate::crypt::ContainerFormat::Cfb) =
992                crate::crypt::detect_container_format(data)
993            {
994                return Err(Error::FileEncrypted);
995            }
996        }
997
998        let outer_size = u64::try_from(data.len()).unwrap_or(u64::MAX);
999        let limits = options.resolved_limits()?;
1000        let mut budget = OpenBudget::new(limits)?;
1001        budget.check_outer_input(outer_size)?;
1002        budget.charge_retained(outer_size)?;
1003        let package = open_package_archive(PackageInput::buffer(data.into()), limits)?;
1004        let mut archive = PackageReader::from_archive(package.clone(), &mut budget)?;
1005        let mut wb = Self::from_archive(&mut archive, options)?;
1006        wb.package_source = Some(PackageSource::new(package, limits));
1007        wb.read_mode = options.read_mode;
1008        Ok(wb)
1009    }
1010
1011    /// Open an encrypted `.xlsx` file using a password.
1012    ///
1013    /// The file must be in OLE/CFB container format. Supports both Standard
1014    /// Encryption (Office 2007, AES-128-ECB) and Agile Encryption (Office
1015    /// 2010+, AES-256-CBC).
1016    #[cfg(feature = "encryption")]
1017    pub fn open_with_password<P: AsRef<Path>>(path: P, password: &str) -> Result<Self> {
1018        Self::open_with_password_with_options(path, password, &OpenOptions::default())
1019    }
1020
1021    /// Open an encrypted workbook from a path with explicit finite limits.
1022    #[cfg(feature = "encryption")]
1023    pub fn open_with_password_with_options<P: AsRef<Path>>(
1024        path: P,
1025        password: &str,
1026        options: &OpenOptions,
1027    ) -> Result<Self> {
1028        let path = path.as_ref();
1029        let budget = OpenBudget::new(options.resolved_limits()?)?;
1030        let data = read_bounded_file(path, &budget, options.crypt_limits)?;
1031        Self::open_encrypted_bytes(data, password, options, budget)
1032    }
1033
1034    /// Open an encrypted workbook from an in-memory CFB container.
1035    #[cfg(feature = "encryption")]
1036    pub fn open_from_buffer_with_password(data: &[u8], password: &str) -> Result<Self> {
1037        Self::open_from_buffer_with_password_with_options(data, password, &OpenOptions::default())
1038    }
1039
1040    /// Open an encrypted in-memory CFB container with explicit finite limits.
1041    #[cfg(feature = "encryption")]
1042    pub fn open_from_buffer_with_password_with_options(
1043        data: &[u8],
1044        password: &str,
1045        options: &OpenOptions,
1046    ) -> Result<Self> {
1047        let budget = OpenBudget::new(options.resolved_limits()?)?;
1048        let observed = u64::try_from(data.len()).unwrap_or(u64::MAX);
1049        budget.check_outer_input(observed)?;
1050        crate::crypt::validate_decrypt_outer_cfb(options.crypt_limits, observed)?;
1051        Self::open_encrypted_bytes(data.to_vec(), password, options, budget)
1052    }
1053
1054    #[cfg(feature = "encryption")]
1055    fn open_encrypted_bytes(
1056        encrypted: Vec<u8>,
1057        password: &str,
1058        options: &OpenOptions,
1059        mut budget: OpenBudget,
1060    ) -> Result<Self> {
1061        let decrypted_zip =
1062            crate::crypt::decrypt_xlsx_with_limits(&encrypted, password, options.crypt_limits)?;
1063        let decrypted_size = u64::try_from(decrypted_zip.len()).unwrap_or(u64::MAX);
1064        budget.check_outer_input(decrypted_size)?;
1065        budget.charge_retained(decrypted_size)?;
1066
1067        let limits = budget.limits();
1068        let package = open_package_archive(PackageInput::buffer(decrypted_zip.into()), limits)?;
1069        let mut workbook = {
1070            let mut archive = PackageReader::from_archive(package.clone(), &mut budget)?;
1071            Self::from_archive(&mut archive, options)?
1072        };
1073        workbook.package_source = Some(PackageSource::new(package, limits));
1074        workbook.read_mode = options.read_mode;
1075        Ok(workbook)
1076    }
1077
1078    /// Save the workbook as an encrypted `.xlsx` file using Agile Encryption
1079    /// (AES-256-CBC + SHA-512, 100K iterations).
1080    #[cfg(feature = "encryption")]
1081    pub fn save_with_password<P: AsRef<Path>>(&self, path: P, password: &str) -> Result<()> {
1082        self.save_with_password_with_output_limits(
1083            path,
1084            password,
1085            crate::crypt::CryptLimits::default(),
1086            crate::save::SaveLimits::default(),
1087        )
1088    }
1089
1090    /// Save an encrypted workbook with explicit finite encryption limits.
1091    #[cfg(feature = "encryption")]
1092    pub fn save_with_password_with_limits<P: AsRef<Path>>(
1093        &self,
1094        path: P,
1095        password: &str,
1096        limits: crate::crypt::CryptLimits,
1097    ) -> Result<()> {
1098        self.save_with_password_with_output_limits(
1099            path,
1100            password,
1101            limits,
1102            crate::save::SaveLimits::default(),
1103        )
1104    }
1105
1106    /// Save an encrypted workbook with explicit encryption and output limits.
1107    #[cfg(feature = "encryption")]
1108    pub fn save_with_password_with_output_limits<P: AsRef<Path>>(
1109        &self,
1110        path: P,
1111        password: &str,
1112        crypt_limits: crate::crypt::CryptLimits,
1113        save_limits: crate::save::SaveLimits,
1114    ) -> Result<()> {
1115        self.save_with_password_with_options(
1116            path,
1117            password,
1118            crypt_limits,
1119            save_limits,
1120            crate::save::SaveOptions::default(),
1121        )
1122    }
1123
1124    /// Save an encrypted workbook with explicit encryption limits, output
1125    /// limits, and durability options. See
1126    /// [`SaveOptions`](crate::save::SaveOptions) for the guarantees of each
1127    /// mode.
1128    #[cfg(feature = "encryption")]
1129    pub fn save_with_password_with_options<P: AsRef<Path>>(
1130        &self,
1131        path: P,
1132        password: &str,
1133        crypt_limits: crate::crypt::CryptLimits,
1134        save_limits: crate::save::SaveLimits,
1135        options: crate::save::SaveOptions,
1136    ) -> Result<()> {
1137        let path = path.as_ref();
1138        let ext = path
1139            .extension()
1140            .and_then(|extension| extension.to_str())
1141            .unwrap_or("");
1142        let target_format = WorkbookFormat::from_extension(ext)
1143            .ok_or_else(|| Error::UnsupportedFileExtension(ext.to_string()))?;
1144
1145        // First, serialize to an in-memory ZIP buffer
1146        let cursor = std::io::Cursor::new(Vec::new());
1147        let zip_options =
1148            SimpleFileOptions::default().compression_method(CompressionMethod::Deflated);
1149        let zip_buf = self
1150            .write_zip_archive_with_limits(cursor, zip_options, Some(target_format), save_limits)?
1151            .into_inner();
1152
1153        // Encrypt and write to CFB container
1154        let cfb_data = crate::crypt::encrypt_xlsx_with_limits(&zip_buf, password, crypt_limits)?;
1155        let observed = u64::try_from(cfb_data.len()).unwrap_or(u64::MAX);
1156        if observed > save_limits.output_bytes {
1157            return Err(crate::save::resource_limit(
1158                crate::resource::ResourceOperation::WorkbookSave,
1159                crate::resource::ResourceCategory::Output,
1160                crate::resource::ResourceDimension::OutputBytes,
1161                save_limits.output_bytes,
1162                observed,
1163                crate::resource::ResourceStage::Write,
1164            ));
1165        }
1166        atomic_write_file(path, options, |file| {
1167            file.write_all(&cfb_data)?;
1168            Ok(())
1169        })
1170    }
1171
1172    /// Write all workbook parts into the given ZIP writer.
1173    ///
1174    /// When `format_override` is `Some`, that format is used for the workbook
1175    /// content type instead of the stored `self.format`. This allows `save()`
1176    /// to infer the format from the file extension without mutating `self`.
1177    fn write_zip_contents<W: std::io::Write + std::io::Seek>(
1178        &self,
1179        zip: &mut zip::ZipWriter<W>,
1180        options: SimpleFileOptions,
1181        format_override: Option<WorkbookFormat>,
1182        limits: crate::save::SaveLimits,
1183    ) -> Result<()> {
1184        let effective_format = format_override.unwrap_or(self.format);
1185        let preserves_vba = matches!(
1186            effective_format,
1187            WorkbookFormat::Xlsm | WorkbookFormat::Xltm | WorkbookFormat::Xlam
1188        );
1189        let emits_vba = preserves_vba && self.vba_blob.is_some();
1190        // OPC part names compare case-insensitively, so every VBA path match
1191        // uses the same ASCII case folding.
1192        let mut vba_part_paths = HashSet::from(["xl/vbaproject.bin".to_string()]);
1193        vba_part_paths.extend(
1194            self.workbook_rels
1195                .relationships
1196                .iter()
1197                .filter(|relationship| relationship.rel_type == VBA_PROJECT_REL_TYPE)
1198                .map(|relationship| {
1199                    resolve_relationship_target("xl/workbook.xml", &relationship.target)
1200                        .to_ascii_lowercase()
1201                }),
1202        );
1203        let is_vba_path = |path: &str| {
1204            vba_part_paths.contains(&path.trim_start_matches('/').to_ascii_lowercase())
1205        };
1206        let mut content_types = self.content_types.clone();
1207
1208        // Ensure the workbook override content type matches the effective format.
1209        if let Some(wb_override) = content_types
1210            .overrides
1211            .iter_mut()
1212            .find(|o| o.part_name == "/xl/workbook.xml")
1213        {
1214            wb_override.content_type = effective_format.content_type().to_string();
1215        }
1216
1217        // Ensure VBA project content type override and workbook relationship are
1218        // present when a VBA blob exists, and absent when it does not.
1219        // Skip when deferred_parts is non-empty: relationships are already correct.
1220        let has_deferred = self.deferred_parts.has_any();
1221        let mut workbook_rels = self.workbook_rels.clone();
1222
1223        // The SST is always emitted, so normalize its package metadata in the
1224        // save-local clones. This also makes repeated open/save cycles idempotent.
1225        content_types
1226            .overrides
1227            .retain(|entry| entry.part_name != "/xl/sharedStrings.xml");
1228        content_types.overrides.push(ContentTypeOverride {
1229            part_name: "/xl/sharedStrings.xml".to_string(),
1230            content_type: mime_types::SHARED_STRINGS.to_string(),
1231        });
1232        workbook_rels.relationships.retain(|relationship| {
1233            relationship.rel_type != rel_types::SHARED_STRINGS
1234                && relationship.target != "sharedStrings.xml"
1235        });
1236        workbook_rels.relationships.push(Relationship {
1237            id: crate::sheet::next_rid(&workbook_rels.relationships),
1238            rel_type: rel_types::SHARED_STRINGS.to_string(),
1239            target: "sharedStrings.xml".to_string(),
1240            target_mode: None,
1241        });
1242        if emits_vba {
1243            let vba_part_name = "/xl/vbaProject.bin";
1244            content_types.overrides.retain(|entry| {
1245                entry.content_type != VBA_PROJECT_CONTENT_TYPE && !is_vba_path(&entry.part_name)
1246            });
1247            content_types.overrides.push(ContentTypeOverride {
1248                part_name: vba_part_name.to_string(),
1249                content_type: VBA_PROJECT_CONTENT_TYPE.to_string(),
1250            });
1251            if !content_types.defaults.iter().any(|d| d.extension == "bin") {
1252                content_types.defaults.push(ContentTypeDefault {
1253                    extension: "bin".to_string(),
1254                    content_type: VBA_PROJECT_CONTENT_TYPE.to_string(),
1255                });
1256            }
1257            workbook_rels
1258                .relationships
1259                .retain(|relationship| relationship.rel_type != VBA_PROJECT_REL_TYPE);
1260            let rid = crate::sheet::next_rid(&workbook_rels.relationships);
1261            workbook_rels.relationships.push(Relationship {
1262                id: rid,
1263                rel_type: VBA_PROJECT_REL_TYPE.to_string(),
1264                target: "vbaProject.bin".to_string(),
1265                target_mode: None,
1266            });
1267        } else if !preserves_vba || !has_deferred {
1268            content_types.overrides.retain(|entry| {
1269                entry.content_type != VBA_PROJECT_CONTENT_TYPE && !is_vba_path(&entry.part_name)
1270            });
1271            content_types
1272                .defaults
1273                .retain(|entry| entry.content_type != VBA_PROJECT_CONTENT_TYPE);
1274            workbook_rels
1275                .relationships
1276                .retain(|r| r.rel_type != VBA_PROJECT_REL_TYPE);
1277        }
1278
1279        let mut worksheet_rels = self.worksheet_rels.clone();
1280
1281        // Synchronize comment/form-control VML parts with worksheet relationships/content types.
1282        // Per-sheet VML bytes to write: (sheet_idx, zip_path, bytes).
1283        let mut vml_parts_to_write: Vec<(usize, String, Vec<u8>)> = Vec::new();
1284        // Per-sheet legacy drawing relationship IDs for worksheet XML serialization.
1285        let mut legacy_drawing_rids: HashMap<usize, String> = HashMap::new();
1286        // Per-sheet controls paired with their VML shape IDs and ctrlProp rIds.
1287        let mut worksheet_controls: HashMap<usize, Vec<(usize, String, String)>> = HashMap::new();
1288        let mut comment_parts_to_write: Vec<(usize, String)> = Vec::new();
1289        let mut control_parts_to_write: Vec<(String, String)> = Vec::new();
1290        let mut allocated_control_paths = self.occupied_part_paths();
1291        let mut allocated_comment_paths = self.occupied_part_paths();
1292        let mut allocated_vml_paths = self.occupied_part_paths();
1293        let mut removed_control_paths: HashSet<String> = HashSet::new();
1294
1295        // Ensure the vml extension default content type is present if any VML exists.
1296        let mut has_any_vml = false;
1297
1298        if !self
1299            .deferred_parts
1300            .has_category(crate::workbook::aux::AuxCategory::Comments)
1301        {
1302            content_types
1303                .overrides
1304                .retain(|entry| entry.content_type != mime_types::COMMENTS);
1305        }
1306        if !self
1307            .deferred_parts
1308            .has_category(crate::workbook::aux::AuxCategory::Vml)
1309        {
1310            content_types
1311                .overrides
1312                .retain(|entry| entry.content_type != mime_types::VML_DRAWING);
1313        }
1314        // When deferred_parts is non-empty (Lazy open), skip comment/VML
1315        // synchronization. The original relationships and content types are already
1316        // correct, and deferred_parts will supply the raw bytes on save.
1317        for sheet_idx in 0..self.worksheets.len() {
1318            let sheet_path = self.sheet_part_path(sheet_idx);
1319            let original_comment_paths: Vec<String> = worksheet_rels
1320                .get(&sheet_idx)
1321                .into_iter()
1322                .flat_map(|relationships| &relationships.relationships)
1323                .filter(|relationship| relationship.rel_type == rel_types::COMMENTS)
1324                .map(|relationship| resolve_relationship_target(&sheet_path, &relationship.target))
1325                .collect();
1326            let original_vml_paths: Vec<String> = worksheet_rels
1327                .get(&sheet_idx)
1328                .into_iter()
1329                .flat_map(|relationships| &relationships.relationships)
1330                .filter(|relationship| relationship.rel_type == rel_types::VML_DRAWING)
1331                .map(|relationship| resolve_relationship_target(&sheet_path, &relationship.target))
1332                .collect();
1333            let controls_dirty = self
1334                .sheet_controls_dirty
1335                .get(sheet_idx)
1336                .copied()
1337                .unwrap_or(false);
1338            let original_control_entries = if controls_dirty {
1339                if let Some(entries) = self
1340                    .raw_sheet_xml
1341                    .get(sheet_idx)
1342                    .and_then(|raw| raw.as_deref())
1343                    .and_then(|raw| std::str::from_utf8(raw).ok())
1344                    .map(parse_worksheet_control_entries)
1345                {
1346                    entries
1347                } else if self
1348                    .sheet_package_backed
1349                    .get(sheet_idx)
1350                    .copied()
1351                    .unwrap_or(false)
1352                {
1353                    let source = self.package_source.as_ref().ok_or_else(|| {
1354                        Error::Internal("package-backed sheet has no source".to_string())
1355                    })?;
1356                    let spool = source.spool_xml_part(&sheet_path)?;
1357                    parse_worksheet_control_entries_reader(std::io::BufReader::new(spool))?
1358                } else {
1359                    Vec::new()
1360                }
1361            } else {
1362                Vec::new()
1363            };
1364            let has_comments = self
1365                .sheet_comments
1366                .get(sheet_idx)
1367                .and_then(|c| c.as_ref())
1368                .is_some();
1369            let has_form_controls = self
1370                .sheet_form_controls
1371                .get(sheet_idx)
1372                .map(|v| !v.is_empty())
1373                .unwrap_or(false);
1374            let has_preserved_vml = self
1375                .sheet_vml
1376                .get(sheet_idx)
1377                .and_then(|v| v.as_ref())
1378                .is_some();
1379
1380            // When deferred_parts is non-empty (Lazy open), skip comment/VML
1381            // synchronization only for sheets whose comment data is still deferred
1382            // (not yet hydrated). Hydrated sheets need normal relationship sync.
1383            if has_deferred
1384                && !has_comments
1385                && !has_form_controls
1386                && !has_preserved_vml
1387                && !controls_dirty
1388            {
1389                continue;
1390            }
1391
1392            content_types.overrides.retain(|entry| {
1393                let path = entry.part_name.trim_start_matches('/');
1394                !original_comment_paths
1395                    .iter()
1396                    .any(|original| original == path)
1397                    && !original_vml_paths.iter().any(|original| original == path)
1398            });
1399
1400            let raw_control_shape_ids = self
1401                .sheet_vml
1402                .get(sheet_idx)
1403                .and_then(|vml| vml.as_deref())
1404                .map(crate::control::form_control_shape_ids)
1405                .unwrap_or_default();
1406            let mut retained_control_entries = if controls_dirty {
1407                original_control_entries
1408                    .iter()
1409                    .filter(|(shape_id, _, _)| raw_control_shape_ids.contains(shape_id))
1410                    .cloned()
1411                    .collect::<Vec<_>>()
1412            } else {
1413                Vec::new()
1414            };
1415            let removed_control_rids: HashSet<&str> = if controls_dirty {
1416                original_control_entries
1417                    .iter()
1418                    .filter(|(shape_id, _, _)| !raw_control_shape_ids.contains(shape_id))
1419                    .map(|(_, rid, _)| rid.as_str())
1420                    .collect()
1421            } else {
1422                HashSet::new()
1423            };
1424
1425            if let Some(rels) = worksheet_rels.get_mut(&sheet_idx) {
1426                rels.relationships
1427                    .retain(|r| r.rel_type != rel_types::COMMENTS);
1428                rels.relationships
1429                    .retain(|r| r.rel_type != rel_types::VML_DRAWING);
1430                if !removed_control_rids.is_empty() {
1431                    for relationship in &rels.relationships {
1432                        if removed_control_rids.contains(relationship.id.as_str()) {
1433                            removed_control_paths.insert(resolve_relationship_target(
1434                                &sheet_path,
1435                                &relationship.target,
1436                            ));
1437                        }
1438                    }
1439                    rels.relationships.retain(|relationship| {
1440                        !removed_control_rids.contains(relationship.id.as_str())
1441                    });
1442                }
1443            }
1444
1445            let needs_vml = has_comments || has_form_controls || has_preserved_vml;
1446            if !needs_vml && !has_comments {
1447                if controls_dirty {
1448                    worksheet_controls.insert(sheet_idx, Vec::new());
1449                }
1450                continue;
1451            }
1452
1453            if has_comments {
1454                let comment_path = original_comment_paths.first().cloned().unwrap_or_else(|| {
1455                    next_numbered_package_path(&allocated_comment_paths, "xl/comments", ".xml")
1456                });
1457                allocated_comment_paths.insert(comment_path.clone());
1458                let part_name = format!("/{}", comment_path);
1459                if !content_types
1460                    .overrides
1461                    .iter()
1462                    .any(|o| o.part_name == part_name && o.content_type == mime_types::COMMENTS)
1463                {
1464                    content_types.overrides.push(ContentTypeOverride {
1465                        part_name,
1466                        content_type: mime_types::COMMENTS.to_string(),
1467                    });
1468                }
1469
1470                let target = relative_relationship_target(&sheet_path, &comment_path);
1471                let rels = worksheet_rels
1472                    .entry(sheet_idx)
1473                    .or_insert_with(default_relationships);
1474                let rid = crate::sheet::next_rid(&rels.relationships);
1475                rels.relationships.push(Relationship {
1476                    id: rid,
1477                    rel_type: rel_types::COMMENTS.to_string(),
1478                    target,
1479                    target_mode: None,
1480                });
1481                comment_parts_to_write.push((sheet_idx, comment_path));
1482            }
1483
1484            if !needs_vml {
1485                continue;
1486            }
1487
1488            // Regenerate only owned shapes while preserving unrelated VML.
1489            let vml_path = original_vml_paths.first().cloned().unwrap_or_else(|| {
1490                next_numbered_package_path(&allocated_vml_paths, "xl/drawings/vmlDrawing", ".vml")
1491            });
1492            allocated_vml_paths.insert(vml_path.clone());
1493            let mut vml_bytes = self
1494                .sheet_vml
1495                .get(sheet_idx)
1496                .and_then(|v| v.as_ref())
1497                .cloned();
1498
1499            if has_comments
1500                && !vml_bytes
1501                    .as_deref()
1502                    .is_some_and(|vml| String::from_utf8_lossy(vml).contains("ObjectType=\"Note\""))
1503            {
1504                let comments = self.sheet_comments[sheet_idx].as_ref().unwrap();
1505                let cells: Vec<&str> = comments
1506                    .comment_list
1507                    .comments
1508                    .iter()
1509                    .map(|comment| comment.r#ref.as_str())
1510                    .collect();
1511                vml_bytes = Some(match vml_bytes {
1512                    Some(existing) => {
1513                        let start_id = crate::control::next_vml_shape_id(&existing);
1514                        crate::vml::merge_vml_comments(&existing, &cells, start_id)
1515                    }
1516                    None => crate::vml::build_vml_drawing(&cells).into_bytes(),
1517                });
1518            }
1519
1520            if controls_dirty && has_form_controls {
1521                let controls = &self.sheet_form_controls[sheet_idx];
1522                if raw_control_shape_ids.len() > controls.len() {
1523                    return Err(Error::InvalidArgument(
1524                        "cannot safely preserve existing form controls".to_string(),
1525                    ));
1526                }
1527                let new_controls = &controls[raw_control_shape_ids.len()..];
1528                let start_id = vml_bytes
1529                    .as_deref()
1530                    .map(crate::control::next_vml_shape_id)
1531                    .unwrap_or(1025);
1532                let last_shape_id = start_id
1533                    .checked_add(new_controls.len().saturating_sub(1))
1534                    .ok_or_else(|| {
1535                        Error::InvalidArgument("form control shape ID overflow".to_string())
1536                    })?;
1537                if (!new_controls.is_empty() && last_shape_id > 67_098_623)
1538                    || raw_control_shape_ids
1539                        .iter()
1540                        .any(|shape_id| *shape_id > 67_098_623)
1541                {
1542                    return Err(Error::InvalidArgument(
1543                        "form control shape IDs exceed Excel's supported range".to_string(),
1544                    ));
1545                }
1546                if !new_controls.is_empty() {
1547                    vml_bytes = Some(match vml_bytes {
1548                        Some(existing) => {
1549                            crate::control::merge_vml_controls(&existing, new_controls, start_id)
1550                        }
1551                        None => {
1552                            crate::control::build_form_control_vml(new_controls, 1025).into_bytes()
1553                        }
1554                    });
1555                }
1556
1557                let mut shape_ids = raw_control_shape_ids.clone();
1558                shape_ids.extend((0..new_controls.len()).map(|offset| start_id + offset));
1559
1560                let rels = worksheet_rels
1561                    .entry(sheet_idx)
1562                    .or_insert_with(default_relationships);
1563                let preserved_by_shape: HashMap<usize, (String, String)> = retained_control_entries
1564                    .drain(..)
1565                    .map(|(shape_id, rid, name)| (shape_id, (rid, name)))
1566                    .collect();
1567                let mut control_entries = Vec::with_capacity(controls.len());
1568                for (offset, (shape_id, control)) in shape_ids.into_iter().zip(controls).enumerate()
1569                {
1570                    if let Some((rid, name)) = preserved_by_shape.get(&shape_id) {
1571                        if rels.relationships.iter().any(|relationship| {
1572                            relationship.id == *rid
1573                                && relationship.rel_type == rel_types::CONTROL_PROPERTIES
1574                        }) {
1575                            control_entries.push((shape_id, rid.clone(), name.clone()));
1576                            continue;
1577                        }
1578                    }
1579                    let control_path = next_control_property_path(&allocated_control_paths);
1580                    allocated_control_paths.insert(control_path.clone());
1581                    let rid = crate::sheet::next_rid(&rels.relationships);
1582                    rels.relationships.push(Relationship {
1583                        id: rid.clone(),
1584                        rel_type: rel_types::CONTROL_PROPERTIES.to_string(),
1585                        target: relative_relationship_target(&sheet_path, &control_path),
1586                        target_mode: None,
1587                    });
1588                    content_types.overrides.push(ContentTypeOverride {
1589                        part_name: format!("/{control_path}"),
1590                        content_type: mime_types::CONTROL_PROPERTIES.to_string(),
1591                    });
1592                    control_parts_to_write.push((
1593                        control_path,
1594                        crate::control::build_control_property_xml(control),
1595                    ));
1596                    control_entries.push((
1597                        shape_id,
1598                        rid,
1599                        format!("{} {}", control.control_type.object_type(), offset + 1),
1600                    ));
1601                }
1602                worksheet_controls.insert(sheet_idx, control_entries);
1603            }
1604
1605            let Some(vml_bytes) = vml_bytes else {
1606                continue;
1607            };
1608
1609            let vml_part_name = format!("/{}", vml_path);
1610            if !content_types
1611                .overrides
1612                .iter()
1613                .any(|o| o.part_name == vml_part_name && o.content_type == mime_types::VML_DRAWING)
1614            {
1615                content_types.overrides.push(ContentTypeOverride {
1616                    part_name: vml_part_name,
1617                    content_type: mime_types::VML_DRAWING.to_string(),
1618                });
1619            }
1620
1621            let rels = worksheet_rels
1622                .entry(sheet_idx)
1623                .or_insert_with(default_relationships);
1624            let vml_target = relative_relationship_target(&sheet_path, &vml_path);
1625            let vml_rid = crate::sheet::next_rid(&rels.relationships);
1626            rels.relationships.push(Relationship {
1627                id: vml_rid.clone(),
1628                rel_type: rel_types::VML_DRAWING.to_string(),
1629                target: vml_target,
1630                target_mode: None,
1631            });
1632
1633            legacy_drawing_rids.insert(sheet_idx, vml_rid);
1634            vml_parts_to_write.push((sheet_idx, vml_path, vml_bytes));
1635            has_any_vml = true;
1636        }
1637
1638        if !removed_control_paths.is_empty() {
1639            content_types.overrides.retain(|entry| {
1640                let path = entry.part_name.trim_start_matches('/');
1641                !removed_control_paths.contains(path)
1642            });
1643        }
1644
1645        // Add vml extension default content type if needed.
1646        if has_any_vml && !content_types.defaults.iter().any(|d| d.extension == "vml") {
1647            content_types.defaults.push(ContentTypeDefault {
1648                extension: "vml".to_string(),
1649                content_type: mime_types::VML_DRAWING.to_string(),
1650            });
1651        }
1652
1653        // Synchronize table parts with worksheet relationships and content types.
1654        // Also build tableParts references for each worksheet.
1655        // In Lazy mode, untouched deferred tables should remain pass-through.
1656        // Once table data is mutated (or new live tables exist), we fully
1657        // resynchronize worksheet rels/content types/tableParts.
1658        use crate::workbook::aux::AuxCategory;
1659        let mut table_parts_by_sheet: HashMap<usize, Vec<String>> = HashMap::new();
1660        let should_sync_tables = !has_deferred
1661            || self.deferred_parts.is_dirty(AuxCategory::Tables)
1662            || !self.tables.is_empty();
1663        if should_sync_tables {
1664            for (sheet_idx, _) in self.worksheets.iter().enumerate() {
1665                if let Some(rels) = worksheet_rels.get_mut(&sheet_idx) {
1666                    rels.relationships
1667                        .retain(|r| r.rel_type != rel_types::TABLE);
1668                }
1669            }
1670            content_types
1671                .overrides
1672                .retain(|o| o.content_type != mime_types::TABLE);
1673        }
1674        for (table_path, _table_xml, sheet_idx) in &self.tables {
1675            let part_name = format!("/{table_path}");
1676            content_types.overrides.push(ContentTypeOverride {
1677                part_name,
1678                content_type: mime_types::TABLE.to_string(),
1679            });
1680
1681            let sheet_path = self.sheet_part_path(*sheet_idx);
1682            let target = relative_relationship_target(&sheet_path, table_path);
1683            let rels = worksheet_rels
1684                .entry(*sheet_idx)
1685                .or_insert_with(default_relationships);
1686            let rid = crate::sheet::next_rid(&rels.relationships);
1687            rels.relationships.push(Relationship {
1688                id: rid.clone(),
1689                rel_type: rel_types::TABLE.to_string(),
1690                target,
1691                target_mode: None,
1692            });
1693            table_parts_by_sheet
1694                .entry(*sheet_idx)
1695                .or_default()
1696                .push(rid);
1697        }
1698
1699        let has_deferred_threaded = self
1700            .deferred_parts
1701            .has_category(crate::workbook::aux::AuxCategory::ThreadedComments)
1702            || self
1703                .deferred_parts
1704                .has_category(crate::workbook::aux::AuxCategory::PersonList);
1705        if !has_deferred_threaded {
1706            // Threaded-comment targets are sheet-index based, so rebuild the entire
1707            // relationship and override set after sheet lifecycle changes.
1708            content_types.overrides.retain(|override_entry| {
1709                override_entry.content_type
1710                    != sheetkit_xml::threaded_comment::THREADED_COMMENTS_CONTENT_TYPE
1711                    && override_entry.content_type
1712                        != sheetkit_xml::threaded_comment::PERSON_LIST_CONTENT_TYPE
1713            });
1714            for rels in worksheet_rels.values_mut() {
1715                rels.relationships.retain(|relationship| {
1716                    relationship.rel_type
1717                        != sheetkit_xml::threaded_comment::REL_TYPE_THREADED_COMMENT
1718                });
1719            }
1720            workbook_rels.relationships.retain(|relationship| {
1721                relationship.rel_type != sheetkit_xml::threaded_comment::REL_TYPE_PERSON
1722            });
1723        }
1724
1725        // Register threaded comment content types and relationships before writing.
1726        let has_any_threaded = self.sheet_threaded_comments.iter().any(|tc| tc.is_some());
1727        if has_any_threaded {
1728            for (i, tc) in self.sheet_threaded_comments.iter().enumerate() {
1729                if tc.is_some() {
1730                    let tc_path = format!("xl/threadedComments/threadedComment{}.xml", i + 1);
1731                    let tc_part_name = format!("/{tc_path}");
1732                    if !content_types.overrides.iter().any(|o| {
1733                        o.part_name == tc_part_name
1734                            && o.content_type
1735                                == sheetkit_xml::threaded_comment::THREADED_COMMENTS_CONTENT_TYPE
1736                    }) {
1737                        content_types.overrides.push(ContentTypeOverride {
1738                            part_name: tc_part_name,
1739                            content_type:
1740                                sheetkit_xml::threaded_comment::THREADED_COMMENTS_CONTENT_TYPE
1741                                    .to_string(),
1742                        });
1743                    }
1744
1745                    let sheet_path = self.sheet_part_path(i);
1746                    let target = relative_relationship_target(&sheet_path, &tc_path);
1747                    let rels = worksheet_rels
1748                        .entry(i)
1749                        .or_insert_with(default_relationships);
1750                    let rid = crate::sheet::next_rid(&rels.relationships);
1751                    rels.relationships.push(Relationship {
1752                        id: rid,
1753                        rel_type: sheetkit_xml::threaded_comment::REL_TYPE_THREADED_COMMENT
1754                            .to_string(),
1755                        target,
1756                        target_mode: None,
1757                    });
1758                }
1759            }
1760
1761            let person_part_name = "/xl/persons/person.xml";
1762            if !content_types.overrides.iter().any(|o| {
1763                o.part_name == person_part_name
1764                    && o.content_type == sheetkit_xml::threaded_comment::PERSON_LIST_CONTENT_TYPE
1765            }) {
1766                content_types.overrides.push(ContentTypeOverride {
1767                    part_name: person_part_name.to_string(),
1768                    content_type: sheetkit_xml::threaded_comment::PERSON_LIST_CONTENT_TYPE
1769                        .to_string(),
1770                });
1771            }
1772
1773            // Add person relationship to workbook_rels so Excel can discover the person list.
1774            let rid = crate::sheet::next_rid(&workbook_rels.relationships);
1775            workbook_rels.relationships.push(Relationship {
1776                id: rid,
1777                rel_type: sheetkit_xml::threaded_comment::REL_TYPE_PERSON.to_string(),
1778                target: "persons/person.xml".to_string(),
1779                target_mode: None,
1780            });
1781        }
1782
1783        let raw_preserved_paths: HashSet<String> = self
1784            .unknown_parts
1785            .iter()
1786            .filter(|(path, _)| !is_vba_path(path))
1787            .map(|(path, _)| path.clone())
1788            .chain(
1789                self.deferred_parts
1790                    .remaining_parts()
1791                    .filter(|(path, _)| !is_vba_path(path))
1792                    .map(|(path, _)| path.to_string()),
1793            )
1794            .collect();
1795        let mut generated_lifecycle_paths: HashSet<String> = HashSet::from([
1796            "[Content_Types].xml".to_string(),
1797            "_rels/.rels".to_string(),
1798            "xl/workbook.xml".to_string(),
1799            "xl/_rels/workbook.xml.rels".to_string(),
1800            "xl/styles.xml".to_string(),
1801            "xl/sharedStrings.xml".to_string(),
1802        ]);
1803        generated_lifecycle_paths
1804            .extend((0..self.worksheets.len()).map(|i| self.sheet_part_path(i)));
1805        generated_lifecycle_paths.extend(
1806            self.sheet_comments
1807                .iter()
1808                .enumerate()
1809                .filter(|(_, comments)| comments.is_some())
1810                .map(|(i, _)| format!("xl/comments{}.xml", i + 1)),
1811        );
1812        generated_lifecycle_paths
1813            .extend(vml_parts_to_write.iter().map(|(_, path, _)| path.clone()));
1814        generated_lifecycle_paths
1815            .extend(control_parts_to_write.iter().map(|(path, _)| path.clone()));
1816        generated_lifecycle_paths.extend(self.drawings.iter().map(|(path, _)| path.clone()));
1817        generated_lifecycle_paths.extend(self.charts.iter().map(|(path, _)| path.clone()));
1818        generated_lifecycle_paths.extend(self.raw_charts.iter().map(|(path, _)| path.clone()));
1819        generated_lifecycle_paths.extend(self.raw_graph_parts.keys().cloned());
1820        generated_lifecycle_paths.extend(self.images.iter().map(|(path, _)| path.clone()));
1821        generated_lifecycle_paths.extend(self.tables.iter().map(|(path, _, _)| path.clone()));
1822        generated_lifecycle_paths.extend(self.pivot_tables.iter().map(|(path, _)| path.clone()));
1823        generated_lifecycle_paths
1824            .extend(self.pivot_cache_defs.iter().map(|(path, _)| path.clone()));
1825        generated_lifecycle_paths.extend(
1826            self.pivot_cache_records
1827                .iter()
1828                .map(|(path, _)| path.clone()),
1829        );
1830        generated_lifecycle_paths.extend(self.slicer_defs.iter().map(|(path, _)| path.clone()));
1831        generated_lifecycle_paths.extend(self.slicer_caches.iter().map(|(path, _)| path.clone()));
1832        generated_lifecycle_paths.extend(
1833            worksheet_rels
1834                .keys()
1835                .map(|sheet_idx| relationship_part_path(&self.sheet_part_path(*sheet_idx))),
1836        );
1837        generated_lifecycle_paths.extend(self.drawing_rels.keys().filter_map(|drawing_idx| {
1838            self.drawings
1839                .get(*drawing_idx)
1840                .map(|(path, _)| relationship_part_path(path))
1841        }));
1842        if self.theme_xml.is_some() {
1843            generated_lifecycle_paths.insert("xl/theme/theme1.xml".to_string());
1844        }
1845        if emits_vba {
1846            generated_lifecycle_paths.insert("xl/vbaProject.bin".to_string());
1847        }
1848        if self.core_properties.is_some() {
1849            generated_lifecycle_paths.insert("docProps/core.xml".to_string());
1850        }
1851        if self.app_properties.is_some() {
1852            generated_lifecycle_paths.insert("docProps/app.xml".to_string());
1853        }
1854        if self.custom_properties.is_some() {
1855            generated_lifecycle_paths.insert("docProps/custom.xml".to_string());
1856        }
1857        generated_lifecycle_paths.extend(self.raw_doc_props.keys().cloned());
1858        if has_any_threaded {
1859            generated_lifecycle_paths.extend(
1860                self.sheet_threaded_comments
1861                    .iter()
1862                    .enumerate()
1863                    .filter(|(_, threaded)| threaded.is_some())
1864                    .map(|(i, _)| format!("xl/threadedComments/threadedComment{}.xml", i + 1)),
1865            );
1866            generated_lifecycle_paths.insert("xl/persons/person.xml".to_string());
1867        }
1868        if let Some(conflict) = generated_lifecycle_paths
1869            .intersection(&raw_preserved_paths)
1870            .next()
1871        {
1872            return Err(Error::InvalidArgument(format!(
1873                "cannot save because owned part path '{conflict}' conflicts with preserved raw data"
1874            )));
1875        }
1876
1877        // [Content_Types].xml
1878        write_xml_part(
1879            zip,
1880            "[Content_Types].xml",
1881            &content_types,
1882            options,
1883            limits.xml_part_bytes,
1884        )?;
1885
1886        // _rels/.rels
1887        write_xml_part(
1888            zip,
1889            "_rels/.rels",
1890            &self.package_rels,
1891            options,
1892            limits.xml_part_bytes,
1893        )?;
1894
1895        // xl/workbook.xml
1896        let slicer_index = self.table_slicer_index();
1897        let slicer_cache_rids: Vec<(&str, Option<bool>)> = workbook_rels
1898            .relationships
1899            .iter()
1900            .filter(|rel| rel.rel_type == rel_types::SLICER_CACHE)
1901            .map(|rel| {
1902                let path = resolve_relationship_target("xl/workbook.xml", &rel.target);
1903                (rel.id.as_str(), slicer_index.cache_is_table(&path))
1904            })
1905            .collect();
1906        let workbook_needs_slicer_extensions = !slicer_cache_rids.is_empty();
1907        if workbook_needs_slicer_extensions {
1908            let raw = self.raw_workbook_xml.as_deref();
1909            let xml = serialize_workbook_with_slicer_extensions(
1910                &self.workbook_xml,
1911                raw,
1912                &slicer_cache_rids,
1913            )?;
1914            write_bytes_part(
1915                zip,
1916                "xl/workbook.xml",
1917                xml.as_bytes(),
1918                options,
1919                limits.xml_part_bytes,
1920            )?;
1921        } else if let (Some(raw), Some(baseline)) =
1922            (&self.raw_workbook_xml, &self.workbook_xml_baseline)
1923        {
1924            if self.workbook_xml == *baseline {
1925                write_bytes_part(zip, "xl/workbook.xml", raw, options, limits.xml_part_bytes)?;
1926            } else {
1927                write_xml_part(
1928                    zip,
1929                    "xl/workbook.xml",
1930                    &self.workbook_xml,
1931                    options,
1932                    limits.xml_part_bytes,
1933                )?;
1934            }
1935        } else {
1936            write_xml_part(
1937                zip,
1938                "xl/workbook.xml",
1939                &self.workbook_xml,
1940                options,
1941                limits.xml_part_bytes,
1942            )?;
1943        }
1944
1945        // xl/_rels/workbook.xml.rels
1946        write_xml_part(
1947            zip,
1948            "xl/_rels/workbook.xml.rels",
1949            &workbook_rels,
1950            options,
1951            limits.xml_part_bytes,
1952        )?;
1953
1954        // xl/worksheets/sheet{N}.xml
1955        for (i, (_name, ws_lock)) in self.worksheets.iter().enumerate() {
1956            let entry_name = self.sheet_part_path(i);
1957            let dirty = self.sheet_dirty.get(i).copied().unwrap_or(true);
1958
1959            // If the sheet has streamed data, write it directly from the temp file.
1960            if let Some(streamed) = self.streamed_sheets.get(&i) {
1961                crate::stream::write_streamed_sheet(
1962                    zip,
1963                    &entry_name,
1964                    streamed,
1965                    options,
1966                    limits.xml_part_bytes,
1967                )?;
1968                continue;
1969            }
1970
1971            // Copy-on-write passthrough: if the sheet has not been modified
1972            // (not dirty) and raw XML bytes are available, write them directly.
1973            // This avoids deserialize-then-serialize overhead for untouched
1974            // sheets. Dirty sheets always take the serialization path even if
1975            // raw bytes happen to still be present.
1976            //
1977            // The passthrough is also disabled when auxiliary parts (comments,
1978            // tables, sparklines) require XML injection into the worksheet,
1979            // since the raw bytes would lack those references.
1980            let sheet_path_for_slicers = self.sheet_part_path(i);
1981            let slicer_rids: Vec<(&str, Option<bool>)> = worksheet_rels
1982                .get(&i)
1983                .map(|rels| {
1984                    rels.relationships
1985                        .iter()
1986                        .filter(|rel| rel.rel_type == rel_types::SLICER)
1987                        .map(|rel| {
1988                            let path =
1989                                resolve_relationship_target(&sheet_path_for_slicers, &rel.target);
1990                            (rel.id.as_str(), slicer_index.slicer_part_is_table(&path))
1991                        })
1992                        .collect()
1993                })
1994                .unwrap_or_default();
1995            let needs_aux_injection = legacy_drawing_rids.contains_key(&i)
1996                || table_parts_by_sheet.contains_key(&i)
1997                || !slicer_rids.is_empty()
1998                || self
1999                    .sheet_sparklines
2000                    .get(i)
2001                    .is_some_and(|sparklines| !sparklines.is_empty());
2002            let included = self.sheet_included.get(i).copied().unwrap_or(true);
2003            let package_backed = self.sheet_package_backed.get(i).copied().unwrap_or(false);
2004            if !dirty && (!included || !needs_aux_injection) {
2005                if let Some(Some(raw_bytes)) = self.raw_sheet_xml.get(i) {
2006                    write_bytes_part(zip, &entry_name, raw_bytes, options, limits.xml_part_bytes)?;
2007                    continue;
2008                }
2009                if package_backed {
2010                    let source = self.package_source.as_ref().ok_or_else(|| {
2011                        Error::Internal("package-backed sheet has no source".to_string())
2012                    })?;
2013                    source.raw_copy_part(&entry_name, zip)?;
2014                    continue;
2015                }
2016            }
2017
2018            // For non-dirty sheets that need aux injection (comments/tables),
2019            // or lazy/deferred sheets whose OnceLock is uninitialized, hydrate
2020            // from raw bytes. We intentionally avoid worksheet_ref_by_index
2021            // here because it applies sheet_rows truncation, which would cause
2022            // data loss on save for sheets that were never read by the user.
2023            //
2024            // Filtered-out sheets (via OpenOptions::sheets) have their OnceLock
2025            // initialized with an empty placeholder while raw_sheet_xml holds
2026            // the real data. We must prefer raw bytes over the placeholder.
2027            let hydrated_for_save: WorksheetXml;
2028            let ws = if !dirty {
2029                if let Some(Some(raw_bytes)) = self.raw_sheet_xml.get(i) {
2030                    hydrated_for_save = deserialize_worksheet_xml(raw_bytes)?;
2031                    &hydrated_for_save
2032                } else if package_backed && self.package_source.is_some() && included {
2033                    hydrated_for_save = self.deserialize_package_sheet_for_save(i)?;
2034                    &hydrated_for_save
2035                } else {
2036                    match ws_lock.get() {
2037                        Some(ws) => ws,
2038                        None => continue,
2039                    }
2040                }
2041            } else if !included
2042                && !self.sheet_materialized.get(i).copied().unwrap_or(true)
2043                && package_backed
2044                && self.package_source.is_some()
2045            {
2046                // Auxiliary-only mutations can dirty an excluded sheet while
2047                // its typed worksheet is still the empty filter placeholder.
2048                // Merge those auxiliary changes into the complete pinned
2049                // package worksheet rather than serializing the placeholder.
2050                hydrated_for_save = self.deserialize_package_sheet_for_save(i)?;
2051                &hydrated_for_save
2052            } else {
2053                match ws_lock.get() {
2054                    Some(ws) => ws,
2055                    None => {
2056                        if let Some(Some(raw_bytes)) = self.raw_sheet_xml.get(i) {
2057                            hydrated_for_save = deserialize_worksheet_xml(raw_bytes)?;
2058                            &hydrated_for_save
2059                        } else if package_backed && self.package_source.is_some() && included {
2060                            hydrated_for_save = self.deserialize_package_sheet_for_save(i)?;
2061                            &hydrated_for_save
2062                        } else {
2063                            continue;
2064                        }
2065                    }
2066                }
2067            };
2068
2069            let empty_sparklines: Vec<crate::sparkline::SparklineConfig> = vec![];
2070            let sparklines = self.sheet_sparklines.get(i).unwrap_or(&empty_sparklines);
2071            let legacy_rid = legacy_drawing_rids.get(&i).map(|s| s.as_str());
2072            let sheet_table_rids = table_parts_by_sheet.get(&i);
2073            let stale_table_parts =
2074                should_sync_tables && sheet_table_rids.is_none() && ws.table_parts.is_some();
2075            let has_extras = legacy_rid.is_some()
2076                || !sparklines.is_empty()
2077                || sheet_table_rids.is_some()
2078                || stale_table_parts
2079                || !slicer_rids.is_empty()
2080                || self.sheet_controls_dirty.get(i).copied().unwrap_or(false);
2081
2082            if !has_extras {
2083                write_xml_part(zip, &entry_name, ws, options, limits.xml_part_bytes)?;
2084            } else {
2085                let ws_to_serialize;
2086                let ws_ref = if let Some(rids) = sheet_table_rids {
2087                    ws_to_serialize = {
2088                        let mut cloned = ws.clone();
2089                        use sheetkit_xml::worksheet::{TablePart, TableParts};
2090                        cloned.table_parts = Some(TableParts {
2091                            count: Some(rids.len() as u32),
2092                            table_parts: rids
2093                                .iter()
2094                                .map(|rid| TablePart { r_id: rid.clone() })
2095                                .collect(),
2096                        });
2097                        cloned
2098                    };
2099                    &ws_to_serialize
2100                } else if stale_table_parts {
2101                    ws_to_serialize = {
2102                        let mut cloned = ws.clone();
2103                        cloned.table_parts = None;
2104                        cloned
2105                    };
2106                    &ws_to_serialize
2107                } else {
2108                    ws
2109                };
2110                let retained_extension = self
2111                    .raw_sheet_xml
2112                    .get(i)
2113                    .and_then(|raw| raw.as_deref())
2114                    .or_else(|| {
2115                        self.raw_sheet_extensions
2116                            .get(i)
2117                            .and_then(|raw| raw.as_deref())
2118                    });
2119                let package_extension = if retained_extension.is_none() && package_backed {
2120                    self.package_source
2121                        .as_ref()
2122                        .map(|source| source.worksheet_extension_fragment(&entry_name))
2123                        .transpose()?
2124                        .flatten()
2125                } else {
2126                    None
2127                };
2128                let raw_sheet = retained_extension.or(package_extension.as_deref());
2129                let xml = serialize_worksheet_with_slicer_extras(
2130                    ws_ref,
2131                    sparklines,
2132                    legacy_rid,
2133                    raw_sheet,
2134                    &slicer_rids,
2135                    worksheet_controls.get(&i).map(Vec::as_slice).unwrap_or(&[]),
2136                    self.sheet_controls_dirty.get(i).copied().unwrap_or(false),
2137                )?;
2138                write_bytes_part(
2139                    zip,
2140                    &entry_name,
2141                    xml.as_bytes(),
2142                    options,
2143                    limits.xml_part_bytes,
2144                )?;
2145            }
2146        }
2147
2148        // xl/styles.xml
2149        write_xml_part(
2150            zip,
2151            "xl/styles.xml",
2152            &self.stylesheet,
2153            options,
2154            limits.xml_part_bytes,
2155        )?;
2156
2157        // xl/sharedStrings.xml -- write from the runtime SST
2158        let sst_xml = self.sst_runtime.to_sst();
2159        write_xml_part(
2160            zip,
2161            "xl/sharedStrings.xml",
2162            &sst_xml,
2163            options,
2164            limits.xml_part_bytes,
2165        )?;
2166
2167        // Write hydrated comments at their retained or newly allocated paths.
2168        for (sheet_idx, path) in &comment_parts_to_write {
2169            if let Some(comments) = self.sheet_comments[*sheet_idx].as_ref() {
2170                write_xml_part(zip, path, comments, options, limits.xml_part_bytes)?;
2171            }
2172        }
2173
2174        // xl/drawings/vmlDrawing{N}.vml -- write VML drawing parts
2175        for (_sheet_idx, vml_path, vml_bytes) in &vml_parts_to_write {
2176            write_bytes_part(zip, vml_path, vml_bytes, options, limits.xml_part_bytes)?;
2177        }
2178
2179        for (path, xml) in &control_parts_to_write {
2180            write_bytes_part(zip, path, xml.as_bytes(), options, limits.xml_part_bytes)?;
2181        }
2182
2183        let mut emitted_graph_paths: HashSet<String> = HashSet::new();
2184
2185        // xl/drawings/drawing{N}.xml -- write drawing parts
2186        for (path, drawing) in &self.drawings {
2187            if let Some(bytes) = self.clean_raw_graph_part(path) {
2188                write_bytes_part(zip, path, bytes, options, limits.xml_part_bytes)?;
2189            } else {
2190                write_xml_part(zip, path, drawing, options, limits.xml_part_bytes)?;
2191            }
2192            emitted_graph_paths.insert(path.clone());
2193        }
2194
2195        // xl/charts/chart{N}.xml -- write chart parts
2196        for (path, chart) in &self.charts {
2197            if let Some(bytes) = self.clean_raw_graph_part(path) {
2198                write_bytes_part(zip, path, bytes, options, limits.xml_part_bytes)?;
2199            } else {
2200                write_xml_part(zip, path, chart, options, limits.xml_part_bytes)?;
2201            }
2202            emitted_graph_paths.insert(path.clone());
2203        }
2204        for (path, data) in &self.raw_charts {
2205            if self.charts.iter().any(|(p, _)| p == path) {
2206                continue;
2207            }
2208            write_bytes_part(
2209                zip,
2210                path,
2211                self.clean_raw_graph_part(path).unwrap_or(data),
2212                options,
2213                limits.xml_part_bytes,
2214            )?;
2215            emitted_graph_paths.insert(path.clone());
2216        }
2217
2218        // xl/media/image{N}.{ext} -- write image data
2219        for (path, data) in &self.images {
2220            write_package_bytes_part(zip, path, data, options, limits.xml_part_bytes)?;
2221        }
2222
2223        // xl/worksheets/_rels/sheet{N}.xml.rels -- write worksheet relationships
2224        for (sheet_idx, rels) in &worksheet_rels {
2225            let sheet_path = self.sheet_part_path(*sheet_idx);
2226            let path = relationship_part_path(&sheet_path);
2227            write_xml_part(zip, &path, rels, options, limits.xml_part_bytes)?;
2228        }
2229
2230        // xl/drawings/_rels/drawing{N}.xml.rels -- write drawing relationships
2231        for (drawing_idx, rels) in &self.drawing_rels {
2232            if let Some((drawing_path, _)) = self.drawings.get(*drawing_idx) {
2233                let path = relationship_part_path(drawing_path);
2234                if let Some(bytes) = self.clean_raw_graph_part(&path) {
2235                    write_bytes_part(zip, &path, bytes, options, limits.xml_part_bytes)?;
2236                } else {
2237                    write_xml_part(zip, &path, rels, options, limits.xml_part_bytes)?;
2238                }
2239                emitted_graph_paths.insert(path);
2240            }
2241        }
2242
2243        // Raw drawing or relationship parts that could not be parsed eagerly.
2244        for (path, data) in &self.raw_graph_parts {
2245            if self.dirty_graph_parts.contains(path) || emitted_graph_paths.contains(path) {
2246                continue;
2247            }
2248            write_bytes_part(zip, path, data, options, limits.xml_part_bytes)?;
2249        }
2250
2251        // xl/pivotTables/pivotTable{N}.xml
2252        for (path, pt) in &self.pivot_tables {
2253            write_xml_part(zip, path, pt, options, limits.xml_part_bytes)?;
2254        }
2255
2256        // xl/pivotCache/pivotCacheDefinition{N}.xml
2257        for (path, pcd) in &self.pivot_cache_defs {
2258            write_xml_part(zip, path, pcd, options, limits.xml_part_bytes)?;
2259        }
2260
2261        // xl/pivotCache/pivotCacheRecords{N}.xml
2262        for (path, pcr) in &self.pivot_cache_records {
2263            let cache_definition =
2264                self.pivot_cache_defs
2265                    .iter()
2266                    .find_map(|(definition_path, definition)| {
2267                        let rels_path = relationship_part_path(definition_path);
2268                        let bytes = self
2269                            .raw_graph_parts
2270                            .get(&rels_path)
2271                            .map(Vec::as_slice)
2272                            .or_else(|| {
2273                                self.unknown_parts
2274                                    .iter()
2275                                    .find(|(unknown_path, _)| unknown_path == &rels_path)
2276                                    .map(|(_, bytes)| bytes.as_slice())
2277                            })?;
2278                        let relationships =
2279                            quick_xml::de::from_reader::<_, Relationships>(bytes).ok()?;
2280                        relationships
2281                            .relationships
2282                            .iter()
2283                            .any(|relationship| {
2284                                relationship.rel_type == rel_types::PIVOT_CACHE_RECORDS
2285                                    && resolve_relationship_target(
2286                                        definition_path,
2287                                        &relationship.target,
2288                                    ) == *path
2289                            })
2290                            .then_some(definition)
2291                    });
2292            let xml = if let Some(definition) = cache_definition {
2293                serialize_pivot_cache_records(pcr, definition)?
2294            } else {
2295                serialize_xml(pcr)?
2296            };
2297            write_bytes_part(zip, path, xml.as_bytes(), options, limits.xml_part_bytes)?;
2298        }
2299
2300        // xl/tables/table{N}.xml
2301        for (path, table_xml, _sheet_idx) in &self.tables {
2302            if let Some(raw) = table_xml.unchanged_source() {
2303                write_bytes_part(zip, path, raw.as_bytes(), options, limits.xml_part_bytes)?;
2304            } else {
2305                write_xml_part(zip, path, table_xml, options, limits.xml_part_bytes)?;
2306            }
2307        }
2308
2309        // xl/slicers/slicer{N}.xml
2310        for (path, sd) in &self.slicer_defs {
2311            write_xml_part(zip, path, sd, options, limits.xml_part_bytes)?;
2312        }
2313
2314        // xl/slicerCaches/slicerCache{N}.xml (manual serialization)
2315        for (path, scd) in &self.slicer_caches {
2316            let xml_str = format!(
2317                "{}\n{}",
2318                XML_DECLARATION,
2319                sheetkit_xml::slicer::serialize_slicer_cache(scd),
2320            );
2321            write_bytes_part(
2322                zip,
2323                path,
2324                xml_str.as_bytes(),
2325                options,
2326                limits.xml_part_bytes,
2327            )?;
2328        }
2329
2330        // xl/theme/theme1.xml
2331        {
2332            let default_theme = crate::theme::default_theme_xml();
2333            let theme_bytes = self.theme_xml.as_deref().unwrap_or(&default_theme);
2334            write_bytes_part(
2335                zip,
2336                "xl/theme/theme1.xml",
2337                theme_bytes,
2338                options,
2339                limits.xml_part_bytes,
2340            )?;
2341        }
2342
2343        // xl/vbaProject.bin -- write VBA blob if present
2344        if let Some(blob) = self.vba_blob.as_ref().filter(|_| emits_vba) {
2345            write_package_bytes_part(
2346                zip,
2347                "xl/vbaProject.bin",
2348                blob,
2349                options,
2350                limits.xml_part_bytes,
2351            )?;
2352        }
2353
2354        // docProps/core.xml
2355        if let Some(raw) = self.clean_raw_doc_prop("docProps/core.xml") {
2356            write_bytes_part(
2357                zip,
2358                "docProps/core.xml",
2359                raw,
2360                options,
2361                limits.xml_part_bytes,
2362            )?;
2363        } else if let Some(ref props) = self.core_properties {
2364            let xml_str = sheetkit_xml::doc_props::serialize_core_properties(props);
2365            write_bytes_part(
2366                zip,
2367                "docProps/core.xml",
2368                xml_str.as_bytes(),
2369                options,
2370                limits.xml_part_bytes,
2371            )?;
2372        }
2373
2374        // docProps/app.xml
2375        if let Some(raw) = self.clean_raw_doc_prop("docProps/app.xml") {
2376            write_bytes_part(zip, "docProps/app.xml", raw, options, limits.xml_part_bytes)?;
2377        } else if let Some(ref props) = self.app_properties {
2378            write_xml_part(
2379                zip,
2380                "docProps/app.xml",
2381                props,
2382                options,
2383                limits.xml_part_bytes,
2384            )?;
2385        }
2386
2387        // docProps/custom.xml
2388        if let Some(raw) = self.clean_raw_doc_prop("docProps/custom.xml") {
2389            write_bytes_part(
2390                zip,
2391                "docProps/custom.xml",
2392                raw,
2393                options,
2394                limits.xml_part_bytes,
2395            )?;
2396        } else if let Some(ref props) = self.custom_properties {
2397            let xml_str = sheetkit_xml::doc_props::serialize_custom_properties(props);
2398            write_bytes_part(
2399                zip,
2400                "docProps/custom.xml",
2401                xml_str.as_bytes(),
2402                options,
2403                limits.xml_part_bytes,
2404            )?;
2405        }
2406
2407        // xl/threadedComments/threadedComment{N}.xml
2408        if has_any_threaded {
2409            for (i, tc) in self.sheet_threaded_comments.iter().enumerate() {
2410                if let Some(ref tc_data) = tc {
2411                    let tc_path = format!("xl/threadedComments/threadedComment{}.xml", i + 1);
2412                    write_xml_part(zip, &tc_path, tc_data, options, limits.xml_part_bytes)?;
2413                }
2414            }
2415            write_xml_part(
2416                zip,
2417                "xl/persons/person.xml",
2418                &self.person_list,
2419                options,
2420                limits.xml_part_bytes,
2421            )?;
2422        }
2423
2424        // Write back unknown parts preserved from the original file.
2425        for (path, data) in &self.unknown_parts {
2426            if removed_control_paths.contains(path) || is_vba_path(path) {
2427                continue;
2428            }
2429            write_package_bytes_part(zip, path, data, options, limits.xml_part_bytes)?;
2430        }
2431
2432        // Write back deferred parts from Lazy open (raw bytes, unparsed).
2433        // Skip any path that was already written by the normal code above. This
2434        // prevents duplicate ZIP entries when an auxiliary part (comments, doc
2435        // properties, etc.) is mutated after a Lazy open.
2436        if self.deferred_parts.has_any() {
2437            let mut emitted_owned: HashSet<String> = HashSet::new();
2438            // Essential parts always written.
2439            emitted_owned.insert("[Content_Types].xml".to_string());
2440            emitted_owned.insert("_rels/.rels".to_string());
2441            emitted_owned.insert("xl/workbook.xml".to_string());
2442            emitted_owned.insert("xl/_rels/workbook.xml.rels".to_string());
2443            emitted_owned.insert("xl/styles.xml".to_string());
2444            emitted_owned.insert("xl/sharedStrings.xml".to_string());
2445            emitted_owned.insert("xl/theme/theme1.xml".to_string());
2446            // Per-sheet worksheet paths.
2447            for i in 0..self.worksheets.len() {
2448                emitted_owned.insert(self.sheet_part_path(i));
2449            }
2450            for (i, comments) in self.sheet_comments.iter().enumerate() {
2451                if comments.is_some() {
2452                    emitted_owned.insert(format!("xl/comments{}.xml", i + 1));
2453                }
2454            }
2455            for (_sheet_idx, vml_path, _) in &vml_parts_to_write {
2456                emitted_owned.insert(vml_path.clone());
2457            }
2458            for (path, _) in &control_parts_to_write {
2459                emitted_owned.insert(path.clone());
2460            }
2461            for (path, _) in &self.drawings {
2462                emitted_owned.insert(path.clone());
2463            }
2464            for (path, _) in &self.charts {
2465                emitted_owned.insert(path.clone());
2466            }
2467            for (path, _) in &self.raw_charts {
2468                emitted_owned.insert(path.clone());
2469            }
2470            emitted_owned.extend(self.raw_graph_parts.keys().cloned());
2471            for (path, _) in &self.images {
2472                emitted_owned.insert(path.clone());
2473            }
2474            for sheet_idx in worksheet_rels.keys() {
2475                let sheet_path = self.sheet_part_path(*sheet_idx);
2476                emitted_owned.insert(relationship_part_path(&sheet_path));
2477            }
2478            for drawing_idx in self.drawing_rels.keys() {
2479                if let Some((drawing_path, _)) = self.drawings.get(*drawing_idx) {
2480                    emitted_owned.insert(relationship_part_path(drawing_path));
2481                }
2482            }
2483            for (path, _) in &self.pivot_tables {
2484                emitted_owned.insert(path.clone());
2485            }
2486            for (path, _) in &self.pivot_cache_defs {
2487                emitted_owned.insert(path.clone());
2488            }
2489            for (path, _) in &self.pivot_cache_records {
2490                emitted_owned.insert(path.clone());
2491            }
2492            for (path, _, _) in &self.tables {
2493                emitted_owned.insert(path.clone());
2494            }
2495            for (path, _) in &self.slicer_defs {
2496                emitted_owned.insert(path.clone());
2497            }
2498            for (path, _) in &self.slicer_caches {
2499                emitted_owned.insert(path.clone());
2500            }
2501            if emits_vba || !preserves_vba {
2502                emitted_owned.insert("xl/vbaProject.bin".to_string());
2503            }
2504            if self.core_properties.is_some() {
2505                emitted_owned.insert("docProps/core.xml".to_string());
2506            }
2507            if self.app_properties.is_some() {
2508                emitted_owned.insert("docProps/app.xml".to_string());
2509            }
2510            if self.custom_properties.is_some() {
2511                emitted_owned.insert("docProps/custom.xml".to_string());
2512            }
2513            emitted_owned.extend(self.raw_doc_props.keys().cloned());
2514            if has_any_threaded {
2515                for (i, tc) in self.sheet_threaded_comments.iter().enumerate() {
2516                    if tc.is_some() {
2517                        emitted_owned
2518                            .insert(format!("xl/threadedComments/threadedComment{}.xml", i + 1));
2519                    }
2520                }
2521                emitted_owned.insert("xl/persons/person.xml".to_string());
2522            }
2523            for (path, _) in &self.unknown_parts {
2524                emitted_owned.insert(path.clone());
2525            }
2526
2527            for (path, data) in self.deferred_parts.remaining_parts() {
2528                if emitted_owned.contains(path) || is_vba_path(path) {
2529                    continue;
2530                }
2531                write_package_bytes_part(zip, path, data, options, limits.xml_part_bytes)?;
2532            }
2533        }
2534
2535        Ok(())
2536    }
2537}
2538
2539impl Default for Workbook {
2540    fn default() -> Self {
2541        Self::new()
2542    }
2543}
2544
2545#[cfg(feature = "encryption")]
2546fn read_bounded_file(
2547    path: &Path,
2548    budget: &OpenBudget,
2549    crypt_limits: crate::crypt::CryptLimits,
2550) -> Result<Vec<u8>> {
2551    let file = std::fs::File::open(path)?;
2552    let declared = file.metadata()?.len();
2553    budget.check_outer_input(declared)?;
2554    let crypt_limit = crate::crypt::validate_decrypt_outer_cfb(crypt_limits, declared)?;
2555
2556    let limit = budget.limits().outer_input_bytes.min(crypt_limit);
2557    let mut reader = file.take(limit.saturating_add(1));
2558    let initial_capacity =
2559        usize::try_from(declared.min(LARGE_BUF_CAPACITY as u64)).unwrap_or(LARGE_BUF_CAPACITY);
2560    let mut data = Vec::new();
2561    data.try_reserve(initial_capacity).map_err(|_| {
2562        Error::Io(std::io::Error::new(
2563            std::io::ErrorKind::OutOfMemory,
2564            "unable to reserve bounded encrypted workbook buffer",
2565        ))
2566    })?;
2567    reader.read_to_end(&mut data)?;
2568    let observed = u64::try_from(data.len()).unwrap_or(u64::MAX);
2569    budget.check_outer_input(observed)?;
2570    crate::crypt::validate_decrypt_outer_cfb(crypt_limits, observed)?;
2571    Ok(data)
2572}
2573
2574/// Replace `path` atomically through a same-directory temporary file. Only
2575/// durable saves request file and directory syncs.
2576fn atomic_write_file(
2577    path: &Path,
2578    options: crate::save::SaveOptions,
2579    write: impl FnOnce(&mut std::fs::File) -> Result<()>,
2580) -> Result<()> {
2581    atomic_write_file_with_sync(
2582        path,
2583        options,
2584        write,
2585        sync_temporary_file,
2586        sync_parent_directory,
2587    )
2588}
2589
2590fn atomic_write_file_with_sync(
2591    path: &Path,
2592    options: crate::save::SaveOptions,
2593    write: impl FnOnce(&mut std::fs::File) -> Result<()>,
2594    sync_file: impl FnOnce(&std::fs::File) -> std::io::Result<()>,
2595    sync_parent: impl FnOnce(&Path) -> std::io::Result<()>,
2596) -> Result<()> {
2597    // Replace the file a symlink points to rather than the link itself.
2598    let (destination, existing_permissions) = resolve_save_destination(path)?;
2599    let parent = destination
2600        .parent()
2601        .filter(|parent| !parent.as_os_str().is_empty())
2602        .unwrap_or_else(|| Path::new("."));
2603    let mut builder = tempfile::Builder::new();
2604    builder.prefix(".sheetkit-");
2605    #[cfg(unix)]
2606    if existing_permissions.is_none() {
2607        // New files get the conventional mode, still narrowed by the umask.
2608        use std::os::unix::fs::PermissionsExt as _;
2609        builder.permissions(std::fs::Permissions::from_mode(0o666));
2610    }
2611    let mut temporary = builder.tempfile_in(parent)?;
2612    write(temporary.as_file_mut())?;
2613    temporary.as_file_mut().flush()?;
2614    #[cfg(unix)]
2615    if let Some(permissions) = existing_permissions {
2616        temporary.as_file().set_permissions(permissions)?;
2617    }
2618    #[cfg(not(unix))]
2619    let _ = existing_permissions;
2620    if options.durable {
2621        sync_file(temporary.as_file())?;
2622    }
2623    // Dropping the temporary on any earlier error removes it.
2624    temporary
2625        .persist(&destination)
2626        .map_err(|error| Error::Io(error.error))?;
2627
2628    // The rename is the commit point, so a failed directory sync cannot undo
2629    // it; the error must say the new file is already in place.
2630    if options.durable {
2631        sync_parent(parent).map_err(|error| {
2632            Error::Io(std::io::Error::new(
2633                error.kind(),
2634                format!(
2635                    "workbook saved to {} but syncing the parent directory failed: {error}; \
2636                     the new file may not survive a crash",
2637                    destination.display()
2638                ),
2639            ))
2640        })?;
2641    }
2642    Ok(())
2643}
2644
2645#[cfg(test)]
2646thread_local! {
2647    static SYNC_CALLS: std::cell::RefCell<Vec<&'static str>> =
2648        const { std::cell::RefCell::new(Vec::new()) };
2649}
2650
2651fn sync_temporary_file(file: &std::fs::File) -> std::io::Result<()> {
2652    #[cfg(test)]
2653    SYNC_CALLS.with(|calls| calls.borrow_mut().push("file"));
2654    file.sync_all()
2655}
2656
2657/// Follow symlinks from `path` to the file a save must replace. Returns the
2658/// final path and the permissions of an existing destination file.
2659fn resolve_save_destination(
2660    path: &Path,
2661) -> std::io::Result<(std::path::PathBuf, Option<std::fs::Permissions>)> {
2662    const MAX_SYMLINK_HOPS: usize = 40;
2663    let mut current = path.to_path_buf();
2664    for _ in 0..MAX_SYMLINK_HOPS {
2665        match std::fs::symlink_metadata(&current) {
2666            Ok(metadata) if metadata.file_type().is_symlink() => {
2667                let target = std::fs::read_link(&current)?;
2668                current = if target.is_absolute() {
2669                    target
2670                } else {
2671                    current
2672                        .parent()
2673                        .map(|parent| parent.join(&target))
2674                        .unwrap_or(target)
2675                };
2676            }
2677            Ok(metadata) => return Ok((current, Some(metadata.permissions()))),
2678            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
2679                return Ok((current, None));
2680            }
2681            Err(error) => return Err(error),
2682        }
2683    }
2684    Err(std::io::Error::new(
2685        std::io::ErrorKind::InvalidInput,
2686        "too many levels of symbolic links in save destination",
2687    ))
2688}
2689
2690/// Sync a directory entry on Unix. Windows has no directory sync, so this is
2691/// a no-op there.
2692fn sync_parent_directory(parent: &Path) -> std::io::Result<()> {
2693    #[cfg(unix)]
2694    {
2695        #[cfg(test)]
2696        SYNC_CALLS.with(|calls| calls.borrow_mut().push("dir"));
2697        std::fs::File::open(parent)?.sync_all()
2698    }
2699
2700    #[cfg(not(unix))]
2701    {
2702        let _ = parent;
2703        Ok(())
2704    }
2705}
2706
2707fn reject_save_metric(
2708    dimension: crate::resource::ResourceDimension,
2709    observed: u64,
2710    limit: u64,
2711) -> Result<()> {
2712    if observed > limit {
2713        return Err(crate::save::resource_limit(
2714            crate::resource::ResourceOperation::WorkbookSave,
2715            crate::resource::ResourceCategory::Output,
2716            dimension,
2717            limit,
2718            observed,
2719            crate::resource::ResourceStage::Serialize,
2720        ));
2721    }
2722    Ok(())
2723}
2724
2725fn worksheet_xml_metrics(bytes: &[u8], limit: u64) -> Result<(u64, u64)> {
2726    reject_save_metric(
2727        crate::resource::ResourceDimension::XmlBytes,
2728        u64::try_from(bytes.len()).unwrap_or(u64::MAX),
2729        limit,
2730    )?;
2731    let mut reader = quick_xml::Reader::from_reader(std::io::Cursor::new(bytes));
2732    let mut buffer = Vec::with_capacity(4096);
2733    let mut rows = 0u64;
2734    let mut cells = 0u64;
2735    loop {
2736        buffer.clear();
2737        match reader
2738            .read_event_into(&mut buffer)
2739            .map_err(|error| Error::XmlParse(error.to_string()))?
2740        {
2741            quick_xml::events::Event::Start(element) | quick_xml::events::Event::Empty(element) => {
2742                match element.local_name().as_ref() {
2743                    b"row" => rows = rows.saturating_add(1),
2744                    b"c" => cells = cells.saturating_add(1),
2745                    _ => {}
2746                }
2747            }
2748            quick_xml::events::Event::Eof => break,
2749            _ => {}
2750        }
2751    }
2752    Ok((rows, cells))
2753}
2754
2755fn streamed_worksheet_xml_bytes(streamed: &crate::stream::StreamedSheetData) -> u64 {
2756    u64::try_from(crate::stream::build_worksheet_header(streamed).len())
2757        .unwrap_or(u64::MAX)
2758        .saturating_add(streamed.data_len)
2759        .saturating_add(
2760            u64::try_from(crate::stream::build_worksheet_footer(streamed).len())
2761                .unwrap_or(u64::MAX),
2762        )
2763}
2764
2765struct SaveOutputWriter<W> {
2766    inner: W,
2767    limit: u64,
2768    position: u64,
2769    length: u64,
2770    resource_error: Option<crate::resource::ResourceLimitError>,
2771}
2772
2773impl<W> SaveOutputWriter<W> {
2774    fn new(inner: W, limit: u64) -> Self {
2775        Self {
2776            inner,
2777            limit,
2778            position: 0,
2779            length: 0,
2780            resource_error: None,
2781        }
2782    }
2783
2784    fn resource_error(&self) -> Option<crate::resource::ResourceLimitError> {
2785        self.resource_error
2786    }
2787
2788    fn into_inner(self) -> W {
2789        self.inner
2790    }
2791
2792    fn mark_output_exceeded(&mut self) {
2793        if self.resource_error.is_none() {
2794            self.resource_error = crate::resource::ResourceLimitError::exceeded(
2795                crate::resource::ResourceOperation::WorkbookSave,
2796                crate::resource::ResourceCategory::Output,
2797                crate::resource::ResourceDimension::OutputBytes,
2798                self.limit,
2799                self.limit.saturating_add(1),
2800                Some(crate::resource::ResourceStage::Write),
2801            );
2802        }
2803    }
2804
2805    fn virtual_seek(&self, position: std::io::SeekFrom) -> std::io::Result<u64> {
2806        let next = match position {
2807            std::io::SeekFrom::Start(offset) => i128::from(offset),
2808            std::io::SeekFrom::Current(offset) => {
2809                i128::from(self.position).saturating_add(i128::from(offset))
2810            }
2811            std::io::SeekFrom::End(offset) => {
2812                i128::from(self.length).saturating_add(i128::from(offset))
2813            }
2814        };
2815        u64::try_from(next).map_err(|_| {
2816            std::io::Error::new(std::io::ErrorKind::InvalidInput, "invalid output seek")
2817        })
2818    }
2819}
2820
2821impl<W: std::io::Write> std::io::Write for SaveOutputWriter<W> {
2822    fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
2823        let amount = u64::try_from(bytes.len()).unwrap_or(u64::MAX);
2824        let observed = self.position.saturating_add(amount);
2825        if self.resource_error.is_some() || observed > self.limit {
2826            self.mark_output_exceeded();
2827            self.position = observed;
2828            self.length = self.length.max(observed);
2829            return Ok(bytes.len());
2830        }
2831        let written = self.inner.write(bytes)?;
2832        self.position = self
2833            .position
2834            .saturating_add(u64::try_from(written).unwrap_or(u64::MAX));
2835        self.length = self.length.max(self.position);
2836        Ok(written)
2837    }
2838
2839    fn flush(&mut self) -> std::io::Result<()> {
2840        if self.resource_error.is_some() {
2841            Ok(())
2842        } else {
2843            self.inner.flush()
2844        }
2845    }
2846}
2847
2848impl<W: std::io::Seek> std::io::Seek for SaveOutputWriter<W> {
2849    fn seek(&mut self, position: std::io::SeekFrom) -> std::io::Result<u64> {
2850        let virtual_next = self.virtual_seek(position)?;
2851        if self.resource_error.is_some() || virtual_next > self.limit {
2852            self.mark_output_exceeded();
2853            self.position = virtual_next;
2854            self.length = self.length.max(virtual_next);
2855            return Ok(virtual_next);
2856        }
2857        let next = self.inner.seek(position)?;
2858        self.position = next;
2859        self.length = self.length.max(next);
2860        Ok(next)
2861    }
2862}
2863
2864/// Serialize a value to XML with the standard XML declaration prepended.
2865pub(crate) fn serialize_xml<T: Serialize>(value: &T) -> Result<String> {
2866    let body = quick_xml::se::to_string(value).map_err(|e| Error::XmlParse(e.to_string()))?;
2867    let mut result = String::with_capacity(XML_DECLARATION.len() + 1 + body.len());
2868    result.push_str(XML_DECLARATION);
2869    result.push('\n');
2870    result.push_str(&body);
2871    Ok(result)
2872}
2873
2874fn serialize_pivot_cache_records(
2875    records: &sheetkit_xml::pivot_cache::PivotCacheRecords,
2876    definition: &sheetkit_xml::pivot_cache::PivotCacheDefinition,
2877) -> Result<String> {
2878    use std::fmt::Write as _;
2879
2880    let field_kinds = definition
2881        .cache_fields
2882        .fields
2883        .iter()
2884        .map(|field| {
2885            let items = field.shared_items.as_ref();
2886            items.is_some_and(|items| {
2887                items.contains_number == Some(true) && items.contains_string != Some(true)
2888            })
2889        })
2890        .collect::<Vec<_>>();
2891    let expected_numbers = field_kinds.iter().filter(|is_number| **is_number).count();
2892    let expected_indexes = field_kinds.len().saturating_sub(expected_numbers);
2893    if records.records.iter().any(|record| {
2894        record.number_fields.len() != expected_numbers
2895            || record.index_fields.len() != expected_indexes
2896            || !record.string_fields.is_empty()
2897            || !record.bool_fields.is_empty()
2898    }) {
2899        return serialize_xml(records);
2900    }
2901
2902    let mut xml = String::new();
2903    xml.push_str(XML_DECLARATION);
2904    xml.push('\n');
2905    write!(
2906        xml,
2907        "<pivotCacheRecords xmlns=\"{}\" xmlns:r=\"{}\" count=\"{}\">",
2908        quick_xml::escape::escape(&records.xmlns),
2909        quick_xml::escape::escape(&records.xmlns_r),
2910        records.count.unwrap_or(records.records.len() as u32),
2911    )
2912    .map_err(|error| Error::Internal(error.to_string()))?;
2913    for record in &records.records {
2914        xml.push_str("<r>");
2915        let mut indexes = record.index_fields.iter();
2916        let mut numbers = record.number_fields.iter();
2917        for is_number in &field_kinds {
2918            if *is_number {
2919                let value = numbers
2920                    .next()
2921                    .ok_or_else(|| Error::Internal("missing pivot cache number".to_string()))?;
2922                write!(xml, "<n v=\"{}\"/>", value.v)
2923                    .map_err(|error| Error::Internal(error.to_string()))?;
2924            } else {
2925                let value = indexes
2926                    .next()
2927                    .ok_or_else(|| Error::Internal("missing pivot cache index".to_string()))?;
2928                write!(xml, "<x v=\"{}\"/>", value.v)
2929                    .map_err(|error| Error::Internal(error.to_string()))?;
2930            }
2931        }
2932        xml.push_str("</r>");
2933    }
2934    xml.push_str("</pivotCacheRecords>");
2935    Ok(xml)
2936}
2937
2938/// Deserialize a `WorksheetXml` from raw XML bytes.
2939///
2940/// This is the on-demand counterpart of `read_xml_part` for worksheet data
2941/// that was stored as raw bytes during open (lazy mode or filtered-out sheets).
2942/// After deserialization, cell column numbers are populated and rows/cells
2943/// are sorted for binary-search correctness.
2944pub(super) fn deserialize_worksheet_xml(bytes: &[u8]) -> Result<WorksheetXml> {
2945    let buf_cap = bytes.len().clamp(8192, LARGE_BUF_CAPACITY);
2946    let reader = std::io::BufReader::with_capacity(buf_cap, bytes);
2947    deserialize_worksheet_xml_with_row_limit(reader, None)
2948}
2949
2950/// Incrementally filter worksheet rows before typed deserialization.
2951///
2952/// Rows beyond `row_limit` are scanned but never copied into the bounded
2953/// intermediate spool and therefore cannot create typed row/cell allocations.
2954pub(super) fn deserialize_worksheet_xml_with_row_limit<R: std::io::BufRead>(
2955    source: R,
2956    row_limit: Option<u32>,
2957) -> Result<WorksheetXml> {
2958    let mut ws: WorksheetXml = if let Some(row_limit) = row_limit {
2959        use std::io::{Seek as _, Write as _};
2960
2961        let mut reader = quick_xml::Reader::from_reader(source);
2962        reader.config_mut().trim_text(false);
2963        let spool = tempfile::tempfile()?;
2964        let mut writer = quick_xml::Writer::new(std::io::BufWriter::new(spool));
2965        let mut buffer = Vec::with_capacity(4096);
2966        let mut in_sheet_data = false;
2967        let mut rows_kept = 0u32;
2968        let mut skipped_depth: Option<usize> = None;
2969
2970        loop {
2971            buffer.clear();
2972            let event = reader
2973                .read_event_into(&mut buffer)
2974                .map_err(|error| Error::XmlParse(error.to_string()))?;
2975
2976            if let Some(depth) = &mut skipped_depth {
2977                match &event {
2978                    quick_xml::events::Event::Start(_) => *depth += 1,
2979                    quick_xml::events::Event::End(_) => {
2980                        *depth -= 1;
2981                        if *depth == 0 {
2982                            skipped_depth = None;
2983                        }
2984                    }
2985                    quick_xml::events::Event::Eof => {
2986                        return Err(Error::XmlParse(
2987                            "unexpected EOF while skipping worksheet row".to_string(),
2988                        ));
2989                    }
2990                    _ => {}
2991                }
2992                continue;
2993            }
2994
2995            match &event {
2996                quick_xml::events::Event::Start(element)
2997                    if element.local_name().as_ref() == b"sheetData" =>
2998                {
2999                    in_sheet_data = true;
3000                }
3001                quick_xml::events::Event::End(element)
3002                    if element.local_name().as_ref() == b"sheetData" =>
3003                {
3004                    in_sheet_data = false;
3005                }
3006                quick_xml::events::Event::Start(element)
3007                    if in_sheet_data && element.local_name().as_ref() == b"row" =>
3008                {
3009                    if rows_kept >= row_limit {
3010                        skipped_depth = Some(1);
3011                        continue;
3012                    }
3013                    rows_kept += 1;
3014                }
3015                quick_xml::events::Event::Empty(element)
3016                    if in_sheet_data && element.local_name().as_ref() == b"row" =>
3017                {
3018                    if rows_kept >= row_limit {
3019                        continue;
3020                    }
3021                    rows_kept += 1;
3022                }
3023                quick_xml::events::Event::Eof => break,
3024                _ => {}
3025            }
3026            writer
3027                .write_event(event.into_owned())
3028                .map_err(|error| Error::XmlParse(error.to_string()))?;
3029        }
3030
3031        let mut spool = writer
3032            .into_inner()
3033            .into_inner()
3034            .map_err(|error| Error::Io(error.into_error()))?;
3035        spool.flush()?;
3036        spool.seek(std::io::SeekFrom::Start(0))?;
3037        quick_xml::de::from_reader(std::io::BufReader::new(spool))
3038            .map_err(|error| Error::XmlDeserialize(error.to_string()))?
3039    } else {
3040        quick_xml::de::from_reader(source)
3041            .map_err(|error| Error::XmlDeserialize(error.to_string()))?
3042    };
3043    // Also shrinks each row's cells while it walks them.
3044    crate::utils::cell_ref::validate_and_index_worksheet(&mut ws)?;
3045    ws.sheet_data.rows.shrink_to_fit();
3046    Ok(ws)
3047}
3048
3049fn resolve_checked_table_target(source_part: &str, target: &str) -> Result<String> {
3050    if target.is_empty()
3051        || target.contains('\\')
3052        || target
3053            .chars()
3054            .any(|character| matches!(character, '?' | '#' | '\0'))
3055        || target.split('/').any(|segment| segment == ".")
3056    {
3057        return Err(Error::InvalidArgument(
3058            "invalid table relationship target".to_string(),
3059        ));
3060    }
3061
3062    let mut segments: Vec<&str> = if target.starts_with('/') {
3063        Vec::new()
3064    } else {
3065        source_part
3066            .rsplit_once('/')
3067            .map(|(directory, _)| directory.split('/').collect())
3068            .unwrap_or_default()
3069    };
3070
3071    for segment in target.trim_start_matches('/').split('/') {
3072        match segment {
3073            "" => {
3074                return Err(Error::InvalidArgument(
3075                    "invalid table relationship target".to_string(),
3076                ));
3077            }
3078            ".." => {
3079                if segments.pop().is_none() {
3080                    return Err(Error::InvalidArgument(
3081                        "table relationship target escapes package root".to_string(),
3082                    ));
3083                }
3084            }
3085            value if value.contains(':') => {
3086                return Err(Error::InvalidArgument(
3087                    "external table relationship target is not allowed".to_string(),
3088                ));
3089            }
3090            value => segments.push(value),
3091        }
3092    }
3093
3094    let resolved = segments.join("/");
3095    if !resolved.starts_with("xl/tables/") || !resolved.ends_with(".xml") {
3096        return Err(Error::InvalidArgument(format!(
3097            "table relationship target is outside xl/tables: {resolved}"
3098        )));
3099    }
3100    Ok(resolved)
3101}
3102
3103fn validate_table_relationship_ownership(
3104    worksheet_paths: &[String],
3105    worksheet_rels: &HashMap<usize, Relationships>,
3106    content_types: &ContentTypes,
3107    package_paths: &HashSet<String>,
3108) -> Result<HashMap<String, usize>> {
3109    let mut declared_tables = HashSet::new();
3110    for entry in &content_types.overrides {
3111        if entry.content_type != mime_types::TABLE {
3112            continue;
3113        }
3114        if !entry.part_name.starts_with('/') {
3115            return Err(Error::InvalidArgument(
3116                "table content type path must be package-absolute".to_string(),
3117            ));
3118        }
3119        let path = resolve_checked_table_target("", &entry.part_name)?;
3120        if !declared_tables.insert(path.clone()) {
3121            return Err(Error::InvalidArgument(format!(
3122                "duplicate table content type declaration: {path}"
3123            )));
3124        }
3125        if !package_paths.contains(&path) {
3126            return Err(Error::InvalidArgument(format!(
3127                "table relationship target is missing from package: {path}"
3128            )));
3129        }
3130    }
3131
3132    let mut owners = HashMap::new();
3133    for (sheet_index, relationships) in worksheet_rels {
3134        let sheet_path = worksheet_paths.get(*sheet_index).ok_or_else(|| {
3135            Error::InvalidArgument(format!(
3136                "table relationship references unknown sheet index {sheet_index}"
3137            ))
3138        })?;
3139        let mut id_counts: HashMap<&str, usize> = HashMap::new();
3140        for relationship in &relationships.relationships {
3141            *id_counts.entry(&relationship.id).or_default() += 1;
3142        }
3143
3144        for relationship in &relationships.relationships {
3145            if relationship.rel_type != rel_types::TABLE {
3146                continue;
3147            }
3148            if !relationship_target_is_internal(relationship) {
3149                return Err(Error::InvalidArgument(format!(
3150                    "external table relationship is not allowed: {}",
3151                    relationship.id
3152                )));
3153            }
3154            if relationship.id.is_empty() || id_counts[relationship.id.as_str()] != 1 {
3155                return Err(Error::InvalidArgument(format!(
3156                    "duplicate or empty table relationship id: {}",
3157                    relationship.id
3158                )));
3159            }
3160
3161            let path = resolve_checked_table_target(sheet_path, &relationship.target)?;
3162            if !declared_tables.contains(&path) || !package_paths.contains(&path) {
3163                return Err(Error::InvalidArgument(format!(
3164                    "table relationship target is missing or undeclared: {path}"
3165                )));
3166            }
3167            if let Some(previous_owner) = owners.insert(path.clone(), *sheet_index) {
3168                return Err(Error::InvalidArgument(format!(
3169                    "table part has multiple owners ({previous_owner}, {sheet_index}): {path}"
3170                )));
3171            }
3172        }
3173    }
3174
3175    for path in declared_tables {
3176        if !owners.contains_key(&path) {
3177            return Err(Error::InvalidArgument(format!(
3178                "table part has no worksheet relationship owner: {path}"
3179            )));
3180        }
3181    }
3182    Ok(owners)
3183}
3184
3185fn resolved_namespace_is(result: &quick_xml::name::ResolveResult<'_>, expected: &str) -> bool {
3186    matches!(
3187        result,
3188        quick_xml::name::ResolveResult::Bound(namespace)
3189            if namespace.as_ref() == expected.as_bytes()
3190    )
3191}
3192
3193fn table_part_relationship_id<R: std::io::BufRead>(
3194    reader: &quick_xml::NsReader<R>,
3195    element: &quick_xml::events::BytesStart<'_>,
3196    sheet_path: &str,
3197) -> Result<String> {
3198    let mut relationship_id = None;
3199    for attribute in element.attributes() {
3200        let attribute = attribute.map_err(|error| Error::XmlParse(error.to_string()))?;
3201        let (namespace, local_name) = reader.resolve_attribute(attribute.key);
3202        if local_name.as_ref() == b"id"
3203            && resolved_namespace_is(&namespace, sheetkit_xml::namespaces::RELATIONSHIPS)
3204        {
3205            if relationship_id.is_some() {
3206                return Err(Error::InvalidArgument(format!(
3207                    "worksheet tablePart has duplicate r:id attributes: {sheet_path}"
3208                )));
3209            }
3210            relationship_id = Some(
3211                attribute
3212                    .decode_and_unescape_value(reader.decoder())
3213                    .map_err(|error| Error::XmlParse(error.to_string()))?
3214                    .into_owned(),
3215            );
3216        }
3217    }
3218    relationship_id.ok_or_else(|| {
3219        Error::InvalidArgument(format!("worksheet tablePart is missing r:id: {sheet_path}"))
3220    })
3221}
3222
3223fn validate_worksheet_table_parts<A: ArchiveAccess>(
3224    archive: &mut A,
3225    worksheet_paths: &[String],
3226    worksheet_rels: &HashMap<usize, Relationships>,
3227    sheet_checked: &[bool],
3228) -> Result<()> {
3229    for (sheet_index, relationships) in worksheet_rels {
3230        if !sheet_checked.get(*sheet_index).copied().unwrap_or(false) {
3231            continue;
3232        }
3233        let expected_ids = table_relationship_ids(Some(relationships));
3234        if expected_ids.is_empty() {
3235            continue;
3236        }
3237
3238        let sheet_path = worksheet_paths.get(*sheet_index).ok_or_else(|| {
3239            Error::InvalidArgument(format!(
3240                "table relationship references unknown sheet index {sheet_index}"
3241            ))
3242        })?;
3243        let (result, read_error) = {
3244            let entry = archive.entry(sheet_path, true)?;
3245            let mut source = PartReader::new(entry, None);
3246            let result = validate_worksheet_table_part_stream(
3247                std::io::BufReader::with_capacity(LARGE_BUF_CAPACITY, &mut source),
3248                &expected_ids,
3249                sheet_path,
3250            );
3251            (result, source.read_error)
3252        };
3253        if let Some(error) = archive.pending_error() {
3254            return Err(error);
3255        }
3256        if let Some(message) = read_error {
3257            return Err(Error::Zip(message));
3258        }
3259        result?;
3260    }
3261    Ok(())
3262}
3263
3264/// Table relationship ids declared by one worksheet relationship part.
3265fn table_relationship_ids(relationships: Option<&Relationships>) -> HashSet<String> {
3266    relationships
3267        .into_iter()
3268        .flat_map(|relationships| &relationships.relationships)
3269        .filter(|relationship| relationship.rel_type == rel_types::TABLE)
3270        .map(|relationship| relationship.id.clone())
3271        .collect()
3272}
3273
3274/// Check that a worksheet's `tableParts` list matches its table relationships.
3275fn validate_worksheet_table_part_stream<R: std::io::BufRead>(
3276    source: R,
3277    expected_ids: &HashSet<String>,
3278    sheet_path: &str,
3279) -> Result<()> {
3280    let mut reader = quick_xml::NsReader::from_reader(source);
3281    let mut buffer = Vec::with_capacity(4096);
3282    let mut declared_count = None;
3283    let mut seen_container = false;
3284    let mut in_container = false;
3285    let mut open_table_part = false;
3286    let mut actual_ids = HashSet::with_capacity(expected_ids.len());
3287
3288    loop {
3289        buffer.clear();
3290        let (namespace, event) = reader
3291            .read_resolved_event_into(&mut buffer)
3292            .map_err(|error| Error::XmlParse(error.to_string()))?;
3293        let is_spreadsheet_ml =
3294            resolved_namespace_is(&namespace, sheetkit_xml::namespaces::SPREADSHEET_ML);
3295        if open_table_part {
3296            match event {
3297                quick_xml::events::Event::End(element)
3298                    if is_spreadsheet_ml && element.local_name().as_ref() == b"tablePart" =>
3299                {
3300                    open_table_part = false;
3301                    continue;
3302                }
3303                quick_xml::events::Event::Text(text)
3304                    if text.as_ref().iter().all(u8::is_ascii_whitespace) =>
3305                {
3306                    continue;
3307                }
3308                quick_xml::events::Event::Comment(_) => continue,
3309                _ => {
3310                    return Err(Error::InvalidArgument(format!(
3311                        "worksheet tablePart must be empty: {sheet_path}"
3312                    )));
3313                }
3314            }
3315        }
3316        match event {
3317            quick_xml::events::Event::Start(element)
3318                if is_spreadsheet_ml && element.local_name().as_ref() == b"tableParts" =>
3319            {
3320                if seen_container {
3321                    return Err(Error::InvalidArgument(format!(
3322                        "worksheet has duplicate tableParts containers: {sheet_path}"
3323                    )));
3324                }
3325                seen_container = true;
3326                in_container = true;
3327                for attribute in element.attributes() {
3328                    let attribute =
3329                        attribute.map_err(|error| Error::XmlParse(error.to_string()))?;
3330                    let (attribute_namespace, local_name) = reader.resolve_attribute(attribute.key);
3331                    if matches!(attribute_namespace, quick_xml::name::ResolveResult::Unbound)
3332                        && local_name.as_ref() == b"count"
3333                    {
3334                        if declared_count.is_some() {
3335                            return Err(Error::InvalidArgument(format!(
3336                                "worksheet tableParts has duplicate count attributes: {sheet_path}"
3337                            )));
3338                        }
3339                        declared_count = Some(
3340                            attribute
3341                                .decode_and_unescape_value(reader.decoder())
3342                                .map_err(|error| Error::XmlParse(error.to_string()))?
3343                                .parse::<u32>()
3344                                .map_err(|error| Error::XmlParse(error.to_string()))?,
3345                        );
3346                    }
3347                }
3348            }
3349            quick_xml::events::Event::End(element)
3350                if is_spreadsheet_ml && element.local_name().as_ref() == b"tableParts" =>
3351            {
3352                in_container = false;
3353            }
3354            quick_xml::events::Event::Empty(element)
3355                if in_container
3356                    && is_spreadsheet_ml
3357                    && element.local_name().as_ref() == b"tablePart" =>
3358            {
3359                let relationship_id = table_part_relationship_id(&reader, &element, sheet_path)?;
3360                if !actual_ids.insert(relationship_id) || actual_ids.len() > expected_ids.len() {
3361                    return Err(Error::InvalidArgument(format!(
3362                        "worksheet tableParts do not match table relationships: {sheet_path}"
3363                    )));
3364                }
3365            }
3366            quick_xml::events::Event::Start(element)
3367                if in_container
3368                    && is_spreadsheet_ml
3369                    && element.local_name().as_ref() == b"tablePart" =>
3370            {
3371                let relationship_id = table_part_relationship_id(&reader, &element, sheet_path)?;
3372                if !actual_ids.insert(relationship_id) || actual_ids.len() > expected_ids.len() {
3373                    return Err(Error::InvalidArgument(format!(
3374                        "worksheet tableParts do not match table relationships: {sheet_path}"
3375                    )));
3376                }
3377                open_table_part = true;
3378            }
3379            quick_xml::events::Event::Eof => break,
3380            _ => {}
3381        }
3382    }
3383
3384    if open_table_part || declared_count.is_some_and(|count| count as usize != actual_ids.len()) {
3385        return Err(Error::InvalidArgument(format!(
3386            "worksheet tableParts count does not match entries: {sheet_path}"
3387        )));
3388    }
3389    if actual_ids.len() != expected_ids.len()
3390        || !actual_ids
3391            .iter()
3392            .all(|relationship_id| expected_ids.contains(relationship_id.as_str()))
3393    {
3394        return Err(Error::InvalidArgument(format!(
3395            "worksheet tableParts do not match table relationships: {sheet_path}"
3396        )));
3397    }
3398    Ok(())
3399}
3400
3401pub(crate) fn validate_materialized_worksheet_table_parts(
3402    worksheet: &WorksheetXml,
3403    relationships: Option<&Relationships>,
3404    sheet_path: &str,
3405) -> Result<()> {
3406    let expected_ids: HashSet<&str> = relationships
3407        .into_iter()
3408        .flat_map(|relationships| &relationships.relationships)
3409        .filter(|relationship| relationship.rel_type == rel_types::TABLE)
3410        .map(|relationship| relationship.id.as_str())
3411        .collect();
3412    if expected_ids.is_empty() {
3413        return Ok(());
3414    }
3415    let Some(table_parts) = &worksheet.table_parts else {
3416        return Err(Error::InvalidArgument(format!(
3417            "worksheet tableParts do not match table relationships: {sheet_path}"
3418        )));
3419    };
3420    if table_parts
3421        .count
3422        .is_some_and(|count| usize::try_from(count).ok() != Some(table_parts.table_parts.len()))
3423    {
3424        return Err(Error::InvalidArgument(format!(
3425            "worksheet tableParts count does not match entries: {sheet_path}"
3426        )));
3427    }
3428    let actual_ids: HashSet<&str> = table_parts
3429        .table_parts
3430        .iter()
3431        .map(|table_part| table_part.r_id.as_str())
3432        .collect();
3433    if actual_ids.len() != table_parts.table_parts.len()
3434        || actual_ids.len() != expected_ids.len()
3435        || !actual_ids.iter().all(|id| expected_ids.contains(id))
3436    {
3437        return Err(Error::InvalidArgument(format!(
3438            "worksheet tableParts do not match table relationships: {sheet_path}"
3439        )));
3440    }
3441    Ok(())
3442}
3443
3444/// BufReader capacity for large XML parts (worksheets, sharedStrings).
3445/// 64 KB reduces read-syscall overhead compared to the 8 KB default.
3446const LARGE_BUF_CAPACITY: usize = 64 * 1024;
3447
3448/// Read a ZIP entry and deserialize it from XML.
3449///
3450/// Uses `quick_xml::de::from_reader` to deserialize directly from the
3451/// decompressed ZIP stream, avoiding the intermediate `String` allocation
3452/// that `read_to_string` + `from_str` would require. The BufReader
3453/// capacity is scaled based on the uncompressed entry size, up to 64 KB,
3454/// to reduce read-syscall overhead on large parts.
3455pub(crate) fn read_xml_part<T: serde::de::DeserializeOwned, A: ArchiveAccess>(
3456    archive: &mut A,
3457    name: &str,
3458) -> Result<T> {
3459    read_xml_entry(archive, name, PartPresence::Required)?
3460        .ok_or_else(|| Error::Internal(format!("required part was not read: {name}")))?
3461}
3462
3463/// Read an optional XML part. Returns `None` when the entry is absent or its
3464/// intact bytes do not deserialize; such parts remain preserved as unknown
3465/// parts. Archive read, checksum, and size failures are returned as errors.
3466fn read_optional_xml_part<T: serde::de::DeserializeOwned, A: ArchiveAccess>(
3467    archive: &mut A,
3468    name: &str,
3469) -> Result<Option<T>> {
3470    Ok(read_xml_entry(archive, name, PartPresence::Optional)?.and_then(Result::ok))
3471}
3472
3473/// Whether a missing archive entry is an error or an absent optional part.
3474#[derive(Clone, Copy, PartialEq, Eq)]
3475enum PartPresence {
3476    Required,
3477    Optional,
3478}
3479
3480/// Stream-deserialize one XML entry. The outer result carries archive
3481/// failures; the inner result carries XML deserialization failures.
3482fn read_xml_entry<T: serde::de::DeserializeOwned, A: ArchiveAccess>(
3483    archive: &mut A,
3484    name: &str,
3485    presence: PartPresence,
3486) -> Result<Option<Result<T>>> {
3487    let (parsed, read_error) = {
3488        let entry = match presence {
3489            PartPresence::Required => archive.entry(name, true)?,
3490            PartPresence::Optional => match archive.entry_optional(name, true)? {
3491                Some(entry) => entry,
3492                None => return Ok(None),
3493            },
3494        };
3495        let mut source = PartReader::new(entry, None);
3496        let parsed = {
3497            let mut reader = std::io::BufReader::with_capacity(LARGE_BUF_CAPACITY, &mut source);
3498            let parsed: Result<T> = quick_xml::de::from_reader(&mut reader)
3499                .map_err(|error| Error::XmlDeserialize(error.to_string()));
3500            if parsed.is_ok() {
3501                // Read to EOF so the checksum and declared size are verified.
3502                let _ = std::io::copy(&mut reader, &mut std::io::sink());
3503            }
3504            parsed
3505        };
3506        (parsed, source.read_error)
3507    };
3508    if let Some(error) = archive.pending_error() {
3509        return Err(error);
3510    }
3511    if let Some(message) = read_error {
3512        return Err(Error::Zip(message));
3513    }
3514    Ok(Some(parsed))
3515}
3516
3517/// Entry reader that records archive read failures separately from parser
3518/// failures and can mirror consumed bytes into a spool.
3519struct PartReader<R> {
3520    inner: R,
3521    copy: Option<std::io::BufWriter<std::fs::File>>,
3522    read_error: Option<String>,
3523    copy_error: Option<std::io::Error>,
3524}
3525
3526impl<R> PartReader<R> {
3527    fn new(inner: R, copy: Option<std::fs::File>) -> Self {
3528        Self {
3529            inner,
3530            copy: copy.map(std::io::BufWriter::new),
3531            read_error: None,
3532            copy_error: None,
3533        }
3534    }
3535}
3536
3537impl<R: std::io::Read> std::io::Read for PartReader<R> {
3538    fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {
3539        let count = match self.inner.read(buffer) {
3540            Ok(count) => count,
3541            Err(error) => {
3542                if self.read_error.is_none() {
3543                    self.read_error = Some(error.to_string());
3544                }
3545                return Err(error);
3546            }
3547        };
3548        if let Some(copy) = &mut self.copy {
3549            if let Err(error) = copy.write_all(&buffer[..count]) {
3550                let message = error.to_string();
3551                self.copy_error.get_or_insert(error);
3552                return Err(std::io::Error::other(message));
3553            }
3554        }
3555        Ok(count)
3556    }
3557}
3558
3559/// Decompress and parse one eagerly opened worksheet exactly once. When
3560/// `capture` is set, the decompressed bytes are also spooled to disk for
3561/// table and extension checks that must not decompress the entry again.
3562fn read_eager_worksheet<A: ArchiveAccess>(
3563    archive: &mut A,
3564    path: &str,
3565    row_limit: Option<u32>,
3566    capture: bool,
3567) -> Result<(WorksheetXml, Option<std::fs::File>)> {
3568    let spool = if capture {
3569        Some(tempfile::tempfile()?)
3570    } else {
3571        None
3572    };
3573    let (parsed, source) = {
3574        let entry = archive.entry(path, true)?;
3575        let mut source = PartReader::new(entry, spool);
3576        let parsed = {
3577            let mut reader = std::io::BufReader::with_capacity(LARGE_BUF_CAPACITY, &mut source);
3578            let parsed = deserialize_worksheet_xml_with_row_limit(&mut reader, row_limit);
3579            if parsed.is_ok() {
3580                let _ = std::io::copy(&mut reader, &mut std::io::sink());
3581            }
3582            parsed
3583        };
3584        (parsed, (source.read_error, source.copy_error, source.copy))
3585    };
3586    let (read_error, copy_error, copy) = source;
3587    if let Some(error) = archive.pending_error() {
3588        return Err(error);
3589    }
3590    if let Some(message) = read_error {
3591        return Err(Error::Zip(message));
3592    }
3593    if let Some(error) = copy_error {
3594        return Err(Error::Io(error));
3595    }
3596    let worksheet = parsed?;
3597    let spool = match copy {
3598        Some(writer) => {
3599            use std::io::Seek as _;
3600            let mut file = writer
3601                .into_inner()
3602                .map_err(|error| Error::Io(error.into_error()))?;
3603            file.seek(std::io::SeekFrom::Start(0))?;
3604            Some(file)
3605        }
3606        None => None,
3607    };
3608    Ok((worksheet, spool))
3609}
3610
3611/// Reject package part names that differ only by ASCII case. OPC part names
3612/// are case-insensitive, so such entries alias one logical part.
3613fn validate_package_part_names(package_paths: &HashSet<String>) -> Result<()> {
3614    let mut folded = HashSet::with_capacity(package_paths.len());
3615    for path in package_paths {
3616        if !folded.insert(path.to_ascii_lowercase()) {
3617            return Err(Error::InvalidArgument(format!(
3618                "package part names differ only by case: {path}"
3619            )));
3620        }
3621    }
3622    Ok(())
3623}
3624
3625/// Resolve each sheet's worksheet part and require a distinct, internal,
3626/// present worksheet part for every sheet.
3627fn resolve_worksheet_paths(
3628    workbook_xml: &WorkbookXml,
3629    workbook_rels: &Relationships,
3630    content_types: &ContentTypes,
3631    package_paths: &HashSet<String>,
3632) -> Result<Vec<String>> {
3633    const RESERVED_PARTS: [&str; 6] = [
3634        "[content_types].xml",
3635        "xl/workbook.xml",
3636        "xl/styles.xml",
3637        "xl/sharedstrings.xml",
3638        "xl/theme/theme1.xml",
3639        "xl/vbaproject.bin",
3640    ];
3641    let mut seen = HashSet::with_capacity(workbook_xml.sheets.sheets.len());
3642    let mut paths = Vec::with_capacity(workbook_xml.sheets.sheets.len());
3643    for sheet in &workbook_xml.sheets.sheets {
3644        let relationship = workbook_rels
3645            .relationships
3646            .iter()
3647            .find(|r| r.id == sheet.r_id && r.rel_type == rel_types::WORKSHEET)
3648            .ok_or_else(|| {
3649                Error::Internal(format!(
3650                    "missing worksheet relationship for sheet '{}'",
3651                    sheet.name
3652                ))
3653            })?;
3654        if !relationship_target_is_internal(relationship) {
3655            return Err(Error::InvalidArgument(format!(
3656                "external worksheet relationship is not allowed: {}",
3657                relationship.id
3658            )));
3659        }
3660        if relationship_target_escapes("xl/workbook.xml", &relationship.target) {
3661            return Err(Error::InvalidArgument(format!(
3662                "worksheet relationship target escapes package root: {}",
3663                relationship.id
3664            )));
3665        }
3666        let path = resolve_relationship_target("xl/workbook.xml", &relationship.target);
3667        let folded = path.to_ascii_lowercase();
3668        if !package_paths.contains(&path) {
3669            return Err(Error::InvalidArgument(format!(
3670                "worksheet relationship target is missing from package: {path}"
3671            )));
3672        }
3673        if RESERVED_PARTS.contains(&folded.as_str())
3674            || folded.ends_with(".rels")
3675            || content_types.overrides.iter().any(|entry| {
3676                entry
3677                    .part_name
3678                    .trim_start_matches('/')
3679                    .eq_ignore_ascii_case(&path)
3680                    && entry.content_type != mime_types::WORKSHEET
3681            })
3682        {
3683            return Err(Error::InvalidArgument(format!(
3684                "worksheet relationship target is not a worksheet part: {path}"
3685            )));
3686        }
3687        if !seen.insert(folded) {
3688            return Err(Error::InvalidArgument(format!(
3689                "worksheet part is shared by multiple sheets: {path}"
3690            )));
3691        }
3692        paths.push(path);
3693    }
3694    Ok(paths)
3695}
3696
3697/// Whether a relative or absolute target leaves the package root or uses a
3698/// URI scheme instead of a package part name.
3699/// Returns true when a relationship resolves inside the package: either the
3700/// TargetMode attribute is absent or it is explicitly "Internal".
3701fn relationship_target_is_internal(
3702    relationship: &sheetkit_xml::relationships::Relationship,
3703) -> bool {
3704    matches!(relationship.target_mode.as_deref(), None | Some("Internal"))
3705}
3706
3707fn relationship_target_escapes(source_part: &str, target: &str) -> bool {
3708    if target.is_empty() || target.contains('\\') || target.contains(':') {
3709        return true;
3710    }
3711    let mut depth = if target.starts_with('/') {
3712        0usize
3713    } else {
3714        source_part.matches('/').count()
3715    };
3716    for segment in target.trim_start_matches('/').split('/') {
3717        match segment {
3718            "" | "." => {}
3719            ".." => match depth.checked_sub(1) {
3720                Some(next) => depth = next,
3721                None => return true,
3722            },
3723            _ => depth += 1,
3724        }
3725    }
3726    false
3727}
3728
3729pub(crate) fn deserialize_xml_bytes<T: serde::de::DeserializeOwned>(bytes: &[u8]) -> Result<T> {
3730    quick_xml::de::from_reader(bytes).map_err(|e| Error::XmlDeserialize(e.to_string()))
3731}
3732
3733#[derive(Default)]
3734struct RawSharedStringText {
3735    plain: Option<String>,
3736    runs: Vec<String>,
3737}
3738
3739enum SharedStringTextTarget {
3740    Plain,
3741    Run,
3742}
3743
3744/// Deserialize an SST while retaining whitespace that quick-xml's serde
3745/// deserializer trims from text nodes.
3746fn read_shared_strings_part<A: ArchiveAccess>(archive: &mut A, name: &str) -> Result<Option<Sst>> {
3747    let Some(bytes) = read_optional_part(archive, name, true, false)? else {
3748        return Ok(None);
3749    };
3750    deserialize_shared_strings_from_bytes(&bytes).map(Some)
3751}
3752
3753fn deserialize_shared_strings<R: std::io::BufRead>(reader: R) -> Result<Sst> {
3754    quick_xml::de::from_reader(reader).map_err(|e| Error::XmlDeserialize(e.to_string()))
3755}
3756
3757fn restore_shared_string_text(mut sst: Sst, raw_items: Vec<RawSharedStringText>) -> Result<Sst> {
3758    if raw_items.len() != sst.items.len() {
3759        return Err(Error::XmlDeserialize(format!(
3760            "shared string item count mismatch: parsed {}, scanned {}",
3761            sst.items.len(),
3762            raw_items.len()
3763        )));
3764    }
3765
3766    for (index, (item, raw)) in sst.items.iter_mut().zip(raw_items).enumerate() {
3767        match (&mut item.t, item.r.as_mut_slice(), raw.plain, raw.runs) {
3768            (Some(text), runs, Some(raw_text), raw_runs) if runs.len() == raw_runs.len() => {
3769                text.value = raw_text;
3770                for (run, raw_text) in runs.iter_mut().zip(raw_runs) {
3771                    run.t.value = raw_text;
3772                }
3773            }
3774            (None, runs, None, raw_runs) if runs.len() == raw_runs.len() => {
3775                for (run, raw_text) in runs.iter_mut().zip(raw_runs) {
3776                    run.t.value = raw_text;
3777                }
3778            }
3779            (None, [], None, raw_runs) if raw_runs.is_empty() => {}
3780            _ => {
3781                return Err(Error::XmlDeserialize(format!(
3782                    "shared string item {index} text shape mismatch"
3783                )));
3784            }
3785        }
3786    }
3787
3788    Ok(sst)
3789}
3790
3791fn deserialize_shared_strings_from_bytes(bytes: &[u8]) -> Result<Sst> {
3792    // A byte slice is already buffered; wrapping it would only add copies.
3793    let sst = deserialize_shared_strings(bytes)?;
3794    if !shared_strings_need_raw_scan(bytes) {
3795        return Ok(sst);
3796    }
3797    let raw_items = scan_shared_string_text(bytes)?;
3798    restore_shared_string_text(sst, raw_items)
3799}
3800
3801/// Whether the bytes contain `:space` or `<![CDATA[`, found in one pass.
3802fn shared_strings_need_raw_scan(bytes: &[u8]) -> bool {
3803    const SPACE: &[u8] = b":space";
3804    const CDATA: &[u8] = b"<![CDATA[";
3805    bytes.iter().enumerate().any(|(index, &byte)| match byte {
3806        b':' => bytes[index..].starts_with(SPACE),
3807        // Key on the rare `!` rather than the ubiquitous `<`.
3808        b'!' => index > 0 && bytes[index - 1..].starts_with(CDATA),
3809        _ => false,
3810    })
3811}
3812
3813fn scan_shared_string_text<R: std::io::BufRead>(reader: R) -> Result<Vec<RawSharedStringText>> {
3814    use quick_xml::events::Event;
3815
3816    let mut reader = quick_xml::Reader::from_reader(reader);
3817    reader.config_mut().trim_text(false);
3818    let mut stack: Vec<Vec<u8>> = Vec::new();
3819    let mut items = Vec::new();
3820    let mut current_item: Option<RawSharedStringText> = None;
3821    let mut text_target: Option<SharedStringTextTarget> = None;
3822    let mut text_value = String::new();
3823    let mut buf = Vec::new();
3824
3825    loop {
3826        match reader.read_event_into(&mut buf) {
3827            Ok(Event::Start(start)) => {
3828                let name = start.local_name().as_ref().to_vec();
3829                let parent = stack.last().map(Vec::as_slice);
3830                if name.as_slice() == b"si" {
3831                    if current_item.is_some() {
3832                        return Err(Error::XmlDeserialize(
3833                            "nested shared string item".to_string(),
3834                        ));
3835                    }
3836                    current_item = Some(RawSharedStringText::default());
3837                } else if name.as_slice() == b"t" && current_item.is_some() {
3838                    text_target = match parent {
3839                        Some(b"si") => Some(SharedStringTextTarget::Plain),
3840                        Some(b"r") => Some(SharedStringTextTarget::Run),
3841                        _ => None,
3842                    };
3843                    text_value.clear();
3844                }
3845                stack.push(name);
3846            }
3847            Ok(Event::Empty(empty)) => {
3848                let name = empty.local_name();
3849                let parent = stack.last().map(Vec::as_slice);
3850                if name.as_ref() == b"si" {
3851                    items.push(RawSharedStringText::default());
3852                } else if name.as_ref() == b"t" {
3853                    if let Some(item) = current_item.as_mut() {
3854                        match parent {
3855                            Some(b"si") => item.plain = Some(String::new()),
3856                            Some(b"r") => item.runs.push(String::new()),
3857                            _ => {}
3858                        }
3859                    }
3860                }
3861            }
3862            Ok(Event::Text(text)) => {
3863                if text_target.is_some() {
3864                    text_value.push_str(
3865                        &text
3866                            .unescape()
3867                            .map_err(|error| Error::XmlParse(error.to_string()))?,
3868                    );
3869                }
3870            }
3871            Ok(Event::CData(cdata)) => {
3872                if text_target.is_some() {
3873                    text_value.push_str(
3874                        &reader
3875                            .decoder()
3876                            .decode(cdata.as_ref())
3877                            .map_err(|error| Error::XmlParse(error.to_string()))?,
3878                    );
3879                }
3880            }
3881            Ok(Event::End(end)) => {
3882                let name = end.local_name();
3883                if name.as_ref() == b"t" {
3884                    if let (Some(item), Some(target)) = (current_item.as_mut(), text_target.take())
3885                    {
3886                        let value = std::mem::take(&mut text_value);
3887                        match target {
3888                            SharedStringTextTarget::Plain => item.plain = Some(value),
3889                            SharedStringTextTarget::Run => item.runs.push(value),
3890                        }
3891                    }
3892                } else if name.as_ref() == b"si" {
3893                    let item = current_item.take().ok_or_else(|| {
3894                        Error::XmlDeserialize("shared string end without start".to_string())
3895                    })?;
3896                    items.push(item);
3897                }
3898                stack.pop();
3899            }
3900            Ok(Event::Eof) => break,
3901            Ok(_) => {}
3902            Err(error) => return Err(Error::XmlParse(error.to_string())),
3903        }
3904        buf.clear();
3905    }
3906
3907    if current_item.is_some() || text_target.is_some() {
3908        return Err(Error::XmlDeserialize(
3909            "unterminated shared string item".to_string(),
3910        ));
3911    }
3912    Ok(items)
3913}
3914
3915/// Read a required ZIP entry as raw bytes, charging them as retained.
3916pub(crate) fn read_bytes_part<A: ArchiveAccess>(archive: &mut A, name: &str) -> Result<Vec<u8>> {
3917    read_part(
3918        archive,
3919        name,
3920        PartPresence::Required,
3921        is_xml_part(name),
3922        true,
3923    )?
3924    .ok_or_else(|| Error::Internal(format!("required part was not read: {name}")))
3925}
3926
3927/// Read an optional ZIP entry as retained raw bytes. Only a missing entry
3928/// yields `None`; read, checksum, and size failures are returned as errors.
3929fn read_optional_bytes_part<A: ArchiveAccess>(
3930    archive: &mut A,
3931    name: &str,
3932) -> Result<Option<Vec<u8>>> {
3933    read_part(
3934        archive,
3935        name,
3936        PartPresence::Optional,
3937        is_xml_part(name),
3938        true,
3939    )
3940}
3941
3942/// Read an optional ZIP entry with explicit XML and retention accounting.
3943fn read_optional_part<A: ArchiveAccess>(
3944    archive: &mut A,
3945    name: &str,
3946    xml: bool,
3947    retained: bool,
3948) -> Result<Option<Vec<u8>>> {
3949    read_part(archive, name, PartPresence::Optional, xml, retained)
3950}
3951
3952fn read_part<A: ArchiveAccess>(
3953    archive: &mut A,
3954    name: &str,
3955    presence: PartPresence,
3956    xml: bool,
3957    retained: bool,
3958) -> Result<Option<Vec<u8>>> {
3959    let mut content = Vec::new();
3960    let read_result = {
3961        let mut entry = match presence {
3962            PartPresence::Required => archive.entry(name, xml)?,
3963            PartPresence::Optional => match archive.entry_optional(name, xml)? {
3964                Some(entry) => entry,
3965                None => return Ok(None),
3966            },
3967        };
3968        let mut chunk = [0_u8; LARGE_BUF_CAPACITY];
3969        loop {
3970            let count = match entry.read(&mut chunk) {
3971                Ok(0) => break Ok(()),
3972                Ok(count) => count,
3973                Err(error) => break Err(error),
3974            };
3975            content.try_reserve(count).map_err(|_| {
3976                Error::Io(std::io::Error::new(
3977                    std::io::ErrorKind::OutOfMemory,
3978                    "unable to reserve bounded workbook part buffer",
3979                ))
3980            })?;
3981            content.extend_from_slice(&chunk[..count]);
3982        }
3983    };
3984    if let Some(error) = archive.pending_error() {
3985        return Err(error);
3986    }
3987    read_result.map_err(|error| Error::Zip(error.to_string()))?;
3988    if retained {
3989        archive.charge_retained(content.len() as u64)?;
3990    }
3991    Ok(Some(content))
3992}
3993
3994fn is_xml_part(name: &str) -> bool {
3995    name.ends_with(".xml") || name.ends_with(".rels") || name.ends_with(".vml")
3996}
3997
3998/// Serialize a worksheet with optional sparklines and legacy drawing injected
3999/// via string manipulation, avoiding a full WorksheetXml clone.
4000pub(crate) fn serialize_worksheet_with_extras(
4001    ws: &WorksheetXml,
4002    sparklines: &[crate::sparkline::SparklineConfig],
4003    legacy_drawing_rid: Option<&str>,
4004) -> Result<String> {
4005    let body = quick_xml::se::to_string(ws).map_err(|e| Error::XmlParse(e.to_string()))?;
4006
4007    let closing = "</worksheet>";
4008    let ext_xml = if sparklines.is_empty() {
4009        String::new()
4010    } else {
4011        build_sparkline_ext_xml(sparklines)
4012    };
4013    let legacy_xml = if let Some(rid) = legacy_drawing_rid {
4014        format!("<legacyDrawing r:id=\"{rid}\"/>")
4015    } else {
4016        String::new()
4017    };
4018
4019    if let Some(pos) = body.rfind(closing) {
4020        // If injecting a legacy drawing, strip any existing one from the serde output
4021        // to avoid duplicates (the original ws.legacy_drawing may already be set).
4022        let body_prefix = &body[..pos];
4023        let stripped;
4024        let prefix = if !legacy_xml.is_empty() {
4025            if let Some(ld_start) = body_prefix.find("<legacyDrawing ") {
4026                // Find the end of the self-closing element.
4027                let ld_end = body_prefix[ld_start..]
4028                    .find("/>")
4029                    .map(|e| ld_start + e + 2)
4030                    .unwrap_or(ld_start);
4031                stripped = format!("{}{}", &body_prefix[..ld_start], &body_prefix[ld_end..]);
4032                stripped.as_str()
4033            } else {
4034                body_prefix
4035            }
4036        } else {
4037            body_prefix
4038        };
4039
4040        let extra_len = ext_xml.len() + legacy_xml.len();
4041        let mut result = String::with_capacity(XML_DECLARATION.len() + 1 + body.len() + extra_len);
4042        result.push_str(XML_DECLARATION);
4043        result.push('\n');
4044        // Clean owners bypass this helper through raw passthrough. Dirty
4045        // owners are rebuilt in worksheet schema order without raw merging.
4046        if !legacy_xml.is_empty() {
4047            if let Some(table_parts_start) = prefix.find("<tableParts") {
4048                result.push_str(&prefix[..table_parts_start]);
4049                result.push_str(&legacy_xml);
4050                result.push_str(&prefix[table_parts_start..]);
4051            } else {
4052                result.push_str(prefix);
4053                result.push_str(&legacy_xml);
4054            }
4055        } else {
4056            result.push_str(prefix);
4057        }
4058        result.push_str(&ext_xml);
4059        result.push_str(closing);
4060        Ok(result)
4061    } else {
4062        Ok(format!("{XML_DECLARATION}\n{body}"))
4063    }
4064}
4065
4066fn serialize_worksheet_with_slicer_extras(
4067    ws: &WorksheetXml,
4068    sparklines: &[crate::sparkline::SparklineConfig],
4069    legacy_drawing_rid: Option<&str>,
4070    raw_sheet: Option<&[u8]>,
4071    slicer_rids: &[(&str, Option<bool>)],
4072    controls: &[(usize, String, String)],
4073    controls_dirty: bool,
4074) -> Result<String> {
4075    let mut xml = serialize_worksheet_with_extras(ws, sparklines, legacy_drawing_rid)?;
4076    if controls_dirty {
4077        xml = replace_worksheet_controls(xml, controls)?;
4078    }
4079    if slicer_rids.is_empty() {
4080        // Sparkline groups carry a broad set of optional style, color, and
4081        // axis children which the public configuration does not model. When
4082        // a structural edit has patched the retained worksheet XML, prefer
4083        // that original extension list over rebuilding a reduced group.
4084        if let Some(raw_xml) = raw_sheet.and_then(|bytes| std::str::from_utf8(bytes).ok()) {
4085            let raw_sparklines = parse_sparklines_from_xml(raw_xml);
4086            if raw_sparklines.as_slice() == sparklines {
4087                if let Some(raw_ext) = ext_list_contents(raw_xml)
4088                    .filter(|contents| contents.contains("sparklineGroups"))
4089                {
4090                    xml = remove_extension_list(xml);
4091                    let closing = "</worksheet>";
4092                    let position = xml.rfind(closing).ok_or_else(|| {
4093                        Error::XmlParse("worksheet closing tag missing".to_string())
4094                    })?;
4095                    xml.insert_str(position, &format!("<extLst>{raw_ext}</extLst>"));
4096                }
4097            }
4098        }
4099        return Ok(xml);
4100    }
4101    let generated_entries = ext_list_contents(&xml).unwrap_or_default();
4102    xml = remove_extension_list(xml);
4103    let raw_ext = raw_sheet
4104        .and_then(|bytes| std::str::from_utf8(bytes).ok())
4105        .and_then(ext_list_contents);
4106    let (table_rids, pivot_rids) =
4107        partition_slicer_rids(slicer_rids, raw_ext.as_deref(), TABLE_SLICER_LIST_EXT_URI);
4108    let raw_entries = raw_ext
4109        .map(|contents| {
4110            let contents = remove_known_slicer_extensions(contents, PIVOT_SLICER_LIST_EXT_URI);
4111            let contents = remove_known_slicer_extensions(contents, TABLE_SLICER_LIST_EXT_URI);
4112            remove_known_slicer_extensions(contents, "05C60535-1F16-4fd2-B633-F4F36F0B64E0")
4113        })
4114        .unwrap_or_default();
4115    let entries = format!("{raw_entries}{generated_entries}");
4116    let slicer_list = |rids: &[&str]| {
4117        let slicers = rids
4118            .iter()
4119            .map(|rid| {
4120                format!(
4121                    "<x14:slicer r:id=\"{}\" xmlns:r=\"{}\"/>",
4122                    rid,
4123                    sheetkit_xml::namespaces::RELATIONSHIPS,
4124                )
4125            })
4126            .collect::<String>();
4127        format!(
4128            "<x14:slicerList xmlns:x14=\"{}\">{slicers}</x14:slicerList>",
4129            sheetkit_xml::namespaces::SLICER_2009
4130        )
4131    };
4132    let mut slicer_entries = String::new();
4133    if !pivot_rids.is_empty() {
4134        slicer_entries.push_str(&format!(
4135            "<ext uri=\"{{{PIVOT_SLICER_LIST_EXT_URI}}}\">{}</ext>",
4136            slicer_list(&pivot_rids)
4137        ));
4138    }
4139    if !table_rids.is_empty() {
4140        slicer_entries.push_str(&format!(
4141            "<ext uri=\"{{{TABLE_SLICER_LIST_EXT_URI}}}\" xmlns:x15=\"{}\">{}</ext>",
4142            sheetkit_xml::namespaces::SLICER_2010,
4143            slicer_list(&table_rids)
4144        ));
4145    }
4146    let extension = format!("<extLst>{entries}{slicer_entries}</extLst>");
4147    let closing = "</worksheet>";
4148    let position = xml
4149        .rfind(closing)
4150        .ok_or_else(|| Error::XmlParse("worksheet closing tag missing".to_string()))?;
4151    xml.insert_str(position, &extension);
4152    Ok(xml)
4153}
4154
4155fn replace_worksheet_controls(
4156    mut xml: String,
4157    controls: &[(usize, String, String)],
4158) -> Result<String> {
4159    if let Some(start) = xml.find("<controls") {
4160        let end = xml[start..]
4161            .find("</controls>")
4162            .map(|offset| start + offset + "</controls>".len())
4163            .ok_or_else(|| Error::XmlParse("worksheet controls closing tag missing".to_string()))?;
4164        xml.replace_range(start..end, "");
4165    }
4166    if controls.is_empty() {
4167        return Ok(xml);
4168    }
4169
4170    let entries = controls
4171        .iter()
4172        .map(|(shape_id, rid, name)| {
4173            format!(
4174                "<control shapeId=\"{shape_id}\" r:id=\"{}\" name=\"{}\"/>",
4175                quick_xml::escape::escape(rid),
4176                quick_xml::escape::escape(name),
4177            )
4178        })
4179        .collect::<String>();
4180    let controls_xml = format!("<controls>{entries}</controls>");
4181    let position = xml
4182        .find("<tableParts")
4183        .or_else(|| xml.find("<extLst"))
4184        .or_else(|| xml.rfind("</worksheet>"))
4185        .ok_or_else(|| Error::XmlParse("worksheet closing tag missing".to_string()))?;
4186    xml.insert_str(position, &controls_xml);
4187    Ok(xml)
4188}
4189
4190fn parse_worksheet_control_entries(xml: &str) -> Vec<(usize, String, String)> {
4191    let mut entries = Vec::new();
4192    let mut search_from = 0;
4193    while let Some(relative_start) = xml[search_from..].find("<control ") {
4194        let start = search_from + relative_start;
4195        let Some(relative_end) = xml[start..].find("/>") else {
4196            break;
4197        };
4198        let end = start + relative_end + 2;
4199        let element = &xml[start..end];
4200        let attribute = |name: &str| {
4201            let marker = format!("{name}=\"");
4202            let value_start = element.find(&marker)? + marker.len();
4203            let value_end = element[value_start..].find('"')? + value_start;
4204            Some(element[value_start..value_end].to_string())
4205        };
4206        if let (Some(shape_id), Some(rid), Some(name)) =
4207            (attribute("shapeId"), attribute("r:id"), attribute("name"))
4208        {
4209            if let Ok(shape_id) = shape_id.parse() {
4210                entries.push((shape_id, rid, name));
4211            }
4212        }
4213        search_from = end;
4214    }
4215    entries
4216}
4217
4218fn parse_worksheet_control_entries_reader<R: std::io::BufRead>(
4219    reader: R,
4220) -> Result<Vec<(usize, String, String)>> {
4221    let mut reader = quick_xml::Reader::from_reader(reader);
4222    let mut buffer = Vec::with_capacity(4096);
4223    let mut entries = Vec::new();
4224    loop {
4225        buffer.clear();
4226        let event = reader
4227            .read_event_into(&mut buffer)
4228            .map_err(|error| Error::XmlParse(error.to_string()))?;
4229        match event {
4230            quick_xml::events::Event::Start(element) | quick_xml::events::Event::Empty(element)
4231                if element.local_name().as_ref() == b"control" =>
4232            {
4233                let mut shape_id = None;
4234                let mut relationship_id = None;
4235                let mut name = None;
4236                for attribute in element.attributes() {
4237                    let attribute =
4238                        attribute.map_err(|error| Error::XmlParse(error.to_string()))?;
4239                    let value = attribute
4240                        .decode_and_unescape_value(reader.decoder())
4241                        .map_err(|error| Error::XmlParse(error.to_string()))?
4242                        .into_owned();
4243                    match attribute.key.local_name().as_ref() {
4244                        b"shapeId" => shape_id = value.parse::<usize>().ok(),
4245                        b"id" => relationship_id = Some(value),
4246                        b"name" => name = Some(value),
4247                        _ => {}
4248                    }
4249                }
4250                if let (Some(shape_id), Some(relationship_id), Some(name)) =
4251                    (shape_id, relationship_id, name)
4252                {
4253                    entries.push((shape_id, relationship_id, name));
4254                }
4255            }
4256            quick_xml::events::Event::Eof => break,
4257            _ => {}
4258        }
4259    }
4260    Ok(entries)
4261}
4262
4263fn next_control_property_path(existing: &HashSet<String>) -> String {
4264    let mut number = 1usize;
4265    loop {
4266        let candidate = format!("xl/ctrlProps/ctrlProp{number}.xml");
4267        if !existing.contains(&candidate) {
4268            return candidate;
4269        }
4270        number += 1;
4271    }
4272}
4273
4274fn next_numbered_package_path(existing: &HashSet<String>, prefix: &str, suffix: &str) -> String {
4275    let mut number = 1usize;
4276    loop {
4277        let candidate = format!("{prefix}{number}{suffix}");
4278        if !existing.contains(&candidate) {
4279            return candidate;
4280        }
4281        number += 1;
4282    }
4283}
4284
4285fn serialize_workbook_with_slicer_extensions(
4286    workbook: &WorkbookXml,
4287    raw_workbook: Option<&[u8]>,
4288    slicer_cache_rids: &[(&str, Option<bool>)],
4289) -> Result<String> {
4290    let mut body =
4291        quick_xml::se::to_string(workbook).map_err(|error| Error::XmlParse(error.to_string()))?;
4292    let raw_ext = raw_workbook
4293        .and_then(|bytes| std::str::from_utf8(bytes).ok())
4294        .and_then(ext_list_contents);
4295    let (table_rids, pivot_rids) = partition_slicer_rids(
4296        slicer_cache_rids,
4297        raw_ext.as_deref(),
4298        TABLE_SLICER_CACHES_EXT_URI,
4299    );
4300    let entries = raw_ext
4301        .map(|contents| {
4302            let contents = remove_known_slicer_extensions(contents, PIVOT_SLICER_CACHES_EXT_URI);
4303            remove_known_slicer_extensions(contents, TABLE_SLICER_CACHES_EXT_URI)
4304        })
4305        .unwrap_or_default();
4306    let caches = |rids: &[&str]| {
4307        rids.iter()
4308            .map(|rid| {
4309                format!(
4310                    "<x14:slicerCache r:id=\"{}\" xmlns:r=\"{}\"/>",
4311                    rid,
4312                    sheetkit_xml::namespaces::RELATIONSHIPS,
4313                )
4314            })
4315            .collect::<String>()
4316    };
4317    let x14 = sheetkit_xml::namespaces::SLICER_2009;
4318    let x15 = sheetkit_xml::namespaces::SLICER_2010;
4319    let mut slicer_entries = String::new();
4320    if !pivot_rids.is_empty() {
4321        slicer_entries.push_str(&format!(
4322            "<ext uri=\"{{{PIVOT_SLICER_CACHES_EXT_URI}}}\"><x14:slicerCaches xmlns:x14=\"{x14}\">{}</x14:slicerCaches></ext>",
4323            caches(&pivot_rids)
4324        ));
4325    }
4326    if !table_rids.is_empty() {
4327        slicer_entries.push_str(&format!(
4328            "<ext uri=\"{{{TABLE_SLICER_CACHES_EXT_URI}}}\" xmlns:x15=\"{x15}\"><x15:slicerCaches xmlns:x14=\"{x14}\">{}</x15:slicerCaches></ext>",
4329            caches(&table_rids)
4330        ));
4331    }
4332    let closing = "</workbook>";
4333    let position = body
4334        .rfind(closing)
4335        .ok_or_else(|| Error::XmlParse("workbook closing tag missing".to_string()))?;
4336    body.insert_str(
4337        position,
4338        &format!("<extLst>{entries}{slicer_entries}</extLst>"),
4339    );
4340    Ok(format!("{XML_DECLARATION}\n{body}"))
4341}
4342
4343/// Workbook extension listing pivot-table slicer caches (`x14:slicerCaches`).
4344const PIVOT_SLICER_CACHES_EXT_URI: &str = "BBE1A952-AA13-448E-AADC-164F8A28A991";
4345/// Workbook extension listing table slicer caches (`x15:slicerCaches`).
4346const TABLE_SLICER_CACHES_EXT_URI: &str = "46BE6895-7355-4a93-B00E-2C351335B9C9";
4347/// Worksheet extension listing pivot-table slicer parts.
4348const PIVOT_SLICER_LIST_EXT_URI: &str = "A8765BA9-456A-4DAB-B4F3-ACF838C121DE";
4349/// Worksheet extension listing table slicer parts.
4350const TABLE_SLICER_LIST_EXT_URI: &str = "3A4CF648-6AED-40f4-86FF-DC5316D8AED3";
4351
4352/// Split slicer relationship IDs into (table-backed, pivot-backed) lists.
4353///
4354/// Entries with unknown backing keep the extension the source file listed
4355/// them under (`table_uri` in `raw_ext`) and default to pivot-backed.
4356fn partition_slicer_rids<'a>(
4357    rids: &[(&'a str, Option<bool>)],
4358    raw_ext: Option<&str>,
4359    table_uri: &str,
4360) -> (Vec<&'a str>, Vec<&'a str>) {
4361    let raw_table_block = raw_ext.and_then(|contents| {
4362        let lower = contents.to_ascii_lowercase();
4363        let offset = lower.find(&table_uri.to_ascii_lowercase())?;
4364        let end = contents[offset..].find("</ext>")? + offset;
4365        Some(contents[offset..end].to_string())
4366    });
4367    let mut table = Vec::new();
4368    let mut pivot = Vec::new();
4369    for (rid, backing) in rids {
4370        let is_table = backing.unwrap_or_else(|| {
4371            raw_table_block
4372                .as_deref()
4373                .is_some_and(|block| block.contains(&format!("id=\"{rid}\"")))
4374        });
4375        if is_table {
4376            table.push(*rid);
4377        } else {
4378            pivot.push(*rid);
4379        }
4380    }
4381    (table, pivot)
4382}
4383
4384/// Index of slicer cache parts and names that are backed by a table.
4385struct TableSlicerIndex {
4386    cache_paths: HashMap<String, bool>,
4387    table_cache_names: HashSet<String>,
4388    parsed_cache_names: HashSet<String>,
4389    slicer_parts: HashMap<String, Vec<String>>,
4390}
4391
4392impl TableSlicerIndex {
4393    /// `Some(true)` for a table-backed cache part, `Some(false)` for a
4394    /// pivot-backed one, `None` when the part was not parsed.
4395    fn cache_is_table(&self, path: &str) -> Option<bool> {
4396        self.cache_paths.get(path).copied()
4397    }
4398
4399    /// Whether any slicer in the part references a table-backed cache, or
4400    /// `None` when the part was not parsed.
4401    fn slicer_part_is_table(&self, path: &str) -> Option<bool> {
4402        let caches = self.slicer_parts.get(path)?;
4403        if caches
4404            .iter()
4405            .any(|cache| self.table_cache_names.contains(cache))
4406        {
4407            return Some(true);
4408        }
4409        // Only classify as pivot-backed when every referenced cache was
4410        // actually parsed; an unparsable cache keeps the source listing.
4411        caches
4412            .iter()
4413            .all(|cache| self.parsed_cache_names.contains(cache))
4414            .then_some(false)
4415    }
4416}
4417
4418impl Workbook {
4419    /// Build the table/pivot classification of every parsed or deferred
4420    /// slicer and slicer cache part.
4421    fn table_slicer_index(&self) -> TableSlicerIndex {
4422        use crate::workbook::aux::AuxCategory;
4423
4424        let mut index = TableSlicerIndex {
4425            cache_paths: HashMap::new(),
4426            table_cache_names: HashSet::new(),
4427            parsed_cache_names: HashSet::new(),
4428            slicer_parts: HashMap::new(),
4429        };
4430        let mut add_cache = |path: &str, cache: &sheetkit_xml::slicer::SlicerCacheDefinition| {
4431            let is_table = cache.table_slicer_cache.is_some();
4432            index.cache_paths.insert(path.to_string(), is_table);
4433            index.parsed_cache_names.insert(cache.name.clone());
4434            if is_table {
4435                index.table_cache_names.insert(cache.name.clone());
4436            }
4437        };
4438        for (path, cache) in &self.slicer_caches {
4439            add_cache(path, cache);
4440        }
4441        for (path, bytes) in self
4442            .deferred_parts
4443            .entries(AuxCategory::SlicerCaches)
4444            .unwrap_or_default()
4445        {
4446            if let Some(cache) = std::str::from_utf8(bytes)
4447                .ok()
4448                .and_then(sheetkit_xml::slicer::parse_slicer_cache)
4449            {
4450                add_cache(path, &cache);
4451            }
4452        }
4453        for (path, defs) in &self.slicer_defs {
4454            index.slicer_parts.insert(
4455                path.clone(),
4456                defs.slicers.iter().map(|s| s.cache.clone()).collect(),
4457            );
4458        }
4459        for (path, bytes) in self
4460            .deferred_parts
4461            .entries(AuxCategory::Slicers)
4462            .unwrap_or_default()
4463        {
4464            if let Some(defs) = std::str::from_utf8(bytes).ok().and_then(|xml| {
4465                quick_xml::de::from_str::<sheetkit_xml::slicer::SlicerDefinitions>(xml).ok()
4466            }) {
4467                index.slicer_parts.insert(
4468                    path.clone(),
4469                    defs.slicers.into_iter().map(|s| s.cache).collect(),
4470                );
4471            }
4472        }
4473        index
4474    }
4475}
4476
4477fn ext_list_contents(xml: &str) -> Option<String> {
4478    let start = xml.find("<extLst")?;
4479    let content_start = xml[start..].find('>')? + start + 1;
4480    let end = xml[content_start..].find("</extLst>")? + content_start;
4481    Some(xml[content_start..end].to_string())
4482}
4483
4484fn remove_extension_list(mut xml: String) -> String {
4485    if let Some(start) = xml.find("<extLst") {
4486        if let Some(end) = xml[start..].find("</extLst>") {
4487            xml.replace_range(start..start + end + "</extLst>".len(), "");
4488        }
4489    }
4490    xml
4491}
4492
4493fn remove_known_slicer_extensions(mut contents: String, uri: &str) -> String {
4494    while let Some(offset) = contents
4495        .to_ascii_lowercase()
4496        .find(&uri.to_ascii_lowercase())
4497    {
4498        let start = contents[..offset].rfind("<ext").unwrap_or(offset);
4499        let Some(end) = contents[offset..].find("</ext>") else {
4500            break;
4501        };
4502        contents.replace_range(start..offset + end + "</ext>".len(), "");
4503    }
4504    contents
4505}
4506
4507/// Build the extLst XML block for sparklines using manual string construction.
4508pub(crate) fn build_sparkline_ext_xml(sparklines: &[crate::sparkline::SparklineConfig]) -> String {
4509    use std::fmt::Write;
4510    let mut xml = String::new();
4511    let _ = write!(
4512        xml,
4513        "<extLst>\
4514         <ext xmlns:x14=\"http://schemas.microsoft.com/office/spreadsheetml/2009/9/main\" \
4515         uri=\"{{05C60535-1F16-4fd2-B633-F4F36F0B64E0}}\">\
4516         <x14:sparklineGroups \
4517         xmlns:xm=\"http://schemas.microsoft.com/office/excel/2006/main\">"
4518    );
4519    for config in sparklines {
4520        let group = crate::sparkline::config_to_xml_group(config);
4521        let _ = write!(xml, "<x14:sparklineGroup");
4522        if let Some(ref t) = group.sparkline_type {
4523            let _ = write!(xml, " type=\"{t}\"");
4524        }
4525        if group.markers == Some(true) {
4526            let _ = write!(xml, " markers=\"1\"");
4527        }
4528        if group.high == Some(true) {
4529            let _ = write!(xml, " high=\"1\"");
4530        }
4531        if group.low == Some(true) {
4532            let _ = write!(xml, " low=\"1\"");
4533        }
4534        if group.first == Some(true) {
4535            let _ = write!(xml, " first=\"1\"");
4536        }
4537        if group.last == Some(true) {
4538            let _ = write!(xml, " last=\"1\"");
4539        }
4540        if group.negative == Some(true) {
4541            let _ = write!(xml, " negative=\"1\"");
4542        }
4543        if group.display_x_axis == Some(true) {
4544            let _ = write!(xml, " displayXAxis=\"1\"");
4545        }
4546        if let Some(w) = group.line_weight {
4547            let _ = write!(xml, " lineWeight=\"{w}\"");
4548        }
4549        let _ = write!(xml, "><x14:sparklines>");
4550        for sp in &group.sparklines.items {
4551            let _ = write!(
4552                xml,
4553                "<x14:sparkline><xm:f>{}</xm:f><xm:sqref>{}</xm:sqref></x14:sparkline>",
4554                quick_xml::escape::escape(&sp.formula),
4555                quick_xml::escape::escape(&sp.sqref)
4556            );
4557        }
4558        let _ = write!(xml, "</x14:sparklines></x14:sparklineGroup>");
4559    }
4560    let _ = write!(xml, "</x14:sparklineGroups></ext></extLst>");
4561    xml
4562}
4563
4564/// Parse sparkline configurations from raw worksheet XML content.
4565pub(crate) fn parse_sparklines_from_xml(xml: &str) -> Vec<crate::sparkline::SparklineConfig> {
4566    use crate::sparkline::{SparklineConfig, SparklineType};
4567
4568    let mut sparklines = Vec::new();
4569
4570    // Find all sparklineGroup elements and parse their attributes and children.
4571    let mut search_from = 0;
4572    while let Some(group_start) = xml[search_from..].find("<x14:sparklineGroup") {
4573        let abs_start = search_from + group_start;
4574        let group_end_tag = "</x14:sparklineGroup>";
4575        let abs_end = match xml[abs_start..].find(group_end_tag) {
4576            Some(pos) => abs_start + pos + group_end_tag.len(),
4577            None => break,
4578        };
4579        let group_xml = &xml[abs_start..abs_end];
4580
4581        // Parse group-level attributes.
4582        let sparkline_type = extract_xml_attr(group_xml, "type")
4583            .and_then(|s| SparklineType::parse(&s))
4584            .unwrap_or_default();
4585        let markers = extract_xml_bool_attr(group_xml, "markers");
4586        let high_point = extract_xml_bool_attr(group_xml, "high");
4587        let low_point = extract_xml_bool_attr(group_xml, "low");
4588        let first_point = extract_xml_bool_attr(group_xml, "first");
4589        let last_point = extract_xml_bool_attr(group_xml, "last");
4590        let negative_points = extract_xml_bool_attr(group_xml, "negative");
4591        let show_axis = extract_xml_bool_attr(group_xml, "displayXAxis");
4592        let line_weight =
4593            extract_xml_attr(group_xml, "lineWeight").and_then(|s| s.parse::<f64>().ok());
4594
4595        // Parse individual sparkline entries within this group.
4596        let mut sp_from = 0;
4597        while let Some(sp_start) = group_xml[sp_from..].find("<x14:sparkline>") {
4598            let sp_abs = sp_from + sp_start;
4599            let sp_end_tag = "</x14:sparkline>";
4600            let sp_abs_end = match group_xml[sp_abs..].find(sp_end_tag) {
4601                Some(pos) => sp_abs + pos + sp_end_tag.len(),
4602                None => break,
4603            };
4604            let sp_xml = &group_xml[sp_abs..sp_abs_end];
4605
4606            let formula = extract_xml_element(sp_xml, "xm:f").unwrap_or_default();
4607            let sqref = extract_xml_element(sp_xml, "xm:sqref").unwrap_or_default();
4608
4609            if !formula.is_empty() && !sqref.is_empty() {
4610                sparklines.push(SparklineConfig {
4611                    data_range: formula,
4612                    location: sqref,
4613                    sparkline_type: sparkline_type.clone(),
4614                    markers,
4615                    high_point,
4616                    low_point,
4617                    first_point,
4618                    last_point,
4619                    negative_points,
4620                    show_axis,
4621                    line_weight,
4622                    style: None,
4623                });
4624            }
4625            sp_from = sp_abs_end;
4626        }
4627        search_from = abs_end;
4628    }
4629    sparklines
4630}
4631
4632/// Extract an XML attribute value from an element's opening tag.
4633///
4634/// Uses manual search to avoid allocating format strings for patterns.
4635pub(crate) fn extract_xml_attr(xml: &str, attr: &str) -> Option<String> {
4636    // Search for ` attr="` or ` attr='` without allocating pattern strings.
4637    for quote in ['"', '\''] {
4638        // Build the search target: " attr=" (space + attr name + = + quote)
4639        let haystack = xml.as_bytes();
4640        let attr_bytes = attr.as_bytes();
4641        let mut pos = 0;
4642        while pos + 1 + attr_bytes.len() + 2 <= haystack.len() {
4643            if haystack[pos] == b' '
4644                && haystack[pos + 1..pos + 1 + attr_bytes.len()] == *attr_bytes
4645                && haystack[pos + 1 + attr_bytes.len()] == b'='
4646                && haystack[pos + 1 + attr_bytes.len() + 1] == quote as u8
4647            {
4648                let val_start = pos + 1 + attr_bytes.len() + 2;
4649                if let Some(end) = xml[val_start..].find(quote) {
4650                    return Some(xml[val_start..val_start + end].to_string());
4651                }
4652            }
4653            pos += 1;
4654        }
4655    }
4656    None
4657}
4658
4659/// Extract a boolean attribute from an XML element (true for "1" or "true").
4660pub(crate) fn extract_xml_bool_attr(xml: &str, attr: &str) -> bool {
4661    extract_xml_attr(xml, attr)
4662        .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
4663        .unwrap_or(false)
4664}
4665
4666/// Extract the text content of an XML element like `<tag>content</tag>`.
4667pub(crate) fn extract_xml_element(xml: &str, tag: &str) -> Option<String> {
4668    let open = format!("<{tag}>");
4669    let close = format!("</{tag}>");
4670    let start = xml.find(&open)?;
4671    let content_start = start + open.len();
4672    let end = xml[content_start..].find(&close)?;
4673    let value = &xml[content_start..content_start + end];
4674    quick_xml::escape::unescape(value)
4675        .map(|value| value.into_owned())
4676        .ok()
4677}
4678
4679/// Serialize a value to XML and write it as a ZIP entry.
4680pub(crate) fn write_xml_part<T: Serialize, W: std::io::Write + std::io::Seek>(
4681    zip: &mut zip::ZipWriter<W>,
4682    name: &str,
4683    value: &T,
4684    options: SimpleFileOptions,
4685    limit: u64,
4686) -> Result<()> {
4687    use std::fmt::Write as _;
4688
4689    struct XmlPartWriter<'a, W: std::io::Write + std::io::Seek> {
4690        zip: &'a mut zip::ZipWriter<W>,
4691        limit: u64,
4692        written: u64,
4693        error: Option<Error>,
4694    }
4695
4696    impl<W: std::io::Write + std::io::Seek> std::fmt::Write for XmlPartWriter<'_, W> {
4697        fn write_str(&mut self, value: &str) -> std::fmt::Result {
4698            if self.error.is_some() {
4699                return Err(std::fmt::Error);
4700            }
4701            let amount = u64::try_from(value.len()).unwrap_or(u64::MAX);
4702            let observed = self.written.saturating_add(amount);
4703            if observed > self.limit {
4704                self.error = Some(crate::save::resource_limit(
4705                    crate::resource::ResourceOperation::WorkbookSave,
4706                    crate::resource::ResourceCategory::Output,
4707                    crate::resource::ResourceDimension::XmlBytes,
4708                    self.limit,
4709                    observed,
4710                    crate::resource::ResourceStage::Serialize,
4711                ));
4712                return Err(std::fmt::Error);
4713            }
4714            if let Err(error) = self.zip.write_all(value.as_bytes()) {
4715                self.error = Some(Error::Io(error));
4716                return Err(std::fmt::Error);
4717            }
4718            self.written = observed;
4719            Ok(())
4720        }
4721    }
4722
4723    zip.start_file(name, options)
4724        .map_err(|error| Error::Zip(error.to_string()))?;
4725    let mut output = XmlPartWriter {
4726        zip,
4727        limit,
4728        written: 0,
4729        error: None,
4730    };
4731    let declaration = writeln!(output, "{XML_DECLARATION}");
4732    if let Some(error) = output.error.take() {
4733        return Err(error);
4734    }
4735    declaration.map_err(|_| Error::Internal("XML declaration serialization failed".to_string()))?;
4736    let result = value.serialize(quick_xml::se::Serializer::new(&mut output));
4737    if let Some(error) = output.error {
4738        return Err(error);
4739    }
4740    result.map_err(|error| Error::XmlParse(error.to_string()))
4741}
4742
4743fn write_bytes_part<W: std::io::Write + std::io::Seek>(
4744    zip: &mut zip::ZipWriter<W>,
4745    name: &str,
4746    bytes: &[u8],
4747    options: SimpleFileOptions,
4748    limit: u64,
4749) -> Result<()> {
4750    reject_save_metric(
4751        crate::resource::ResourceDimension::XmlBytes,
4752        u64::try_from(bytes.len()).unwrap_or(u64::MAX),
4753        limit,
4754    )?;
4755    zip.start_file(name, options)
4756        .map_err(|e| Error::Zip(e.to_string()))?;
4757    zip.write_all(bytes)?;
4758    Ok(())
4759}
4760
4761fn write_package_bytes_part<W: std::io::Write + std::io::Seek>(
4762    zip: &mut zip::ZipWriter<W>,
4763    name: &str,
4764    bytes: &[u8],
4765    options: SimpleFileOptions,
4766    xml_limit: u64,
4767) -> Result<()> {
4768    let extension = name.rsplit_once('.').map(|(_, extension)| extension);
4769    if extension.is_some_and(|extension| {
4770        extension.eq_ignore_ascii_case("xml")
4771            || extension.eq_ignore_ascii_case("rels")
4772            || extension.eq_ignore_ascii_case("vml")
4773    }) {
4774        return write_bytes_part(zip, name, bytes, options, xml_limit);
4775    }
4776    zip.start_file(name, options)
4777        .map_err(|error| Error::Zip(error.to_string()))?;
4778    zip.write_all(bytes)?;
4779    Ok(())
4780}
4781
4782#[cfg(test)]
4783#[allow(clippy::unnecessary_map_or)]
4784mod tests {
4785    use super::*;
4786    use tempfile::TempDir;
4787
4788    #[test]
4789    fn known_slicer_extensions_are_removed_case_insensitively() {
4790        let contents = concat!(
4791            "<ext uri=\"{bbe1a952-aa13-448e-aadc-164f8a28a991}\">",
4792            "<x14:slicerCaches/>",
4793            "</ext>",
4794            "<ext uri=\"{opaque}\"><opaque:payload/></ext>"
4795        );
4796
4797        let remaining = remove_known_slicer_extensions(
4798            contents.to_string(),
4799            "BBE1A952-AA13-448E-AADC-164F8A28A991",
4800        );
4801
4802        assert!(!remaining.contains("slicerCaches"));
4803        assert!(remaining.contains("{opaque}"));
4804    }
4805
4806    #[test]
4807    fn adding_a_slicer_merges_existing_workbook_and_sheet_extensions() {
4808        let mut workbook = Workbook::new();
4809        workbook
4810            .add_table(
4811                "Sheet1",
4812                &crate::table::TableConfig {
4813                    name: "Table1".to_string(),
4814                    display_name: "Table1".to_string(),
4815                    range: "A1:B3".to_string(),
4816                    columns: vec![
4817                        crate::table::TableColumn {
4818                            name: "Status".to_string(),
4819                            totals_row_function: None,
4820                            totals_row_label: None,
4821                        },
4822                        crate::table::TableColumn {
4823                            name: "Value".to_string(),
4824                            totals_row_function: None,
4825                            totals_row_label: None,
4826                        },
4827                    ],
4828                    ..crate::table::TableConfig::default()
4829                },
4830            )
4831            .unwrap();
4832        let base = workbook.save_to_buffer().unwrap();
4833        let workbook_xml = String::from_utf8(zip_part(&base, "xl/workbook.xml"))
4834            .unwrap()
4835            .replacen(
4836                "</workbook>",
4837                concat!(
4838                    "<extLst>",
4839                    "<ext uri=\"{opaque-workbook}\">",
4840                    "<opaque:payload xmlns:opaque=\"urn:sheetkit:workbook\"/>",
4841                    "</ext>",
4842                    "<ext uri=\"{bbe1a952-aa13-448e-aadc-164f8a28a991}\">",
4843                    "<x14:slicerCaches xmlns:x14=\"",
4844                    "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main",
4845                    "\"/>",
4846                    "</ext>",
4847                    "</extLst></workbook>"
4848                ),
4849                1,
4850            );
4851        let sheet_xml = String::from_utf8(zip_part(&base, "xl/worksheets/sheet1.xml"))
4852            .unwrap()
4853            .replacen(
4854                "</worksheet>",
4855                concat!(
4856                    "<extLst>",
4857                    "<ext uri=\"{opaque-sheet}\">",
4858                    "<opaque:payload xmlns:opaque=\"urn:sheetkit:sheet\"/>",
4859                    "</ext>",
4860                    "<ext uri=\"{a8765ba9-456a-4dab-b4f3-acf838c121de}\">",
4861                    "<x14:slicerList xmlns:x14=\"",
4862                    "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main",
4863                    "\"/>",
4864                    "</ext>",
4865                    "</extLst></worksheet>"
4866                ),
4867                1,
4868            );
4869        let input = rewrite_zip_parts(
4870            &base,
4871            &[
4872                ("xl/workbook.xml", Some(workbook_xml.into_bytes())),
4873                ("xl/worksheets/sheet1.xml", Some(sheet_xml.into_bytes())),
4874            ],
4875        );
4876        let options = OpenOptions::new()
4877            .read_mode(ReadMode::Eager)
4878            .aux_parts(AuxParts::EagerLoad);
4879        let mut opened = Workbook::open_from_buffer_with_options(&input, &options).unwrap();
4880
4881        opened
4882            .add_slicer(
4883                "Sheet1",
4884                &crate::slicer::SlicerConfig {
4885                    name: "StatusFilter".to_string(),
4886                    cell: "D1".to_string(),
4887                    table_name: "Table1".to_string(),
4888                    column_name: "Status".to_string(),
4889                    caption: None,
4890                    style: None,
4891                    width: None,
4892                    height: None,
4893                    show_caption: None,
4894                    column_count: None,
4895                },
4896            )
4897            .unwrap();
4898        let saved = opened.save_to_buffer().unwrap();
4899        let saved_workbook = String::from_utf8(zip_part(&saved, "xl/workbook.xml")).unwrap();
4900        let saved_sheet = String::from_utf8(zip_part(&saved, "xl/worksheets/sheet1.xml")).unwrap();
4901
4902        assert!(saved_workbook.contains("urn:sheetkit:workbook"));
4903        assert!(saved_sheet.contains("urn:sheetkit:sheet"));
4904        assert_eq!(saved_workbook.matches("<extLst>").count(), 1);
4905        assert_eq!(saved_sheet.matches("<extLst>").count(), 1);
4906        // Table-backed caches belong in the x15 extension; the stale pivot
4907        // extension from the source is replaced, not duplicated.
4908        assert_eq!(saved_workbook.matches("<x14:slicerCaches").count(), 0);
4909        assert_eq!(saved_workbook.matches("<x15:slicerCaches").count(), 1);
4910        assert_eq!(saved_sheet.matches("<x14:slicerList").count(), 1);
4911        assert!(saved_sheet.contains("3A4CF648-6AED-40f4-86FF-DC5316D8AED3"));
4912        assert!(!saved_sheet
4913            .to_ascii_lowercase()
4914            .contains("a8765ba9-456a-4dab-b4f3-acf838c121de"));
4915    }
4916
4917    fn zip_part(buffer: &[u8], name: &str) -> Vec<u8> {
4918        let mut archive = zip::ZipArchive::new(std::io::Cursor::new(buffer)).unwrap();
4919        let mut bytes = Vec::new();
4920        archive
4921            .by_name(name)
4922            .unwrap()
4923            .read_to_end(&mut bytes)
4924            .unwrap();
4925        bytes
4926    }
4927
4928    fn zip_entry_count(buffer: &[u8], name: &str) -> usize {
4929        let mut archive = zip::ZipArchive::new(std::io::Cursor::new(buffer)).unwrap();
4930        (0..archive.len())
4931            .filter(|index| archive.by_index(*index).unwrap().name() == name)
4932            .count()
4933    }
4934
4935    fn assert_all_package_targets_exist(buffer: &[u8]) {
4936        let mut archive = zip::ZipArchive::new(std::io::Cursor::new(buffer)).unwrap();
4937        let names: HashSet<String> = (0..archive.len())
4938            .map(|index| archive.by_index(index).unwrap().name().to_string())
4939            .collect();
4940        let content_types: ContentTypes = {
4941            let mut xml = String::new();
4942            archive
4943                .by_name("[Content_Types].xml")
4944                .unwrap()
4945                .read_to_string(&mut xml)
4946                .unwrap();
4947            quick_xml::de::from_str(&xml).unwrap()
4948        };
4949        for entry in content_types.overrides {
4950            let path = entry.part_name.trim_start_matches('/');
4951            if matches!(
4952                path,
4953                "docProps/core.xml" | "docProps/app.xml" | "docProps/custom.xml"
4954            ) && !names.contains(path)
4955            {
4956                continue;
4957            }
4958            assert!(
4959                names.contains(path),
4960                "content type target missing: {}",
4961                entry.part_name
4962            );
4963        }
4964
4965        let relationship_paths: Vec<String> = names
4966            .iter()
4967            .filter(|name| name.ends_with(".rels"))
4968            .cloned()
4969            .collect();
4970        for relationship_path in relationship_paths {
4971            let relationships: Relationships = {
4972                let mut xml = String::new();
4973                archive
4974                    .by_name(&relationship_path)
4975                    .unwrap()
4976                    .read_to_string(&mut xml)
4977                    .unwrap();
4978                quick_xml::de::from_str(&xml).unwrap()
4979            };
4980            let owner = if relationship_path == "_rels/.rels" {
4981                String::new()
4982            } else {
4983                let (directory, filename) = relationship_path.rsplit_once("/_rels/").unwrap();
4984                format!("{directory}/{}", filename.trim_end_matches(".rels"))
4985            };
4986            for relationship in relationships.relationships {
4987                if relationship.target_mode.as_deref() == Some("External") {
4988                    continue;
4989                }
4990                let target = resolve_relationship_target(&owner, &relationship.target);
4991                if relationship_path == "_rels/.rels"
4992                    && matches!(
4993                        relationship.rel_type.as_str(),
4994                        rel_types::CORE_PROPERTIES
4995                            | rel_types::EXTENDED_PROPERTIES
4996                            | rel_types::CUSTOM_PROPERTIES
4997                    )
4998                    && !names.contains(&target)
4999                {
5000                    continue;
5001                }
5002                assert!(
5003                    names.contains(&target),
5004                    "relationship target missing: {relationship_path} -> {target}"
5005                );
5006            }
5007        }
5008    }
5009
5010    fn rewrite_zip_parts(buffer: &[u8], replacements: &[(&str, Option<Vec<u8>>)]) -> Vec<u8> {
5011        let mut archive = zip::ZipArchive::new(std::io::Cursor::new(buffer)).unwrap();
5012        let mut output = Vec::new();
5013        {
5014            let mut writer = zip::ZipWriter::new(std::io::Cursor::new(&mut output));
5015            let options =
5016                SimpleFileOptions::default().compression_method(CompressionMethod::Deflated);
5017            for index in 0..archive.len() {
5018                let mut entry = archive.by_index(index).unwrap();
5019                let name = entry.name().to_string();
5020                let replacement = replacements
5021                    .iter()
5022                    .find(|(path, _)| *path == name)
5023                    .map(|(_, value)| value);
5024                if matches!(replacement, Some(None)) {
5025                    continue;
5026                }
5027                let mut bytes = Vec::new();
5028                entry.read_to_end(&mut bytes).unwrap();
5029                let bytes = replacement.and_then(Option::as_ref).unwrap_or(&bytes);
5030                writer.start_file(name, options).unwrap();
5031                writer.write_all(bytes).unwrap();
5032            }
5033            writer.finish().unwrap();
5034        }
5035        output
5036    }
5037
5038    fn workbook_with_chart_buffer() -> Vec<u8> {
5039        use crate::chart::{ChartConfig, ChartSeries, ChartType};
5040
5041        let mut workbook = Workbook::new();
5042        workbook.new_sheet("Sheet2").unwrap();
5043        workbook
5044            .add_chart(
5045                "Sheet1",
5046                "E2",
5047                "L15",
5048                &ChartConfig {
5049                    chart_type: ChartType::Col,
5050                    title: Some("Preserved chart".to_string()),
5051                    series: vec![ChartSeries {
5052                        name: "Values".to_string(),
5053                        categories: "Sheet1!$A$1:$A$3".to_string(),
5054                        values: "Sheet1!$B$1:$B$3".to_string(),
5055                        x_values: None,
5056                        bubble_sizes: None,
5057                    }],
5058                    show_legend: true,
5059                    view_3d: None,
5060                },
5061            )
5062            .unwrap();
5063        workbook.save_to_buffer().unwrap()
5064    }
5065
5066    fn opaque_graph_buffer() -> (Vec<u8>, Vec<u8>, Vec<u8>, Vec<u8>) {
5067        let base = workbook_with_chart_buffer();
5068
5069        let chart = String::from_utf8(zip_part(&base, "xl/charts/chart1.xml")).unwrap();
5070        let chart = chart.replacen(
5071            "xmlns:c=\"http://schemas.openxmlformats.org/drawingml/2006/chart\"",
5072            "xmlns:c='http://schemas.openxmlformats.org/drawingml/2006/chart'",
5073            1,
5074        );
5075        assert!(chart.contains("xmlns:c='"));
5076
5077        let drawing = String::from_utf8(zip_part(&base, "xl/drawings/drawing1.xml")).unwrap();
5078        let drawing = drawing.replacen(
5079            "xmlns:xdr=\"http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing\"",
5080            "xmlns:xdr='http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing'",
5081            1,
5082        );
5083        assert!(drawing.contains("xmlns:xdr='"));
5084        if let Err(error) = deserialize_xml_bytes::<WsDr>(drawing.as_bytes()) {
5085            panic!("opaque drawing must remain partially parseable: {error}");
5086        }
5087
5088        let drawing_rels =
5089            String::from_utf8(zip_part(&base, "xl/drawings/_rels/drawing1.xml.rels"))
5090                .unwrap()
5091                .replacen(
5092                    "</Relationships>",
5093                    "<!--preserve-this-comment--></Relationships>",
5094                    1,
5095                );
5096
5097        let chart = chart.into_bytes();
5098        let drawing = drawing.into_bytes();
5099        let drawing_rels = drawing_rels.into_bytes();
5100        let rewritten = rewrite_zip_parts(
5101            &base,
5102            &[
5103                ("xl/charts/chart1.xml", Some(chart.clone())),
5104                ("xl/drawings/drawing1.xml", Some(drawing.clone())),
5105                (
5106                    "xl/drawings/_rels/drawing1.xml.rels",
5107                    Some(drawing_rels.clone()),
5108                ),
5109            ],
5110        );
5111        (rewritten, chart, drawing, drawing_rels)
5112    }
5113
5114    fn unsupported_graph_buffer() -> (Vec<u8>, Vec<u8>, Vec<u8>) {
5115        let base = workbook_with_chart_buffer();
5116        let chart = String::from_utf8(zip_part(&base, "xl/charts/chart1.xml")).unwrap();
5117        let chart = chart.replacen(
5118            "</c:barChart>",
5119            "<c:dLbls><c:showVal val=\"1\"/></c:dLbls></c:barChart>",
5120            1,
5121        );
5122        let chart = chart.replacen(
5123            "</c:plotArea>",
5124            concat!(
5125                "<c:dateAx><c:axId val=\"9001\"/></c:dateAx>",
5126                "<c:valAx><c:axId val=\"9002\"/></c:valAx>",
5127                "<c:spPr><a:solidFill xmlns:a=\"http://schemas.openxmlformats.org/",
5128                "drawingml/2006/main\"><a:srgbClr val=\"123456\"/></a:solidFill></c:spPr>",
5129                "</c:plotArea>"
5130            ),
5131            1,
5132        );
5133
5134        let drawing = String::from_utf8(zip_part(&base, "xl/drawings/drawing1.xml")).unwrap();
5135        let drawing = drawing.replacen(
5136            "<xdr:twoCellAnchor>",
5137            "<xdr:twoCellAnchor editAs=\"oneCell\">",
5138            1,
5139        );
5140        let drawing = drawing.replacen(
5141            "</xdr:twoCellAnchor>",
5142            concat!(
5143                "<xdr:cxnSp/><xdr:grpSp/>",
5144                "</xdr:twoCellAnchor>",
5145                "<xdr:absoluteAnchor><xdr:pos x=\"0\" y=\"0\"/>",
5146                "<xdr:ext cx=\"1\" cy=\"1\"/><xdr:sp/></xdr:absoluteAnchor>"
5147            ),
5148            1,
5149        );
5150
5151        let chart = chart.into_bytes();
5152        let drawing = drawing.into_bytes();
5153        let rewritten = rewrite_zip_parts(
5154            &base,
5155            &[
5156                ("xl/charts/chart1.xml", Some(chart.clone())),
5157                ("xl/drawings/drawing1.xml", Some(drawing.clone())),
5158            ],
5159        );
5160        (rewritten, chart, drawing)
5161    }
5162
5163    fn assert_canonical_sst_metadata(buffer: &[u8]) {
5164        let mut archive = zip::ZipArchive::new(std::io::Cursor::new(buffer)).unwrap();
5165        let content_types: ContentTypes =
5166            read_xml_part(&mut archive, "[Content_Types].xml").unwrap();
5167        let relationships: Relationships =
5168            read_xml_part(&mut archive, "xl/_rels/workbook.xml.rels").unwrap();
5169        assert_eq!(
5170            content_types
5171                .overrides
5172                .iter()
5173                .filter(|entry| {
5174                    entry.part_name == "/xl/sharedStrings.xml"
5175                        && entry.content_type == mime_types::SHARED_STRINGS
5176                })
5177                .count(),
5178            1
5179        );
5180        assert_eq!(
5181            relationships
5182                .relationships
5183                .iter()
5184                .filter(|relationship| {
5185                    relationship.rel_type == rel_types::SHARED_STRINGS
5186                        && relationship.target == "sharedStrings.xml"
5187                })
5188                .count(),
5189            1
5190        );
5191    }
5192
5193    #[test]
5194    fn test_extract_xml_attr() {
5195        let xml = r#"<tag type="column" markers="1" weight="2.5">"#;
5196        assert_eq!(extract_xml_attr(xml, "type"), Some("column".to_string()));
5197        assert_eq!(extract_xml_attr(xml, "markers"), Some("1".to_string()));
5198        assert_eq!(extract_xml_attr(xml, "weight"), Some("2.5".to_string()));
5199        assert_eq!(extract_xml_attr(xml, "missing"), None);
5200        // Single-quoted attributes
5201        let xml2 = "<tag name='hello'>";
5202        assert_eq!(extract_xml_attr(xml2, "name"), Some("hello".to_string()));
5203    }
5204
5205    #[test]
5206    fn test_extract_xml_bool_attr() {
5207        let xml = r#"<tag markers="1" hidden="0" visible="true">"#;
5208        assert!(extract_xml_bool_attr(xml, "markers"));
5209        assert!(!extract_xml_bool_attr(xml, "hidden"));
5210        assert!(extract_xml_bool_attr(xml, "visible"));
5211        assert!(!extract_xml_bool_attr(xml, "missing"));
5212    }
5213
5214    #[test]
5215    fn test_new_workbook_has_sheet1() {
5216        let wb = Workbook::new();
5217        assert_eq!(wb.sheet_names(), vec!["Sheet1"]);
5218    }
5219
5220    #[test]
5221    fn test_new_workbook_writes_interop_workbook_defaults() {
5222        let wb = Workbook::new();
5223        let buf = wb.save_to_buffer().unwrap();
5224
5225        let cursor = std::io::Cursor::new(buf);
5226        let mut archive = zip::ZipArchive::new(cursor).unwrap();
5227        let mut workbook_xml = String::new();
5228        std::io::Read::read_to_string(
5229            &mut archive.by_name("xl/workbook.xml").unwrap(),
5230            &mut workbook_xml,
5231        )
5232        .unwrap();
5233
5234        assert!(workbook_xml.contains("<fileVersion"));
5235        assert!(workbook_xml.contains("appName=\"xl\""));
5236        assert!(workbook_xml.contains("lastEdited=\"7\""));
5237        assert!(workbook_xml.contains("lowestEdited=\"7\""));
5238        assert!(workbook_xml.contains("rupBuild=\"27425\""));
5239
5240        assert!(workbook_xml.contains("<workbookPr"));
5241        assert!(workbook_xml.contains("defaultThemeVersion=\"166925\""));
5242
5243        assert!(workbook_xml.contains("<bookViews>"));
5244        assert!(workbook_xml.contains("<workbookView"));
5245        assert!(workbook_xml.contains("activeTab=\"0\""));
5246        assert!(!workbook_xml.contains("xWindow="));
5247        assert!(!workbook_xml.contains("yWindow="));
5248        assert!(!workbook_xml.contains("windowWidth="));
5249        assert!(!workbook_xml.contains("windowHeight="));
5250    }
5251
5252    #[test]
5253    fn test_new_workbook_save_creates_file() {
5254        let dir = TempDir::new().unwrap();
5255        let path = dir.path().join("test.xlsx");
5256        let wb = Workbook::new();
5257        wb.save(&path).unwrap();
5258        assert!(path.exists());
5259    }
5260
5261    #[test]
5262    fn test_save_and_open_roundtrip() {
5263        let dir = TempDir::new().unwrap();
5264        let path = dir.path().join("roundtrip.xlsx");
5265
5266        let wb = Workbook::new();
5267        wb.save(&path).unwrap();
5268
5269        let wb2 = Workbook::open(&path).unwrap();
5270        assert_eq!(wb2.sheet_names(), vec!["Sheet1"]);
5271    }
5272
5273    #[test]
5274    fn test_saved_file_is_valid_zip() {
5275        let dir = TempDir::new().unwrap();
5276        let path = dir.path().join("valid.xlsx");
5277        let wb = Workbook::new();
5278        wb.save(&path).unwrap();
5279
5280        // Verify it's a valid ZIP with expected entries
5281        let file = std::fs::File::open(&path).unwrap();
5282        let mut archive = zip::ZipArchive::new(file).unwrap();
5283
5284        let expected_files = [
5285            "[Content_Types].xml",
5286            "_rels/.rels",
5287            "xl/workbook.xml",
5288            "xl/_rels/workbook.xml.rels",
5289            "xl/worksheets/sheet1.xml",
5290            "xl/styles.xml",
5291            "xl/sharedStrings.xml",
5292        ];
5293
5294        for name in &expected_files {
5295            assert!(archive.by_name(name).is_ok(), "Missing ZIP entry: {}", name);
5296        }
5297    }
5298
5299    #[test]
5300    fn test_open_nonexistent_file_returns_error() {
5301        let result = Workbook::open("/nonexistent/path.xlsx");
5302        assert!(result.is_err());
5303    }
5304
5305    #[test]
5306    fn test_saved_xml_has_declarations() {
5307        let dir = TempDir::new().unwrap();
5308        let path = dir.path().join("decl.xlsx");
5309        let wb = Workbook::new();
5310        wb.save(&path).unwrap();
5311
5312        let file = std::fs::File::open(&path).unwrap();
5313        let mut archive = zip::ZipArchive::new(file).unwrap();
5314
5315        let mut content = String::new();
5316        std::io::Read::read_to_string(
5317            &mut archive.by_name("[Content_Types].xml").unwrap(),
5318            &mut content,
5319        )
5320        .unwrap();
5321        assert!(content.starts_with("<?xml"));
5322    }
5323
5324    #[test]
5325    fn test_default_trait() {
5326        let wb = Workbook::default();
5327        assert_eq!(wb.sheet_names(), vec!["Sheet1"]);
5328    }
5329
5330    #[test]
5331    fn test_serialize_xml_helper() {
5332        let ct = ContentTypes::default();
5333        let xml = serialize_xml(&ct).unwrap();
5334        assert!(xml.starts_with("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"));
5335        assert!(xml.contains("<Types"));
5336    }
5337
5338    #[test]
5339    fn test_save_to_buffer_and_open_from_buffer_roundtrip() {
5340        let mut wb = Workbook::new();
5341        wb.set_cell_value("Sheet1", "A1", CellValue::String("Hello".to_string()))
5342            .unwrap();
5343        wb.set_cell_value("Sheet1", "B2", CellValue::Number(42.0))
5344            .unwrap();
5345
5346        let buf = wb.save_to_buffer().unwrap();
5347        assert!(!buf.is_empty());
5348
5349        let wb2 = Workbook::open_from_buffer(&buf).unwrap();
5350        assert_eq!(wb2.sheet_names(), vec!["Sheet1"]);
5351        assert_eq!(
5352            wb2.get_cell_value("Sheet1", "A1").unwrap(),
5353            CellValue::String("Hello".to_string())
5354        );
5355        assert_eq!(
5356            wb2.get_cell_value("Sheet1", "B2").unwrap(),
5357            CellValue::Number(42.0)
5358        );
5359    }
5360
5361    #[test]
5362    fn test_save_to_buffer_produces_valid_zip() {
5363        let wb = Workbook::new();
5364        let buf = wb.save_to_buffer().unwrap();
5365
5366        let cursor = std::io::Cursor::new(buf);
5367        let mut archive = zip::ZipArchive::new(cursor).unwrap();
5368
5369        let expected_files = [
5370            "[Content_Types].xml",
5371            "_rels/.rels",
5372            "xl/workbook.xml",
5373            "xl/_rels/workbook.xml.rels",
5374            "xl/worksheets/sheet1.xml",
5375            "xl/styles.xml",
5376            "xl/sharedStrings.xml",
5377        ];
5378
5379        for name in &expected_files {
5380            assert!(archive.by_name(name).is_ok(), "Missing ZIP entry: {}", name);
5381        }
5382    }
5383
5384    #[test]
5385    fn test_save_adds_canonical_sst_metadata_to_inline_string_package() {
5386        let base = Workbook::new().save_to_buffer().unwrap();
5387        let mut content_types: ContentTypes = {
5388            let mut archive = zip::ZipArchive::new(std::io::Cursor::new(&base)).unwrap();
5389            read_xml_part(&mut archive, "[Content_Types].xml").unwrap()
5390        };
5391        content_types
5392            .overrides
5393            .retain(|entry| entry.part_name != "/xl/sharedStrings.xml");
5394        let mut workbook_rels: Relationships = {
5395            let mut archive = zip::ZipArchive::new(std::io::Cursor::new(&base)).unwrap();
5396            read_xml_part(&mut archive, "xl/_rels/workbook.xml.rels").unwrap()
5397        };
5398        workbook_rels
5399            .relationships
5400            .retain(|relationship| relationship.rel_type != rel_types::SHARED_STRINGS);
5401        let worksheet = String::from_utf8(zip_part(&base, "xl/worksheets/sheet1.xml"))
5402            .unwrap()
5403            .replace(
5404                "<sheetData/>",
5405                "<sheetData><row r=\"1\"><c r=\"A1\" t=\"inlineStr\"><is><t>Inline</t></is></c></row></sheetData>",
5406            );
5407        let input = rewrite_zip_parts(
5408            &base,
5409            &[
5410                ("xl/sharedStrings.xml", None),
5411                (
5412                    "[Content_Types].xml",
5413                    Some(serialize_xml(&content_types).unwrap().into_bytes()),
5414                ),
5415                (
5416                    "xl/_rels/workbook.xml.rels",
5417                    Some(serialize_xml(&workbook_rels).unwrap().into_bytes()),
5418                ),
5419                ("xl/worksheets/sheet1.xml", Some(worksheet.into_bytes())),
5420            ],
5421        );
5422
5423        let mut workbook = Workbook::open_from_buffer(&input).unwrap();
5424        workbook
5425            .set_cell_value("Sheet1", "B1", CellValue::String("Shared".to_string()))
5426            .unwrap();
5427        let first = workbook.save_to_buffer().unwrap();
5428        assert_canonical_sst_metadata(&first);
5429        let reopened = Workbook::open_from_buffer(&first).unwrap();
5430        let second = reopened.save_to_buffer().unwrap();
5431        assert_canonical_sst_metadata(&second);
5432        assert_eq!(zip_entry_count(&second, "xl/sharedStrings.xml"), 1);
5433        let reopened_second = Workbook::open_from_buffer(&second).unwrap();
5434        assert_eq!(
5435            reopened_second.get_cell_value("Sheet1", "A1").unwrap(),
5436            CellValue::String("Inline".to_string())
5437        );
5438        assert_eq!(
5439            reopened_second.get_cell_value("Sheet1", "B1").unwrap(),
5440            CellValue::String("Shared".to_string())
5441        );
5442    }
5443
5444    #[test]
5445    fn test_deserialize_shared_strings_preserves_text_exactly() {
5446        let xml = br#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
5447<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="3" uniqueCount="3">
5448  <si><t xml:space="preserve">  plain&#9;line&#10;&amp;  </t></si>
5449  <si><t xml:space="preserve"> direct </t><r><rPr><b/></rPr><t xml:space="preserve"> rich </t></r><r><t><![CDATA[tail  ]]></t></r></si>
5450  <si><t>entity &lt;value&gt;</t></si>
5451</sst>"#;
5452        let sst = deserialize_shared_strings_from_bytes(xml).unwrap();
5453        assert_eq!(sst.items[0].t.as_ref().unwrap().value, "  plain\tline\n&  ");
5454        assert_eq!(sst.items[1].t.as_ref().unwrap().value, " direct ");
5455        assert_eq!(sst.items[1].r[0].t.value, " rich ");
5456        assert_eq!(sst.items[1].r[1].t.value, "tail  ");
5457        assert!(sst.items[1].r[0].r_pr.as_ref().unwrap().b.is_some());
5458        assert_eq!(sst.items[2].t.as_ref().unwrap().value, "entity <value>");
5459    }
5460
5461    #[test]
5462    fn shared_string_raw_scan_fast_path_preserves_signaled_text() {
5463        let ordinary = br#"<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><si><t>ordinary text</t></si><si><r><t>rich text</t></r></si></sst>"#;
5464        assert!(!shared_strings_need_raw_scan(ordinary));
5465        let ordinary_sst = deserialize_shared_strings_from_bytes(ordinary).unwrap();
5466        assert_eq!(
5467            ordinary_sst.items[0].t.as_ref().unwrap().value,
5468            "ordinary text"
5469        );
5470        assert_eq!(ordinary_sst.items[1].r[0].t.value, "rich text");
5471
5472        let single_quoted = br#"<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><si><x:t xml:space='preserve' xmlns:x="urn:test">  kept  </x:t></si></sst>"#;
5473        assert!(shared_strings_need_raw_scan(single_quoted));
5474        let single_quoted_sst = deserialize_shared_strings_from_bytes(single_quoted).unwrap();
5475        assert_eq!(
5476            single_quoted_sst.items[0].t.as_ref().unwrap().value,
5477            "  kept  "
5478        );
5479
5480        let cdata = br#"<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><si><t><![CDATA[  cdata  ]]></t></si></sst>"#;
5481        assert!(shared_strings_need_raw_scan(cdata));
5482        let cdata_sst = deserialize_shared_strings_from_bytes(cdata).unwrap();
5483        assert_eq!(cdata_sst.items[0].t.as_ref().unwrap().value, "  cdata  ");
5484    }
5485
5486    #[test]
5487    fn shared_string_raw_scan_matches_substring_search_at_boundaries() {
5488        let reference = |bytes: &[u8]| {
5489            [b":space".as_slice(), b"<![CDATA[".as_slice()]
5490                .iter()
5491                .any(|marker| bytes.windows(marker.len()).any(|window| window == *marker))
5492        };
5493        let cases: [&[u8]; 14] = [
5494            b"",
5495            b":space",
5496            b"<![CDATA[",
5497            b"x:spac",
5498            b"<![CDATA",
5499            b"!",
5500            b"!<![CDATA[",
5501            b"<<![CDATA[x",
5502            b"<!-- c --><!DOCTYPE>",
5503            b"::space",
5504            b"a:b:space",
5505            b"<t>12:30</t>",
5506            b"<![cdata[",
5507            b":SPACE",
5508        ];
5509        for case in cases {
5510            assert_eq!(
5511                shared_strings_need_raw_scan(case),
5512                reference(case),
5513                "{:?}",
5514                String::from_utf8_lossy(case)
5515            );
5516        }
5517    }
5518
5519    #[test]
5520    fn scan_shared_string_text_reads_from_buffered_stream() {
5521        struct ChunkedReader {
5522            bytes: Vec<u8>,
5523            offset: usize,
5524        }
5525
5526        impl std::io::Read for ChunkedReader {
5527            fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
5528                if self.offset == self.bytes.len() {
5529                    return Ok(0);
5530                }
5531                let len = (self.bytes.len() - self.offset).min(buf.len()).min(3);
5532                buf[..len].copy_from_slice(&self.bytes[self.offset..self.offset + len]);
5533                self.offset += len;
5534                Ok(len)
5535            }
5536        }
5537
5538        let reader = std::io::BufReader::with_capacity(
5539            5,
5540            ChunkedReader {
5541                bytes: b"<sst><si><t>  spaced  </t></si></sst>".to_vec(),
5542                offset: 0,
5543            },
5544        );
5545        let items = scan_shared_string_text(reader).unwrap();
5546        assert_eq!(items[0].plain.as_deref(), Some("  spaced  "));
5547    }
5548
5549    #[test]
5550    fn read_shared_strings_part_preserves_highly_compressible_whitespace() {
5551        use std::io::Write;
5552
5553        let padding = " ".repeat(1024 * 1024);
5554        let xml = format!(
5555            "<sst xmlns=\"{}\"><si><t xml:space=\"preserve\">{padding}value{padding}</t></si></sst>",
5556            sheetkit_xml::namespaces::SPREADSHEET_ML
5557        );
5558        let mut zip_bytes = Vec::new();
5559        {
5560            let mut writer = zip::ZipWriter::new(std::io::Cursor::new(&mut zip_bytes));
5561            writer
5562                .start_file(
5563                    "xl/sharedStrings.xml",
5564                    SimpleFileOptions::default().compression_method(CompressionMethod::Deflated),
5565                )
5566                .unwrap();
5567            writer.write_all(xml.as_bytes()).unwrap();
5568            writer.finish().unwrap();
5569        }
5570        assert!(zip_bytes.len() < xml.len() / 100);
5571
5572        let mut archive = zip::ZipArchive::new(std::io::Cursor::new(zip_bytes)).unwrap();
5573        let sst = read_shared_strings_part(&mut archive, "xl/sharedStrings.xml")
5574            .unwrap()
5575            .unwrap();
5576        assert_eq!(
5577            sst.items[0].t.as_ref().unwrap().value,
5578            format!("{padding}value{padding}")
5579        );
5580    }
5581
5582    #[test]
5583    fn read_shared_strings_part_opens_and_reads_entry_once() {
5584        struct CountingEntry<'archive> {
5585            reader: std::io::Cursor<&'archive [u8]>,
5586            actual_bytes: &'archive mut usize,
5587        }
5588
5589        impl std::io::Read for CountingEntry<'_> {
5590            fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {
5591                let count = self.reader.read(buffer)?;
5592                *self.actual_bytes += count;
5593                Ok(count)
5594            }
5595        }
5596
5597        struct CountingArchive {
5598            bytes: Vec<u8>,
5599            opens: usize,
5600            actual_bytes: usize,
5601        }
5602
5603        impl ArchiveAccess for CountingArchive {
5604            type Entry<'entry>
5605                = CountingEntry<'entry>
5606            where
5607                Self: 'entry;
5608
5609            fn entry_names(&self) -> Vec<String> {
5610                vec!["xl/sharedStrings.xml".to_string()]
5611            }
5612
5613            fn entry<'entry>(
5614                &'entry mut self,
5615                name: &str,
5616                _xml: bool,
5617            ) -> Result<Self::Entry<'entry>> {
5618                assert_eq!(name, "xl/sharedStrings.xml");
5619                self.opens += 1;
5620                Ok(CountingEntry {
5621                    reader: std::io::Cursor::new(&self.bytes),
5622                    actual_bytes: &mut self.actual_bytes,
5623                })
5624            }
5625
5626            fn entry_optional<'entry>(
5627                &'entry mut self,
5628                name: &str,
5629                xml: bool,
5630            ) -> Result<Option<Self::Entry<'entry>>> {
5631                self.entry(name, xml).map(Some)
5632            }
5633
5634            fn pending_error(&mut self) -> Option<Error> {
5635                None
5636            }
5637
5638            fn charge_retained(&mut self, _amount: u64) -> Result<()> {
5639                Ok(())
5640            }
5641        }
5642
5643        let bytes = format!(
5644            "<sst xmlns=\"{}\"><si><t xml:space=\"preserve\"> value </t></si></sst>",
5645            sheetkit_xml::namespaces::SPREADSHEET_ML
5646        )
5647        .into_bytes();
5648        let mut archive = CountingArchive {
5649            bytes,
5650            opens: 0,
5651            actual_bytes: 0,
5652        };
5653
5654        let sst = read_shared_strings_part(&mut archive, "xl/sharedStrings.xml")
5655            .unwrap()
5656            .unwrap();
5657
5658        assert_eq!(archive.opens, 1);
5659        assert_eq!(archive.actual_bytes, archive.bytes.len());
5660        assert_eq!(sst.items[0].t.as_ref().unwrap().value, " value ");
5661    }
5662
5663    #[test]
5664    fn clean_control_metadata_round_trips_without_rebuild() {
5665        let mut workbook = Workbook::new();
5666        workbook
5667            .add_form_control(
5668                "Sheet1",
5669                crate::control::FormControlConfig::button("B2", "Run"),
5670            )
5671            .unwrap();
5672        let first = workbook.save_to_buffer().unwrap();
5673        let options = OpenOptions::new()
5674            .read_mode(ReadMode::Eager)
5675            .aux_parts(AuxParts::EagerLoad);
5676        let reopened = Workbook::open_from_buffer_with_options(&first, &options).unwrap();
5677
5678        assert!(!reopened.sheet_controls_dirty[0]);
5679        let second = reopened.save_to_buffer().unwrap();
5680
5681        let first_sheet = String::from_utf8(zip_part(&first, "xl/worksheets/sheet1.xml")).unwrap();
5682        let second_sheet =
5683            String::from_utf8(zip_part(&second, "xl/worksheets/sheet1.xml")).unwrap();
5684        assert_eq!(
5685            parse_worksheet_control_entries(&second_sheet),
5686            parse_worksheet_control_entries(&first_sheet)
5687        );
5688        assert!(second_sheet.contains("<legacyDrawing r:id=\"rId2\"/>"));
5689    }
5690
5691    #[test]
5692    fn test_shared_string_whitespace_survives_open_save_reopen() {
5693        let mut workbook = Workbook::new();
5694        workbook
5695            .set_cell_value("Sheet1", "A1", CellValue::String("placeholder".to_string()))
5696            .unwrap();
5697        let base = workbook.save_to_buffer().unwrap();
5698        let exact = "  leading\tand\nmultiple  spaces & entities <ok>  rich tail  ";
5699        let sst = format!(
5700            "{XML_DECLARATION}\n<sst xmlns=\"{}\" count=\"1\" uniqueCount=\"1\"><si><t xml:space=\"preserve\">  leading&#9;and&#10;multiple  spaces &amp; entities &lt;ok&gt;  </t><r><rPr><b/></rPr><t xml:space=\"preserve\">rich </t></r><r><t><![CDATA[tail  ]]></t></r></si></sst>",
5701            sheetkit_xml::namespaces::SPREADSHEET_ML
5702        );
5703        let input = rewrite_zip_parts(&base, &[("xl/sharedStrings.xml", Some(sst.into_bytes()))]);
5704        let opened = Workbook::open_from_buffer(&input).unwrap();
5705        assert_eq!(
5706            opened.get_cell_value("Sheet1", "A1").unwrap(),
5707            CellValue::String(exact.to_string())
5708        );
5709        let saved = opened.save_to_buffer().unwrap();
5710        let reopened = Workbook::open_from_buffer(&saved).unwrap();
5711        assert_eq!(
5712            reopened.get_cell_value("Sheet1", "A1").unwrap(),
5713            CellValue::String(exact.to_string())
5714        );
5715        let roundtripped = reopened.sst_runtime.to_sst();
5716        let item = &roundtripped.items[0];
5717        assert_eq!(
5718            item.t.as_ref().unwrap().value,
5719            "  leading\tand\nmultiple  spaces & entities <ok>  "
5720        );
5721        assert_eq!(item.r[0].t.value, "rich ");
5722        assert!(item.r[0].r_pr.as_ref().unwrap().b.is_some());
5723        assert_eq!(item.r[1].t.value, "tail  ");
5724    }
5725
5726    fn workbook_with_slicer() -> Workbook {
5727        let mut workbook = Workbook::new();
5728        workbook
5729            .add_table(
5730                "Sheet1",
5731                &crate::table::TableConfig {
5732                    name: "Table1".to_string(),
5733                    display_name: "Table1".to_string(),
5734                    range: "A1:B3".to_string(),
5735                    columns: vec![
5736                        crate::table::TableColumn {
5737                            name: "Status".to_string(),
5738                            totals_row_function: None,
5739                            totals_row_label: None,
5740                        },
5741                        crate::table::TableColumn {
5742                            name: "Value".to_string(),
5743                            totals_row_function: None,
5744                            totals_row_label: None,
5745                        },
5746                    ],
5747                    ..crate::table::TableConfig::default()
5748                },
5749            )
5750            .unwrap();
5751        workbook
5752            .add_slicer(
5753                "Sheet1",
5754                &crate::slicer::SlicerConfig {
5755                    name: "StatusFilter".to_string(),
5756                    cell: "D1".to_string(),
5757                    table_name: "Table1".to_string(),
5758                    column_name: "Status".to_string(),
5759                    caption: None,
5760                    style: None,
5761                    width: None,
5762                    height: None,
5763                    show_caption: None,
5764                    column_count: None,
5765                },
5766            )
5767            .unwrap();
5768        workbook
5769    }
5770
5771    #[test]
5772    fn test_eager_slicer_parts_are_emitted_once_across_two_saves() {
5773        use crate::workbook::open_options::{AuxParts, OpenOptions, ReadMode};
5774
5775        let initial = workbook_with_slicer().save_to_buffer().unwrap();
5776        let options = OpenOptions::new()
5777            .read_mode(ReadMode::Eager)
5778            .aux_parts(AuxParts::EagerLoad);
5779        let opened = Workbook::open_from_buffer_with_options(&initial, &options).unwrap();
5780        let first = opened.save_to_buffer().unwrap();
5781        let reopened = Workbook::open_from_buffer_with_options(&first, &options).unwrap();
5782        let second = reopened.save_to_buffer().unwrap();
5783
5784        for buffer in [&first, &second] {
5785            assert_eq!(zip_entry_count(buffer, "xl/slicers/slicer1.xml"), 1);
5786            assert_eq!(
5787                zip_entry_count(buffer, "xl/slicerCaches/slicerCache1.xml"),
5788                1
5789            );
5790        }
5791    }
5792
5793    #[test]
5794    fn test_lazy_hydration_preserves_malformed_slicer_parts_as_raw() {
5795        use crate::workbook::open_options::{AuxParts, OpenOptions, ReadMode};
5796
5797        let initial = workbook_with_slicer().save_to_buffer().unwrap();
5798        let malformed_slicer = b"<x14:slicers><broken>".to_vec();
5799        let malformed_cache = b"<x14:slicerCacheDefinition><broken>".to_vec();
5800        let input = rewrite_zip_parts(
5801            &initial,
5802            &[
5803                ("xl/slicers/slicer1.xml", Some(malformed_slicer.clone())),
5804                (
5805                    "xl/slicerCaches/slicerCache1.xml",
5806                    Some(malformed_cache.clone()),
5807                ),
5808            ],
5809        );
5810        let options = OpenOptions::new()
5811            .read_mode(ReadMode::Lazy)
5812            .aux_parts(AuxParts::Deferred);
5813        let mut opened = Workbook::open_from_buffer_with_options(&input, &options).unwrap();
5814        assert!(opened.delete_slicer("Sheet1", "Missing").is_err());
5815        let saved = opened.save_to_buffer().unwrap();
5816
5817        assert_eq!(zip_entry_count(&saved, "xl/slicers/slicer1.xml"), 1);
5818        assert_eq!(zip_part(&saved, "xl/slicers/slicer1.xml"), malformed_slicer);
5819        assert_eq!(
5820            zip_entry_count(&saved, "xl/slicerCaches/slicerCache1.xml"),
5821            1
5822        );
5823        assert_eq!(
5824            zip_part(&saved, "xl/slicerCaches/slicerCache1.xml"),
5825            malformed_cache
5826        );
5827    }
5828
5829    #[test]
5830    fn test_open_from_buffer_invalid_data() {
5831        let result = Workbook::open_from_buffer(b"not a zip file");
5832        assert!(result.is_err());
5833    }
5834
5835    #[cfg(feature = "encryption")]
5836    #[test]
5837    fn test_save_and_open_with_password_roundtrip() {
5838        let dir = TempDir::new().unwrap();
5839        let path = dir.path().join("encrypted.xlsx");
5840
5841        // Create a workbook with some data
5842        let mut wb = Workbook::new();
5843        wb.set_cell_value("Sheet1", "A1", CellValue::String("Hello".to_string()))
5844            .unwrap();
5845        wb.set_cell_value("Sheet1", "B2", CellValue::Number(42.0))
5846            .unwrap();
5847
5848        // Save with password
5849        wb.save_with_password(&path, "test123").unwrap();
5850
5851        // Verify it's a CFB file, not a ZIP
5852        let data = std::fs::read(&path).unwrap();
5853        assert_eq!(
5854            &data[..8],
5855            &[0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]
5856        );
5857
5858        // Open without password should fail
5859        let result = Workbook::open(&path);
5860        assert!(matches!(result, Err(Error::FileEncrypted)));
5861
5862        // Open with wrong password should fail
5863        let result = Workbook::open_with_password(&path, "wrong");
5864        assert!(matches!(result, Err(Error::IncorrectPassword)));
5865
5866        // Open with correct password should succeed
5867        let wb2 = Workbook::open_with_password(&path, "test123").unwrap();
5868        assert_eq!(
5869            wb2.get_cell_value("Sheet1", "A1").unwrap(),
5870            CellValue::String("Hello".to_string())
5871        );
5872        assert_eq!(
5873            wb2.get_cell_value("Sheet1", "B2").unwrap(),
5874            CellValue::Number(42.0)
5875        );
5876    }
5877
5878    /// Create a test xlsx buffer with extra custom ZIP entries that sheetkit
5879    /// does not natively handle.
5880    fn create_xlsx_with_custom_entries() -> Vec<u8> {
5881        let mut wb = Workbook::new();
5882        wb.set_cell_value("Sheet1", "A1", CellValue::String("hello".to_string()))
5883            .unwrap();
5884        let base_buf = wb.save_to_buffer().unwrap();
5885
5886        // Re-open the ZIP and inject custom entries.
5887        let cursor = std::io::Cursor::new(&base_buf);
5888        let mut archive = zip::ZipArchive::new(cursor).unwrap();
5889        let mut out = Vec::new();
5890        {
5891            let out_cursor = std::io::Cursor::new(&mut out);
5892            let mut zip_writer = zip::ZipWriter::new(out_cursor);
5893            let options =
5894                SimpleFileOptions::default().compression_method(CompressionMethod::Deflated);
5895
5896            // Copy all existing entries.
5897            for i in 0..archive.len() {
5898                let mut entry = archive.by_index(i).unwrap();
5899                let name = entry.name().to_string();
5900                let mut data = Vec::new();
5901                std::io::Read::read_to_end(&mut entry, &mut data).unwrap();
5902                zip_writer.start_file(&name, options).unwrap();
5903                std::io::Write::write_all(&mut zip_writer, &data).unwrap();
5904            }
5905
5906            // Add custom entries that sheetkit does not handle.
5907            zip_writer
5908                .start_file("customXml/item1.xml", options)
5909                .unwrap();
5910            std::io::Write::write_all(&mut zip_writer, b"<custom>data1</custom>").unwrap();
5911
5912            zip_writer
5913                .start_file("customXml/itemProps1.xml", options)
5914                .unwrap();
5915            std::io::Write::write_all(
5916                &mut zip_writer,
5917                b"<ds:datastoreItem xmlns:ds=\"http://schemas.openxmlformats.org/officeDocument/2006/customXml\"/>",
5918            )
5919            .unwrap();
5920
5921            zip_writer
5922                .start_file("xl/printerSettings/printerSettings1.bin", options)
5923                .unwrap();
5924            std::io::Write::write_all(&mut zip_writer, b"\x00\x01\x02\x03PRINTER").unwrap();
5925
5926            zip_writer.finish().unwrap();
5927        }
5928        out
5929    }
5930
5931    #[test]
5932    fn test_unknown_zip_entries_preserved_on_roundtrip() {
5933        let buf = create_xlsx_with_custom_entries();
5934
5935        // Open, verify the data is still accessible.
5936        let wb = Workbook::open_from_buffer(&buf).unwrap();
5937        assert_eq!(
5938            wb.get_cell_value("Sheet1", "A1").unwrap(),
5939            CellValue::String("hello".to_string())
5940        );
5941
5942        // Save and re-open.
5943        let saved = wb.save_to_buffer().unwrap();
5944        let cursor = std::io::Cursor::new(&saved);
5945        let mut archive = zip::ZipArchive::new(cursor).unwrap();
5946
5947        // Verify custom entries are present in the output.
5948        let mut custom_xml = String::new();
5949        std::io::Read::read_to_string(
5950            &mut archive.by_name("customXml/item1.xml").unwrap(),
5951            &mut custom_xml,
5952        )
5953        .unwrap();
5954        assert_eq!(custom_xml, "<custom>data1</custom>");
5955
5956        let mut props_xml = String::new();
5957        std::io::Read::read_to_string(
5958            &mut archive.by_name("customXml/itemProps1.xml").unwrap(),
5959            &mut props_xml,
5960        )
5961        .unwrap();
5962        assert!(props_xml.contains("datastoreItem"));
5963
5964        let mut printer = Vec::new();
5965        std::io::Read::read_to_end(
5966            &mut archive
5967                .by_name("xl/printerSettings/printerSettings1.bin")
5968                .unwrap(),
5969            &mut printer,
5970        )
5971        .unwrap();
5972        assert_eq!(printer, b"\x00\x01\x02\x03PRINTER");
5973    }
5974
5975    #[test]
5976    fn test_unknown_entries_survive_multiple_roundtrips() {
5977        let buf = create_xlsx_with_custom_entries();
5978        let wb1 = Workbook::open_from_buffer(&buf).unwrap();
5979        let buf2 = wb1.save_to_buffer().unwrap();
5980        let wb2 = Workbook::open_from_buffer(&buf2).unwrap();
5981        let buf3 = wb2.save_to_buffer().unwrap();
5982
5983        let cursor = std::io::Cursor::new(&buf3);
5984        let mut archive = zip::ZipArchive::new(cursor).unwrap();
5985
5986        let mut custom_xml = String::new();
5987        std::io::Read::read_to_string(
5988            &mut archive.by_name("customXml/item1.xml").unwrap(),
5989            &mut custom_xml,
5990        )
5991        .unwrap();
5992        assert_eq!(custom_xml, "<custom>data1</custom>");
5993
5994        let mut printer = Vec::new();
5995        std::io::Read::read_to_end(
5996            &mut archive
5997                .by_name("xl/printerSettings/printerSettings1.bin")
5998                .unwrap(),
5999            &mut printer,
6000        )
6001        .unwrap();
6002        assert_eq!(printer, b"\x00\x01\x02\x03PRINTER");
6003    }
6004
6005    #[test]
6006    fn test_new_workbook_has_no_unknown_parts() {
6007        let wb = Workbook::new();
6008        let buf = wb.save_to_buffer().unwrap();
6009        let wb2 = Workbook::open_from_buffer(&buf).unwrap();
6010        assert!(wb2.unknown_parts.is_empty());
6011    }
6012
6013    #[test]
6014    fn test_known_entries_not_duplicated_as_unknown() {
6015        let wb = Workbook::new();
6016        let buf = wb.save_to_buffer().unwrap();
6017        let wb2 = Workbook::open_from_buffer(&buf).unwrap();
6018
6019        // None of the standard entries should appear in unknown_parts.
6020        let unknown_paths: Vec<&str> = wb2.unknown_parts.iter().map(|(p, _)| p.as_str()).collect();
6021        assert!(
6022            !unknown_paths.contains(&"[Content_Types].xml"),
6023            "Content_Types should not be in unknown_parts"
6024        );
6025        assert!(
6026            !unknown_paths.contains(&"xl/workbook.xml"),
6027            "workbook.xml should not be in unknown_parts"
6028        );
6029        assert!(
6030            !unknown_paths.contains(&"xl/styles.xml"),
6031            "styles.xml should not be in unknown_parts"
6032        );
6033    }
6034
6035    #[test]
6036    fn test_modifications_preserved_alongside_unknown_parts() {
6037        let buf = create_xlsx_with_custom_entries();
6038        let mut wb = Workbook::open_from_buffer(&buf).unwrap();
6039
6040        // Modify data in the workbook.
6041        wb.set_cell_value("Sheet1", "B1", CellValue::Number(42.0))
6042            .unwrap();
6043
6044        let saved = wb.save_to_buffer().unwrap();
6045        let wb2 = Workbook::open_from_buffer(&saved).unwrap();
6046
6047        // Original data preserved.
6048        assert_eq!(
6049            wb2.get_cell_value("Sheet1", "A1").unwrap(),
6050            CellValue::String("hello".to_string())
6051        );
6052        // New data present.
6053        assert_eq!(
6054            wb2.get_cell_value("Sheet1", "B1").unwrap(),
6055            CellValue::Number(42.0)
6056        );
6057        // Unknown parts still present.
6058        let cursor = std::io::Cursor::new(&saved);
6059        let mut archive = zip::ZipArchive::new(cursor).unwrap();
6060        assert!(archive.by_name("customXml/item1.xml").is_ok());
6061    }
6062
6063    #[test]
6064    fn test_threaded_comment_person_rel_in_workbook_rels() {
6065        let mut wb = Workbook::new();
6066        wb.add_threaded_comment(
6067            "Sheet1",
6068            "A1",
6069            &crate::threaded_comment::ThreadedCommentInput {
6070                author: "Alice".to_string(),
6071                text: "Test comment".to_string(),
6072                parent_id: None,
6073            },
6074        )
6075        .unwrap();
6076
6077        let buf = wb.save_to_buffer().unwrap();
6078        let wb2 = Workbook::open_from_buffer(&buf).unwrap();
6079
6080        // Verify workbook_rels contains a REL_TYPE_PERSON relationship.
6081        let has_person_rel = wb2.workbook_rels.relationships.iter().any(|r| {
6082            r.rel_type == sheetkit_xml::threaded_comment::REL_TYPE_PERSON
6083                && r.target == "persons/person.xml"
6084        });
6085        assert!(
6086            has_person_rel,
6087            "workbook_rels must contain a person relationship for threaded comments"
6088        );
6089    }
6090
6091    #[test]
6092    fn test_no_person_rel_without_threaded_comments() {
6093        let wb = Workbook::new();
6094        let buf = wb.save_to_buffer().unwrap();
6095        let wb2 = Workbook::open_from_buffer(&buf).unwrap();
6096
6097        let has_person_rel = wb2
6098            .workbook_rels
6099            .relationships
6100            .iter()
6101            .any(|r| r.rel_type == sheetkit_xml::threaded_comment::REL_TYPE_PERSON);
6102        assert!(
6103            !has_person_rel,
6104            "workbook_rels must not contain a person relationship when there are no threaded comments"
6105        );
6106    }
6107
6108    #[cfg(feature = "encryption")]
6109    #[test]
6110    fn test_open_encrypted_file_without_password_returns_file_encrypted() {
6111        let dir = TempDir::new().unwrap();
6112        let path = dir.path().join("encrypted2.xlsx");
6113
6114        let wb = Workbook::new();
6115        wb.save_with_password(&path, "secret").unwrap();
6116
6117        let result = Workbook::open(&path);
6118        assert!(matches!(result, Err(Error::FileEncrypted)))
6119    }
6120
6121    #[test]
6122    fn test_workbook_format_from_content_type() {
6123        use sheetkit_xml::content_types::mime_types;
6124        assert_eq!(
6125            WorkbookFormat::from_content_type(mime_types::WORKBOOK),
6126            Some(WorkbookFormat::Xlsx)
6127        );
6128        assert_eq!(
6129            WorkbookFormat::from_content_type(mime_types::WORKBOOK_MACRO),
6130            Some(WorkbookFormat::Xlsm)
6131        );
6132        assert_eq!(
6133            WorkbookFormat::from_content_type(mime_types::WORKBOOK_TEMPLATE),
6134            Some(WorkbookFormat::Xltx)
6135        );
6136        assert_eq!(
6137            WorkbookFormat::from_content_type(mime_types::WORKBOOK_TEMPLATE_MACRO),
6138            Some(WorkbookFormat::Xltm)
6139        );
6140        assert_eq!(
6141            WorkbookFormat::from_content_type(mime_types::WORKBOOK_ADDIN_MACRO),
6142            Some(WorkbookFormat::Xlam)
6143        );
6144        assert_eq!(
6145            WorkbookFormat::from_content_type("application/unknown"),
6146            None
6147        );
6148    }
6149
6150    #[test]
6151    fn test_workbook_format_content_type_roundtrip() {
6152        for fmt in [
6153            WorkbookFormat::Xlsx,
6154            WorkbookFormat::Xlsm,
6155            WorkbookFormat::Xltx,
6156            WorkbookFormat::Xltm,
6157            WorkbookFormat::Xlam,
6158        ] {
6159            let ct = fmt.content_type();
6160            assert_eq!(WorkbookFormat::from_content_type(ct), Some(fmt));
6161        }
6162    }
6163
6164    #[test]
6165    fn test_new_workbook_defaults_to_xlsx_format() {
6166        let wb = Workbook::new();
6167        assert_eq!(wb.format(), WorkbookFormat::Xlsx);
6168    }
6169
6170    #[test]
6171    fn test_xlsx_roundtrip_preserves_format() {
6172        let dir = TempDir::new().unwrap();
6173        let path = dir.path().join("roundtrip_format.xlsx");
6174
6175        let wb = Workbook::new();
6176        assert_eq!(wb.format(), WorkbookFormat::Xlsx);
6177        wb.save(&path).unwrap();
6178
6179        let wb2 = Workbook::open(&path).unwrap();
6180        assert_eq!(wb2.format(), WorkbookFormat::Xlsx);
6181    }
6182
6183    #[test]
6184    fn test_save_writes_correct_content_type_for_each_extension() {
6185        let dir = TempDir::new().unwrap();
6186
6187        let cases = [
6188            (WorkbookFormat::Xlsx, "test.xlsx"),
6189            (WorkbookFormat::Xlsm, "test.xlsm"),
6190            (WorkbookFormat::Xltx, "test.xltx"),
6191            (WorkbookFormat::Xltm, "test.xltm"),
6192            (WorkbookFormat::Xlam, "test.xlam"),
6193        ];
6194
6195        for (expected_fmt, filename) in cases {
6196            let path = dir.path().join(filename);
6197            let wb = Workbook::new();
6198            wb.save(&path).unwrap();
6199
6200            let file = std::fs::File::open(&path).unwrap();
6201            let mut archive = zip::ZipArchive::new(file).unwrap();
6202
6203            let ct: ContentTypes = read_xml_part(&mut archive, "[Content_Types].xml").unwrap();
6204            let wb_override = ct
6205                .overrides
6206                .iter()
6207                .find(|o| o.part_name == "/xl/workbook.xml")
6208                .expect("workbook override must exist");
6209            assert_eq!(
6210                wb_override.content_type,
6211                expected_fmt.content_type(),
6212                "content type mismatch for {}",
6213                filename
6214            );
6215        }
6216    }
6217
6218    #[test]
6219    fn test_set_format_changes_workbook_format() {
6220        let mut wb = Workbook::new();
6221        assert_eq!(wb.format(), WorkbookFormat::Xlsx);
6222
6223        wb.set_format(WorkbookFormat::Xlsm);
6224        assert_eq!(wb.format(), WorkbookFormat::Xlsm);
6225    }
6226
6227    #[test]
6228    fn test_save_buffer_roundtrip_with_xlsm_format() {
6229        let mut wb = Workbook::new();
6230        wb.set_format(WorkbookFormat::Xlsm);
6231        wb.set_cell_value("Sheet1", "A1", CellValue::String("test".to_string()))
6232            .unwrap();
6233
6234        let buf = wb.save_to_buffer().unwrap();
6235        let wb2 = Workbook::open_from_buffer(&buf).unwrap();
6236        assert_eq!(wb2.format(), WorkbookFormat::Xlsm);
6237        assert_eq!(
6238            wb2.get_cell_value("Sheet1", "A1").unwrap(),
6239            CellValue::String("test".to_string())
6240        );
6241    }
6242
6243    #[test]
6244    fn test_open_with_default_options_is_equivalent_to_open() {
6245        let dir = TempDir::new().unwrap();
6246        let path = dir.path().join("default_opts.xlsx");
6247        let mut wb = Workbook::new();
6248        wb.set_cell_value("Sheet1", "A1", CellValue::String("test".to_string()))
6249            .unwrap();
6250        wb.save(&path).unwrap();
6251
6252        let wb2 = Workbook::open_with_options(&path, &OpenOptions::default()).unwrap();
6253        assert_eq!(wb2.sheet_names(), vec!["Sheet1"]);
6254        assert_eq!(
6255            wb2.get_cell_value("Sheet1", "A1").unwrap(),
6256            CellValue::String("test".to_string())
6257        );
6258    }
6259
6260    #[test]
6261    fn test_format_inference_from_content_types_overrides() {
6262        use sheetkit_xml::content_types::mime_types;
6263
6264        // Simulate a content_types with xlsm workbook type.
6265        let ct = ContentTypes {
6266            xmlns: "http://schemas.openxmlformats.org/package/2006/content-types".to_string(),
6267            defaults: vec![],
6268            overrides: vec![ContentTypeOverride {
6269                part_name: "/xl/workbook.xml".to_string(),
6270                content_type: mime_types::WORKBOOK_MACRO.to_string(),
6271            }],
6272        };
6273
6274        let detected = ct
6275            .overrides
6276            .iter()
6277            .find(|o| o.part_name == "/xl/workbook.xml")
6278            .and_then(|o| WorkbookFormat::from_content_type(&o.content_type))
6279            .unwrap_or_default();
6280        assert_eq!(detected, WorkbookFormat::Xlsm);
6281    }
6282
6283    #[test]
6284    fn test_workbook_format_default_is_xlsx() {
6285        assert_eq!(WorkbookFormat::default(), WorkbookFormat::Xlsx);
6286    }
6287
6288    fn build_xlsm_with_vba(vba_bytes: &[u8]) -> Vec<u8> {
6289        use std::io::Write;
6290        let mut buf = Vec::new();
6291        {
6292            let cursor = std::io::Cursor::new(&mut buf);
6293            let mut zip = zip::ZipWriter::new(cursor);
6294            let opts = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated);
6295
6296            let ct_xml = format!(
6297                r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
6298<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
6299  <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
6300  <Default Extension="xml" ContentType="application/xml"/>
6301  <Default Extension="bin" ContentType="application/vnd.ms-office.vbaProject"/>
6302  <Override PartName="/xl/workbook.xml" ContentType="{wb_ct}"/>
6303  <Override PartName="/xl/worksheets/sheet1.xml" ContentType="{ws_ct}"/>
6304  <Override PartName="/xl/styles.xml" ContentType="{st_ct}"/>
6305  <Override PartName="/xl/sharedStrings.xml" ContentType="{sst_ct}"/>
6306  <Override PartName="/xl/vbaProject.bin" ContentType="application/vnd.ms-office.vbaProject"/>
6307</Types>"#,
6308                wb_ct = mime_types::WORKBOOK_MACRO,
6309                ws_ct = mime_types::WORKSHEET,
6310                st_ct = mime_types::STYLES,
6311                sst_ct = mime_types::SHARED_STRINGS,
6312            );
6313            zip.start_file("[Content_Types].xml", opts).unwrap();
6314            zip.write_all(ct_xml.as_bytes()).unwrap();
6315
6316            let pkg_rels = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
6317<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
6318  <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>
6319</Relationships>"#;
6320            zip.start_file("_rels/.rels", opts).unwrap();
6321            zip.write_all(pkg_rels.as_bytes()).unwrap();
6322
6323            let wb_rels = format!(
6324                r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
6325<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
6326  <Relationship Id="rId1" Type="{ws_rel}" Target="worksheets/sheet1.xml"/>
6327  <Relationship Id="rId2" Type="{st_rel}" Target="styles.xml"/>
6328  <Relationship Id="rId3" Type="{sst_rel}" Target="sharedStrings.xml"/>
6329  <Relationship Id="rId4" Type="{vba_rel}" Target="vbaProject.bin"/>
6330</Relationships>"#,
6331                ws_rel = rel_types::WORKSHEET,
6332                st_rel = rel_types::STYLES,
6333                sst_rel = rel_types::SHARED_STRINGS,
6334                vba_rel = VBA_PROJECT_REL_TYPE,
6335            );
6336            zip.start_file("xl/_rels/workbook.xml.rels", opts).unwrap();
6337            zip.write_all(wb_rels.as_bytes()).unwrap();
6338
6339            let wb_xml = concat!(
6340                r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>"#,
6341                r#"<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main""#,
6342                r#" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">"#,
6343                r#"<sheets><sheet name="Sheet1" sheetId="1" r:id="rId1"/></sheets>"#,
6344                r#"</workbook>"#,
6345            );
6346            zip.start_file("xl/workbook.xml", opts).unwrap();
6347            zip.write_all(wb_xml.as_bytes()).unwrap();
6348
6349            let ws_xml = concat!(
6350                r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>"#,
6351                r#"<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main""#,
6352                r#" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">"#,
6353                r#"<sheetData/>"#,
6354                r#"</worksheet>"#,
6355            );
6356            zip.start_file("xl/worksheets/sheet1.xml", opts).unwrap();
6357            zip.write_all(ws_xml.as_bytes()).unwrap();
6358
6359            let styles_xml = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
6360<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
6361  <fonts count="1"><font><sz val="11"/><name val="Calibri"/></font></fonts>
6362  <fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills>
6363  <borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>
6364  <cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>
6365  <cellXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/></cellXfs>
6366</styleSheet>"#;
6367            zip.start_file("xl/styles.xml", opts).unwrap();
6368            zip.write_all(styles_xml.as_bytes()).unwrap();
6369
6370            let sst_xml = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
6371<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="0" uniqueCount="0"/>"#;
6372            zip.start_file("xl/sharedStrings.xml", opts).unwrap();
6373            zip.write_all(sst_xml.as_bytes()).unwrap();
6374
6375            zip.start_file("xl/vbaProject.bin", opts).unwrap();
6376            zip.write_all(vba_bytes).unwrap();
6377
6378            zip.finish().unwrap();
6379        }
6380        buf
6381    }
6382
6383    #[test]
6384    fn test_vba_blob_loaded_when_present() {
6385        use crate::workbook::open_options::{AuxParts, OpenOptions, ReadMode};
6386
6387        let vba_data = b"FAKE_VBA_PROJECT_BINARY_DATA_1234567890";
6388        let xlsm = build_xlsm_with_vba(vba_data);
6389        let opts = OpenOptions::new()
6390            .read_mode(ReadMode::Eager)
6391            .aux_parts(AuxParts::EagerLoad);
6392        let wb = Workbook::open_from_buffer_with_options(&xlsm, &opts).unwrap();
6393        assert!(wb.vba_blob.is_some());
6394        assert_eq!(wb.vba_blob.as_deref().unwrap(), vba_data);
6395    }
6396
6397    #[test]
6398    fn lazy_vba_open_applies_exact_and_plus_one_input_limits() {
6399        let vba_data = b"FINITE_VBA_PROJECT";
6400        let xlsm = build_xlsm_with_vba(vba_data);
6401        let exact = crate::vba::VbaLimits {
6402            input_bytes: vba_data.len() as u64,
6403            ..crate::vba::VbaLimits::default()
6404        };
6405        let workbook =
6406            Workbook::open_from_buffer_with_options(&xlsm, &OpenOptions::new().vba_limits(exact))
6407                .unwrap();
6408        assert_eq!(workbook.get_vba_project(), Some(vba_data.as_slice()));
6409
6410        let rejected = crate::vba::VbaLimits {
6411            input_bytes: vba_data.len() as u64 - 1,
6412            ..crate::vba::VbaLimits::default()
6413        };
6414        let error = match Workbook::open_from_buffer_with_options(
6415            &xlsm,
6416            &OpenOptions::new().vba_limits(rejected),
6417        ) {
6418            Ok(_) => panic!("expected VBA input limit"),
6419            Err(error) => error,
6420        };
6421        assert_eq!(
6422            error.resource_metadata().unwrap().dimension(),
6423            crate::resource::ResourceDimension::InputBytes
6424        );
6425    }
6426
6427    #[test]
6428    fn macro_free_target_strips_vba_without_mutating_source() {
6429        let vba_data = b"VALIDATED_VBA_PROJECT";
6430        let source = build_xlsm_with_vba(vba_data);
6431        let workbook = Workbook::open_from_buffer(&source).unwrap();
6432        let directory = TempDir::new().unwrap();
6433        let xlsx_path = directory.path().join("converted.xlsx");
6434        let xlsm_path = directory.path().join("preserved.xlsm");
6435
6436        workbook.save(&xlsx_path).unwrap();
6437        let mut xlsx = zip::ZipArchive::new(std::fs::File::open(&xlsx_path).unwrap()).unwrap();
6438        assert!(xlsx.by_name("xl/vbaProject.bin").is_err());
6439        let content_types: ContentTypes = read_xml_part(&mut xlsx, "[Content_Types].xml").unwrap();
6440        assert!(content_types
6441            .overrides
6442            .iter()
6443            .all(|entry| entry.content_type != VBA_PROJECT_CONTENT_TYPE));
6444        let relationships: Relationships =
6445            read_xml_part(&mut xlsx, "xl/_rels/workbook.xml.rels").unwrap();
6446        assert!(relationships
6447            .relationships
6448            .iter()
6449            .all(|entry| entry.rel_type != VBA_PROJECT_REL_TYPE));
6450        drop(xlsx);
6451
6452        workbook.save(&xlsm_path).unwrap();
6453        let mut xlsm = zip::ZipArchive::new(std::fs::File::open(&xlsm_path).unwrap()).unwrap();
6454        let mut preserved = Vec::new();
6455        xlsm.by_name("xl/vbaProject.bin")
6456            .unwrap()
6457            .read_to_end(&mut preserved)
6458            .unwrap();
6459        assert_eq!(preserved, vba_data);
6460    }
6461
6462    #[cfg(feature = "encryption")]
6463    #[test]
6464    fn encrypted_save_infers_target_format_for_vba_filtering() {
6465        let password = "bounded-password";
6466        let vba_data = b"ENCRYPTED_VBA_PROJECT";
6467        let workbook = Workbook::open_from_buffer(&build_xlsm_with_vba(vba_data)).unwrap();
6468        let directory = TempDir::new().unwrap();
6469
6470        for (extension, preserves_vba) in [("xlsx", false), ("xlsm", true)] {
6471            let path = directory.path().join(format!("encrypted.{extension}"));
6472            workbook.save_with_password(&path, password).unwrap();
6473            let encrypted = std::fs::read(path).unwrap();
6474            let decrypted = crate::crypt::decrypt_xlsx(&encrypted, password).unwrap();
6475            let mut archive = zip::ZipArchive::new(std::io::Cursor::new(decrypted)).unwrap();
6476            assert_eq!(archive.by_name("xl/vbaProject.bin").is_ok(), preserves_vba);
6477        }
6478    }
6479
6480    #[cfg(feature = "encryption")]
6481    #[test]
6482    fn encrypted_save_limits_accept_exact_package_and_reject_plus_one() {
6483        let workbook = Workbook::new();
6484        let directory = TempDir::new().unwrap();
6485        let baseline_path = directory.path().join("baseline.xlsx");
6486        let exact_path = directory.path().join("exact.xlsx");
6487        let rejected_path = directory.path().join("rejected.xlsx");
6488        workbook
6489            .save_with_password(&baseline_path, "password")
6490            .unwrap();
6491        let baseline = std::fs::read(&baseline_path).unwrap();
6492        let compound = cfb::CompoundFile::open(std::io::Cursor::new(baseline)).unwrap();
6493        let package_limit = compound.entry("/EncryptedPackage").unwrap().len();
6494
6495        workbook
6496            .save_with_password_with_limits(
6497                &exact_path,
6498                "password",
6499                crate::crypt::CryptLimits {
6500                    encrypted_package_bytes: package_limit,
6501                    ..crate::crypt::CryptLimits::default()
6502                },
6503            )
6504            .unwrap();
6505        let error = workbook
6506            .save_with_password_with_limits(
6507                &rejected_path,
6508                "password",
6509                crate::crypt::CryptLimits {
6510                    encrypted_package_bytes: package_limit - 1,
6511                    ..crate::crypt::CryptLimits::default()
6512                },
6513            )
6514            .unwrap_err();
6515        let metadata = error.resource_metadata().expect("resource metadata");
6516        assert_eq!(metadata.operation(), crate::ResourceOperation::Encrypt);
6517        assert_eq!(metadata.dimension(), crate::ResourceDimension::InputBytes);
6518        assert_eq!(metadata.limit(), package_limit - 1);
6519        assert_eq!(metadata.observed(), package_limit);
6520        assert!(!rejected_path.exists());
6521    }
6522
6523    #[test]
6524    fn failed_atomic_xlsx_stage_preserves_destination_and_workbook() {
6525        let vba_data = b"REUSABLE_VBA_PROJECT";
6526        let workbook = Workbook::open_from_buffer(&build_xlsm_with_vba(vba_data)).unwrap();
6527        let directory = TempDir::new().unwrap();
6528        let destination = directory.path().join("existing.xlsx");
6529        let later = directory.path().join("later.xlsm");
6530        let original = b"existing destination bytes";
6531        std::fs::write(&destination, original).unwrap();
6532
6533        let error = atomic_write_file(&destination, crate::save::SaveOptions::default(), |file| {
6534            let mut zip = zip::ZipWriter::new(file);
6535            let options =
6536                SimpleFileOptions::default().compression_method(CompressionMethod::Deflated);
6537            workbook.write_zip_contents(
6538                &mut zip,
6539                options,
6540                Some(WorkbookFormat::Xlsx),
6541                crate::save::SaveLimits::default(),
6542            )?;
6543            zip.finish()
6544                .map_err(|error| Error::Zip(error.to_string()))?;
6545            Err(Error::Internal(
6546                "injected before atomic replace".to_string(),
6547            ))
6548        })
6549        .unwrap_err();
6550        assert!(matches!(error, Error::Internal(_)));
6551        assert_eq!(std::fs::read(&destination).unwrap(), original);
6552        assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 1);
6553
6554        workbook.save(&later).unwrap();
6555        let mut archive = zip::ZipArchive::new(std::fs::File::open(later).unwrap()).unwrap();
6556        let mut preserved = Vec::new();
6557        archive
6558            .by_name("xl/vbaProject.bin")
6559            .unwrap()
6560            .read_to_end(&mut preserved)
6561            .unwrap();
6562        assert_eq!(preserved, vba_data);
6563    }
6564
6565    const DURABLE: crate::save::SaveOptions = crate::save::SaveOptions { durable: true };
6566
6567    fn sheetkit_temporaries(directory: &Path) -> Vec<String> {
6568        std::fs::read_dir(directory)
6569            .unwrap()
6570            .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
6571            .filter(|name| name.starts_with(".sheetkit-"))
6572            .collect()
6573    }
6574
6575    fn take_sync_calls() -> Vec<&'static str> {
6576        SYNC_CALLS.with(|calls| std::mem::take(&mut *calls.borrow_mut()))
6577    }
6578
6579    fn expected_durable_syncs() -> Vec<&'static str> {
6580        if cfg!(unix) {
6581            vec!["file", "dir"]
6582        } else {
6583            vec!["file"]
6584        }
6585    }
6586
6587    #[test]
6588    fn default_save_requests_neither_file_nor_directory_sync() {
6589        let directory = TempDir::new().unwrap();
6590        let destination = directory.path().join("existing.xlsx");
6591        std::fs::write(&destination, b"old contents").unwrap();
6592
6593        atomic_write_file_with_sync(
6594            &destination,
6595            crate::save::SaveOptions::default(),
6596            |file| {
6597                file.write_all(b"new contents")?;
6598                Ok(())
6599            },
6600            |_| panic!("default save must not sync the file"),
6601            |_| panic!("default save must not sync the directory"),
6602        )
6603        .unwrap();
6604
6605        assert_eq!(std::fs::read(&destination).unwrap(), b"new contents");
6606        assert!(sheetkit_temporaries(directory.path()).is_empty());
6607    }
6608
6609    #[test]
6610    fn durable_save_syncs_file_before_rename_and_directory_after() {
6611        let directory = TempDir::new().unwrap();
6612        let destination = directory.path().join("existing.xlsx");
6613        std::fs::write(&destination, b"old contents").unwrap();
6614        let events = std::cell::RefCell::new(Vec::new());
6615
6616        atomic_write_file_with_sync(
6617            &destination,
6618            DURABLE,
6619            |file| {
6620                file.write_all(b"new contents")?;
6621                Ok(())
6622            },
6623            |_| {
6624                let current = std::fs::read(&destination).unwrap();
6625                events.borrow_mut().push(("file", current));
6626                Ok(())
6627            },
6628            |parent| {
6629                assert_eq!(parent, directory.path());
6630                let current = std::fs::read(&destination).unwrap();
6631                events.borrow_mut().push(("dir", current));
6632                Ok(())
6633            },
6634        )
6635        .unwrap();
6636
6637        assert_eq!(
6638            events.into_inner(),
6639            vec![
6640                ("file", b"old contents".to_vec()),
6641                ("dir", b"new contents".to_vec()),
6642            ]
6643        );
6644    }
6645
6646    #[test]
6647    fn durable_directory_sync_failure_is_reported_after_replacement() {
6648        let directory = TempDir::new().unwrap();
6649        let destination = directory.path().join("existing.xlsx");
6650        std::fs::write(&destination, b"old contents").unwrap();
6651
6652        let error = atomic_write_file_with_sync(
6653            &destination,
6654            DURABLE,
6655            |file| {
6656                file.write_all(b"new contents")?;
6657                Ok(())
6658            },
6659            |_| Ok(()),
6660            |_| {
6661                Err(std::io::Error::new(
6662                    std::io::ErrorKind::PermissionDenied,
6663                    "injected directory sync failure",
6664                ))
6665            },
6666        )
6667        .unwrap_err();
6668
6669        let Error::Io(io_error) = &error else {
6670            panic!("expected an I/O error, got {error:?}");
6671        };
6672        assert_eq!(io_error.kind(), std::io::ErrorKind::PermissionDenied);
6673        let message = error.to_string();
6674        assert!(
6675            message.contains(&format!("workbook saved to {}", destination.display())),
6676            "{message}"
6677        );
6678        assert!(message.contains("syncing the parent directory failed"));
6679        assert!(message.contains("injected directory sync failure"));
6680        assert!(message.contains("the new file may not survive a crash"));
6681        assert_eq!(std::fs::read(&destination).unwrap(), b"new contents");
6682        assert!(sheetkit_temporaries(directory.path()).is_empty());
6683    }
6684
6685    #[test]
6686    fn durable_file_sync_failure_preserves_destination() {
6687        let directory = TempDir::new().unwrap();
6688        let destination = directory.path().join("existing.xlsx");
6689        std::fs::write(&destination, b"old contents").unwrap();
6690
6691        let error = atomic_write_file_with_sync(
6692            &destination,
6693            DURABLE,
6694            |file| {
6695                file.write_all(b"new contents")?;
6696                Ok(())
6697            },
6698            |_| Err(std::io::Error::other("injected file sync failure")),
6699            |_| panic!("directory sync must not run after a failed file sync"),
6700        )
6701        .unwrap_err();
6702
6703        assert!(matches!(error, Error::Io(_)));
6704        assert_eq!(std::fs::read(&destination).unwrap(), b"old contents");
6705        assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 1);
6706    }
6707
6708    #[test]
6709    fn write_failure_preserves_destination_in_both_modes() {
6710        for options in [crate::save::SaveOptions::default(), DURABLE] {
6711            let directory = TempDir::new().unwrap();
6712            let destination = directory.path().join("existing.xlsx");
6713            std::fs::write(&destination, b"old contents").unwrap();
6714
6715            let error = atomic_write_file_with_sync(
6716                &destination,
6717                options,
6718                |file| {
6719                    file.write_all(b"partial")?;
6720                    Err(std::io::Error::other("injected write failure").into())
6721                },
6722                |_| panic!("file sync must not run after a failed write"),
6723                |_| panic!("directory sync must not run after a failed write"),
6724            )
6725            .unwrap_err();
6726
6727            assert!(matches!(error, Error::Io(_)));
6728            assert_eq!(std::fs::read(&destination).unwrap(), b"old contents");
6729            assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 1);
6730        }
6731    }
6732
6733    #[test]
6734    fn public_save_apis_apply_save_options() {
6735        let directory = TempDir::new().unwrap();
6736        let path = directory.path().join("book.xlsx");
6737        let workbook = Workbook::new();
6738        take_sync_calls();
6739
6740        workbook.save(&path).unwrap();
6741        assert!(take_sync_calls().is_empty());
6742        workbook
6743            .save_with_limits(&path, crate::save::SaveLimits::default())
6744            .unwrap();
6745        assert!(take_sync_calls().is_empty());
6746        workbook
6747            .save_with_options(
6748                &path,
6749                crate::save::SaveLimits::default(),
6750                crate::save::SaveOptions::default(),
6751            )
6752            .unwrap();
6753        assert!(take_sync_calls().is_empty());
6754
6755        workbook
6756            .save_with_options(&path, crate::save::SaveLimits::default(), DURABLE)
6757            .unwrap();
6758        assert_eq!(take_sync_calls(), expected_durable_syncs());
6759        Workbook::open(&path).unwrap();
6760    }
6761
6762    #[cfg(feature = "encryption")]
6763    #[test]
6764    fn encrypted_save_applies_save_options() {
6765        let directory = TempDir::new().unwrap();
6766        let path = directory.path().join("secret.xlsx");
6767        let mut workbook = Workbook::new();
6768        workbook
6769            .set_cell_value("Sheet1", "A1", CellValue::String("hidden".into()))
6770            .unwrap();
6771        take_sync_calls();
6772
6773        workbook.save_with_password(&path, "pw").unwrap();
6774        assert!(take_sync_calls().is_empty());
6775
6776        workbook
6777            .save_with_password_with_options(
6778                &path,
6779                "pw",
6780                crate::crypt::CryptLimits::default(),
6781                crate::save::SaveLimits::default(),
6782                DURABLE,
6783            )
6784            .unwrap();
6785        assert_eq!(take_sync_calls(), expected_durable_syncs());
6786        let reopened = Workbook::open_with_password(&path, "pw").unwrap();
6787        assert_eq!(
6788            reopened.get_cell_value("Sheet1", "A1").unwrap(),
6789            CellValue::String("hidden".into())
6790        );
6791    }
6792
6793    #[test]
6794    fn test_vba_blob_none_for_plain_xlsx() {
6795        let wb = Workbook::new();
6796        assert!(wb.vba_blob.is_none());
6797
6798        let buf = wb.save_to_buffer().unwrap();
6799        let wb2 = Workbook::open_from_buffer(&buf).unwrap();
6800        assert!(wb2.vba_blob.is_none());
6801    }
6802
6803    #[test]
6804    fn test_vba_blob_survives_roundtrip_with_identical_bytes() {
6805        use crate::workbook::open_options::{AuxParts, OpenOptions, ReadMode};
6806
6807        let vba_data: Vec<u8> = (0..=255).cycle().take(1024).collect();
6808        let xlsm = build_xlsm_with_vba(&vba_data);
6809
6810        let opts = OpenOptions::new()
6811            .read_mode(ReadMode::Eager)
6812            .aux_parts(AuxParts::EagerLoad);
6813        let wb = Workbook::open_from_buffer_with_options(&xlsm, &opts).unwrap();
6814        assert_eq!(wb.vba_blob.as_deref().unwrap(), &vba_data[..]);
6815
6816        let saved = wb.save_to_buffer().unwrap();
6817        let cursor = std::io::Cursor::new(&saved);
6818        let mut archive = zip::ZipArchive::new(cursor).unwrap();
6819
6820        let mut roundtripped = Vec::new();
6821        std::io::Read::read_to_end(
6822            &mut archive.by_name("xl/vbaProject.bin").unwrap(),
6823            &mut roundtripped,
6824        )
6825        .unwrap();
6826        assert_eq!(roundtripped, vba_data);
6827    }
6828
6829    #[test]
6830    fn test_vba_relationship_preserved_on_roundtrip() {
6831        let vba_data = b"VBA_BLOB";
6832        let xlsm = build_xlsm_with_vba(vba_data);
6833
6834        let wb = Workbook::open_from_buffer(&xlsm).unwrap();
6835        let saved = wb.save_to_buffer().unwrap();
6836
6837        let cursor = std::io::Cursor::new(&saved);
6838        let mut archive = zip::ZipArchive::new(cursor).unwrap();
6839
6840        let rels: Relationships =
6841            read_xml_part(&mut archive, "xl/_rels/workbook.xml.rels").unwrap();
6842        let vba_rel = rels
6843            .relationships
6844            .iter()
6845            .find(|r| r.rel_type == VBA_PROJECT_REL_TYPE);
6846        assert!(vba_rel.is_some(), "VBA relationship must be preserved");
6847        assert_eq!(vba_rel.unwrap().target, "vbaProject.bin");
6848    }
6849
6850    #[test]
6851    fn test_vba_content_type_preserved_on_roundtrip() {
6852        let vba_data = b"VBA_BLOB";
6853        let xlsm = build_xlsm_with_vba(vba_data);
6854
6855        let wb = Workbook::open_from_buffer(&xlsm).unwrap();
6856        let saved = wb.save_to_buffer().unwrap();
6857
6858        let cursor = std::io::Cursor::new(&saved);
6859        let mut archive = zip::ZipArchive::new(cursor).unwrap();
6860
6861        let ct: ContentTypes = read_xml_part(&mut archive, "[Content_Types].xml").unwrap();
6862        let vba_override = ct
6863            .overrides
6864            .iter()
6865            .find(|o| o.part_name == "/xl/vbaProject.bin");
6866        assert!(
6867            vba_override.is_some(),
6868            "VBA content type override must be preserved"
6869        );
6870        assert_eq!(vba_override.unwrap().content_type, VBA_PROJECT_CONTENT_TYPE);
6871    }
6872
6873    #[test]
6874    fn test_non_vba_save_has_no_vba_entries() {
6875        let wb = Workbook::new();
6876        let buf = wb.save_to_buffer().unwrap();
6877
6878        let cursor = std::io::Cursor::new(&buf);
6879        let mut archive = zip::ZipArchive::new(cursor).unwrap();
6880
6881        assert!(
6882            archive.by_name("xl/vbaProject.bin").is_err(),
6883            "plain xlsx must not contain vbaProject.bin"
6884        );
6885
6886        let rels: Relationships =
6887            read_xml_part(&mut archive, "xl/_rels/workbook.xml.rels").unwrap();
6888        assert!(
6889            !rels
6890                .relationships
6891                .iter()
6892                .any(|r| r.rel_type == VBA_PROJECT_REL_TYPE),
6893            "plain xlsx must not have VBA relationship"
6894        );
6895
6896        let ct: ContentTypes = read_xml_part(&mut archive, "[Content_Types].xml").unwrap();
6897        assert!(
6898            !ct.overrides
6899                .iter()
6900                .any(|o| o.content_type == VBA_PROJECT_CONTENT_TYPE),
6901            "plain xlsx must not have VBA content type override"
6902        );
6903    }
6904
6905    #[test]
6906    fn test_xlsm_format_detected_with_vba() {
6907        let vba_data = b"VBA_BLOB";
6908        let xlsm = build_xlsm_with_vba(vba_data);
6909        let wb = Workbook::open_from_buffer(&xlsm).unwrap();
6910        assert_eq!(wb.format(), WorkbookFormat::Xlsm);
6911    }
6912
6913    #[test]
6914    fn test_from_extension_recognized() {
6915        assert_eq!(
6916            WorkbookFormat::from_extension("xlsx"),
6917            Some(WorkbookFormat::Xlsx)
6918        );
6919        assert_eq!(
6920            WorkbookFormat::from_extension("xlsm"),
6921            Some(WorkbookFormat::Xlsm)
6922        );
6923        assert_eq!(
6924            WorkbookFormat::from_extension("xltx"),
6925            Some(WorkbookFormat::Xltx)
6926        );
6927        assert_eq!(
6928            WorkbookFormat::from_extension("xltm"),
6929            Some(WorkbookFormat::Xltm)
6930        );
6931        assert_eq!(
6932            WorkbookFormat::from_extension("xlam"),
6933            Some(WorkbookFormat::Xlam)
6934        );
6935    }
6936
6937    #[test]
6938    fn test_from_extension_case_insensitive() {
6939        assert_eq!(
6940            WorkbookFormat::from_extension("XLSX"),
6941            Some(WorkbookFormat::Xlsx)
6942        );
6943        assert_eq!(
6944            WorkbookFormat::from_extension("Xlsm"),
6945            Some(WorkbookFormat::Xlsm)
6946        );
6947        assert_eq!(
6948            WorkbookFormat::from_extension("XLTX"),
6949            Some(WorkbookFormat::Xltx)
6950        );
6951    }
6952
6953    #[test]
6954    fn test_from_extension_unrecognized() {
6955        assert_eq!(WorkbookFormat::from_extension("csv"), None);
6956        assert_eq!(WorkbookFormat::from_extension("xls"), None);
6957        assert_eq!(WorkbookFormat::from_extension("txt"), None);
6958        assert_eq!(WorkbookFormat::from_extension("pdf"), None);
6959        assert_eq!(WorkbookFormat::from_extension(""), None);
6960    }
6961
6962    #[test]
6963    fn test_save_unsupported_extension_csv() {
6964        let dir = TempDir::new().unwrap();
6965        let path = dir.path().join("output.csv");
6966        let wb = Workbook::new();
6967        let result = wb.save(&path);
6968        assert!(matches!(result, Err(Error::UnsupportedFileExtension(ext)) if ext == "csv"));
6969    }
6970
6971    #[test]
6972    fn test_save_unsupported_extension_xls() {
6973        let dir = TempDir::new().unwrap();
6974        let path = dir.path().join("output.xls");
6975        let wb = Workbook::new();
6976        let result = wb.save(&path);
6977        assert!(matches!(result, Err(Error::UnsupportedFileExtension(ext)) if ext == "xls"));
6978    }
6979
6980    #[test]
6981    fn test_save_unsupported_extension_unknown() {
6982        let dir = TempDir::new().unwrap();
6983        let path = dir.path().join("output.foo");
6984        let wb = Workbook::new();
6985        let result = wb.save(&path);
6986        assert!(matches!(result, Err(Error::UnsupportedFileExtension(ext)) if ext == "foo"));
6987    }
6988
6989    #[test]
6990    fn test_save_no_extension_fails() {
6991        let dir = TempDir::new().unwrap();
6992        let path = dir.path().join("noext");
6993        let wb = Workbook::new();
6994        let result = wb.save(&path);
6995        assert!(matches!(
6996            result,
6997            Err(Error::UnsupportedFileExtension(ext)) if ext.is_empty()
6998        ));
6999    }
7000
7001    #[test]
7002    fn test_save_as_xlsm_writes_xlsm_content_type() {
7003        let dir = TempDir::new().unwrap();
7004        let path = dir.path().join("output.xlsm");
7005        let wb = Workbook::new();
7006        wb.save(&path).unwrap();
7007
7008        let file = std::fs::File::open(&path).unwrap();
7009        let mut archive = zip::ZipArchive::new(file).unwrap();
7010        let ct: ContentTypes = read_xml_part(&mut archive, "[Content_Types].xml").unwrap();
7011        let wb_ct = ct
7012            .overrides
7013            .iter()
7014            .find(|o| o.part_name == "/xl/workbook.xml")
7015            .expect("workbook override must exist");
7016        assert_eq!(wb_ct.content_type, WorkbookFormat::Xlsm.content_type());
7017    }
7018
7019    #[test]
7020    fn test_save_as_xltx_writes_template_content_type() {
7021        let dir = TempDir::new().unwrap();
7022        let path = dir.path().join("output.xltx");
7023        let wb = Workbook::new();
7024        wb.save(&path).unwrap();
7025
7026        let file = std::fs::File::open(&path).unwrap();
7027        let mut archive = zip::ZipArchive::new(file).unwrap();
7028        let ct: ContentTypes = read_xml_part(&mut archive, "[Content_Types].xml").unwrap();
7029        let wb_ct = ct
7030            .overrides
7031            .iter()
7032            .find(|o| o.part_name == "/xl/workbook.xml")
7033            .expect("workbook override must exist");
7034        assert_eq!(wb_ct.content_type, WorkbookFormat::Xltx.content_type());
7035    }
7036
7037    #[test]
7038    fn test_save_as_xltm_writes_template_macro_content_type() {
7039        let dir = TempDir::new().unwrap();
7040        let path = dir.path().join("output.xltm");
7041        let wb = Workbook::new();
7042        wb.save(&path).unwrap();
7043
7044        let file = std::fs::File::open(&path).unwrap();
7045        let mut archive = zip::ZipArchive::new(file).unwrap();
7046        let ct: ContentTypes = read_xml_part(&mut archive, "[Content_Types].xml").unwrap();
7047        let wb_ct = ct
7048            .overrides
7049            .iter()
7050            .find(|o| o.part_name == "/xl/workbook.xml")
7051            .expect("workbook override must exist");
7052        assert_eq!(wb_ct.content_type, WorkbookFormat::Xltm.content_type());
7053    }
7054
7055    #[test]
7056    fn test_save_as_xlam_writes_addin_content_type() {
7057        let dir = TempDir::new().unwrap();
7058        let path = dir.path().join("output.xlam");
7059        let wb = Workbook::new();
7060        wb.save(&path).unwrap();
7061
7062        let file = std::fs::File::open(&path).unwrap();
7063        let mut archive = zip::ZipArchive::new(file).unwrap();
7064        let ct: ContentTypes = read_xml_part(&mut archive, "[Content_Types].xml").unwrap();
7065        let wb_ct = ct
7066            .overrides
7067            .iter()
7068            .find(|o| o.part_name == "/xl/workbook.xml")
7069            .expect("workbook override must exist");
7070        assert_eq!(wb_ct.content_type, WorkbookFormat::Xlam.content_type());
7071    }
7072
7073    #[test]
7074    fn test_save_extension_overrides_stored_format() {
7075        let dir = TempDir::new().unwrap();
7076        let path = dir.path().join("output.xlsm");
7077
7078        // Workbook has Xlsx format stored, but saved as .xlsm
7079        let wb = Workbook::new();
7080        assert_eq!(wb.format(), WorkbookFormat::Xlsx);
7081        wb.save(&path).unwrap();
7082
7083        let file = std::fs::File::open(&path).unwrap();
7084        let mut archive = zip::ZipArchive::new(file).unwrap();
7085        let ct: ContentTypes = read_xml_part(&mut archive, "[Content_Types].xml").unwrap();
7086        let wb_ct = ct
7087            .overrides
7088            .iter()
7089            .find(|o| o.part_name == "/xl/workbook.xml")
7090            .expect("workbook override must exist");
7091        assert_eq!(
7092            wb_ct.content_type,
7093            WorkbookFormat::Xlsm.content_type(),
7094            "extension .xlsm must override stored Xlsx format"
7095        );
7096    }
7097
7098    #[test]
7099    fn test_save_to_buffer_preserves_stored_format() {
7100        let mut wb = Workbook::new();
7101        wb.set_format(WorkbookFormat::Xltx);
7102
7103        let buf = wb.save_to_buffer().unwrap();
7104        let wb2 = Workbook::open_from_buffer(&buf).unwrap();
7105        assert_eq!(
7106            wb2.format(),
7107            WorkbookFormat::Xltx,
7108            "save_to_buffer must use the stored format, not infer from extension"
7109        );
7110    }
7111
7112    #[test]
7113    fn test_sheet_rows_limits_rows_read() {
7114        let dir = TempDir::new().unwrap();
7115        let path = dir.path().join("sheet_rows.xlsx");
7116
7117        let mut wb = Workbook::new();
7118        for i in 1..=20 {
7119            let cell = format!("A{}", i);
7120            wb.set_cell_value("Sheet1", &cell, CellValue::Number(i as f64))
7121                .unwrap();
7122        }
7123        wb.save(&path).unwrap();
7124
7125        let opts = OpenOptions::new().sheet_rows(5);
7126        let wb2 = Workbook::open_with_options(&path, &opts).unwrap();
7127
7128        // First 5 rows should be present
7129        for i in 1..=5 {
7130            let cell = format!("A{}", i);
7131            assert_eq!(
7132                wb2.get_cell_value("Sheet1", &cell).unwrap(),
7133                CellValue::Number(i as f64)
7134            );
7135        }
7136
7137        // Rows 6+ should return Empty
7138        for i in 6..=20 {
7139            let cell = format!("A{}", i);
7140            assert_eq!(
7141                wb2.get_cell_value("Sheet1", &cell).unwrap(),
7142                CellValue::Empty
7143            );
7144        }
7145    }
7146
7147    #[test]
7148    fn test_sheet_rows_with_buffer() {
7149        let mut wb = Workbook::new();
7150        for i in 1..=10 {
7151            let cell = format!("A{}", i);
7152            wb.set_cell_value("Sheet1", &cell, CellValue::Number(i as f64))
7153                .unwrap();
7154        }
7155        let buf = wb.save_to_buffer().unwrap();
7156
7157        let opts = OpenOptions::new().sheet_rows(3);
7158        let wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
7159
7160        assert_eq!(
7161            wb2.get_cell_value("Sheet1", "A3").unwrap(),
7162            CellValue::Number(3.0)
7163        );
7164        assert_eq!(
7165            wb2.get_cell_value("Sheet1", "A4").unwrap(),
7166            CellValue::Empty
7167        );
7168    }
7169
7170    #[test]
7171    fn test_save_xlsx_preserves_existing_behavior() {
7172        let dir = TempDir::new().unwrap();
7173        let path = dir.path().join("preserved.xlsx");
7174
7175        let mut wb = Workbook::new();
7176        wb.set_cell_value("Sheet1", "A1", CellValue::String("hello".to_string()))
7177            .unwrap();
7178        wb.save(&path).unwrap();
7179
7180        let wb2 = Workbook::open(&path).unwrap();
7181        assert_eq!(wb2.format(), WorkbookFormat::Xlsx);
7182        assert_eq!(wb2.sheet_names(), vec!["Sheet1"]);
7183        assert_eq!(
7184            wb2.get_cell_value("Sheet1", "A1").unwrap(),
7185            CellValue::String("hello".to_string())
7186        );
7187    }
7188
7189    #[test]
7190    fn test_selective_sheet_parsing() {
7191        let dir = TempDir::new().unwrap();
7192        let path = dir.path().join("selective.xlsx");
7193
7194        let mut wb = Workbook::new();
7195        wb.new_sheet("Sales").unwrap();
7196        wb.new_sheet("Data").unwrap();
7197        wb.set_cell_value("Sheet1", "A1", CellValue::String("Sheet1 data".to_string()))
7198            .unwrap();
7199        wb.set_cell_value("Sales", "A1", CellValue::String("Sales data".to_string()))
7200            .unwrap();
7201        wb.set_cell_value("Data", "A1", CellValue::String("Data data".to_string()))
7202            .unwrap();
7203        wb.save(&path).unwrap();
7204
7205        let opts = OpenOptions::new().sheets(vec!["Sales".to_string()]);
7206        let wb2 = Workbook::open_with_options(&path, &opts).unwrap();
7207
7208        // All sheets exist in the workbook
7209        assert_eq!(wb2.sheet_names(), vec!["Sheet1", "Sales", "Data"]);
7210
7211        // Only Sales should have data
7212        assert_eq!(
7213            wb2.get_cell_value("Sales", "A1").unwrap(),
7214            CellValue::String("Sales data".to_string())
7215        );
7216
7217        // Sheet1 and Data were not parsed, so they should be empty
7218        assert_eq!(
7219            wb2.get_cell_value("Sheet1", "A1").unwrap(),
7220            CellValue::Empty
7221        );
7222        assert_eq!(wb2.get_cell_value("Data", "A1").unwrap(), CellValue::Empty);
7223    }
7224
7225    #[test]
7226    fn test_selective_sheets_multiple() {
7227        let mut wb = Workbook::new();
7228        wb.new_sheet("Alpha").unwrap();
7229        wb.new_sheet("Beta").unwrap();
7230        wb.set_cell_value("Sheet1", "A1", CellValue::Number(1.0))
7231            .unwrap();
7232        wb.set_cell_value("Alpha", "A1", CellValue::Number(2.0))
7233            .unwrap();
7234        wb.set_cell_value("Beta", "A1", CellValue::Number(3.0))
7235            .unwrap();
7236        let buf = wb.save_to_buffer().unwrap();
7237
7238        let opts = OpenOptions::new().sheets(vec!["Sheet1".to_string(), "Beta".to_string()]);
7239        let wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
7240
7241        assert_eq!(
7242            wb2.get_cell_value("Sheet1", "A1").unwrap(),
7243            CellValue::Number(1.0)
7244        );
7245        assert_eq!(wb2.get_cell_value("Alpha", "A1").unwrap(), CellValue::Empty);
7246        assert_eq!(
7247            wb2.get_cell_value("Beta", "A1").unwrap(),
7248            CellValue::Number(3.0)
7249        );
7250    }
7251
7252    #[test]
7253    fn test_save_does_not_mutate_stored_format() {
7254        let dir = TempDir::new().unwrap();
7255        let path = dir.path().join("test.xlsm");
7256        let wb = Workbook::new();
7257        assert_eq!(wb.format(), WorkbookFormat::Xlsx);
7258        wb.save(&path).unwrap();
7259        // The save call takes &self, so the stored format is unchanged.
7260        assert_eq!(wb.format(), WorkbookFormat::Xlsx);
7261    }
7262
7263    #[test]
7264    fn test_max_zip_entries_exceeded() {
7265        let wb = Workbook::new();
7266        let buf = wb.save_to_buffer().unwrap();
7267
7268        // A basic workbook has at least 8 ZIP entries -- set limit to 2
7269        let opts = OpenOptions::new().max_zip_entries(2);
7270        let result = Workbook::open_from_buffer_with_options(&buf, &opts);
7271        let Err(Error::ResourceLimitExceeded(metadata)) = result else {
7272            panic!("expected an entry count resource error");
7273        };
7274        assert_eq!(metadata.dimension(), crate::ResourceDimension::EntryCount);
7275    }
7276
7277    #[test]
7278    fn test_max_zip_entries_within_limit() {
7279        let wb = Workbook::new();
7280        let buf = wb.save_to_buffer().unwrap();
7281
7282        let opts = OpenOptions::new().max_zip_entries(1000);
7283        let wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
7284        assert_eq!(wb2.sheet_names(), vec!["Sheet1"]);
7285    }
7286
7287    #[test]
7288    fn test_max_unzip_size_exceeded() {
7289        let mut wb = Workbook::new();
7290        // Write enough data so the decompressed size is non-trivial
7291        for i in 1..=100 {
7292            let cell = format!("A{}", i);
7293            wb.set_cell_value(
7294                "Sheet1",
7295                &cell,
7296                CellValue::String("long_value_for_size_check".repeat(10)),
7297            )
7298            .unwrap();
7299        }
7300        let buf = wb.save_to_buffer().unwrap();
7301
7302        // Set a very small decompressed size limit
7303        let opts = OpenOptions::new().max_unzip_size(100);
7304        let result = Workbook::open_from_buffer_with_options(&buf, &opts);
7305        let Err(Error::ResourceLimitExceeded(metadata)) = result else {
7306            panic!("expected an aggregate declared bytes resource error");
7307        };
7308        assert_eq!(
7309            metadata.dimension(),
7310            crate::ResourceDimension::AggregateDeclaredBytes
7311        );
7312    }
7313
7314    #[test]
7315    fn test_max_unzip_size_within_limit() {
7316        let wb = Workbook::new();
7317        let buf = wb.save_to_buffer().unwrap();
7318
7319        let opts = OpenOptions::new().max_unzip_size(1_000_000_000);
7320        let wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
7321        assert_eq!(wb2.sheet_names(), vec!["Sheet1"]);
7322    }
7323
7324    #[test]
7325    fn test_combined_options() {
7326        let mut wb = Workbook::new();
7327        wb.new_sheet("Parsed").unwrap();
7328        wb.new_sheet("Skipped").unwrap();
7329        for i in 1..=10 {
7330            let cell = format!("A{}", i);
7331            wb.set_cell_value("Parsed", &cell, CellValue::Number(i as f64))
7332                .unwrap();
7333            wb.set_cell_value("Skipped", &cell, CellValue::Number(i as f64))
7334                .unwrap();
7335        }
7336        let buf = wb.save_to_buffer().unwrap();
7337
7338        let opts = OpenOptions::new()
7339            .sheets(vec!["Parsed".to_string()])
7340            .sheet_rows(3);
7341        let wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
7342
7343        // Parsed sheet has only 3 rows
7344        assert_eq!(
7345            wb2.get_cell_value("Parsed", "A3").unwrap(),
7346            CellValue::Number(3.0)
7347        );
7348        assert_eq!(
7349            wb2.get_cell_value("Parsed", "A4").unwrap(),
7350            CellValue::Empty
7351        );
7352
7353        // Skipped sheet is empty
7354        assert_eq!(
7355            wb2.get_cell_value("Skipped", "A1").unwrap(),
7356            CellValue::Empty
7357        );
7358    }
7359
7360    #[test]
7361    fn test_sheet_rows_zero_means_no_rows() {
7362        let mut wb = Workbook::new();
7363        wb.set_cell_value("Sheet1", "A1", CellValue::Number(1.0))
7364            .unwrap();
7365        let buf = wb.save_to_buffer().unwrap();
7366
7367        let opts = OpenOptions::new().sheet_rows(0);
7368        let wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
7369        assert_eq!(
7370            wb2.get_cell_value("Sheet1", "A1").unwrap(),
7371            CellValue::Empty
7372        );
7373    }
7374
7375    #[test]
7376    fn test_selective_sheet_parsing_preserves_unparsed_sheets_on_save() {
7377        let dir = TempDir::new().unwrap();
7378        let path1 = dir.path().join("original.xlsx");
7379        let path2 = dir.path().join("resaved.xlsx");
7380
7381        // Create a workbook with 3 sheets, each with distinct data.
7382        let mut wb = Workbook::new();
7383        wb.new_sheet("Sales").unwrap();
7384        wb.new_sheet("Data").unwrap();
7385        wb.set_cell_value(
7386            "Sheet1",
7387            "A1",
7388            CellValue::String("Sheet1 value".to_string()),
7389        )
7390        .unwrap();
7391        wb.set_cell_value("Sheet1", "B2", CellValue::Number(100.0))
7392            .unwrap();
7393        wb.set_cell_value("Sales", "A1", CellValue::String("Sales value".to_string()))
7394            .unwrap();
7395        wb.set_cell_value("Sales", "C3", CellValue::Number(200.0))
7396            .unwrap();
7397        wb.set_cell_value("Data", "A1", CellValue::String("Data value".to_string()))
7398            .unwrap();
7399        wb.set_cell_value("Data", "D4", CellValue::Bool(true))
7400            .unwrap();
7401        wb.save(&path1).unwrap();
7402
7403        // Reopen with only Sheet1 parsed.
7404        let opts = OpenOptions::new().sheets(vec!["Sheet1".to_string()]);
7405        let wb2 = Workbook::open_with_options(&path1, &opts).unwrap();
7406
7407        // Verify Sheet1 was parsed.
7408        assert_eq!(
7409            wb2.get_cell_value("Sheet1", "A1").unwrap(),
7410            CellValue::String("Sheet1 value".to_string())
7411        );
7412
7413        // Save to a new file.
7414        wb2.save(&path2).unwrap();
7415
7416        // Reopen the resaved file with all sheets parsed.
7417        let wb3 = Workbook::open(&path2).unwrap();
7418        assert_eq!(wb3.sheet_names(), vec!["Sheet1", "Sales", "Data"]);
7419
7420        // Sheet1 data should be intact.
7421        assert_eq!(
7422            wb3.get_cell_value("Sheet1", "A1").unwrap(),
7423            CellValue::String("Sheet1 value".to_string())
7424        );
7425        assert_eq!(
7426            wb3.get_cell_value("Sheet1", "B2").unwrap(),
7427            CellValue::Number(100.0)
7428        );
7429
7430        // Sales data should be preserved from raw XML.
7431        assert_eq!(
7432            wb3.get_cell_value("Sales", "A1").unwrap(),
7433            CellValue::String("Sales value".to_string())
7434        );
7435        assert_eq!(
7436            wb3.get_cell_value("Sales", "C3").unwrap(),
7437            CellValue::Number(200.0)
7438        );
7439
7440        // Data sheet should be preserved from raw XML.
7441        assert_eq!(
7442            wb3.get_cell_value("Data", "A1").unwrap(),
7443            CellValue::String("Data value".to_string())
7444        );
7445        assert_eq!(
7446            wb3.get_cell_value("Data", "D4").unwrap(),
7447            CellValue::Bool(true)
7448        );
7449    }
7450
7451    #[test]
7452    fn test_open_from_buffer_with_options_backwards_compatible() {
7453        let mut wb = Workbook::new();
7454        wb.set_cell_value("Sheet1", "A1", CellValue::String("Hello".to_string()))
7455            .unwrap();
7456        let buf = wb.save_to_buffer().unwrap();
7457
7458        let wb2 = Workbook::open_from_buffer(&buf).unwrap();
7459        assert_eq!(
7460            wb2.get_cell_value("Sheet1", "A1").unwrap(),
7461            CellValue::String("Hello".to_string())
7462        );
7463    }
7464
7465    use crate::workbook::open_options::ReadMode;
7466
7467    #[test]
7468    fn test_readfast_open_reads_cell_data() {
7469        let mut wb = Workbook::new();
7470        wb.set_cell_value("Sheet1", "A1", CellValue::String("Hello".to_string()))
7471            .unwrap();
7472        wb.set_cell_value("Sheet1", "B2", CellValue::Number(42.0))
7473            .unwrap();
7474        wb.set_cell_value("Sheet1", "C3", CellValue::Bool(true))
7475            .unwrap();
7476        let buf = wb.save_to_buffer().unwrap();
7477
7478        let opts = OpenOptions::new().read_mode(ReadMode::Lazy);
7479        let wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
7480        assert_eq!(wb2.sheet_names(), vec!["Sheet1"]);
7481        assert_eq!(
7482            wb2.get_cell_value("Sheet1", "A1").unwrap(),
7483            CellValue::String("Hello".to_string())
7484        );
7485        assert_eq!(
7486            wb2.get_cell_value("Sheet1", "B2").unwrap(),
7487            CellValue::Number(42.0)
7488        );
7489        assert_eq!(
7490            wb2.get_cell_value("Sheet1", "C3").unwrap(),
7491            CellValue::Bool(true)
7492        );
7493    }
7494
7495    #[test]
7496    fn test_readfast_open_multi_sheet() {
7497        let mut wb = Workbook::new();
7498        wb.new_sheet("Sheet2").unwrap();
7499        wb.set_cell_value("Sheet1", "A1", CellValue::String("S1".to_string()))
7500            .unwrap();
7501        wb.set_cell_value("Sheet2", "A1", CellValue::String("S2".to_string()))
7502            .unwrap();
7503        let buf = wb.save_to_buffer().unwrap();
7504
7505        let opts = OpenOptions::new().read_mode(ReadMode::Lazy);
7506        let wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
7507        assert_eq!(wb2.sheet_names(), vec!["Sheet1", "Sheet2"]);
7508        assert_eq!(
7509            wb2.get_cell_value("Sheet1", "A1").unwrap(),
7510            CellValue::String("S1".to_string())
7511        );
7512        assert_eq!(
7513            wb2.get_cell_value("Sheet2", "A1").unwrap(),
7514            CellValue::String("S2".to_string())
7515        );
7516    }
7517
7518    #[test]
7519    fn test_readfast_skips_comments() {
7520        let mut wb = Workbook::new();
7521        wb.set_cell_value("Sheet1", "A1", CellValue::String("data".to_string()))
7522            .unwrap();
7523        wb.add_comment(
7524            "Sheet1",
7525            &crate::comment::CommentConfig {
7526                cell: "A1".to_string(),
7527                author: "Tester".to_string(),
7528                text: "A test comment".to_string(),
7529            },
7530        )
7531        .unwrap();
7532        let buf = wb.save_to_buffer().unwrap();
7533
7534        let opts = OpenOptions::new().read_mode(ReadMode::Lazy);
7535        let mut wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
7536
7537        // Cell data is readable.
7538        assert_eq!(
7539            wb2.get_cell_value("Sheet1", "A1").unwrap(),
7540            CellValue::String("data".to_string())
7541        );
7542        // Comments are hydrated on demand from deferred parts.
7543        let comments = wb2.get_comments("Sheet1").unwrap();
7544        assert_eq!(comments.len(), 1);
7545        assert_eq!(comments[0].text, "A test comment");
7546    }
7547
7548    #[test]
7549    fn test_readfast_get_doc_properties_without_mutation() {
7550        let mut wb = Workbook::new();
7551        wb.set_cell_value("Sheet1", "A1", CellValue::Number(1.0))
7552            .unwrap();
7553        wb.set_doc_props(crate::doc_props::DocProperties {
7554            title: Some("Test Title".to_string()),
7555            ..Default::default()
7556        });
7557        let buf = wb.save_to_buffer().unwrap();
7558
7559        let opts = OpenOptions::new().read_mode(ReadMode::Lazy);
7560        let wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
7561
7562        // Cell data is readable.
7563        assert_eq!(
7564            wb2.get_cell_value("Sheet1", "A1").unwrap(),
7565            CellValue::Number(1.0)
7566        );
7567        // Doc properties should be readable directly from deferred parts.
7568        let props = wb2.get_doc_props();
7569        assert_eq!(props.title.as_deref(), Some("Test Title"));
7570    }
7571
7572    #[test]
7573    fn test_readfast_save_roundtrip_preserves_all_parts() {
7574        let mut wb = Workbook::new();
7575        wb.set_cell_value("Sheet1", "A1", CellValue::String("data".to_string()))
7576            .unwrap();
7577        wb.add_comment(
7578            "Sheet1",
7579            &crate::comment::CommentConfig {
7580                cell: "A1".to_string(),
7581                author: "Tester".to_string(),
7582                text: "A comment".to_string(),
7583            },
7584        )
7585        .unwrap();
7586        wb.set_doc_props(crate::doc_props::DocProperties {
7587            title: Some("Title".to_string()),
7588            ..Default::default()
7589        });
7590        let buf = wb.save_to_buffer().unwrap();
7591
7592        // Open in Lazy mode.
7593        let opts = OpenOptions::new().read_mode(ReadMode::Lazy);
7594        let wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
7595        let saved = wb2.save_to_buffer().unwrap();
7596
7597        // Re-open in Eager mode and verify all parts were preserved.
7598        let mut wb3 = Workbook::open_from_buffer(&saved).unwrap();
7599        assert_eq!(
7600            wb3.get_cell_value("Sheet1", "A1").unwrap(),
7601            CellValue::String("data".to_string())
7602        );
7603        let comments = wb3.get_comments("Sheet1").unwrap();
7604        assert_eq!(comments.len(), 1);
7605        assert_eq!(comments[0].text, "A comment");
7606        let props = wb3.get_doc_props();
7607        assert_eq!(props.title, Some("Title".to_string()));
7608    }
7609
7610    #[test]
7611    fn test_readfast_with_sheet_rows_limit() {
7612        let mut wb = Workbook::new();
7613        for i in 1..=100 {
7614            wb.set_cell_value("Sheet1", &format!("A{}", i), CellValue::Number(i as f64))
7615                .unwrap();
7616        }
7617        let buf = wb.save_to_buffer().unwrap();
7618
7619        let opts = OpenOptions::new().read_mode(ReadMode::Lazy).sheet_rows(10);
7620        let wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
7621        let rows = wb2.get_rows("Sheet1").unwrap();
7622        assert_eq!(rows.len(), 10);
7623    }
7624
7625    #[test]
7626    fn test_readfast_with_sheets_filter() {
7627        let mut wb = Workbook::new();
7628        wb.new_sheet("Sheet2").unwrap();
7629        wb.set_cell_value("Sheet1", "A1", CellValue::String("S1".to_string()))
7630            .unwrap();
7631        wb.set_cell_value("Sheet2", "A1", CellValue::String("S2".to_string()))
7632            .unwrap();
7633        let buf = wb.save_to_buffer().unwrap();
7634
7635        let opts = OpenOptions::new()
7636            .read_mode(ReadMode::Lazy)
7637            .sheets(vec!["Sheet2".to_string()]);
7638        let wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
7639        assert_eq!(wb2.sheet_names(), vec!["Sheet1", "Sheet2"]);
7640        assert_eq!(
7641            wb2.get_cell_value("Sheet2", "A1").unwrap(),
7642            CellValue::String("S2".to_string())
7643        );
7644        // Sheet1 was not parsed, should return empty.
7645        assert_eq!(
7646            wb2.get_cell_value("Sheet1", "A1").unwrap(),
7647            CellValue::Empty
7648        );
7649    }
7650
7651    #[test]
7652    fn test_readfast_preserves_styles() {
7653        let mut wb = Workbook::new();
7654        let style_id = wb
7655            .add_style(&crate::style::Style {
7656                font: Some(crate::style::FontStyle {
7657                    bold: true,
7658                    ..Default::default()
7659                }),
7660                ..Default::default()
7661            })
7662            .unwrap();
7663        wb.set_cell_value("Sheet1", "A1", CellValue::String("bold".to_string()))
7664            .unwrap();
7665        wb.set_cell_style("Sheet1", "A1", style_id).unwrap();
7666        let buf = wb.save_to_buffer().unwrap();
7667
7668        let opts = OpenOptions::new().read_mode(ReadMode::Lazy);
7669        let wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
7670        let sid = wb2.get_cell_style("Sheet1", "A1").unwrap();
7671        assert!(sid.is_some());
7672        let style = crate::style::get_style(&wb2.stylesheet, sid.unwrap());
7673        assert!(style.is_some());
7674        assert!(style.unwrap().font.map_or(false, |f| f.bold));
7675    }
7676
7677    #[test]
7678    fn test_readfast_full_mode_unchanged() {
7679        let mut wb = Workbook::new();
7680        wb.set_cell_value("Sheet1", "A1", CellValue::String("test".to_string()))
7681            .unwrap();
7682        wb.add_comment(
7683            "Sheet1",
7684            &crate::comment::CommentConfig {
7685                cell: "A1".to_string(),
7686                author: "Author".to_string(),
7687                text: "comment text".to_string(),
7688            },
7689        )
7690        .unwrap();
7691        let buf = wb.save_to_buffer().unwrap();
7692
7693        // Eager mode: everything should be parsed.
7694        let opts = OpenOptions::new().read_mode(ReadMode::Eager);
7695        let mut wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
7696        let comments = wb2.get_comments("Sheet1").unwrap();
7697        assert_eq!(comments.len(), 1);
7698    }
7699
7700    #[test]
7701    fn test_readfast_open_from_file() {
7702        let dir = TempDir::new().unwrap();
7703        let path = dir.path().join("readfast_test.xlsx");
7704
7705        let mut wb = Workbook::new();
7706        wb.set_cell_value("Sheet1", "A1", CellValue::String("file test".to_string()))
7707            .unwrap();
7708        wb.save(&path).unwrap();
7709
7710        let opts = OpenOptions::new().read_mode(ReadMode::Lazy);
7711        let wb2 = Workbook::open_with_options(&path, &opts).unwrap();
7712        assert_eq!(
7713            wb2.get_cell_value("Sheet1", "A1").unwrap(),
7714            CellValue::String("file test".to_string())
7715        );
7716    }
7717
7718    #[test]
7719    fn test_readfast_roundtrip_with_custom_zip_entries() {
7720        let buf = create_xlsx_with_custom_entries();
7721
7722        let opts = OpenOptions::new().read_mode(ReadMode::Lazy);
7723        let wb = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
7724        assert_eq!(
7725            wb.get_cell_value("Sheet1", "A1").unwrap(),
7726            CellValue::String("hello".to_string())
7727        );
7728
7729        let saved = wb.save_to_buffer().unwrap();
7730        let cursor = std::io::Cursor::new(&saved);
7731        let mut archive = zip::ZipArchive::new(cursor).unwrap();
7732
7733        // Custom entries should be preserved through Lazy open/save.
7734        let mut custom_xml = String::new();
7735        std::io::Read::read_to_string(
7736            &mut archive.by_name("customXml/item1.xml").unwrap(),
7737            &mut custom_xml,
7738        )
7739        .unwrap();
7740        assert_eq!(custom_xml, "<custom>data1</custom>");
7741
7742        let mut printer = Vec::new();
7743        std::io::Read::read_to_end(
7744            &mut archive
7745                .by_name("xl/printerSettings/printerSettings1.bin")
7746                .unwrap(),
7747            &mut printer,
7748        )
7749        .unwrap();
7750        assert_eq!(printer, b"\x00\x01\x02\x03PRINTER");
7751    }
7752
7753    #[test]
7754    fn test_readfast_deferred_parts_not_empty_when_auxiliary_exist() {
7755        let mut wb = Workbook::new();
7756        wb.set_cell_value("Sheet1", "A1", CellValue::String("data".to_string()))
7757            .unwrap();
7758        wb.add_comment(
7759            "Sheet1",
7760            &crate::comment::CommentConfig {
7761                cell: "A1".to_string(),
7762                author: "Tester".to_string(),
7763                text: "comment".to_string(),
7764            },
7765        )
7766        .unwrap();
7767        let buf = wb.save_to_buffer().unwrap();
7768
7769        let opts = OpenOptions::new().read_mode(ReadMode::Lazy);
7770        let wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
7771        // When auxiliary parts exist, they should be captured in deferred_parts.
7772        assert!(
7773            wb2.deferred_parts.has_any(),
7774            "deferred_parts should contain skipped auxiliary parts"
7775        );
7776    }
7777
7778    #[test]
7779    fn test_readfast_eager_mode_has_no_deferred_parts() {
7780        use crate::workbook::open_options::{AuxParts, OpenOptions, ReadMode};
7781
7782        let mut wb = Workbook::new();
7783        wb.set_cell_value("Sheet1", "A1", CellValue::String("data".to_string()))
7784            .unwrap();
7785        wb.add_comment(
7786            "Sheet1",
7787            &crate::comment::CommentConfig {
7788                cell: "A1".to_string(),
7789                author: "Tester".to_string(),
7790                text: "comment".to_string(),
7791            },
7792        )
7793        .unwrap();
7794        let buf = wb.save_to_buffer().unwrap();
7795
7796        // Eager mode: deferred_parts should be empty.
7797        let opts = OpenOptions::new()
7798            .read_mode(ReadMode::Eager)
7799            .aux_parts(AuxParts::EagerLoad);
7800        let wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
7801        assert!(
7802            !wb2.deferred_parts.has_any(),
7803            "Eager mode should not have deferred parts"
7804        );
7805    }
7806
7807    #[test]
7808    fn test_readfast_table_parts_preserved_on_roundtrip() {
7809        let mut wb = Workbook::new();
7810        wb.set_cell_value("Sheet1", "A1", CellValue::String("Name".to_string()))
7811            .unwrap();
7812        wb.set_cell_value("Sheet1", "B1", CellValue::String("Value".to_string()))
7813            .unwrap();
7814        wb.set_cell_value("Sheet1", "A2", CellValue::String("Alice".to_string()))
7815            .unwrap();
7816        wb.set_cell_value("Sheet1", "B2", CellValue::Number(10.0))
7817            .unwrap();
7818        wb.add_table(
7819            "Sheet1",
7820            &crate::table::TableConfig {
7821                name: "Table1".to_string(),
7822                display_name: "Table1".to_string(),
7823                range: "A1:B2".to_string(),
7824                columns: vec![
7825                    crate::table::TableColumn {
7826                        name: "Name".to_string(),
7827                        totals_row_function: None,
7828                        totals_row_label: None,
7829                    },
7830                    crate::table::TableColumn {
7831                        name: "Value".to_string(),
7832                        totals_row_function: None,
7833                        totals_row_label: None,
7834                    },
7835                ],
7836                ..Default::default()
7837            },
7838        )
7839        .unwrap();
7840        let buf = wb.save_to_buffer().unwrap();
7841
7842        // Open in Lazy mode and save.
7843        let opts = OpenOptions::new().read_mode(ReadMode::Lazy);
7844        let wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
7845        let saved = wb2.save_to_buffer().unwrap();
7846
7847        // Re-open in Eager mode and verify the table survived the round-trip.
7848        let wb3 = Workbook::open_from_buffer(&saved).unwrap();
7849        let tables = wb3.get_tables("Sheet1").unwrap();
7850        assert_eq!(tables.len(), 1);
7851        assert_eq!(tables[0].name, "Table1");
7852    }
7853
7854    #[test]
7855    fn malformed_cell_structure_fails_in_eager_lazy_and_stream_modes() {
7856        let mut workbook = Workbook::new();
7857        workbook.set_cell_value("Sheet1", "A1", 1.0).unwrap();
7858        let base = workbook.save_to_buffer().unwrap();
7859        let sheet_path = "xl/worksheets/sheet1.xml";
7860        let malformed = String::from_utf8(zip_part(&base, sheet_path))
7861            .unwrap()
7862            .replacen("r=\"A1\"", "r=\"A2\"", 1);
7863        let input = rewrite_zip_parts(&base, &[(sheet_path, Some(malformed.into_bytes()))]);
7864        let directory = tempfile::tempdir().unwrap();
7865        let path = directory.path().join("malformed-cell.xlsx");
7866        std::fs::write(&path, &input).unwrap();
7867
7868        let assert_invalid = |result: Result<Workbook>| match result {
7869            Err(error) => assert!(matches!(error, Error::InvalidCellReference(_))),
7870            Ok(workbook) => {
7871                let error = workbook.get_cell_value("Sheet1", "A1").unwrap_err();
7872                assert!(matches!(error, Error::InvalidCellReference(_)));
7873            }
7874        };
7875
7876        for mode in [ReadMode::Eager, ReadMode::Lazy, ReadMode::Stream] {
7877            let options = OpenOptions::new().read_mode(mode);
7878            assert_invalid(Workbook::open_from_buffer_with_options(&input, &options));
7879            assert_invalid(Workbook::open_with_options(&path, &options));
7880        }
7881    }
7882
7883    #[test]
7884    fn table_ownership_fails_closed_in_every_read_mode() {
7885        let mut workbook = Workbook::new();
7886        workbook
7887            .add_table(
7888                "Sheet1",
7889                &crate::table::TableConfig {
7890                    name: "Table1".to_string(),
7891                    display_name: "Table1".to_string(),
7892                    range: "A1:B2".to_string(),
7893                    columns: vec![
7894                        crate::table::TableColumn {
7895                            name: "Name".to_string(),
7896                            totals_row_function: None,
7897                            totals_row_label: None,
7898                        },
7899                        crate::table::TableColumn {
7900                            name: "Value".to_string(),
7901                            totals_row_function: None,
7902                            totals_row_label: None,
7903                        },
7904                    ],
7905                    ..Default::default()
7906                },
7907            )
7908            .unwrap();
7909        let base = workbook.save_to_buffer().unwrap();
7910        let relationships_path = "xl/worksheets/_rels/sheet1.xml.rels";
7911        let relationships_xml = zip_part(&base, relationships_path);
7912        let relationships: Relationships = deserialize_xml_bytes(&relationships_xml).unwrap();
7913        let table_relationship_id = relationships
7914            .relationships
7915            .iter()
7916            .find(|relationship| relationship.rel_type == rel_types::TABLE)
7917            .unwrap()
7918            .id
7919            .clone();
7920        let sheet_path = "xl/worksheets/sheet1.xml";
7921        let sheet_xml = String::from_utf8(zip_part(&base, sheet_path)).unwrap();
7922        let table_parts = format!(
7923            "<tableParts count=\"1\"><tablePart r:id=\"{table_relationship_id}\"/></tableParts>"
7924        );
7925        assert!(sheet_xml.contains(&table_parts));
7926
7927        let mut orphan = relationships.clone();
7928        orphan
7929            .relationships
7930            .retain(|relationship| relationship.rel_type != rel_types::TABLE);
7931        let orphan = rewrite_zip_parts(
7932            &base,
7933            &[(
7934                relationships_path,
7935                Some(serialize_xml(&orphan).unwrap().into_bytes()),
7936            )],
7937        );
7938
7939        let mut external = relationships.clone();
7940        external
7941            .relationships
7942            .iter_mut()
7943            .find(|relationship| relationship.rel_type == rel_types::TABLE)
7944            .unwrap()
7945            .target_mode = Some("External".to_string());
7946        let external = rewrite_zip_parts(
7947            &base,
7948            &[(
7949                relationships_path,
7950                Some(serialize_xml(&external).unwrap().into_bytes()),
7951            )],
7952        );
7953
7954        let mut traversal = relationships.clone();
7955        traversal
7956            .relationships
7957            .iter_mut()
7958            .find(|relationship| relationship.rel_type == rel_types::TABLE)
7959            .unwrap()
7960            .target = "../../../tables/table1.xml".to_string();
7961        let traversal = rewrite_zip_parts(
7962            &base,
7963            &[(
7964                relationships_path,
7965                Some(serialize_xml(&traversal).unwrap().into_bytes()),
7966            )],
7967        );
7968
7969        let mut duplicate = relationships;
7970        let mut duplicate_relationship = duplicate
7971            .relationships
7972            .iter()
7973            .find(|relationship| relationship.rel_type == rel_types::TABLE)
7974            .unwrap()
7975            .clone();
7976        duplicate_relationship.id = "duplicateTableOwner".to_string();
7977        duplicate.relationships.push(duplicate_relationship);
7978        let duplicate = rewrite_zip_parts(
7979            &base,
7980            &[(
7981                relationships_path,
7982                Some(serialize_xml(&duplicate).unwrap().into_bytes()),
7983            )],
7984        );
7985
7986        let missing = rewrite_zip_parts(&base, &[("xl/tables/table1.xml", None)]);
7987
7988        let missing_table_parts = rewrite_zip_parts(
7989            &base,
7990            &[(
7991                sheet_path,
7992                Some(sheet_xml.replacen(&table_parts, "", 1).into_bytes()),
7993            )],
7994        );
7995        let unknown_table_part = rewrite_zip_parts(
7996            &base,
7997            &[(
7998                sheet_path,
7999                Some(
8000                    sheet_xml
8001                        .replacen(
8002                            &format!("r:id=\"{table_relationship_id}\""),
8003                            "r:id=\"unknownTableRelationship\"",
8004                            1,
8005                        )
8006                        .into_bytes(),
8007                ),
8008            )],
8009        );
8010        let duplicate_table_part = rewrite_zip_parts(
8011            &base,
8012            &[(
8013                sheet_path,
8014                Some(
8015                    sheet_xml
8016                        .replacen(
8017                            &format!("<tablePart r:id=\"{table_relationship_id}\"/>"),
8018                            &format!(
8019                                "<tablePart r:id=\"{table_relationship_id}\"/><tablePart r:id=\"{table_relationship_id}\"/>"
8020                            ),
8021                            1,
8022                        )
8023                        .into_bytes(),
8024                ),
8025            )],
8026        );
8027        let mismatched_table_part_count = rewrite_zip_parts(
8028            &base,
8029            &[(
8030                sheet_path,
8031                Some(
8032                    sheet_xml
8033                        .replacen("<tableParts count=\"1\">", "<tableParts count=\"2\">", 1)
8034                        .into_bytes(),
8035                ),
8036            )],
8037        );
8038        let foreign_table_parts_xml = sheet_xml
8039            .replacen("<worksheet ", "<worksheet xmlns:f=\"urn:foreign\" ", 1)
8040            .replacen(
8041                &table_parts,
8042                &format!(
8043                    "<f:tableParts count=\"1\"><f:tablePart f:id=\"{table_relationship_id}\"/></f:tableParts>"
8044                ),
8045                1,
8046            );
8047        let foreign_table_parts = rewrite_zip_parts(
8048            &base,
8049            &[(sheet_path, Some(foreign_table_parts_xml.into_bytes()))],
8050        );
8051        let expanded_table_part = rewrite_zip_parts(
8052            &base,
8053            &[(
8054                sheet_path,
8055                Some(
8056                    sheet_xml
8057                        .replacen(
8058                            &format!("<tablePart r:id=\"{table_relationship_id}\"/>"),
8059                            &format!("<tablePart r:id=\"{table_relationship_id}\"></tablePart>"),
8060                            1,
8061                        )
8062                        .into_bytes(),
8063                ),
8064            )],
8065        );
8066        let directory = tempfile::tempdir().unwrap();
8067        let path = directory.path().join("invalid-table-owner.xlsx");
8068
8069        for input in [
8070            &orphan,
8071            &external,
8072            &traversal,
8073            &duplicate,
8074            &missing,
8075            &missing_table_parts,
8076            &unknown_table_part,
8077            &duplicate_table_part,
8078            &mismatched_table_part_count,
8079            &foreign_table_parts,
8080        ] {
8081            std::fs::write(&path, input).unwrap();
8082            for mode in [ReadMode::Eager, ReadMode::Lazy, ReadMode::Stream] {
8083                let options = OpenOptions::new().read_mode(mode);
8084                assert!(Workbook::open_from_buffer_with_options(input, &options).is_err());
8085                assert!(Workbook::open_with_options(&path, &options).is_err());
8086            }
8087        }
8088
8089        std::fs::write(&path, &expanded_table_part).unwrap();
8090        for mode in [ReadMode::Eager, ReadMode::Lazy, ReadMode::Stream] {
8091            let options = OpenOptions::new().read_mode(mode);
8092            Workbook::open_from_buffer_with_options(&expanded_table_part, &options).unwrap();
8093            Workbook::open_with_options(&path, &options).unwrap();
8094        }
8095    }
8096
8097    #[test]
8098    fn test_readfast_delete_table_with_other_deferred_cleans_references() {
8099        use std::io::Read as _;
8100
8101        let mut wb = Workbook::new();
8102        wb.set_cell_value("Sheet1", "A1", CellValue::String("Name".to_string()))
8103            .unwrap();
8104        wb.set_cell_value("Sheet1", "B1", CellValue::String("Value".to_string()))
8105            .unwrap();
8106        wb.set_cell_value("Sheet1", "A2", CellValue::String("Alice".to_string()))
8107            .unwrap();
8108        wb.set_cell_value("Sheet1", "B2", CellValue::Number(10.0))
8109            .unwrap();
8110        wb.add_table(
8111            "Sheet1",
8112            &crate::table::TableConfig {
8113                name: "Table1".to_string(),
8114                display_name: "Table1".to_string(),
8115                range: "A1:B2".to_string(),
8116                columns: vec![
8117                    crate::table::TableColumn {
8118                        name: "Name".to_string(),
8119                        totals_row_function: None,
8120                        totals_row_label: None,
8121                    },
8122                    crate::table::TableColumn {
8123                        name: "Value".to_string(),
8124                        totals_row_function: None,
8125                        totals_row_label: None,
8126                    },
8127                ],
8128                ..Default::default()
8129            },
8130        )
8131        .unwrap();
8132        // Keep another deferred category so has_deferred remains true in Lazy mode.
8133        wb.set_doc_props(crate::doc_props::DocProperties {
8134            title: Some("Keep deferred".to_string()),
8135            ..Default::default()
8136        });
8137        let buf = wb.save_to_buffer().unwrap();
8138
8139        let opts = OpenOptions::new().read_mode(ReadMode::Lazy);
8140        let mut wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
8141        wb2.delete_table("Sheet1", "Table1").unwrap();
8142        let saved = wb2.save_to_buffer().unwrap();
8143
8144        let wb3 = Workbook::open_from_buffer(&saved).unwrap();
8145        assert!(wb3.get_tables("Sheet1").unwrap().is_empty());
8146
8147        let cursor = std::io::Cursor::new(saved);
8148        let mut archive = zip::ZipArchive::new(cursor).unwrap();
8149
8150        let mut ct_xml = String::new();
8151        archive
8152            .by_name("[Content_Types].xml")
8153            .unwrap()
8154            .read_to_string(&mut ct_xml)
8155            .unwrap();
8156        assert!(
8157            !ct_xml.contains("/xl/tables/table1.xml"),
8158            "content types must not reference the deleted table part"
8159        );
8160        assert!(
8161            !ct_xml.contains(mime_types::TABLE),
8162            "content types must not keep table override after deletion"
8163        );
8164
8165        let mut rels_xml = String::new();
8166        archive
8167            .by_name("xl/worksheets/_rels/sheet1.xml.rels")
8168            .unwrap()
8169            .read_to_string(&mut rels_xml)
8170            .unwrap();
8171        assert!(
8172            !rels_xml.contains(rel_types::TABLE),
8173            "worksheet rels must not contain table relationship after deletion"
8174        );
8175
8176        let mut sheet_xml = String::new();
8177        archive
8178            .by_name("xl/worksheets/sheet1.xml")
8179            .unwrap()
8180            .read_to_string(&mut sheet_xml)
8181            .unwrap();
8182        assert!(
8183            !sheet_xml.contains("tableParts"),
8184            "worksheet XML must not contain tableParts after deletion"
8185        );
8186    }
8187
8188    #[test]
8189    fn test_readfast_add_comment_then_save_no_duplicate() {
8190        let mut wb = Workbook::new();
8191        wb.set_cell_value("Sheet1", "A1", CellValue::String("data".to_string()))
8192            .unwrap();
8193        wb.add_comment(
8194            "Sheet1",
8195            &crate::comment::CommentConfig {
8196                cell: "A1".to_string(),
8197                author: "Tester".to_string(),
8198                text: "Original comment".to_string(),
8199            },
8200        )
8201        .unwrap();
8202        let buf = wb.save_to_buffer().unwrap();
8203
8204        // Open in Lazy mode, add a new comment, and save.
8205        let opts = OpenOptions::new().read_mode(ReadMode::Lazy);
8206        let mut wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
8207        wb2.add_comment(
8208            "Sheet1",
8209            &crate::comment::CommentConfig {
8210                cell: "B1".to_string(),
8211                author: "Tester".to_string(),
8212                text: "New comment".to_string(),
8213            },
8214        )
8215        .unwrap();
8216        // This must not fail with a duplicate ZIP entry error.
8217        let saved = wb2.save_to_buffer().unwrap();
8218
8219        // Re-open and verify both old and new comments are present.
8220        let mut wb3 = Workbook::open_from_buffer(&saved).unwrap();
8221        let comments = wb3.get_comments("Sheet1").unwrap();
8222        assert!(
8223            comments.iter().any(|c| c.text == "New comment"),
8224            "New comment should be present after Lazy + add_comment round-trip"
8225        );
8226        assert!(
8227            comments.iter().any(|c| c.text == "Original comment"),
8228            "Original comment must be preserved after Lazy + add_comment round-trip"
8229        );
8230        assert_eq!(
8231            comments.len(),
8232            2,
8233            "Both original and new comments must survive"
8234        );
8235    }
8236
8237    #[test]
8238    fn test_readfast_add_comment_preserves_existing_comments() {
8239        // Regression test: opening with Lazy mode, adding a comment, and saving
8240        // must not drop pre-existing comments.
8241        let mut wb = Workbook::new();
8242        wb.set_cell_value("Sheet1", "A1", CellValue::String("data".to_string()))
8243            .unwrap();
8244        wb.add_comment(
8245            "Sheet1",
8246            &crate::comment::CommentConfig {
8247                cell: "A1".to_string(),
8248                author: "Alice".to_string(),
8249                text: "First comment".to_string(),
8250            },
8251        )
8252        .unwrap();
8253        wb.add_comment(
8254            "Sheet1",
8255            &crate::comment::CommentConfig {
8256                cell: "B2".to_string(),
8257                author: "Bob".to_string(),
8258                text: "Second comment".to_string(),
8259            },
8260        )
8261        .unwrap();
8262        let buf = wb.save_to_buffer().unwrap();
8263
8264        let opts = OpenOptions::new().read_mode(ReadMode::Lazy);
8265        let mut wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
8266
8267        // Add a third comment.
8268        wb2.add_comment(
8269            "Sheet1",
8270            &crate::comment::CommentConfig {
8271                cell: "C3".to_string(),
8272                author: "Charlie".to_string(),
8273                text: "Third comment".to_string(),
8274            },
8275        )
8276        .unwrap();
8277        let saved = wb2.save_to_buffer().unwrap();
8278
8279        let mut wb3 = Workbook::open_from_buffer(&saved).unwrap();
8280        let comments = wb3.get_comments("Sheet1").unwrap();
8281        assert_eq!(comments.len(), 3, "All three comments must be present");
8282        assert!(comments
8283            .iter()
8284            .any(|c| c.cell == "A1" && c.text == "First comment"));
8285        assert!(comments
8286            .iter()
8287            .any(|c| c.cell == "B2" && c.text == "Second comment"));
8288        assert!(comments
8289            .iter()
8290            .any(|c| c.cell == "C3" && c.text == "Third comment"));
8291    }
8292
8293    #[test]
8294    fn test_readfast_get_comments_hydrates_deferred() {
8295        // get_comments should return deferred comments even if no mutation occurred.
8296        let mut wb = Workbook::new();
8297        wb.add_comment(
8298            "Sheet1",
8299            &crate::comment::CommentConfig {
8300                cell: "A1".to_string(),
8301                author: "Author".to_string(),
8302                text: "Deferred comment".to_string(),
8303            },
8304        )
8305        .unwrap();
8306        let buf = wb.save_to_buffer().unwrap();
8307
8308        let opts = OpenOptions::new().read_mode(ReadMode::Lazy);
8309        let mut wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
8310
8311        // get_comments should hydrate and return the deferred comment.
8312        let comments = wb2.get_comments("Sheet1").unwrap();
8313        assert_eq!(comments.len(), 1);
8314        assert_eq!(comments[0].cell, "A1");
8315        assert_eq!(comments[0].text, "Deferred comment");
8316    }
8317
8318    #[test]
8319    fn test_readfast_remove_comment_hydrates_first() {
8320        // remove_comment on a Lazy workbook must hydrate deferred comments,
8321        // then remove only the target comment, preserving others.
8322        let mut wb = Workbook::new();
8323        wb.add_comment(
8324            "Sheet1",
8325            &crate::comment::CommentConfig {
8326                cell: "A1".to_string(),
8327                author: "Alice".to_string(),
8328                text: "Keep me".to_string(),
8329            },
8330        )
8331        .unwrap();
8332        wb.add_comment(
8333            "Sheet1",
8334            &crate::comment::CommentConfig {
8335                cell: "B2".to_string(),
8336                author: "Bob".to_string(),
8337                text: "Remove me".to_string(),
8338            },
8339        )
8340        .unwrap();
8341        let buf = wb.save_to_buffer().unwrap();
8342
8343        let opts = OpenOptions::new().read_mode(ReadMode::Lazy);
8344        let mut wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
8345        wb2.remove_comment("Sheet1", "B2").unwrap();
8346
8347        let saved = wb2.save_to_buffer().unwrap();
8348        let mut wb3 = Workbook::open_from_buffer(&saved).unwrap();
8349        let comments = wb3.get_comments("Sheet1").unwrap();
8350        assert_eq!(comments.len(), 1);
8351        assert_eq!(comments[0].cell, "A1");
8352        assert_eq!(comments[0].text, "Keep me");
8353    }
8354
8355    #[test]
8356    fn test_readfast_add_comment_no_preexisting_comments() {
8357        // Adding a comment to a sheet that had no comments when opened in Lazy mode
8358        // must create proper relationships and content types on save, even when
8359        // deferred_parts is non-empty due to other auxiliary parts (e.g. doc props).
8360        let mut wb = Workbook::new();
8361        wb.set_cell_value("Sheet1", "A1", CellValue::String("data".to_string()))
8362            .unwrap();
8363        // Add doc props so that Lazy mode will have non-empty deferred_parts.
8364        wb.set_doc_props(crate::doc_props::DocProperties {
8365            title: Some("Trigger deferred".to_string()),
8366            ..Default::default()
8367        });
8368        let buf = wb.save_to_buffer().unwrap();
8369
8370        let opts = OpenOptions::new().read_mode(ReadMode::Lazy);
8371        let mut wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
8372        wb2.add_comment(
8373            "Sheet1",
8374            &crate::comment::CommentConfig {
8375                cell: "A1".to_string(),
8376                author: "Newcomer".to_string(),
8377                text: "Brand new comment".to_string(),
8378            },
8379        )
8380        .unwrap();
8381
8382        let saved = wb2.save_to_buffer().unwrap();
8383
8384        // Verify the comment is readable after re-open.
8385        let mut wb3 = Workbook::open_from_buffer(&saved).unwrap();
8386        let comments = wb3.get_comments("Sheet1").unwrap();
8387        assert_eq!(comments.len(), 1);
8388        assert_eq!(comments[0].text, "Brand new comment");
8389
8390        // Verify the ZIP contains the comment XML and VML parts.
8391        let reader = std::io::Cursor::new(&saved);
8392        let mut archive = zip::ZipArchive::new(reader).unwrap();
8393        assert!(
8394            archive.by_name("xl/comments1.xml").is_ok(),
8395            "comments1.xml must be present"
8396        );
8397        assert!(
8398            archive.by_name("xl/drawings/vmlDrawing1.vml").is_ok(),
8399            "vmlDrawing1.vml must be present for the comment"
8400        );
8401    }
8402
8403    #[test]
8404    fn test_readfast_add_comment_vml_roundtrip() {
8405        // Verify that VML parts are correct after Lazy hydration + add comment.
8406        let mut wb = Workbook::new();
8407        wb.add_comment(
8408            "Sheet1",
8409            &crate::comment::CommentConfig {
8410                cell: "A1".to_string(),
8411                author: "Original".to_string(),
8412                text: "Has VML".to_string(),
8413            },
8414        )
8415        .unwrap();
8416        let buf = wb.save_to_buffer().unwrap();
8417
8418        let opts = OpenOptions::new().read_mode(ReadMode::Lazy);
8419        let mut wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
8420        wb2.add_comment(
8421            "Sheet1",
8422            &crate::comment::CommentConfig {
8423                cell: "B2".to_string(),
8424                author: "New".to_string(),
8425                text: "Also has VML".to_string(),
8426            },
8427        )
8428        .unwrap();
8429        let saved = wb2.save_to_buffer().unwrap();
8430
8431        // Verify VML part is present and references both cells.
8432        let reader = std::io::Cursor::new(&saved);
8433        let mut archive = zip::ZipArchive::new(reader).unwrap();
8434        assert!(archive.by_name("xl/drawings/vmlDrawing1.vml").is_ok());
8435
8436        // Verify both comments survive a full open.
8437        let mut wb3 = Workbook::open_from_buffer(&saved).unwrap();
8438        let comments = wb3.get_comments("Sheet1").unwrap();
8439        assert_eq!(comments.len(), 2);
8440    }
8441
8442    #[test]
8443    fn test_lazy_sparse_comment_paths_remain_package_consistent_after_mutation() {
8444        use crate::workbook::aux::AuxCategory;
8445
8446        let mut workbook = Workbook::new();
8447        workbook.new_sheet("Sheet2").unwrap();
8448        for (sheet, cell) in [("Sheet1", "A1"), ("Sheet2", "B2")] {
8449            workbook
8450                .add_comment(
8451                    sheet,
8452                    &crate::comment::CommentConfig {
8453                        cell: cell.to_string(),
8454                        author: "Author".to_string(),
8455                        text: format!("Comment on {sheet}"),
8456                    },
8457                )
8458                .unwrap();
8459        }
8460        let options = OpenOptions::new().read_mode(ReadMode::Lazy);
8461        let base = workbook.save_to_buffer().unwrap();
8462        let mut sparse = Workbook::open_from_buffer_with_options(&base, &options).unwrap();
8463
8464        for (sheet_idx, old_number, new_number) in [(0, 1, 7), (1, 2, 9)] {
8465            let sheet_path = sparse.sheet_part_path(sheet_idx);
8466            for (category, old_path, new_path) in [
8467                (
8468                    AuxCategory::Comments,
8469                    format!("xl/comments{old_number}.xml"),
8470                    format!("xl/comments{new_number}.xml"),
8471                ),
8472                (
8473                    AuxCategory::Vml,
8474                    format!("xl/drawings/vmlDrawing{old_number}.vml"),
8475                    format!("xl/drawings/vmlDrawing{new_number}.vml"),
8476                ),
8477            ] {
8478                let bytes = sparse
8479                    .deferred_parts
8480                    .remove_path(category, &old_path)
8481                    .unwrap();
8482                assert!(sparse.deferred_parts.insert(new_path.clone(), bytes));
8483                for entry in &mut sparse.content_types.overrides {
8484                    if entry.part_name == format!("/{old_path}") {
8485                        entry.part_name = format!("/{new_path}");
8486                    }
8487                }
8488                for relationship in &mut sparse
8489                    .worksheet_rels
8490                    .get_mut(&sheet_idx)
8491                    .unwrap()
8492                    .relationships
8493                {
8494                    if resolve_relationship_target(&sheet_path, &relationship.target) == old_path {
8495                        relationship.target = relative_relationship_target(&sheet_path, &new_path);
8496                    }
8497                }
8498            }
8499        }
8500        let sparse_package = sparse.save_to_buffer().unwrap();
8501        let mut opened =
8502            Workbook::open_from_buffer_with_options(&sparse_package, &options).unwrap();
8503        opened
8504            .add_comment(
8505                "Sheet1",
8506                &crate::comment::CommentConfig {
8507                    cell: "C3".to_string(),
8508                    author: "Author".to_string(),
8509                    text: "Added comment".to_string(),
8510                },
8511            )
8512            .unwrap();
8513
8514        let saved = opened.save_to_buffer().unwrap();
8515        assert_all_package_targets_exist(&saved);
8516        let mut archive = zip::ZipArchive::new(std::io::Cursor::new(&saved)).unwrap();
8517        for path in [
8518            "xl/comments7.xml",
8519            "xl/comments9.xml",
8520            "xl/drawings/vmlDrawing7.vml",
8521            "xl/drawings/vmlDrawing9.vml",
8522        ] {
8523            assert!(
8524                archive.by_name(path).is_ok(),
8525                "missing retained part: {path}"
8526            );
8527        }
8528    }
8529
8530    #[test]
8531    fn test_readfast_set_doc_props_then_save_no_duplicate() {
8532        let mut wb = Workbook::new();
8533        wb.set_cell_value("Sheet1", "A1", CellValue::Number(1.0))
8534            .unwrap();
8535        wb.set_doc_props(crate::doc_props::DocProperties {
8536            title: Some("Original Title".to_string()),
8537            ..Default::default()
8538        });
8539        let buf = wb.save_to_buffer().unwrap();
8540
8541        // Open in Lazy mode, update doc props, and save.
8542        let opts = OpenOptions::new().read_mode(ReadMode::Lazy);
8543        let mut wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
8544        wb2.set_doc_props(crate::doc_props::DocProperties {
8545            title: Some("Updated Title".to_string()),
8546            ..Default::default()
8547        });
8548        // This must not fail with a duplicate ZIP entry error.
8549        let saved = wb2.save_to_buffer().unwrap();
8550
8551        // Re-open and verify the updated doc props.
8552        let wb3 = Workbook::open_from_buffer(&saved).unwrap();
8553        let props = wb3.get_doc_props();
8554        assert_eq!(props.title, Some("Updated Title".to_string()));
8555    }
8556
8557    #[test]
8558    fn test_read_xml_part_from_reader_worksheet() {
8559        use sheetkit_xml::worksheet::WorksheetXml;
8560        let ws_xml = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
8561<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
8562  <sheetData>
8563    <row r="1"><c r="A1" t="s"><v>0</v></c></row>
8564    <row r="2"><c r="A2"><v>42</v></c></row>
8565  </sheetData>
8566</worksheet>"#;
8567        let mut buf = Vec::new();
8568        {
8569            let cursor = std::io::Cursor::new(&mut buf);
8570            let mut zip = zip::ZipWriter::new(cursor);
8571            let opts = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated);
8572            zip.start_file("test.xml", opts).unwrap();
8573            use std::io::Write;
8574            zip.write_all(ws_xml.as_bytes()).unwrap();
8575            zip.finish().unwrap();
8576        }
8577        let cursor = std::io::Cursor::new(&buf);
8578        let mut archive = zip::ZipArchive::new(cursor).unwrap();
8579        let ws: WorksheetXml = read_xml_part(&mut archive, "test.xml").unwrap();
8580        assert_eq!(ws.sheet_data.rows.len(), 2);
8581        assert_eq!(ws.sheet_data.rows[0].r, 1);
8582        assert_eq!(ws.sheet_data.rows[0].cells[0].r, "A1");
8583        assert_eq!(ws.sheet_data.rows[1].r, 2);
8584        assert_eq!(ws.sheet_data.rows[1].cells[0].v, Some("42".to_string()));
8585    }
8586
8587    #[test]
8588    fn test_read_xml_part_from_reader_sst() {
8589        use sheetkit_xml::shared_strings::Sst;
8590        let sst_xml = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
8591<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="2" uniqueCount="2">
8592  <si><t>Hello</t></si>
8593  <si><t>World</t></si>
8594</sst>"#;
8595        let mut buf = Vec::new();
8596        {
8597            let cursor = std::io::Cursor::new(&mut buf);
8598            let mut zip = zip::ZipWriter::new(cursor);
8599            let opts = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated);
8600            zip.start_file("sst.xml", opts).unwrap();
8601            use std::io::Write;
8602            zip.write_all(sst_xml.as_bytes()).unwrap();
8603            zip.finish().unwrap();
8604        }
8605        let cursor = std::io::Cursor::new(&buf);
8606        let mut archive = zip::ZipArchive::new(cursor).unwrap();
8607        let sst: Sst = read_xml_part(&mut archive, "sst.xml").unwrap();
8608        assert_eq!(sst.count, Some(2));
8609        assert_eq!(sst.unique_count, Some(2));
8610        assert_eq!(sst.items.len(), 2);
8611        assert_eq!(sst.items[0].t.as_ref().unwrap().value, "Hello");
8612        assert_eq!(sst.items[1].t.as_ref().unwrap().value, "World");
8613    }
8614
8615    #[test]
8616    fn test_read_xml_part_from_reader_large_worksheet() {
8617        use sheetkit_xml::worksheet::WorksheetXml;
8618        let mut ws_xml = String::from(
8619            r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
8620<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
8621  <sheetData>"#,
8622        );
8623        for i in 1..=500 {
8624            ws_xml.push_str(&format!(
8625                "<row r=\"{i}\"><c r=\"A{i}\"><v>{}</v></c><c r=\"B{i}\"><v>{}</v></c></row>",
8626                i * 10,
8627                i * 20,
8628            ));
8629        }
8630        ws_xml.push_str("</sheetData></worksheet>");
8631
8632        let mut buf = Vec::new();
8633        {
8634            let cursor = std::io::Cursor::new(&mut buf);
8635            let mut zip = zip::ZipWriter::new(cursor);
8636            let opts = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated);
8637            zip.start_file("sheet.xml", opts).unwrap();
8638            use std::io::Write;
8639            zip.write_all(ws_xml.as_bytes()).unwrap();
8640            zip.finish().unwrap();
8641        }
8642        let cursor = std::io::Cursor::new(&buf);
8643        let mut archive = zip::ZipArchive::new(cursor).unwrap();
8644        let ws: WorksheetXml = read_xml_part(&mut archive, "sheet.xml").unwrap();
8645        assert_eq!(ws.sheet_data.rows.len(), 500);
8646        assert_eq!(ws.sheet_data.rows[0].r, 1);
8647        assert_eq!(ws.sheet_data.rows[0].cells[0].v, Some("10".to_string()));
8648        assert_eq!(ws.sheet_data.rows[499].r, 500);
8649        assert_eq!(
8650            ws.sheet_data.rows[499].cells[1].v,
8651            Some("10000".to_string())
8652        );
8653    }
8654
8655    // -- Copy-on-write passthrough tests --
8656
8657    #[test]
8658    fn test_lazy_open_save_without_modification_roundtrips() {
8659        let mut wb = Workbook::new();
8660        wb.set_cell_value("Sheet1", "A1", "Hello").unwrap();
8661        wb.set_cell_value("Sheet1", "B1", 42.0f64).unwrap();
8662        let buf = wb.save_to_buffer().unwrap();
8663
8664        let opts = crate::workbook::open_options::OpenOptions::new()
8665            .read_mode(crate::workbook::open_options::ReadMode::Lazy);
8666        let wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
8667
8668        // No modifications: save should use passthrough for the worksheet.
8669        let saved = wb2.save_to_buffer().unwrap();
8670
8671        // Re-open in Eager mode and verify data integrity.
8672        let wb3 = Workbook::open_from_buffer(&saved).unwrap();
8673        assert_eq!(
8674            wb3.get_cell_value("Sheet1", "A1").unwrap(),
8675            CellValue::String("Hello".to_string())
8676        );
8677        assert_eq!(
8678            wb3.get_cell_value("Sheet1", "B1").unwrap(),
8679            CellValue::Number(42.0)
8680        );
8681    }
8682
8683    #[test]
8684    fn test_lazy_open_modify_one_sheet_passthroughs_others() {
8685        let mut wb = Workbook::new();
8686        wb.set_cell_value("Sheet1", "A1", "First sheet").unwrap();
8687        wb.new_sheet("Sheet2").unwrap();
8688        wb.set_cell_value("Sheet2", "A1", "Second sheet").unwrap();
8689        wb.new_sheet("Sheet3").unwrap();
8690        wb.set_cell_value("Sheet3", "A1", "Third sheet").unwrap();
8691        let buf = wb.save_to_buffer().unwrap();
8692
8693        let opts = crate::workbook::open_options::OpenOptions::new()
8694            .read_mode(crate::workbook::open_options::ReadMode::Lazy);
8695        let mut wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
8696
8697        // Only modify Sheet2; Sheet1 and Sheet3 should use passthrough.
8698        wb2.set_cell_value("Sheet2", "B1", "Modified").unwrap();
8699
8700        // Verify dirty tracking.
8701        assert!(!wb2.is_sheet_dirty(0), "Sheet1 should not be dirty");
8702        assert!(wb2.is_sheet_dirty(1), "Sheet2 should be dirty");
8703        assert!(!wb2.is_sheet_dirty(2), "Sheet3 should not be dirty");
8704
8705        let saved = wb2.save_to_buffer().unwrap();
8706
8707        let wb3 = Workbook::open_from_buffer(&saved).unwrap();
8708        assert_eq!(
8709            wb3.get_cell_value("Sheet1", "A1").unwrap(),
8710            CellValue::String("First sheet".to_string())
8711        );
8712        assert_eq!(
8713            wb3.get_cell_value("Sheet2", "A1").unwrap(),
8714            CellValue::String("Second sheet".to_string())
8715        );
8716        assert_eq!(
8717            wb3.get_cell_value("Sheet2", "B1").unwrap(),
8718            CellValue::String("Modified".to_string())
8719        );
8720        assert_eq!(
8721            wb3.get_cell_value("Sheet3", "A1").unwrap(),
8722            CellValue::String("Third sheet".to_string())
8723        );
8724    }
8725
8726    #[test]
8727    fn test_lazy_open_deferred_aux_parts_preserved() {
8728        let mut wb = Workbook::new();
8729        wb.set_cell_value("Sheet1", "A1", "data").unwrap();
8730        wb.set_doc_props(crate::doc_props::DocProperties {
8731            title: Some("Test Title".to_string()),
8732            creator: Some("Test Author".to_string()),
8733            ..Default::default()
8734        });
8735        wb.add_comment(
8736            "Sheet1",
8737            &crate::comment::CommentConfig {
8738                cell: "A1".to_string(),
8739                author: "Tester".to_string(),
8740                text: "A comment".to_string(),
8741            },
8742        )
8743        .unwrap();
8744        let buf = wb.save_to_buffer().unwrap();
8745
8746        let opts = crate::workbook::open_options::OpenOptions::new()
8747            .read_mode(crate::workbook::open_options::ReadMode::Lazy);
8748        let wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
8749
8750        // Save without touching anything; deferred aux parts should be preserved.
8751        let saved = wb2.save_to_buffer().unwrap();
8752
8753        let mut wb3 = Workbook::open_from_buffer(&saved).unwrap();
8754        assert_eq!(
8755            wb3.get_cell_value("Sheet1", "A1").unwrap(),
8756            CellValue::String("data".to_string())
8757        );
8758        let props = wb3.get_doc_props();
8759        assert_eq!(props.title.as_deref(), Some("Test Title"));
8760        assert_eq!(props.creator.as_deref(), Some("Test Author"));
8761        let comments = wb3.get_comments("Sheet1").unwrap();
8762        assert_eq!(comments.len(), 1);
8763        assert_eq!(comments[0].text, "A comment");
8764    }
8765
8766    #[test]
8767    fn test_eager_open_save_preserves_all_data() {
8768        let mut wb = Workbook::new();
8769        wb.set_cell_value("Sheet1", "A1", "data").unwrap();
8770        wb.set_cell_value("Sheet1", "B1", 42.0f64).unwrap();
8771        wb.new_sheet("Sheet2").unwrap();
8772        wb.set_cell_value("Sheet2", "A1", "sheet2").unwrap();
8773        let buf = wb.save_to_buffer().unwrap();
8774
8775        // Eager mode (default): all sheets parsed at open time.
8776        let wb2 = Workbook::open_from_buffer(&buf).unwrap();
8777        let saved = wb2.save_to_buffer().unwrap();
8778
8779        let wb3 = Workbook::open_from_buffer(&saved).unwrap();
8780        assert_eq!(
8781            wb3.get_cell_value("Sheet1", "A1").unwrap(),
8782            CellValue::String("data".to_string())
8783        );
8784        assert_eq!(
8785            wb3.get_cell_value("Sheet1", "B1").unwrap(),
8786            CellValue::Number(42.0)
8787        );
8788        assert_eq!(
8789            wb3.get_cell_value("Sheet2", "A1").unwrap(),
8790            CellValue::String("sheet2".to_string())
8791        );
8792    }
8793
8794    #[test]
8795    fn test_lazy_read_then_save_passthrough() {
8796        let mut wb = Workbook::new();
8797        wb.set_cell_value("Sheet1", "A1", "value").unwrap();
8798        let buf = wb.save_to_buffer().unwrap();
8799
8800        let opts = crate::workbook::open_options::OpenOptions::new()
8801            .read_mode(crate::workbook::open_options::ReadMode::Lazy);
8802        let wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
8803
8804        // Read the value (triggers hydration via worksheet_ref, not mutation).
8805        let val = wb2.get_cell_value("Sheet1", "A1").unwrap();
8806        assert_eq!(val, CellValue::String("value".to_string()));
8807
8808        // Sheet was read but not modified, so it should NOT be dirty.
8809        assert!(!wb2.is_sheet_dirty(0));
8810
8811        // Save should still use passthrough for the untouched sheet.
8812        let saved = wb2.save_to_buffer().unwrap();
8813        let wb3 = Workbook::open_from_buffer(&saved).unwrap();
8814        assert_eq!(
8815            wb3.get_cell_value("Sheet1", "A1").unwrap(),
8816            CellValue::String("value".to_string())
8817        );
8818    }
8819
8820    #[test]
8821    fn test_cow_passthrough_with_styles_and_formulas() {
8822        let mut wb = Workbook::new();
8823        let style_id = wb
8824            .add_style(&crate::style::Style {
8825                font: Some(crate::style::FontStyle {
8826                    bold: true,
8827                    ..Default::default()
8828                }),
8829                ..Default::default()
8830            })
8831            .unwrap();
8832        wb.set_cell_value("Sheet1", "A1", "styled").unwrap();
8833        wb.set_cell_style("Sheet1", "A1", style_id).unwrap();
8834        wb.set_cell_formula("Sheet1", "B1", "LEN(A1)").unwrap();
8835        wb.new_sheet("Sheet2").unwrap();
8836        wb.set_cell_value("Sheet2", "A1", "other").unwrap();
8837        let buf = wb.save_to_buffer().unwrap();
8838
8839        let opts = crate::workbook::open_options::OpenOptions::new()
8840            .read_mode(crate::workbook::open_options::ReadMode::Lazy);
8841        let wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
8842        let saved = wb2.save_to_buffer().unwrap();
8843
8844        let wb3 = Workbook::open_from_buffer(&saved).unwrap();
8845        assert_eq!(
8846            wb3.get_cell_value("Sheet1", "A1").unwrap(),
8847            CellValue::String("styled".to_string())
8848        );
8849        assert_eq!(wb3.get_cell_style("Sheet1", "A1").unwrap(), Some(style_id));
8850        match wb3.get_cell_value("Sheet1", "B1").unwrap() {
8851            CellValue::Formula { expr, .. } => assert_eq!(expr, "LEN(A1)"),
8852            other => panic!("expected formula, got {:?}", other),
8853        }
8854        assert_eq!(
8855            wb3.get_cell_value("Sheet2", "A1").unwrap(),
8856            CellValue::String("other".to_string())
8857        );
8858    }
8859
8860    #[test]
8861    fn test_new_workbook_sheets_are_dirty() {
8862        let wb = Workbook::new();
8863        assert!(wb.is_sheet_dirty(0), "new workbook sheet should be dirty");
8864    }
8865
8866    #[test]
8867    fn test_eager_open_sheets_start_clean() {
8868        use crate::workbook::open_options::{AuxParts, OpenOptions, ReadMode};
8869
8870        let mut wb = Workbook::new();
8871        wb.set_cell_value("Sheet1", "A1", "test").unwrap();
8872        let buf = wb.save_to_buffer().unwrap();
8873
8874        let opts = OpenOptions::new()
8875            .read_mode(ReadMode::Eager)
8876            .aux_parts(AuxParts::EagerLoad);
8877        let wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
8878        assert!(
8879            !wb2.is_sheet_dirty(0),
8880            "eagerly parsed sheet should retain raw bytes and start clean"
8881        );
8882    }
8883
8884    #[test]
8885    fn test_lazy_open_sheets_start_clean() {
8886        let mut wb = Workbook::new();
8887        wb.set_cell_value("Sheet1", "A1", "test").unwrap();
8888        let buf = wb.save_to_buffer().unwrap();
8889
8890        let opts = crate::workbook::open_options::OpenOptions::new()
8891            .read_mode(crate::workbook::open_options::ReadMode::Lazy);
8892        let wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
8893        assert!(
8894            !wb2.is_sheet_dirty(0),
8895            "lazily deferred sheet should start clean"
8896        );
8897    }
8898
8899    #[test]
8900    fn test_lazy_mutation_marks_dirty() {
8901        let mut wb = Workbook::new();
8902        wb.set_cell_value("Sheet1", "A1", "test").unwrap();
8903        let buf = wb.save_to_buffer().unwrap();
8904
8905        let opts = crate::workbook::open_options::OpenOptions::new()
8906            .read_mode(crate::workbook::open_options::ReadMode::Lazy);
8907        let mut wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
8908        assert!(!wb2.is_sheet_dirty(0));
8909
8910        wb2.set_cell_value("Sheet1", "B1", "new").unwrap();
8911        assert!(
8912            wb2.is_sheet_dirty(0),
8913            "sheet should be dirty after mutation"
8914        );
8915    }
8916
8917    #[test]
8918    fn test_lazy_open_multi_sheet_selective_dirty() {
8919        let mut wb = Workbook::new();
8920        wb.set_cell_value("Sheet1", "A1", "s1").unwrap();
8921        wb.new_sheet("Sheet2").unwrap();
8922        wb.set_cell_value("Sheet2", "A1", "s2").unwrap();
8923        wb.new_sheet("Sheet3").unwrap();
8924        wb.set_cell_value("Sheet3", "A1", "s3").unwrap();
8925        let buf = wb.save_to_buffer().unwrap();
8926
8927        let opts = crate::workbook::open_options::OpenOptions::new()
8928            .read_mode(crate::workbook::open_options::ReadMode::Lazy);
8929        let mut wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
8930
8931        // All sheets start clean.
8932        assert!(!wb2.is_sheet_dirty(0));
8933        assert!(!wb2.is_sheet_dirty(1));
8934        assert!(!wb2.is_sheet_dirty(2));
8935
8936        // Read Sheet1 (no mutation).
8937        let _ = wb2.get_cell_value("Sheet1", "A1").unwrap();
8938        assert!(!wb2.is_sheet_dirty(0), "reading should not dirty a sheet");
8939
8940        // Mutate Sheet3.
8941        wb2.set_cell_value("Sheet3", "B1", "modified").unwrap();
8942        assert!(!wb2.is_sheet_dirty(0));
8943        assert!(!wb2.is_sheet_dirty(1));
8944        assert!(wb2.is_sheet_dirty(2));
8945
8946        // Save and verify all data.
8947        let saved = wb2.save_to_buffer().unwrap();
8948        let wb3 = Workbook::open_from_buffer(&saved).unwrap();
8949        assert_eq!(
8950            wb3.get_cell_value("Sheet1", "A1").unwrap(),
8951            CellValue::String("s1".to_string())
8952        );
8953        assert_eq!(
8954            wb3.get_cell_value("Sheet2", "A1").unwrap(),
8955            CellValue::String("s2".to_string())
8956        );
8957        assert_eq!(
8958            wb3.get_cell_value("Sheet3", "A1").unwrap(),
8959            CellValue::String("s3".to_string())
8960        );
8961        assert_eq!(
8962            wb3.get_cell_value("Sheet3", "B1").unwrap(),
8963            CellValue::String("modified".to_string())
8964        );
8965    }
8966
8967    #[test]
8968    fn test_sheets_filter_preserves_filtered_sheet_with_comments_on_save() {
8969        let mut wb = Workbook::new();
8970        wb.new_sheet("Sheet2").unwrap();
8971        wb.set_cell_value("Sheet1", "A1", CellValue::String("keep_me".to_string()))
8972            .unwrap();
8973        wb.set_cell_value("Sheet2", "A1", CellValue::String("s2".to_string()))
8974            .unwrap();
8975        wb.add_comment(
8976            "Sheet1",
8977            &crate::comment::CommentConfig {
8978                cell: "A1".to_string(),
8979                author: "Test".to_string(),
8980                text: "a comment".to_string(),
8981            },
8982        )
8983        .unwrap();
8984        let buf = wb.save_to_buffer().unwrap();
8985
8986        let opts = OpenOptions::new().sheets(vec!["Sheet2".to_string()]);
8987        let wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
8988        assert_eq!(
8989            wb2.get_cell_value("Sheet1", "A1").unwrap(),
8990            CellValue::Empty
8991        );
8992
8993        let buf2 = wb2.save_to_buffer().unwrap();
8994        let opts_all = OpenOptions::new()
8995            .read_mode(ReadMode::Eager)
8996            .aux_parts(AuxParts::EagerLoad);
8997        let wb3 = Workbook::open_from_buffer_with_options(&buf2, &opts_all).unwrap();
8998        assert_eq!(
8999            wb3.get_cell_value("Sheet1", "A1").unwrap(),
9000            CellValue::String("keep_me".to_string()),
9001        );
9002        assert_eq!(
9003            wb3.get_cell_value("Sheet2", "A1").unwrap(),
9004            CellValue::String("s2".to_string()),
9005        );
9006    }
9007
9008    #[test]
9009    fn eager_open_preserves_clean_graph_xml() {
9010        let (input, chart, drawing, drawing_rels) = opaque_graph_buffer();
9011        let options = OpenOptions::new()
9012            .read_mode(ReadMode::Eager)
9013            .aux_parts(AuxParts::EagerLoad);
9014        let mut workbook = Workbook::open_from_buffer_with_options(&input, &options).unwrap();
9015
9016        assert_eq!(workbook.raw_charts.len(), 1);
9017        assert!(!workbook
9018            .raw_graph_parts
9019            .contains_key("xl/charts/chart1.xml"));
9020        assert_eq!(
9021            workbook.drawings.len(),
9022            1,
9023            "drawing must parse successfully"
9024        );
9025        workbook
9026            .set_cell_value("Sheet1", "A20", "unrelated edit")
9027            .unwrap();
9028        assert!(workbook.dirty_graph_parts.is_empty());
9029
9030        let saved = workbook.save_to_buffer().unwrap();
9031        assert_eq!(zip_part(&saved, "xl/charts/chart1.xml"), chart);
9032        assert_eq!(zip_part(&saved, "xl/drawings/drawing1.xml"), drawing);
9033        assert_eq!(
9034            zip_part(&saved, "xl/drawings/_rels/drawing1.xml.rels"),
9035            drawing_rels
9036        );
9037    }
9038
9039    #[test]
9040    fn clean_typed_chart_owner_prefers_its_raw_original() {
9041        let base = workbook_with_chart_buffer();
9042        let raw_chart = zip_part(&base, "xl/charts/chart1.xml")
9043            .into_iter()
9044            .chain(b"\n".iter().copied())
9045            .collect::<Vec<_>>();
9046        let mut workbook = Workbook::new();
9047        use crate::chart::{ChartConfig, ChartSeries, ChartType};
9048        workbook
9049            .add_chart(
9050                "Sheet1",
9051                "E2",
9052                "L15",
9053                &ChartConfig {
9054                    chart_type: ChartType::Col,
9055                    title: None,
9056                    series: vec![ChartSeries {
9057                        name: "Values".to_string(),
9058                        categories: "Sheet1!$A$1:$A$3".to_string(),
9059                        values: "Sheet1!$B$1:$B$3".to_string(),
9060                        x_values: None,
9061                        bubble_sizes: None,
9062                    }],
9063                    show_legend: false,
9064                    view_3d: None,
9065                },
9066            )
9067            .unwrap();
9068        workbook.remember_raw_graph_part("xl/charts/chart1.xml".to_string(), raw_chart.clone());
9069        workbook.dirty_graph_parts.remove("xl/charts/chart1.xml");
9070
9071        let saved = workbook.save_to_buffer().unwrap();
9072        assert_eq!(zip_part(&saved, "xl/charts/chart1.xml"), raw_chart);
9073    }
9074
9075    #[test]
9076    fn raw_graph_paths_are_reserved_for_part_allocation() {
9077        let mut workbook = Workbook::new();
9078        workbook.remember_raw_graph_part("xl/charts/chart1.xml".to_string(), b"chart".to_vec());
9079        workbook
9080            .remember_raw_graph_part("xl/drawings/drawing1.xml".to_string(), b"drawing".to_vec());
9081
9082        assert_eq!(
9083            workbook.next_available_part_path("xl/charts/chart", ".xml"),
9084            "xl/charts/chart2.xml"
9085        );
9086        assert_eq!(
9087            workbook.next_available_part_path("xl/drawings/drawing", ".xml"),
9088            "xl/drawings/drawing2.xml"
9089        );
9090    }
9091
9092    #[test]
9093    fn lazy_hydration_is_read_only_for_graph_parts() {
9094        let (input, chart, drawing, drawing_rels) = opaque_graph_buffer();
9095        let options = OpenOptions::new().read_mode(ReadMode::Lazy);
9096        let mut workbook = Workbook::open_from_buffer_with_options(&input, &options).unwrap();
9097
9098        workbook.hydrate_drawings();
9099        assert_eq!(workbook.raw_charts.len(), 1);
9100        assert!(!workbook
9101            .raw_graph_parts
9102            .contains_key("xl/charts/chart1.xml"));
9103        assert_eq!(
9104            workbook.drawings.len(),
9105            1,
9106            "drawing must hydrate successfully"
9107        );
9108        assert!(workbook.dirty_graph_parts.is_empty());
9109
9110        let saved = workbook.save_to_buffer().unwrap();
9111        assert_eq!(zip_part(&saved, "xl/charts/chart1.xml"), chart);
9112        assert_eq!(zip_part(&saved, "xl/drawings/drawing1.xml"), drawing);
9113        assert_eq!(
9114            zip_part(&saved, "xl/drawings/_rels/drawing1.xml.rels"),
9115            drawing_rels
9116        );
9117    }
9118
9119    #[test]
9120    fn eager_open_preserves_parse_failed_drawing_and_relationships() {
9121        let base = workbook_with_chart_buffer();
9122        let drawing = b"<xdr:wsDr><broken></xdr:wsDr>".to_vec();
9123        let drawing_rels = b"<Relationships><broken></Relationships>".to_vec();
9124        let input = rewrite_zip_parts(
9125            &base,
9126            &[
9127                ("xl/drawings/drawing1.xml", Some(drawing.clone())),
9128                (
9129                    "xl/drawings/_rels/drawing1.xml.rels",
9130                    Some(drawing_rels.clone()),
9131                ),
9132            ],
9133        );
9134
9135        let options = OpenOptions::new()
9136            .read_mode(ReadMode::Eager)
9137            .aux_parts(AuxParts::EagerLoad);
9138        let mut workbook = Workbook::open_from_buffer_with_options(&input, &options).unwrap();
9139        workbook
9140            .set_cell_value("Sheet1", "A20", "unrelated edit")
9141            .unwrap();
9142        let saved = workbook.save_to_buffer().unwrap();
9143
9144        assert_eq!(zip_part(&saved, "xl/drawings/drawing1.xml"), drawing);
9145        assert_eq!(
9146            zip_part(&saved, "xl/drawings/_rels/drawing1.xml.rels"),
9147            drawing_rels
9148        );
9149    }
9150
9151    #[test]
9152    fn eager_open_preserves_unsupported_chart_and_drawing_nodes() {
9153        let (input, chart, drawing) = unsupported_graph_buffer();
9154        let options = OpenOptions::new()
9155            .read_mode(ReadMode::Eager)
9156            .aux_parts(AuxParts::EagerLoad);
9157        let mut workbook = Workbook::open_from_buffer_with_options(&input, &options).unwrap();
9158
9159        workbook
9160            .set_cell_value("Sheet1", "A20", "unrelated edit")
9161            .unwrap();
9162        let saved = workbook.save_to_buffer().unwrap();
9163
9164        assert_eq!(zip_part(&saved, "xl/charts/chart1.xml"), chart);
9165        assert_eq!(zip_part(&saved, "xl/drawings/drawing1.xml"), drawing);
9166    }
9167
9168    #[test]
9169    fn mutating_drawing_keeps_existing_chart_raw_xml_clean() {
9170        use crate::chart::{ChartConfig, ChartSeries, ChartType};
9171
9172        let (input, chart, drawing, _) = opaque_graph_buffer();
9173        let options = OpenOptions::new()
9174            .read_mode(ReadMode::Eager)
9175            .aux_parts(AuxParts::EagerLoad);
9176        let mut workbook = Workbook::open_from_buffer_with_options(&input, &options).unwrap();
9177        workbook
9178            .add_chart(
9179                "Sheet1",
9180                "E20",
9181                "L30",
9182                &ChartConfig {
9183                    chart_type: ChartType::Line,
9184                    title: None,
9185                    series: vec![ChartSeries {
9186                        name: "New values".to_string(),
9187                        categories: "Sheet1!$A$1:$A$3".to_string(),
9188                        values: "Sheet1!$C$1:$C$3".to_string(),
9189                        x_values: None,
9190                        bubble_sizes: None,
9191                    }],
9192                    show_legend: false,
9193                    view_3d: None,
9194                },
9195            )
9196            .unwrap();
9197        assert!(!workbook.dirty_graph_parts.contains("xl/charts/chart1.xml"));
9198        assert!(workbook.dirty_graph_parts.contains("xl/charts/chart2.xml"));
9199        assert!(workbook
9200            .dirty_graph_parts
9201            .contains("xl/drawings/drawing1.xml"));
9202        assert!(workbook
9203            .dirty_graph_parts
9204            .contains("xl/drawings/_rels/drawing1.xml.rels"));
9205
9206        let saved = workbook.save_to_buffer().unwrap();
9207        assert_eq!(zip_part(&saved, "xl/charts/chart1.xml"), chart);
9208        assert_ne!(zip_part(&saved, "xl/drawings/drawing1.xml"), drawing);
9209        assert!(zip_entry_count(&saved, "xl/charts/chart2.xml") == 1);
9210    }
9211
9212    #[test]
9213    fn graph_relationship_mutations_reject_unparseable_raw_rels_atomically() {
9214        use crate::chart::{ChartConfig, ChartSeries, ChartType};
9215        use crate::image::{ImageConfig, ImageFormat};
9216
9217        let base = workbook_with_chart_buffer();
9218        let input = rewrite_zip_parts(
9219            &base,
9220            &[(
9221                "xl/drawings/_rels/drawing1.xml.rels",
9222                Some(b"<Relationships><opaque></Relationships>".to_vec()),
9223            )],
9224        );
9225        let options = OpenOptions::new()
9226            .read_mode(ReadMode::Eager)
9227            .aux_parts(AuxParts::EagerLoad);
9228        let mut workbook = Workbook::open_from_buffer_with_options(&input, &options).unwrap();
9229        assert_eq!(workbook.drawings.len(), 1);
9230        assert!(!workbook.drawing_rels.contains_key(&0));
9231        let before = workbook.save_to_buffer().unwrap();
9232
9233        let chart_error = workbook
9234            .add_chart(
9235                "Sheet1",
9236                "E20",
9237                "L30",
9238                &ChartConfig {
9239                    chart_type: ChartType::Line,
9240                    title: None,
9241                    series: vec![ChartSeries {
9242                        name: "New values".to_string(),
9243                        categories: "Sheet1!$A$1:$A$3".to_string(),
9244                        values: "Sheet1!$C$1:$C$3".to_string(),
9245                        x_values: None,
9246                        bubble_sizes: None,
9247                    }],
9248                    show_legend: false,
9249                    view_3d: None,
9250                },
9251            )
9252            .unwrap_err();
9253        assert!(matches!(chart_error, Error::InvalidArgument(_)));
9254        assert_eq!(workbook.save_to_buffer().unwrap(), before);
9255
9256        let image_error = workbook
9257            .add_image(
9258                "Sheet1",
9259                &ImageConfig {
9260                    data: vec![0x89, 0x50, 0x4e, 0x47],
9261                    format: ImageFormat::Png,
9262                    from_cell: "A20".to_string(),
9263                    width_px: 10,
9264                    height_px: 10,
9265                },
9266            )
9267            .unwrap_err();
9268        assert!(matches!(image_error, Error::InvalidArgument(_)));
9269        assert_eq!(workbook.save_to_buffer().unwrap(), before);
9270    }
9271
9272    #[test]
9273    fn delete_sheet_rejects_owned_unparseable_raw_drawing_atomically() {
9274        let base = workbook_with_chart_buffer();
9275        let opaque_drawing = b"<xdr:wsDr><opaque></xdr:wsDr>".to_vec();
9276        let input = rewrite_zip_parts(
9277            &base,
9278            &[("xl/drawings/drawing1.xml", Some(opaque_drawing.clone()))],
9279        );
9280        let options = OpenOptions::new()
9281            .read_mode(ReadMode::Eager)
9282            .aux_parts(AuxParts::EagerLoad);
9283        let mut workbook = Workbook::open_from_buffer_with_options(&input, &options).unwrap();
9284        assert!(!workbook.worksheet_drawings.contains_key(&0));
9285        let before = workbook.save_to_buffer().unwrap();
9286
9287        let error = workbook.delete_sheet("Sheet1").unwrap_err();
9288        assert!(matches!(error, Error::InvalidArgument(_)));
9289        assert_eq!(workbook.sheet_names(), vec!["Sheet1", "Sheet2"]);
9290        let after = workbook.save_to_buffer().unwrap();
9291        assert_eq!(after, before);
9292        assert_eq!(zip_part(&after, "xl/drawings/drawing1.xml"), opaque_drawing);
9293        assert_eq!(zip_entry_count(&after, "xl/drawings/drawing1.xml"), 1);
9294    }
9295
9296    #[test]
9297    fn eager_edit_preserves_untouched_worksheet_bytes_with_extensions() {
9298        let mut workbook = Workbook::new();
9299        workbook.new_sheet("Untouched").unwrap();
9300        let base = workbook.save_to_buffer().unwrap();
9301        let sheet_path = "xl/worksheets/sheet2.xml";
9302        let raw_sheet = String::from_utf8(zip_part(&base, sheet_path)).unwrap();
9303        let raw_sheet = raw_sheet.replacen(
9304            "</worksheet>",
9305            concat!(
9306                "<colBreaks count=\"1\" manualBreakCount=\"1\">",
9307                "<brk id=\"3\" min=\"0\" max=\"1048575\" man=\"true\"/>",
9308                "</colBreaks>",
9309                "<extLst><ext uri=\"{opaque-sheet-extension}\">",
9310                "<opaque:payload xmlns:opaque=\"urn:sheetkit:test\" value=\"keep\"/>",
9311                "</ext></extLst></worksheet>"
9312            ),
9313            1,
9314        );
9315        let raw_sheet = raw_sheet.into_bytes();
9316        let input = rewrite_zip_parts(&base, &[(sheet_path, Some(raw_sheet.clone()))]);
9317        let options = OpenOptions::new()
9318            .read_mode(ReadMode::Eager)
9319            .aux_parts(AuxParts::EagerLoad);
9320        let mut opened = Workbook::open_from_buffer_with_options(&input, &options).unwrap();
9321
9322        assert!(!opened.is_sheet_dirty(0));
9323        assert!(!opened.is_sheet_dirty(1));
9324        opened.set_cell_value("Sheet1", "A1", "changed").unwrap();
9325        let saved = opened.save_to_buffer().unwrap();
9326
9327        assert_eq!(zip_part(&saved, sheet_path), raw_sheet);
9328        assert_eq!(zip_entry_count(&saved, sheet_path), 1);
9329        let saved_sheet = String::from_utf8(zip_part(&saved, sheet_path)).unwrap();
9330        assert_eq!(saved_sheet.matches("<extLst>").count(), 1);
9331    }
9332
9333    #[test]
9334    fn eager_sparkline_removal_does_not_reuse_stale_raw_sheet_xml() {
9335        let mut workbook = Workbook::new();
9336        workbook
9337            .add_sparkline(
9338                "Sheet1",
9339                &crate::sparkline::SparklineConfig::new("Sheet1!A1:A3", "B1"),
9340            )
9341            .unwrap();
9342        let base = workbook.save_to_buffer().unwrap();
9343        assert!(
9344            String::from_utf8(zip_part(&base, "xl/worksheets/sheet1.xml"))
9345                .unwrap()
9346                .contains("sparklineGroups")
9347        );
9348
9349        let options = OpenOptions::new()
9350            .read_mode(ReadMode::Eager)
9351            .aux_parts(AuxParts::EagerLoad);
9352        let mut opened = Workbook::open_from_buffer_with_options(&base, &options).unwrap();
9353        opened.remove_sparkline("Sheet1", "B1").unwrap();
9354        let saved = opened.save_to_buffer().unwrap();
9355        let saved_sheet = String::from_utf8(zip_part(&saved, "xl/worksheets/sheet1.xml")).unwrap();
9356
9357        assert!(!saved_sheet.contains("sparklineGroups"));
9358        assert!(!saved_sheet.contains("<extLst>"));
9359        assert_eq!(zip_entry_count(&saved, "xl/worksheets/sheet1.xml"), 1);
9360    }
9361
9362    #[test]
9363    fn lazy_sparkline_addition_bypasses_clean_package_raw_copy() {
9364        let base = Workbook::new().save_to_buffer().unwrap();
9365        let mut opened = Workbook::open_from_buffer_with_options(
9366            &base,
9367            &OpenOptions::new().read_mode(ReadMode::Lazy),
9368        )
9369        .unwrap();
9370        opened
9371            .add_sparkline(
9372                "Sheet1",
9373                &crate::sparkline::SparklineConfig::new("Sheet1!A1:A3", "B1"),
9374            )
9375            .unwrap();
9376        opened
9377            .add_sparkline(
9378                "Sheet1",
9379                &crate::sparkline::SparklineConfig::new("Sheet1!C1:C3", "D1"),
9380            )
9381            .unwrap();
9382
9383        let saved = opened.save_to_buffer().unwrap();
9384        let reopened = Workbook::open_from_buffer_with_options(
9385            &saved,
9386            &OpenOptions::new()
9387                .read_mode(ReadMode::Eager)
9388                .aux_parts(AuxParts::EagerLoad),
9389        )
9390        .unwrap();
9391        assert_eq!(reopened.get_sparklines("Sheet1").unwrap().len(), 2);
9392    }
9393
9394    #[test]
9395    fn dirty_sheet_extras_follow_worksheet_schema_order() {
9396        let mut workbook = Workbook::new();
9397        workbook
9398            .add_table(
9399                "Sheet1",
9400                &crate::table::TableConfig {
9401                    name: "Table1".to_string(),
9402                    display_name: "Table1".to_string(),
9403                    range: "A1:B3".to_string(),
9404                    columns: vec![
9405                        crate::table::TableColumn {
9406                            name: "Name".to_string(),
9407                            totals_row_function: None,
9408                            totals_row_label: None,
9409                        },
9410                        crate::table::TableColumn {
9411                            name: "Value".to_string(),
9412                            totals_row_function: None,
9413                            totals_row_label: None,
9414                        },
9415                    ],
9416                    ..crate::table::TableConfig::default()
9417                },
9418            )
9419            .unwrap();
9420        workbook
9421            .add_comment(
9422                "Sheet1",
9423                &crate::comment::CommentConfig {
9424                    cell: "A1".to_string(),
9425                    author: "Author".to_string(),
9426                    text: "Comment".to_string(),
9427                },
9428            )
9429            .unwrap();
9430        workbook
9431            .add_sparkline(
9432                "Sheet1",
9433                &crate::sparkline::SparklineConfig::new("Sheet1!B1:B3", "C1"),
9434            )
9435            .unwrap();
9436
9437        let saved = workbook.save_to_buffer().unwrap();
9438        let sheet = String::from_utf8(zip_part(&saved, "xl/worksheets/sheet1.xml")).unwrap();
9439        let legacy = sheet.find("<legacyDrawing ").unwrap();
9440        let tables = sheet.find("<tableParts ").unwrap();
9441        let extensions = sheet.find("<extLst>").unwrap();
9442        let closing = sheet.rfind("</worksheet>").unwrap();
9443
9444        assert!(legacy < tables, "legacyDrawing must precede tableParts");
9445        assert!(tables < extensions, "tableParts must precede extLst");
9446        assert!(
9447            extensions < closing,
9448            "extLst must be the final worksheet child"
9449        );
9450    }
9451
9452    #[test]
9453    fn workbook_xml_uses_raw_bytes_until_its_typed_owner_changes() {
9454        let base = Workbook::new().save_to_buffer().unwrap();
9455        let raw_workbook = String::from_utf8(zip_part(&base, "xl/workbook.xml")).unwrap();
9456        let raw_workbook = raw_workbook
9457            .replacen(
9458                "<workbookPr",
9459                concat!(
9460                    "<fileSharing readOnlyRecommended=\"true\" userName=\"owner\"/>",
9461                    "<workbookPr"
9462                ),
9463                1,
9464            )
9465            .replacen(
9466                "</sheets>",
9467                concat!(
9468                    "</sheets><externalReferences>",
9469                    "<externalReference r:id=\"rIdExternal\"/>",
9470                    "</externalReferences>"
9471                ),
9472                1,
9473            )
9474            .replacen(
9475                "</workbook>",
9476                concat!(
9477                    "<oleSize ref=\"A1:C3\"/>",
9478                    "<extLst><ext uri=\"{opaque-workbook-extension}\">",
9479                    "<opaque:payload xmlns:opaque=\"urn:sheetkit:test\" value=\"keep\"/>",
9480                    "</ext></extLst></workbook>"
9481                ),
9482                1,
9483            );
9484        assert!(raw_workbook.contains("fileSharing"));
9485        let raw_workbook = raw_workbook.into_bytes();
9486        let input = rewrite_zip_parts(&base, &[("xl/workbook.xml", Some(raw_workbook.clone()))]);
9487        let options = OpenOptions::new()
9488            .read_mode(ReadMode::Eager)
9489            .aux_parts(AuxParts::EagerLoad);
9490
9491        let mut cell_edit = Workbook::open_from_buffer_with_options(&input, &options).unwrap();
9492        assert_eq!(
9493            cell_edit
9494                .workbook_xml
9495                .file_sharing
9496                .as_ref()
9497                .and_then(|sharing| sharing.user_name.as_deref()),
9498            Some("owner")
9499        );
9500        assert_eq!(
9501            cell_edit
9502                .workbook_xml
9503                .ole_size
9504                .as_ref()
9505                .map(|size| size.reference.as_str()),
9506            Some("A1:C3")
9507        );
9508        assert_eq!(
9509            cell_edit
9510                .workbook_xml
9511                .external_references
9512                .as_ref()
9513                .and_then(|references| references.references.first())
9514                .map(|reference| reference.r_id.as_str()),
9515            Some("rIdExternal")
9516        );
9517        cell_edit.set_cell_value("Sheet1", "A1", "changed").unwrap();
9518        let cell_saved = cell_edit.save_to_buffer().unwrap();
9519        assert_eq!(zip_part(&cell_saved, "xl/workbook.xml"), raw_workbook);
9520        assert_eq!(zip_entry_count(&cell_saved, "xl/workbook.xml"), 1);
9521
9522        let mut owner_edit = Workbook::open_from_buffer_with_options(&input, &options).unwrap();
9523        owner_edit.new_sheet("Added").unwrap();
9524        let owner_saved = owner_edit.save_to_buffer().unwrap();
9525        let owner_xml = zip_part(&owner_saved, "xl/workbook.xml");
9526        assert_ne!(owner_xml, raw_workbook);
9527        let owner_xml = String::from_utf8(owner_xml).unwrap();
9528        assert!(owner_xml.contains("name=\"Added\""));
9529        assert!(owner_xml.contains("r:id=\"rIdExternal\""));
9530        assert_eq!(zip_entry_count(&owner_saved, "xl/workbook.xml"), 1);
9531    }
9532
9533    fn opaque_doc_props_buffer() -> (Vec<u8>, Vec<u8>, Vec<u8>, Vec<u8>) {
9534        let mut workbook = Workbook::new();
9535        workbook.set_doc_props(crate::doc_props::DocProperties {
9536            title: Some("Original".to_string()),
9537            ..Default::default()
9538        });
9539        workbook.set_app_props(crate::doc_props::AppProperties {
9540            application: Some("Original app".to_string()),
9541            ..Default::default()
9542        });
9543        workbook.set_custom_property(
9544            "Original",
9545            crate::doc_props::CustomPropertyValue::String("value".to_string()),
9546        );
9547        let base = workbook.save_to_buffer().unwrap();
9548        let core = b"<cp:coreProperties xmlns:cp=\"http://schemas.openxmlformats.org/package/2006/metadata/core-properties\"><broken></cp:coreProperties>".to_vec();
9549        let app = b"<Properties xmlns=\"http://schemas.openxmlformats.org/officeDocument/2006/extended-properties\"><broken></Properties>".to_vec();
9550        let custom = concat!(
9551            "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>",
9552            "<Properties xmlns=\"http://schemas.openxmlformats.org/officeDocument/2006/custom-properties\" ",
9553            "xmlns:vt=\"http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes\">",
9554            "<property fmtid=\"{D5CDD505-2E9C-101B-9397-08002B2CF9AE}\" pid=\"2\" name=\"Empty\">",
9555            "<vt:empty/></property></Properties>"
9556        )
9557        .as_bytes()
9558        .to_vec();
9559        let input = rewrite_zip_parts(
9560            &base,
9561            &[
9562                ("docProps/core.xml", Some(core.clone())),
9563                ("docProps/app.xml", Some(app.clone())),
9564                ("docProps/custom.xml", Some(custom.clone())),
9565            ],
9566        );
9567        (input, core, app, custom)
9568    }
9569
9570    fn doc_props_options(read_mode: ReadMode) -> OpenOptions {
9571        let options = OpenOptions::new().read_mode(read_mode);
9572        if read_mode == ReadMode::Eager {
9573            options.aux_parts(AuxParts::EagerLoad)
9574        } else {
9575            options
9576        }
9577    }
9578
9579    #[test]
9580    fn eager_and_lazy_noop_preserve_each_opaque_doc_props_part() {
9581        let (input, core, app, custom) = opaque_doc_props_buffer();
9582        for read_mode in [ReadMode::Eager, ReadMode::Lazy] {
9583            let opened =
9584                Workbook::open_from_buffer_with_options(&input, &doc_props_options(read_mode))
9585                    .unwrap();
9586            let saved = opened.save_to_buffer().unwrap();
9587
9588            for (path, expected) in [
9589                ("docProps/core.xml", core.as_slice()),
9590                ("docProps/app.xml", app.as_slice()),
9591                ("docProps/custom.xml", custom.as_slice()),
9592            ] {
9593                assert_eq!(zip_part(&saved, path), expected, "{read_mode:?}: {path}");
9594                assert_eq!(zip_entry_count(&saved, path), 1, "{read_mode:?}: {path}");
9595            }
9596        }
9597    }
9598
9599    #[test]
9600    fn eager_and_lazy_doc_props_mutations_only_rewrite_the_target_part() {
9601        let (input, core, app, custom) = opaque_doc_props_buffer();
9602        for read_mode in [ReadMode::Eager, ReadMode::Lazy] {
9603            let options = doc_props_options(read_mode);
9604
9605            let mut core_edit = Workbook::open_from_buffer_with_options(&input, &options).unwrap();
9606            core_edit.set_doc_props(crate::doc_props::DocProperties {
9607                title: Some("Updated".to_string()),
9608                ..Default::default()
9609            });
9610            let saved = core_edit.save_to_buffer().unwrap();
9611            assert_ne!(zip_part(&saved, "docProps/core.xml"), core);
9612            assert_eq!(zip_part(&saved, "docProps/app.xml"), app);
9613            assert_eq!(zip_part(&saved, "docProps/custom.xml"), custom);
9614
9615            let mut app_edit = Workbook::open_from_buffer_with_options(&input, &options).unwrap();
9616            app_edit.set_app_props(crate::doc_props::AppProperties {
9617                application: Some("Updated app".to_string()),
9618                ..Default::default()
9619            });
9620            let saved = app_edit.save_to_buffer().unwrap();
9621            assert_eq!(zip_part(&saved, "docProps/core.xml"), core);
9622            assert_ne!(zip_part(&saved, "docProps/app.xml"), app);
9623            assert_eq!(zip_part(&saved, "docProps/custom.xml"), custom);
9624
9625            let mut custom_edit =
9626                Workbook::open_from_buffer_with_options(&input, &options).unwrap();
9627            custom_edit
9628                .set_custom_property("Updated", crate::doc_props::CustomPropertyValue::Bool(true));
9629            let saved = custom_edit.save_to_buffer().unwrap();
9630            assert_eq!(zip_part(&saved, "docProps/core.xml"), core);
9631            assert_eq!(zip_part(&saved, "docProps/app.xml"), app);
9632            assert_ne!(zip_part(&saved, "docProps/custom.xml"), custom);
9633            for path in [
9634                "docProps/core.xml",
9635                "docProps/app.xml",
9636                "docProps/custom.xml",
9637            ] {
9638                assert_eq!(zip_entry_count(&saved, path), 1, "{read_mode:?}: {path}");
9639            }
9640        }
9641    }
9642}