Skip to main content

sheetkit_core/
col.rs

1//! Column operations for worksheet manipulation.
2//!
3//! All functions operate directly on a [`WorksheetXml`] structure, keeping the
4//! business logic decoupled from the [`Workbook`](crate::workbook::Workbook)
5//! wrapper.
6
7use sheetkit_xml::worksheet::{Col, Cols, WorksheetXml};
8
9use crate::cell::CellValue;
10use crate::error::{Error, Result};
11use crate::raw_transfer::SharedFollowers;
12use crate::row::{cell_cloned_payload_bytes, resolve_cell_value};
13use crate::sst::SharedStringTable;
14use crate::traversal::{check_limit, TraversalLimits};
15use crate::utils::cell_ref::{
16    cell_name_to_coordinates, column_name_to_number, column_number_to_name, compact_cell_ref,
17};
18use crate::utils::constants::{MAX_COLUMNS, MAX_COLUMN_WIDTH, MAX_ROWS};
19
20/// Get all columns with their data from a worksheet.
21///
22/// Returns a Vec of `(column_name, Vec<(row_number, CellValue)>)` tuples.
23/// Only columns that have data are included (sparse). The columns are sorted
24/// by column order (A, B, ..., Z, AA, AB, ...). `style_is_date` has the
25/// same meaning as in [`crate::row::get_rows`].
26#[allow(clippy::type_complexity)]
27pub fn get_cols(
28    ws: &WorksheetXml,
29    sst: &SharedStringTable,
30    style_is_date: &[bool],
31) -> Result<Vec<(String, Vec<(u32, CellValue)>)>> {
32    get_cols_with_limits(ws, sst, style_is_date, TraversalLimits::default())
33}
34
35/// Gets sparse columns with explicit finite materialization limits.
36///
37/// Counts and retained cloned bytes are admitted before result allocation.
38#[allow(clippy::type_complexity)]
39pub fn get_cols_with_limits(
40    ws: &WorksheetXml,
41    sst: &SharedStringTable,
42    style_is_date: &[bool],
43    limits: TraversalLimits,
44) -> Result<Vec<(String, Vec<(u32, CellValue)>)>> {
45    let mut column_counts = [0u64; MAX_COLUMNS as usize];
46    let mut row_count = 0u64;
47    let mut column_count = 0u64;
48    let mut cell_count = 0u64;
49    let mut retained_bytes = 0u64;
50
51    for row in &ws.sheet_data.rows {
52        if row.cells.is_empty() {
53            continue;
54        }
55        if row.r == 0 || row.r > MAX_ROWS {
56            return Err(Error::InvalidRowNumber(row.r));
57        }
58        row_count = row_count.saturating_add(1);
59        check_limit(
60            crate::ResourceDimension::RowCount,
61            limits.max_rows(),
62            row_count,
63        )?;
64
65        for cell in &row.cells {
66            let col_num = if cell.col > 0 {
67                cell.col
68            } else {
69                cell_name_to_coordinates(cell.r.as_str())?.0
70            };
71            if col_num == 0 || col_num > MAX_COLUMNS {
72                return Err(Error::InvalidColumnNumber(col_num));
73            }
74            let column_slot = usize::try_from(col_num - 1)
75                .map_err(|_| Error::Internal("column index is not addressable".to_string()))?;
76            if column_counts[column_slot] == 0 {
77                column_count = column_count.saturating_add(1);
78                check_limit(
79                    crate::ResourceDimension::ColumnCount,
80                    limits.max_columns(),
81                    column_count,
82                )?;
83                retained_bytes = retained_bytes
84                    .saturating_add(
85                        u64::try_from(std::mem::size_of::<(String, Vec<(u32, CellValue)>)>())
86                            .unwrap_or(u64::MAX),
87                    )
88                    .saturating_add(column_name_byte_len(col_num));
89            }
90            column_counts[column_slot] = column_counts[column_slot].saturating_add(1);
91            cell_count = cell_count.saturating_add(1);
92            check_limit(
93                crate::ResourceDimension::CellCount,
94                limits.max_cells(),
95                cell_count,
96            )?;
97            retained_bytes = retained_bytes
98                .saturating_add(
99                    u64::try_from(std::mem::size_of::<(u32, CellValue)>()).unwrap_or(u64::MAX),
100                )
101                .saturating_add(cell_cloned_payload_bytes(cell, sst));
102            check_limit(
103                crate::ResourceDimension::RetainedBytes,
104                limits.max_output_bytes(),
105                retained_bytes,
106            )?;
107        }
108    }
109
110    let mut result = Vec::new();
111    result
112        .try_reserve_exact(
113            usize::try_from(column_count).map_err(|_| {
114                Error::Internal("column result size is not addressable".to_string())
115            })?,
116        )
117        .map_err(|_| Error::Internal("column result allocation failed".to_string()))?;
118    for (column_slot, count_slot) in column_counts.iter_mut().enumerate() {
119        let count = *count_slot;
120        if count == 0 {
121            continue;
122        }
123        let col_num = u32::try_from(column_slot + 1)
124            .map_err(|_| Error::Internal("column number is not representable".to_string()))?;
125        let mut cells = Vec::new();
126        cells
127            .try_reserve_exact(
128                usize::try_from(count).map_err(|_| {
129                    Error::Internal("column cell count is not addressable".to_string())
130                })?,
131            )
132            .map_err(|_| Error::Internal("column cell allocation failed".to_string()))?;
133        *count_slot = u64::try_from(result.len())
134            .map_err(|_| Error::Internal("column result index is not representable".to_string()))?;
135        result.push((column_number_to_name(col_num)?, cells));
136    }
137
138    let mut followers = SharedFollowers::new(ws, limits, retained_bytes, None)?;
139    for row in &ws.sheet_data.rows {
140        for cell in &row.cells {
141            let col_num = if cell.col > 0 {
142                cell.col
143            } else {
144                cell_name_to_coordinates(cell.r.as_str())?.0
145            };
146            let column_slot = usize::try_from(col_num - 1)
147                .map_err(|_| Error::Internal("column index is not addressable".to_string()))?;
148            let result_index = usize::try_from(column_counts[column_slot]).map_err(|_| {
149                Error::Internal("column result index is not addressable".to_string())
150            })?;
151            let mut value = resolve_cell_value(cell, sst, style_is_date);
152            followers.resolve(&mut value, cell)?;
153            result[result_index].1.push((row.r, value));
154        }
155    }
156
157    Ok(result)
158}
159
160const fn column_name_byte_len(column: u32) -> u64 {
161    if column <= 26 {
162        1
163    } else if column <= 26 * 27 {
164        2
165    } else {
166        3
167    }
168}
169
170/// Set the width of a column. Creates the `Cols` container and/or a `Col`
171/// entry if they do not yet exist.
172///
173/// Valid range: `0.0 ..= 255.0`.
174pub fn set_col_width(ws: &mut WorksheetXml, col: &str, width: f64) -> Result<()> {
175    let col_num = column_name_to_number(col)?;
176    if !(0.0..=MAX_COLUMN_WIDTH).contains(&width) {
177        return Err(Error::ColumnWidthExceeded {
178            width,
179            max: MAX_COLUMN_WIDTH,
180        });
181    }
182
183    let col_entry = find_or_create_col(ws, col_num);
184    col_entry.width = Some(width);
185    col_entry.custom_width = Some(true);
186    Ok(())
187}
188
189/// Get the width of a column. Returns `None` when there is no explicit width
190/// defined for the column.
191pub fn get_col_width(ws: &WorksheetXml, col: &str) -> Option<f64> {
192    let col_num = column_name_to_number(col).ok()?;
193    ws.cols
194        .as_ref()
195        .and_then(|cols| {
196            cols.cols
197                .iter()
198                .find(|c| col_num >= c.min && col_num <= c.max)
199        })
200        .and_then(|c| c.width)
201}
202
203/// Set the visibility of a column.
204pub fn set_col_visible(ws: &mut WorksheetXml, col: &str, visible: bool) -> Result<()> {
205    let col_num = column_name_to_number(col)?;
206    let col_entry = find_or_create_col(ws, col_num);
207    col_entry.hidden = if visible { None } else { Some(true) };
208    Ok(())
209}
210
211/// Get the visibility of a column. Returns true if visible (not hidden).
212///
213/// Columns are visible by default, so this returns true if no `Col` entry
214/// exists or if it has no `hidden` attribute set.
215pub fn get_col_visible(ws: &WorksheetXml, col: &str) -> Result<bool> {
216    let col_num = column_name_to_number(col)?;
217    let hidden = ws
218        .cols
219        .as_ref()
220        .and_then(|cols| {
221            cols.cols
222                .iter()
223                .find(|c| col_num >= c.min && col_num <= c.max)
224        })
225        .and_then(|c| c.hidden)
226        .unwrap_or(false);
227    Ok(!hidden)
228}
229
230/// Set the outline (grouping) level of a column.
231///
232/// Valid range: `0..=7` (Excel supports up to 7 outline levels).
233pub fn set_col_outline_level(ws: &mut WorksheetXml, col: &str, level: u8) -> Result<()> {
234    let col_num = column_name_to_number(col)?;
235    if level > 7 {
236        return Err(Error::OutlineLevelExceeded { level, max: 7 });
237    }
238
239    let col_entry = find_or_create_col(ws, col_num);
240    col_entry.outline_level = if level == 0 { None } else { Some(level) };
241    Ok(())
242}
243
244/// Get the outline (grouping) level of a column. Returns 0 if not set.
245pub fn get_col_outline_level(ws: &WorksheetXml, col: &str) -> Result<u8> {
246    let col_num = column_name_to_number(col)?;
247    let level = ws
248        .cols
249        .as_ref()
250        .and_then(|cols| {
251            cols.cols
252                .iter()
253                .find(|c| col_num >= c.min && col_num <= c.max)
254        })
255        .and_then(|c| c.outline_level)
256        .unwrap_or(0);
257    Ok(level)
258}
259
260/// Insert `count` columns starting at `col`, shifting existing columns at
261/// and to the right of `col` further right.
262///
263/// Cell references are updated: e.g. when inserting 2 columns at "B", a cell
264/// "C3" becomes "E3".
265pub fn insert_cols(ws: &mut WorksheetXml, col: &str, count: u32) -> Result<()> {
266    let start_col = column_name_to_number(col)?;
267    if count == 0 {
268        return Ok(());
269    }
270
271    // Validate we won't exceed max columns.
272    let max_existing = ws
273        .sheet_data
274        .rows
275        .iter()
276        .flat_map(|r| r.cells.iter())
277        .filter_map(|c| cell_name_to_coordinates(c.r.as_str()).ok())
278        .map(|(col_n, _)| col_n)
279        .max()
280        .unwrap_or(0);
281    let furthest = max_existing.max(start_col);
282    if furthest.checked_add(count).is_none_or(|v| v > MAX_COLUMNS) {
283        return Err(Error::InvalidColumnNumber(furthest.saturating_add(count)));
284    }
285    let spans = validated_col_spans(ws)?;
286
287    // Shift cell references.
288    for row in ws.sheet_data.rows.iter_mut() {
289        for cell in row.cells.iter_mut() {
290            let (c, r) = cell_name_to_coordinates(cell.r.as_str())?;
291            if c >= start_col {
292                let new_col = c + count;
293                cell.r = compact_cell_ref(new_col, r)?;
294                cell.col = new_col;
295            }
296        }
297    }
298
299    // Shift Col definitions. Spans pushed past the last column are dropped
300    // and spans reaching it stay pinned to it.
301    if let Some(ref mut cols) = ws.cols {
302        let mut kept = Vec::with_capacity(cols.cols.len());
303        for (mut c, (min, max)) in std::mem::take(&mut cols.cols).into_iter().zip(spans) {
304            let shift = |value: u32| {
305                if value >= start_col {
306                    value.checked_add(count)
307                } else {
308                    Some(value)
309                }
310            };
311            let Some(min) = shift(min).filter(|min| *min <= MAX_COLUMNS) else {
312                continue;
313            };
314            c.min = min;
315            c.max = shift(max).map_or(MAX_COLUMNS, |max| max.min(MAX_COLUMNS));
316            kept.push(c);
317        }
318        cols.cols = kept;
319        if cols.cols.is_empty() {
320            ws.cols = None;
321        }
322    }
323
324    Ok(())
325}
326
327/// Validate every `<col>` span and return its bounds with `max` clamped to
328/// the last worksheet column. Spans with `min` outside `1..=MAX_COLUMNS` or
329/// `max < min` are rejected.
330fn validated_col_spans(ws: &WorksheetXml) -> Result<Vec<(u32, u32)>> {
331    let Some(cols) = &ws.cols else {
332        return Ok(Vec::new());
333    };
334    cols.cols
335        .iter()
336        .map(|c| {
337            if !(1..=MAX_COLUMNS).contains(&c.min) {
338                return Err(Error::InvalidColumnNumber(c.min));
339            }
340            if c.max < c.min {
341                return Err(Error::InvalidColumnNumber(c.max));
342            }
343            Ok((c.min, c.max.min(MAX_COLUMNS)))
344        })
345        .collect()
346}
347
348/// Remove a single column, shifting columns to its right leftward by one.
349pub fn remove_col(ws: &mut WorksheetXml, col: &str) -> Result<()> {
350    let col_num = column_name_to_number(col)?;
351    let spans = validated_col_spans(ws)?;
352
353    // Remove cells in the target column and shift cells to the right.
354    for row in ws.sheet_data.rows.iter_mut() {
355        // Remove cells at the target column.
356        row.cells.retain(|cell| {
357            cell_name_to_coordinates(cell.r.as_str())
358                .map(|(c, _)| c != col_num)
359                .unwrap_or(true)
360        });
361
362        // Shift cells that are to the right of the removed column.
363        for cell in row.cells.iter_mut() {
364            let (c, r) = cell_name_to_coordinates(cell.r.as_str())?;
365            if c > col_num {
366                let new_col = c - 1;
367                cell.r = compact_cell_ref(new_col, r)?;
368                cell.col = new_col;
369            }
370        }
371    }
372
373    // Shift Col definitions.
374    if let Some(ref mut cols) = ws.cols {
375        for (c, (min, max)) in cols.cols.iter_mut().zip(spans) {
376            c.min = min;
377            c.max = max;
378        }
379        // Remove col entries that exactly span the removed column only.
380        cols.cols
381            .retain(|c| !(c.min == col_num && c.max == col_num));
382
383        for c in cols.cols.iter_mut() {
384            if c.min > col_num {
385                c.min -= 1;
386            }
387            if c.max >= col_num {
388                c.max -= 1;
389            }
390        }
391
392        // Remove the Cols wrapper if it's now empty.
393        if cols.cols.is_empty() {
394            ws.cols = None;
395        }
396    }
397
398    Ok(())
399}
400
401/// Set the style for an entire column. The `style_id` is the ID returned by
402/// `add_style()`.
403pub fn set_col_style(ws: &mut WorksheetXml, col: &str, style_id: u32) -> Result<()> {
404    let col_num = column_name_to_number(col)?;
405    let col_entry = find_or_create_col(ws, col_num);
406    col_entry.style = Some(style_id);
407    Ok(())
408}
409
410/// Get the style ID for a column. Returns 0 (default) if the column has no
411/// explicit style set.
412pub fn get_col_style(ws: &WorksheetXml, col: &str) -> Result<u32> {
413    let col_num = column_name_to_number(col)?;
414    let style = ws
415        .cols
416        .as_ref()
417        .and_then(|cols| {
418            cols.cols
419                .iter()
420                .find(|c| col_num >= c.min && col_num <= c.max)
421        })
422        .and_then(|c| c.style)
423        .unwrap_or(0);
424    Ok(style)
425}
426
427/// Find an existing Col entry that covers `col_num`, splitting a range into
428/// left, target, and right entries when necessary, or create a new entry.
429fn find_or_create_col(ws: &mut WorksheetXml, col_num: u32) -> &mut Col {
430    // Ensure the Cols container exists.
431    if ws.cols.is_none() {
432        ws.cols = Some(Cols { cols: vec![] });
433    }
434    let cols = ws.cols.as_mut().unwrap();
435
436    let existing = cols
437        .cols
438        .iter()
439        .position(|c| col_num >= c.min && col_num <= c.max);
440
441    if let Some(idx) = existing {
442        if cols.cols[idx].min == col_num && cols.cols[idx].max == col_num {
443            return &mut cols.cols[idx];
444        }
445
446        let original = cols.cols.remove(idx);
447        let has_left = original.min < col_num;
448        let has_right = col_num < original.max;
449        let mut replacements = Vec::with_capacity(1 + has_left as usize + has_right as usize);
450        if has_left {
451            let mut left = original.clone();
452            left.max = col_num - 1;
453            replacements.push(left);
454        }
455        let mut target = original.clone();
456        target.min = col_num;
457        target.max = col_num;
458        replacements.push(target);
459        if has_right {
460            let mut right = original;
461            right.min = col_num + 1;
462            replacements.push(right);
463        }
464        cols.cols.splice(idx..idx, replacements);
465        return &mut cols.cols[idx + has_left as usize];
466    }
467
468    // Create a new single-column entry.
469    cols.cols.push(Col {
470        min: col_num,
471        max: col_num,
472        width: None,
473        style: None,
474        hidden: None,
475        custom_width: None,
476        outline_level: None,
477    });
478    let last = cols.cols.len() - 1;
479    &mut cols.cols[last]
480}
481
482#[cfg(test)]
483#[allow(clippy::field_reassign_with_default)]
484mod tests {
485    use super::*;
486    use sheetkit_xml::worksheet::{Cell, CellTypeTag, Row, SheetData};
487
488    /// Helper: build a worksheet with some cells for column tests.
489    fn sample_ws() -> WorksheetXml {
490        let mut ws = WorksheetXml::default();
491        ws.sheet_data = SheetData {
492            rows: vec![
493                Row {
494                    r: 1,
495                    spans: None,
496                    s: None,
497                    custom_format: None,
498                    ht: None,
499                    hidden: None,
500                    custom_height: None,
501                    outline_level: None,
502                    cells: vec![
503                        Cell {
504                            r: "A1".try_into().unwrap(),
505                            col: 1,
506                            s: None,
507                            t: CellTypeTag::None,
508                            v: Some("10".to_string()),
509                            f: None,
510                            is: None,
511                        },
512                        Cell {
513                            r: "B1".try_into().unwrap(),
514                            col: 2,
515                            s: None,
516                            t: CellTypeTag::None,
517                            v: Some("20".to_string()),
518                            f: None,
519                            is: None,
520                        },
521                        Cell {
522                            r: "D1".try_into().unwrap(),
523                            col: 4,
524                            s: None,
525                            t: CellTypeTag::None,
526                            v: Some("40".to_string()),
527                            f: None,
528                            is: None,
529                        },
530                    ],
531                },
532                Row {
533                    r: 2,
534                    spans: None,
535                    s: None,
536                    custom_format: None,
537                    ht: None,
538                    hidden: None,
539                    custom_height: None,
540                    outline_level: None,
541                    cells: vec![
542                        Cell {
543                            r: "A2".try_into().unwrap(),
544                            col: 1,
545                            s: None,
546                            t: CellTypeTag::None,
547                            v: Some("100".to_string()),
548                            f: None,
549                            is: None,
550                        },
551                        Cell {
552                            r: "C2".try_into().unwrap(),
553                            col: 3,
554                            s: None,
555                            t: CellTypeTag::None,
556                            v: Some("300".to_string()),
557                            f: None,
558                            is: None,
559                        },
560                    ],
561                },
562            ],
563        };
564        ws
565    }
566
567    #[test]
568    fn test_set_and_get_col_width() {
569        let mut ws = WorksheetXml::default();
570        set_col_width(&mut ws, "A", 15.0).unwrap();
571        assert_eq!(get_col_width(&ws, "A"), Some(15.0));
572    }
573
574    #[test]
575    fn test_set_col_width_creates_cols_container() {
576        let mut ws = WorksheetXml::default();
577        assert!(ws.cols.is_none());
578        set_col_width(&mut ws, "B", 20.0).unwrap();
579        assert!(ws.cols.is_some());
580        let cols = ws.cols.as_ref().unwrap();
581        assert_eq!(cols.cols.len(), 1);
582        assert_eq!(cols.cols[0].min, 2);
583        assert_eq!(cols.cols[0].max, 2);
584        assert_eq!(cols.cols[0].custom_width, Some(true));
585    }
586
587    #[test]
588    fn test_set_col_width_zero_is_valid() {
589        let mut ws = WorksheetXml::default();
590        set_col_width(&mut ws, "A", 0.0).unwrap();
591        assert_eq!(get_col_width(&ws, "A"), Some(0.0));
592    }
593
594    #[test]
595    fn test_set_col_width_max_is_valid() {
596        let mut ws = WorksheetXml::default();
597        set_col_width(&mut ws, "A", 255.0).unwrap();
598        assert_eq!(get_col_width(&ws, "A"), Some(255.0));
599    }
600
601    #[test]
602    fn test_set_col_width_exceeds_max_returns_error() {
603        let mut ws = WorksheetXml::default();
604        let result = set_col_width(&mut ws, "A", 256.0);
605        assert!(result.is_err());
606        assert!(matches!(
607            result.unwrap_err(),
608            Error::ColumnWidthExceeded { .. }
609        ));
610    }
611
612    #[test]
613    fn test_set_col_width_negative_returns_error() {
614        let mut ws = WorksheetXml::default();
615        let result = set_col_width(&mut ws, "A", -1.0);
616        assert!(result.is_err());
617    }
618
619    #[test]
620    fn test_get_col_width_nonexistent_returns_none() {
621        let ws = WorksheetXml::default();
622        assert_eq!(get_col_width(&ws, "Z"), None);
623    }
624
625    #[test]
626    fn test_set_col_width_invalid_column_returns_error() {
627        let mut ws = WorksheetXml::default();
628        let result = set_col_width(&mut ws, "XFE", 10.0);
629        assert!(result.is_err());
630    }
631
632    #[test]
633    fn test_set_col_hidden() {
634        let mut ws = WorksheetXml::default();
635        set_col_visible(&mut ws, "A", false).unwrap();
636
637        let col = &ws.cols.as_ref().unwrap().cols[0];
638        assert_eq!(col.hidden, Some(true));
639    }
640
641    #[test]
642    fn test_set_col_visible_clears_hidden() {
643        let mut ws = WorksheetXml::default();
644        set_col_visible(&mut ws, "A", false).unwrap();
645        set_col_visible(&mut ws, "A", true).unwrap();
646
647        let col = &ws.cols.as_ref().unwrap().cols[0];
648        assert_eq!(col.hidden, None);
649    }
650
651    #[test]
652    fn test_insert_cols_shifts_cells_right() {
653        let mut ws = sample_ws();
654        insert_cols(&mut ws, "B", 2).unwrap();
655
656        // Row 1: A1 stays, B1->D1, D1->F1.
657        let r1 = &ws.sheet_data.rows[0];
658        assert_eq!(r1.cells[0].r, "A1");
659        assert_eq!(r1.cells[1].r, "D1"); // B shifted by 2
660        assert_eq!(r1.cells[2].r, "F1"); // D shifted by 2
661
662        // Row 2: A2 stays, C2->E2.
663        let r2 = &ws.sheet_data.rows[1];
664        assert_eq!(r2.cells[0].r, "A2");
665        assert_eq!(r2.cells[1].r, "E2"); // C shifted by 2
666    }
667
668    #[test]
669    fn test_insert_cols_at_column_a() {
670        let mut ws = sample_ws();
671        insert_cols(&mut ws, "A", 1).unwrap();
672
673        // All cells shift right by 1.
674        let r1 = &ws.sheet_data.rows[0];
675        assert_eq!(r1.cells[0].r, "B1"); // A->B
676        assert_eq!(r1.cells[1].r, "C1"); // B->C
677        assert_eq!(r1.cells[2].r, "E1"); // D->E
678    }
679
680    #[test]
681    fn test_insert_cols_count_zero_is_noop() {
682        let mut ws = sample_ws();
683        insert_cols(&mut ws, "B", 0).unwrap();
684        assert_eq!(ws.sheet_data.rows[0].cells[0].r, "A1");
685        assert_eq!(ws.sheet_data.rows[0].cells[1].r, "B1");
686    }
687
688    #[test]
689    fn test_insert_cols_on_empty_sheet() {
690        let mut ws = WorksheetXml::default();
691        insert_cols(&mut ws, "A", 5).unwrap();
692        assert!(ws.sheet_data.rows.is_empty());
693    }
694
695    #[test]
696    fn test_insert_cols_u32_overflow_returns_error_without_mutation() {
697        let mut ws = sample_ws();
698        let before = ws.clone();
699
700        let result = insert_cols(&mut ws, "A", u32::MAX);
701
702        assert!(matches!(result, Err(Error::InvalidColumnNumber(u32::MAX))));
703        assert_eq!(ws, before);
704    }
705
706    #[test]
707    fn test_insert_cols_shifts_col_definitions() {
708        let mut ws = WorksheetXml::default();
709        set_col_width(&mut ws, "C", 20.0).unwrap();
710        insert_cols(&mut ws, "B", 2).unwrap();
711
712        // Col C (3) should now be at col 5 (E).
713        let col = &ws.cols.as_ref().unwrap().cols[0];
714        assert_eq!(col.min, 5);
715        assert_eq!(col.max, 5);
716    }
717
718    #[test]
719    fn test_remove_col_shifts_cells_left() {
720        let mut ws = sample_ws();
721        remove_col(&mut ws, "B").unwrap();
722
723        // Row 1: A1 stays, B1 removed, D1->C1.
724        let r1 = &ws.sheet_data.rows[0];
725        assert_eq!(r1.cells.len(), 2);
726        assert_eq!(r1.cells[0].r, "A1");
727        assert_eq!(r1.cells[1].r, "C1"); // D shifted left
728        assert_eq!(r1.cells[1].v, Some("40".to_string()));
729
730        // Row 2: A2 stays, C2->B2.
731        let r2 = &ws.sheet_data.rows[1];
732        assert_eq!(r2.cells[0].r, "A2");
733        assert_eq!(r2.cells[1].r, "B2"); // C shifted left
734    }
735
736    #[test]
737    fn test_remove_first_col() {
738        let mut ws = sample_ws();
739        remove_col(&mut ws, "A").unwrap();
740
741        // Row 1: A1 removed, B1->A1, D1->C1.
742        let r1 = &ws.sheet_data.rows[0];
743        assert_eq!(r1.cells.len(), 2);
744        assert_eq!(r1.cells[0].r, "A1");
745        assert_eq!(r1.cells[0].v, Some("20".to_string())); // was B1
746        assert_eq!(r1.cells[1].r, "C1");
747        assert_eq!(r1.cells[1].v, Some("40".to_string())); // was D1
748    }
749
750    #[test]
751    fn test_remove_col_with_col_definitions() {
752        let mut ws = WorksheetXml::default();
753        set_col_width(&mut ws, "B", 20.0).unwrap();
754        remove_col(&mut ws, "B").unwrap();
755
756        // The Col entry for B should be removed.
757        assert!(ws.cols.is_none());
758    }
759
760    #[test]
761    fn test_remove_col_shrinks_range_ending_at_removed_column() {
762        // Range B:C (min=2, max=3); removing column C should shrink to B:B (min=2, max=2).
763        let mut ws = WorksheetXml::default();
764        set_col_width(&mut ws, "B", 15.0).unwrap();
765        // Manually extend the col entry to span B:C.
766        ws.cols.as_mut().unwrap().cols[0].max = 3;
767        remove_col(&mut ws, "C").unwrap();
768        let col = &ws.cols.as_ref().unwrap().cols[0];
769        assert_eq!(col.min, 2);
770        assert_eq!(col.max, 2);
771    }
772
773    #[test]
774    fn test_remove_col_shrinks_range_spanning_removed_column() {
775        // Range B:E (min=2, max=5); removing column C should shrink to B:D (min=2, max=4).
776        let mut ws = WorksheetXml::default();
777        set_col_width(&mut ws, "B", 15.0).unwrap();
778        ws.cols.as_mut().unwrap().cols[0].max = 5;
779        remove_col(&mut ws, "C").unwrap();
780        let col = &ws.cols.as_ref().unwrap().cols[0];
781        assert_eq!(col.min, 2);
782        assert_eq!(col.max, 4);
783    }
784
785    #[test]
786    fn test_remove_col_invalid_column_returns_error() {
787        let mut ws = WorksheetXml::default();
788        let result = remove_col(&mut ws, "XFE");
789        assert!(result.is_err());
790    }
791
792    #[test]
793    fn test_set_multiple_col_widths() {
794        let mut ws = WorksheetXml::default();
795        set_col_width(&mut ws, "A", 10.0).unwrap();
796        set_col_width(&mut ws, "C", 30.0).unwrap();
797
798        assert_eq!(get_col_width(&ws, "A"), Some(10.0));
799        assert_eq!(get_col_width(&ws, "B"), None);
800        assert_eq!(get_col_width(&ws, "C"), Some(30.0));
801    }
802
803    #[test]
804    fn test_overwrite_col_width() {
805        let mut ws = WorksheetXml::default();
806        set_col_width(&mut ws, "A", 10.0).unwrap();
807        set_col_width(&mut ws, "A", 25.0).unwrap();
808
809        assert_eq!(get_col_width(&ws, "A"), Some(25.0));
810    }
811
812    #[test]
813    fn test_setters_split_loaded_column_spans_preserving_attributes_and_order() {
814        let mut ws = WorksheetXml::default();
815        ws.cols = Some(Cols {
816            cols: vec![
817                Col {
818                    min: 1,
819                    max: 5,
820                    width: Some(12.0),
821                    style: Some(3),
822                    hidden: Some(true),
823                    custom_width: Some(true),
824                    outline_level: Some(2),
825                },
826                Col {
827                    min: 7,
828                    max: 8,
829                    width: Some(20.0),
830                    style: None,
831                    hidden: None,
832                    custom_width: Some(true),
833                    outline_level: None,
834                },
835            ],
836        });
837
838        set_col_width(&mut ws, "C", 25.0).unwrap();
839        let cols = &ws.cols.as_ref().unwrap().cols;
840        assert_eq!(cols.len(), 4);
841        assert_eq!(
842            (cols[0].min, cols[0].max, cols[0].width),
843            (1, 2, Some(12.0))
844        );
845        assert_eq!(
846            (cols[1].min, cols[1].max, cols[1].width),
847            (3, 3, Some(25.0))
848        );
849        assert_eq!(cols[1].style, Some(3));
850        assert_eq!(
851            (cols[2].min, cols[2].max, cols[2].width),
852            (4, 5, Some(12.0))
853        );
854        assert_eq!(
855            (cols[3].min, cols[3].max, cols[3].width),
856            (7, 8, Some(20.0))
857        );
858
859        set_col_visible(&mut ws, "D", true).unwrap();
860        let cols = &ws.cols.as_ref().unwrap().cols;
861        assert_eq!((cols[2].min, cols[2].max), (4, 4));
862        assert_eq!(cols[2].hidden, None);
863        assert_eq!((cols[3].min, cols[3].max), (5, 5));
864        assert_eq!(cols[3].hidden, Some(true));
865        assert_eq!((cols[4].min, cols[4].max), (7, 8));
866    }
867
868    #[test]
869    fn test_get_col_visible_default_is_true() {
870        let ws = WorksheetXml::default();
871        assert!(get_col_visible(&ws, "A").unwrap());
872    }
873
874    #[test]
875    fn test_get_col_visible_after_hide() {
876        let mut ws = WorksheetXml::default();
877        set_col_visible(&mut ws, "B", false).unwrap();
878        assert!(!get_col_visible(&ws, "B").unwrap());
879    }
880
881    #[test]
882    fn test_get_col_visible_after_hide_then_show() {
883        let mut ws = WorksheetXml::default();
884        set_col_visible(&mut ws, "A", false).unwrap();
885        set_col_visible(&mut ws, "A", true).unwrap();
886        assert!(get_col_visible(&ws, "A").unwrap());
887    }
888
889    #[test]
890    fn test_get_col_visible_invalid_column_returns_error() {
891        let ws = WorksheetXml::default();
892        let result = get_col_visible(&ws, "XFE");
893        assert!(result.is_err());
894    }
895
896    #[test]
897    fn test_set_col_outline_level() {
898        let mut ws = WorksheetXml::default();
899        set_col_outline_level(&mut ws, "A", 3).unwrap();
900
901        let col = &ws.cols.as_ref().unwrap().cols[0];
902        assert_eq!(col.outline_level, Some(3));
903    }
904
905    #[test]
906    fn test_set_col_outline_level_zero_clears() {
907        let mut ws = WorksheetXml::default();
908        set_col_outline_level(&mut ws, "A", 3).unwrap();
909        set_col_outline_level(&mut ws, "A", 0).unwrap();
910
911        let col = &ws.cols.as_ref().unwrap().cols[0];
912        assert_eq!(col.outline_level, None);
913    }
914
915    #[test]
916    fn test_set_col_outline_level_exceeds_max_returns_error() {
917        let mut ws = WorksheetXml::default();
918        let result = set_col_outline_level(&mut ws, "A", 8);
919        assert!(result.is_err());
920    }
921
922    #[test]
923    fn test_set_col_outline_level_max_valid() {
924        let mut ws = WorksheetXml::default();
925        set_col_outline_level(&mut ws, "A", 7).unwrap();
926
927        let col = &ws.cols.as_ref().unwrap().cols[0];
928        assert_eq!(col.outline_level, Some(7));
929    }
930
931    #[test]
932    fn test_get_col_outline_level_default_is_zero() {
933        let ws = WorksheetXml::default();
934        assert_eq!(get_col_outline_level(&ws, "A").unwrap(), 0);
935    }
936
937    #[test]
938    fn test_get_col_outline_level_after_set() {
939        let mut ws = WorksheetXml::default();
940        set_col_outline_level(&mut ws, "B", 5).unwrap();
941        assert_eq!(get_col_outline_level(&ws, "B").unwrap(), 5);
942    }
943
944    #[test]
945    fn test_get_col_outline_level_after_clear() {
946        let mut ws = WorksheetXml::default();
947        set_col_outline_level(&mut ws, "C", 4).unwrap();
948        set_col_outline_level(&mut ws, "C", 0).unwrap();
949        assert_eq!(get_col_outline_level(&ws, "C").unwrap(), 0);
950    }
951
952    #[test]
953    fn test_get_col_outline_level_invalid_column_returns_error() {
954        let ws = WorksheetXml::default();
955        let result = get_col_outline_level(&ws, "XFE");
956        assert!(result.is_err());
957    }
958
959    // -- get_cols tests --
960
961    #[test]
962    fn test_get_cols_empty_sheet() {
963        let ws = WorksheetXml::default();
964        let sst = SharedStringTable::new();
965        let cols = get_cols(&ws, &sst, &[]).unwrap();
966        assert!(cols.is_empty());
967    }
968
969    #[test]
970    fn test_get_cols_transposes_row_data() {
971        let ws = sample_ws();
972        let sst = SharedStringTable::new();
973        let cols = get_cols(&ws, &sst, &[]).unwrap();
974
975        // sample_ws has:
976        //   Row 1: A1=10, B1=20, D1=40
977        //   Row 2: A2=100, C2=300
978        // Columns should be: A, B, C, D
979
980        assert_eq!(cols.len(), 4);
981
982        // Column A: (1, 10.0), (2, 100.0)
983        assert_eq!(cols[0].0, "A");
984        assert_eq!(cols[0].1.len(), 2);
985        assert_eq!(cols[0].1[0], (1, CellValue::Number(10.0)));
986        assert_eq!(cols[0].1[1], (2, CellValue::Number(100.0)));
987
988        // Column B: (1, 20.0)
989        assert_eq!(cols[1].0, "B");
990        assert_eq!(cols[1].1.len(), 1);
991        assert_eq!(cols[1].1[0], (1, CellValue::Number(20.0)));
992
993        // Column C: (2, 300.0)
994        assert_eq!(cols[2].0, "C");
995        assert_eq!(cols[2].1.len(), 1);
996        assert_eq!(cols[2].1[0], (2, CellValue::Number(300.0)));
997
998        // Column D: (1, 40.0)
999        assert_eq!(cols[3].0, "D");
1000        assert_eq!(cols[3].1.len(), 1);
1001        assert_eq!(cols[3].1[0], (1, CellValue::Number(40.0)));
1002    }
1003
1004    #[test]
1005    fn get_cols_with_limits_accepts_exact_retained_bytes_and_rejects_plus_one() {
1006        let ws = sample_ws();
1007        let sst = SharedStringTable::new();
1008        let exact = 4 * u64::try_from(std::mem::size_of::<(String, Vec<(u32, CellValue)>)>())
1009            .unwrap()
1010            + 4
1011            + 5 * u64::try_from(std::mem::size_of::<(u32, CellValue)>()).unwrap();
1012        let exact_limits = crate::traversal::TraversalLimits::new(2, 4, 5, exact).unwrap();
1013
1014        assert_eq!(
1015            get_cols_with_limits(&ws, &sst, &[], exact_limits).unwrap(),
1016            get_cols(&ws, &sst, &[]).unwrap()
1017        );
1018
1019        let error = get_cols_with_limits(
1020            &ws,
1021            &sst,
1022            &[],
1023            crate::traversal::TraversalLimits::new(2, 4, 5, exact - 1).unwrap(),
1024        )
1025        .unwrap_err();
1026        let Error::ResourceLimitExceeded(metadata) = error else {
1027            panic!("expected resource limit error");
1028        };
1029        assert_eq!(
1030            metadata.dimension(),
1031            crate::ResourceDimension::RetainedBytes
1032        );
1033        assert_eq!(metadata.limit(), exact - 1);
1034        assert_eq!(metadata.observed(), exact);
1035    }
1036
1037    #[test]
1038    fn get_cols_with_limits_rejects_counts_before_materialization() {
1039        let ws = sample_ws();
1040        let sst = SharedStringTable::new();
1041        let error = get_cols_with_limits(
1042            &ws,
1043            &sst,
1044            &[],
1045            crate::traversal::TraversalLimits::new(1, 4, 5, 1_024).unwrap(),
1046        )
1047        .unwrap_err();
1048        let Error::ResourceLimitExceeded(metadata) = error else {
1049            panic!("expected resource limit error");
1050        };
1051        assert_eq!(metadata.dimension(), crate::ResourceDimension::RowCount);
1052        assert_eq!(metadata.limit(), 1);
1053        assert_eq!(metadata.observed(), 2);
1054    }
1055
1056    #[test]
1057    fn test_get_cols_with_shared_strings() {
1058        let mut sst = SharedStringTable::new();
1059        sst.add("Name");
1060        sst.add("Age");
1061        sst.add("Alice");
1062
1063        let mut ws = WorksheetXml::default();
1064        ws.sheet_data = SheetData {
1065            rows: vec![
1066                Row {
1067                    r: 1,
1068                    spans: None,
1069                    s: None,
1070                    custom_format: None,
1071                    ht: None,
1072                    hidden: None,
1073                    custom_height: None,
1074                    outline_level: None,
1075                    cells: vec![
1076                        Cell {
1077                            r: "A1".try_into().unwrap(),
1078                            col: 1,
1079                            s: None,
1080                            t: CellTypeTag::SharedString,
1081                            v: Some("0".to_string()),
1082                            f: None,
1083                            is: None,
1084                        },
1085                        Cell {
1086                            r: "B1".try_into().unwrap(),
1087                            col: 2,
1088                            s: None,
1089                            t: CellTypeTag::SharedString,
1090                            v: Some("1".to_string()),
1091                            f: None,
1092                            is: None,
1093                        },
1094                    ],
1095                },
1096                Row {
1097                    r: 2,
1098                    spans: None,
1099                    s: None,
1100                    custom_format: None,
1101                    ht: None,
1102                    hidden: None,
1103                    custom_height: None,
1104                    outline_level: None,
1105                    cells: vec![
1106                        Cell {
1107                            r: "A2".try_into().unwrap(),
1108                            col: 1,
1109                            s: None,
1110                            t: CellTypeTag::SharedString,
1111                            v: Some("2".to_string()),
1112                            f: None,
1113                            is: None,
1114                        },
1115                        Cell {
1116                            r: "B2".try_into().unwrap(),
1117                            col: 2,
1118                            s: None,
1119                            t: CellTypeTag::None,
1120                            v: Some("30".to_string()),
1121                            f: None,
1122                            is: None,
1123                        },
1124                    ],
1125                },
1126            ],
1127        };
1128
1129        let cols = get_cols(&ws, &sst, &[]).unwrap();
1130        assert_eq!(cols.len(), 2);
1131
1132        // Column A: "Name", "Alice"
1133        assert_eq!(cols[0].0, "A");
1134        assert_eq!(cols[0].1[0].1, CellValue::String("Name".to_string()));
1135        assert_eq!(cols[0].1[1].1, CellValue::String("Alice".to_string()));
1136
1137        // Column B: "Age", 30
1138        assert_eq!(cols[1].0, "B");
1139        assert_eq!(cols[1].1[0].1, CellValue::String("Age".to_string()));
1140        assert_eq!(cols[1].1[1].1, CellValue::Number(30.0));
1141    }
1142
1143    #[test]
1144    fn test_get_cols_sorted_correctly() {
1145        // Verify that columns are sorted by length then alphabetically:
1146        // A, B, ..., Z, AA, AB, ...
1147        let mut ws = WorksheetXml::default();
1148        ws.sheet_data = SheetData {
1149            rows: vec![Row {
1150                r: 1,
1151                spans: None,
1152                s: None,
1153                custom_format: None,
1154                ht: None,
1155                hidden: None,
1156                custom_height: None,
1157                outline_level: None,
1158                cells: vec![
1159                    Cell {
1160                        r: "AA1".try_into().unwrap(),
1161                        col: 27,
1162                        s: None,
1163                        t: CellTypeTag::None,
1164                        v: Some("1".to_string()),
1165                        f: None,
1166                        is: None,
1167                    },
1168                    Cell {
1169                        r: "B1".try_into().unwrap(),
1170                        col: 2,
1171                        s: None,
1172                        t: CellTypeTag::None,
1173                        v: Some("2".to_string()),
1174                        f: None,
1175                        is: None,
1176                    },
1177                    Cell {
1178                        r: "A1".try_into().unwrap(),
1179                        col: 1,
1180                        s: None,
1181                        t: CellTypeTag::None,
1182                        v: Some("3".to_string()),
1183                        f: None,
1184                        is: None,
1185                    },
1186                ],
1187            }],
1188        };
1189
1190        let sst = SharedStringTable::new();
1191        let cols = get_cols(&ws, &sst, &[]).unwrap();
1192
1193        assert_eq!(cols.len(), 3);
1194        assert_eq!(cols[0].0, "A");
1195        assert_eq!(cols[1].0, "B");
1196        assert_eq!(cols[2].0, "AA");
1197    }
1198
1199    // -- set_col_style / get_col_style tests --
1200
1201    #[test]
1202    fn test_get_col_style_default_is_zero() {
1203        let ws = WorksheetXml::default();
1204        assert_eq!(get_col_style(&ws, "A").unwrap(), 0);
1205    }
1206
1207    #[test]
1208    fn test_set_col_style_applies_style() {
1209        let mut ws = WorksheetXml::default();
1210        set_col_style(&mut ws, "B", 4).unwrap();
1211
1212        let col = &ws.cols.as_ref().unwrap().cols[0];
1213        assert_eq!(col.style, Some(4));
1214    }
1215
1216    #[test]
1217    fn test_get_col_style_after_set() {
1218        let mut ws = WorksheetXml::default();
1219        set_col_style(&mut ws, "C", 10).unwrap();
1220        assert_eq!(get_col_style(&ws, "C").unwrap(), 10);
1221    }
1222
1223    #[test]
1224    fn test_set_col_style_creates_cols_container() {
1225        let mut ws = WorksheetXml::default();
1226        assert!(ws.cols.is_none());
1227        set_col_style(&mut ws, "A", 2).unwrap();
1228        assert!(ws.cols.is_some());
1229    }
1230
1231    #[test]
1232    fn test_set_col_style_overwrite() {
1233        let mut ws = WorksheetXml::default();
1234        set_col_style(&mut ws, "A", 3).unwrap();
1235        set_col_style(&mut ws, "A", 7).unwrap();
1236        assert_eq!(get_col_style(&ws, "A").unwrap(), 7);
1237    }
1238
1239    #[test]
1240    fn test_get_col_style_invalid_column_returns_error() {
1241        let ws = WorksheetXml::default();
1242        let result = get_col_style(&ws, "XFE");
1243        assert!(result.is_err());
1244    }
1245
1246    #[test]
1247    fn test_set_col_style_invalid_column_returns_error() {
1248        let mut ws = WorksheetXml::default();
1249        let result = set_col_style(&mut ws, "XFE", 1);
1250        assert!(result.is_err());
1251    }
1252}