rhwp 0.9.1

HWP/HWPX document engine for Rust applications, WebAssembly, and CLI automation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
use crate::model::control::{Control, Equation};
use crate::model::document::{Document, Section};
use crate::model::page::{ColumnDef, ColumnDirection, ColumnType, PageDef};
use crate::model::paragraph::{ColumnBreakType, Paragraph};
use crate::model::shape::{
    CommonObjAttr, HorzAlign, HorzRelTo, RectangleShape, ShapeObject, TextWrap, VertAlign,
    VertRelTo,
};
use crate::model::table::{Cell, Table, VerticalAlign};
use crate::parser::HmlImportMetadata;

use super::error::{unsupported_ir, HmlExportError};
use super::xml::XmlWriter;

pub(crate) fn write_body(
    writer: &mut XmlWriter,
    document: &Document,
    metadata: &HmlImportMetadata,
) -> Result<(), HmlExportError> {
    writer.open("BODY", &[]);
    super::fragments::write_at_anchor(writer, metadata, "BODY", 0);
    for (section_index, section) in document.sections.iter().enumerate() {
        write_section(writer, section, section_index)?;
        super::fragments::write_at_anchor(writer, metadata, "BODY", section_index + 1);
    }
    writer.close("BODY");
    Ok(())
}

fn write_section(
    writer: &mut XmlWriter,
    section: &Section,
    section_index: usize,
) -> Result<(), HmlExportError> {
    writer.open("SECTION", &[("Id", section_index.to_string())]);
    for (paragraph_index, paragraph) in section.paragraphs.iter().enumerate() {
        let page_def = (paragraph_index == 0).then_some(&section.section_def.page_def);
        let path = format!("/HWPML/BODY/SECTION[{section_index}]/P[{paragraph_index}]");
        write_paragraph(writer, paragraph, page_def, &path)?;
    }
    writer.close("SECTION");
    Ok(())
}

fn write_paragraph(
    writer: &mut XmlWriter,
    paragraph: &Paragraph,
    page_def: Option<&PageDef>,
    path: &str,
) -> Result<(), HmlExportError> {
    writer.open(
        "P",
        &[
            ("ParaShape", paragraph.para_shape_id.to_string()),
            ("Style", paragraph.style_id.to_string()),
            (
                "PageBreak",
                (paragraph.column_type == ColumnBreakType::Page).to_string(),
            ),
            (
                "ColumnBreak",
                (paragraph.column_type == ColumnBreakType::Column).to_string(),
            ),
        ],
    );
    if let Some(page_def) = page_def {
        write_section_definition(writer, paragraph, page_def);
    }
    write_paragraph_content(writer, paragraph, path)?;
    writer.close("P");
    Ok(())
}

fn write_section_definition(writer: &mut XmlWriter, paragraph: &Paragraph, page: &PageDef) {
    writer.open(
        "TEXT",
        &[("CharShape", char_shape_at(paragraph, 0).to_string())],
    );
    writer.open("SECDEF", &[]);
    writer.open(
        "PAGEDEF",
        &[
            ("Width", page.width.to_string()),
            ("Height", page.height.to_string()),
            ("Landscape", u8::from(page.landscape).to_string()),
        ],
    );
    writer.empty(
        "PAGEMARGIN",
        &[
            ("Left", page.margin_left.to_string()),
            ("Right", page.margin_right.to_string()),
            ("Top", page.margin_top.to_string()),
            ("Bottom", page.margin_bottom.to_string()),
            ("Header", page.margin_header.to_string()),
            ("Footer", page.margin_footer.to_string()),
            ("Gutter", page.margin_gutter.to_string()),
        ],
    );
    writer.close("PAGEDEF");
    writer.close("SECDEF");
    writer.close("TEXT");
}

fn write_paragraph_content(
    writer: &mut XmlWriter,
    paragraph: &Paragraph,
    path: &str,
) -> Result<(), HmlExportError> {
    let characters = paragraph.text.chars().collect::<Vec<_>>();
    let offsets = paragraph_offsets(paragraph, &characters, path)?;
    let mut expected_offset = 0u32;
    let mut control_index = 0usize;
    let mut text_start = 0usize;

    for (index, actual_offset) in offsets.iter().copied().enumerate() {
        if actual_offset > expected_offset {
            write_text_slice(writer, paragraph, &characters, &offsets, text_start, index);
            insert_controls_until(
                writer,
                paragraph,
                path,
                &mut control_index,
                &mut expected_offset,
                actual_offset,
            )?;
            text_start = index;
        }
        ensure_offset(path, actual_offset, expected_offset)?;
        expected_offset += characters[index].len_utf16() as u32;
    }
    write_text_slice(
        writer,
        paragraph,
        &characters,
        &offsets,
        text_start,
        characters.len(),
    );
    write_remaining_controls(writer, paragraph, path, control_index, expected_offset)?;
    if characters.is_empty() && paragraph.controls.is_empty() {
        write_empty_text(writer, paragraph);
    }
    Ok(())
}

fn paragraph_offsets(
    paragraph: &Paragraph,
    characters: &[char],
    path: &str,
) -> Result<Vec<u32>, HmlExportError> {
    if paragraph.char_offsets.len() == characters.len() {
        return Ok(paragraph.char_offsets.clone());
    }
    Err(unsupported_ir(
        path,
        "문단 문자 위치 정보가 편집된 텍스트와 일치하지 않습니다",
    ))
}

fn insert_controls_until(
    writer: &mut XmlWriter,
    paragraph: &Paragraph,
    path: &str,
    control_index: &mut usize,
    expected_offset: &mut u32,
    target_offset: u32,
) -> Result<(), HmlExportError> {
    while *control_index < paragraph.controls.len() && *expected_offset + 8 <= target_offset {
        write_control_run(
            writer,
            paragraph,
            &paragraph.controls[*control_index],
            *expected_offset,
            &format!("{path}/CONTROL[{control_index}]"),
        )?;
        *control_index += 1;
        *expected_offset += 8;
    }
    Ok(())
}

fn write_remaining_controls(
    writer: &mut XmlWriter,
    paragraph: &Paragraph,
    path: &str,
    mut control_index: usize,
    mut offset: u32,
) -> Result<(), HmlExportError> {
    while control_index < paragraph.controls.len() {
        write_control_run(
            writer,
            paragraph,
            &paragraph.controls[control_index],
            offset,
            &format!("{path}/CONTROL[{control_index}]"),
        )?;
        control_index += 1;
        offset += 8;
    }
    Ok(())
}

fn write_text_slice(
    writer: &mut XmlWriter,
    paragraph: &Paragraph,
    characters: &[char],
    offsets: &[u32],
    start: usize,
    end: usize,
) {
    let mut run_start = start;
    while run_start < end {
        let shape_id = char_shape_at(paragraph, offsets[run_start]);
        let run_end = (run_start + 1..end)
            .find(|index| char_shape_at(paragraph, offsets[*index]) != shape_id)
            .unwrap_or(end);
        let text = characters[run_start..run_end].iter().collect::<String>();
        writer.open("TEXT", &[("CharShape", shape_id.to_string())]);
        writer.open("CHAR", &[]);
        writer.text(&text);
        writer.close("CHAR");
        writer.close("TEXT");
        run_start = run_end;
    }
}

fn write_empty_text(writer: &mut XmlWriter, paragraph: &Paragraph) {
    writer.open(
        "TEXT",
        &[("CharShape", char_shape_at(paragraph, 0).to_string())],
    );
    writer.empty("CHAR", &[]);
    writer.close("TEXT");
}

fn write_control_run(
    writer: &mut XmlWriter,
    paragraph: &Paragraph,
    control: &Control,
    offset: u32,
    path: &str,
) -> Result<(), HmlExportError> {
    writer.open(
        "TEXT",
        &[("CharShape", char_shape_at(paragraph, offset).to_string())],
    );
    let result = match control {
        Control::Equation(equation) => write_equation(writer, equation),
        Control::Table(table) => write_table(writer, table, path),
        Control::Shape(shape) => write_shape(writer, shape, path),
        Control::ColumnDef(column_def) => write_column_def(writer, column_def),
        _ => Err(unsupported_ir(
            path,
            "HML reader가 매핑하지 않는 컨트롤입니다",
        )),
    };
    writer.close("TEXT");
    result
}

fn write_equation(writer: &mut XmlWriter, equation: &Equation) -> Result<(), HmlExportError> {
    let mut attributes = vec![
        ("BaseLine", equation.baseline.to_string()),
        ("BaseUnit", equation.font_size.to_string()),
        ("TextColor", equation.color.to_string()),
        ("Version", equation.version_info.clone()),
    ];
    if !equation.font_name.is_empty() {
        attributes.push(("Font", equation.font_name.clone()));
    }
    writer.open("EQUATION", &attributes);
    writer.open("SCRIPT", &[]);
    writer.text(&equation.script);
    writer.close("SCRIPT");
    writer.close("EQUATION");
    Ok(())
}

/// [#4386] `Control::ColumnDef` → `COLDEF`. reader.rs의 `capture_col_def`가 읽는
/// `Count`/`Layout`/`SameGap`/`SameSize`/`Type` 다섯 속성만 왕복한다(HML 실물에서 관찰된
/// 전부). `widths`/`gaps`/`separator_*`/`raw_attr`는 `validate_column_def`(preflight)가
/// 기본값이 아니면 미리 export를 막으므로 여기서는 항상 무시해도 안전하다.
fn write_column_def(writer: &mut XmlWriter, column_def: &ColumnDef) -> Result<(), HmlExportError> {
    writer.empty(
        "COLDEF",
        &[
            ("Count", column_def.column_count.to_string()),
            (
                "Layout",
                column_direction_name(column_def.direction).to_string(),
            ),
            ("SameGap", column_def.spacing.to_string()),
            ("SameSize", column_def.same_width.to_string()),
            ("Type", column_type_name(column_def.column_type).to_string()),
        ],
    );
    Ok(())
}

fn column_type_name(column_type: ColumnType) -> &'static str {
    match column_type {
        ColumnType::Normal => "Newspaper",
        ColumnType::Distribute => "Distribute",
        ColumnType::Parallel => "Parallel",
    }
}

fn column_direction_name(direction: ColumnDirection) -> &'static str {
    match direction {
        ColumnDirection::LeftToRight => "Left",
        ColumnDirection::RightToLeft => "Right",
        ColumnDirection::Mirror => "Mirror",
    }
}

fn write_shape(
    writer: &mut XmlWriter,
    shape: &ShapeObject,
    path: &str,
) -> Result<(), HmlExportError> {
    let ShapeObject::Rectangle(rectangle) = shape else {
        return Err(unsupported_ir(
            path,
            "HML reader가 매핑하지 않는 도형 종류입니다",
        ));
    };
    write_rectangle(writer, rectangle, path)
}

fn write_rectangle(
    writer: &mut XmlWriter,
    rectangle: &RectangleShape,
    path: &str,
) -> Result<(), HmlExportError> {
    writer.open("RECTANGLE", &rectangle_coordinates(rectangle));
    write_shape_object(writer, &rectangle.common, "Figure");
    writer.open("DRAWINGOBJECT", &[]);
    write_shape_component(writer, rectangle);
    write_line_shape(writer, rectangle);
    write_rectangle_fill(writer, rectangle);
    if let Some(text_box) = &rectangle.drawing.text_box {
        writer.open("DRAWTEXT", &[]);
        writer.empty(
            "TEXTMARGIN",
            &padding_attributes(
                text_box.margin_left,
                text_box.margin_right,
                text_box.margin_top,
                text_box.margin_bottom,
            ),
        );
        writer.open("PARALIST", &[]);
        for (index, paragraph) in text_box.paragraphs.iter().enumerate() {
            write_paragraph(
                writer,
                paragraph,
                None,
                &format!("{path}/DRAWTEXT/P[{index}]"),
            )?;
        }
        writer.close("PARALIST");
        writer.close("DRAWTEXT");
    }
    writer.close("DRAWINGOBJECT");
    writer.close("RECTANGLE");
    Ok(())
}

fn rectangle_coordinates(rectangle: &RectangleShape) -> Vec<(&'static str, String)> {
    ["X0", "X1", "X2", "X3"]
        .into_iter()
        .zip(rectangle.x_coords)
        .chain(["Y0", "Y1", "Y2", "Y3"].into_iter().zip(rectangle.y_coords))
        .map(|(name, value)| (name, value.to_string()))
        .collect()
}

fn write_shape_object(writer: &mut XmlWriter, common: &CommonObjAttr, numbering_type: &str) {
    writer.open(
        "SHAPEOBJECT",
        &[
            ("NumberingType", numbering_type.into()),
            ("TextWrap", text_wrap_name(common.text_wrap).into()),
        ],
    );
    writer.empty(
        "SIZE",
        &[
            ("Width", common.width.to_string()),
            ("Height", common.height.to_string()),
        ],
    );
    writer.empty("POSITION", &position_attributes(common));
    writer.close("SHAPEOBJECT");
}

fn write_shape_component(writer: &mut XmlWriter, rectangle: &RectangleShape) {
    let shape = &rectangle.drawing.shape_attr;
    writer.empty(
        "SHAPECOMPONENT",
        &[
            ("XPos", shape.offset_x.to_string()),
            ("YPos", shape.offset_y.to_string()),
            ("OriWidth", shape.original_width.to_string()),
            ("OriHeight", shape.original_height.to_string()),
            ("CurWidth", shape.current_width.to_string()),
            ("CurHeight", shape.current_height.to_string()),
        ],
    );
}

fn write_line_shape(writer: &mut XmlWriter, rectangle: &RectangleShape) {
    writer.empty(
        "LINESHAPE",
        &[
            ("Width", rectangle.drawing.border_line.width.to_string()),
            ("Style", "Solid".into()),
            ("EndCap", "Flat".into()),
            ("Alpha", "0".into()),
        ],
    );
}

fn write_rectangle_fill(writer: &mut XmlWriter, rectangle: &RectangleShape) {
    if let Some(solid) = rectangle.drawing.fill.solid {
        writer.open("FILLBRUSH", &[]);
        writer.empty(
            "WINDOWBRUSH",
            &[
                ("FaceColor", solid.background_color.to_string()),
                ("HatchColor", solid.pattern_color.to_string()),
                ("Alpha", rectangle.drawing.fill.alpha.to_string()),
            ],
        );
        writer.close("FILLBRUSH");
    }
}

fn write_table(writer: &mut XmlWriter, table: &Table, path: &str) -> Result<(), HmlExportError> {
    writer.open(
        "TABLE",
        &[
            ("RowCount", table.row_count.to_string()),
            ("ColCount", table.col_count.to_string()),
            ("CellSpacing", table.cell_spacing.to_string()),
            ("BorderFill", table.border_fill_id.to_string()),
        ],
    );
    write_shape_object(writer, &table.common, "Table");
    writer.empty(
        "INSIDEMARGIN",
        &padding_attributes(
            table.padding.left,
            table.padding.right,
            table.padding.top,
            table.padding.bottom,
        ),
    );
    // [#2751] 실셀의 최대 행까지만 <ROW> 방출. 무검증 row_count가 과도하게 크면
    // 빈 <ROW>가 다수 방출되어 XML이 25배 이상 팽창하고 저장이 4.4초 지연된다.
    let row_end = table
        .cells
        .iter()
        .map(|c| c.row)
        .max()
        .map(|max_row| (max_row.saturating_add(1)).min(table.row_count))
        .unwrap_or(table.row_count);
    for row in 0..row_end {
        writer.open("ROW", &[]);
        for (cell_index, cell) in table
            .cells
            .iter()
            .enumerate()
            .filter(|(_, cell)| cell.row == row)
        {
            write_cell(writer, cell, &format!("{path}/CELL[{cell_index}]"))?;
        }
        writer.close("ROW");
    }
    writer.close("TABLE");
    Ok(())
}

fn write_cell(writer: &mut XmlWriter, cell: &Cell, path: &str) -> Result<(), HmlExportError> {
    writer.open(
        "CELL",
        &[
            ("ColAddr", cell.col.to_string()),
            ("RowAddr", cell.row.to_string()),
            ("ColSpan", cell.col_span.to_string()),
            ("RowSpan", cell.row_span.to_string()),
            ("Width", cell.width.to_string()),
            ("Height", cell.height.to_string()),
            ("BorderFill", cell.border_fill_id.to_string()),
        ],
    );
    writer.empty(
        "CELLMARGIN",
        &padding_attributes(
            cell.padding.left,
            cell.padding.right,
            cell.padding.top,
            cell.padding.bottom,
        ),
    );
    // [#3189] 종전엔 속성 없이 방출해 셀 세로 정렬이 저장 때마다 사라졌다.
    // 한컴 실물 HML 도 CELL/PARALIST 에 VertAlign 을 적어 넣는다.
    writer.open(
        "PARALIST",
        &[(
            "VertAlign",
            cell_vert_align_name(cell.vertical_align).to_string(),
        )],
    );
    for (index, paragraph) in cell.paragraphs.iter().enumerate() {
        write_paragraph(writer, paragraph, None, &format!("{path}/P[{index}]"))?;
    }
    writer.close("PARALIST");
    writer.close("CELL");
    Ok(())
}

fn position_attributes(common: &CommonObjAttr) -> Vec<(&'static str, String)> {
    vec![
        ("HorzOffset", (common.horizontal_offset as i32).to_string()),
        ("VertOffset", (common.vertical_offset as i32).to_string()),
        ("TreatAsChar", common.treat_as_char.to_string()),
        ("FlowWithText", common.flow_with_text.to_string()),
        ("AllowOverlap", common.allow_overlap.to_string()),
        ("HorzRelTo", horz_rel_name(common.horz_rel_to).into()),
        ("VertRelTo", vert_rel_name(common.vert_rel_to).into()),
        ("HorzAlign", horz_align_name(common.horz_align).into()),
        ("VertAlign", vert_align_name(common.vert_align).into()),
    ]
}

fn padding_attributes(left: i16, right: i16, top: i16, bottom: i16) -> Vec<(&'static str, String)> {
    vec![
        ("Left", left.to_string()),
        ("Right", right.to_string()),
        ("Top", top.to_string()),
        ("Bottom", bottom.to_string()),
    ]
}

fn char_shape_at(paragraph: &Paragraph, offset: u32) -> u32 {
    paragraph
        .char_shapes
        .iter()
        .rev()
        .find(|reference| reference.start_pos <= offset)
        .map(|reference| reference.char_shape_id)
        .unwrap_or(0)
}

fn ensure_offset(path: &str, actual: u32, expected: u32) -> Result<(), HmlExportError> {
    if actual == expected {
        return Ok(());
    }
    Err(unsupported_ir(
        path,
        &format!("문자 위치 {actual}을 HML 제어문자 위치 {expected}로 역변환할 수 없습니다"),
    ))
}

fn vert_rel_name(value: VertRelTo) -> &'static str {
    match value {
        VertRelTo::Page => "Page",
        VertRelTo::Para => "Para",
        VertRelTo::Paper => "Paper",
    }
}

fn vert_align_name(value: VertAlign) -> &'static str {
    match value {
        VertAlign::Center => "Center",
        VertAlign::Bottom => "Bottom",
        VertAlign::Inside => "Inside",
        VertAlign::Outside => "Outside",
        VertAlign::Top => "Top",
    }
}

/// [#3189] 셀 세로 정렬 이름. 개체 위치용 `vert_align_name`(VertAlign) 과 달리
/// 표 셀은 Top/Center/Bottom 세 값뿐이다.
fn cell_vert_align_name(value: VerticalAlign) -> &'static str {
    match value {
        VerticalAlign::Top => "Top",
        VerticalAlign::Center => "Center",
        VerticalAlign::Bottom => "Bottom",
    }
}

fn horz_rel_name(value: HorzRelTo) -> &'static str {
    match value {
        HorzRelTo::Page => "Page",
        HorzRelTo::Column => "Column",
        HorzRelTo::Para => "Para",
        HorzRelTo::Paper => "Paper",
    }
}

fn horz_align_name(value: HorzAlign) -> &'static str {
    match value {
        HorzAlign::Center => "Center",
        HorzAlign::Right => "Right",
        HorzAlign::Inside => "Inside",
        HorzAlign::Outside => "Outside",
        HorzAlign::Left => "Left",
    }
}

fn text_wrap_name(value: TextWrap) -> &'static str {
    match value {
        TextWrap::Tight => "Tight",
        TextWrap::Through => "Through",
        TextWrap::TopAndBottom => "TopAndBottom",
        TextWrap::BehindText => "BehindText",
        TextWrap::InFrontOfText => "InFrontOfText",
        TextWrap::Square => "Square",
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::table::Cell;

    /// row_count 행 중 실제 셀은 cell_rows 행만 덮는 표를 만든다 (행당 1셀, 1열).
    fn table_with_rows(row_count: u16, cell_rows: u16) -> Table {
        let mut table = Table {
            row_count,
            col_count: 1,
            ..Default::default()
        };
        table.cells = (0..cell_rows)
            .map(|row| Cell {
                row,
                col: 0,
                col_span: 1,
                row_span: 1,
                ..Default::default()
            })
            .collect();
        table
    }

    fn serialize_table_to_hml(table: &Table) -> String {
        let mut writer = XmlWriter::default();
        write_table(&mut writer, table, "/TABLE").expect("table should serialize");
        String::from_utf8(writer.finish()).expect("HML is UTF-8")
    }

    // [#2751 회귀] row_count 는 크게, 실셀은 적게: 방출되는 <ROW> 는 실셀 범위로
    // 제한되어야 한다. 종전에는 무검증 row_count 만큼 빈 <ROW> 9600개가 방출되어
    // XML 이 25배 팽창하고 저장이 4.4초 지연됐다. 이 결함은 되돌아가도 abort 없이
    // 조용히 통과하므로 방출 개수 자체를 고정한다.
    #[test]
    fn hml_table_row_emission_is_bounded_by_actual_cells() {
        let table = table_with_rows(10_000, 400);

        let xml = serialize_table_to_hml(&table);
        let row_count = xml.matches("<ROW").count();

        assert!(
            row_count <= 400,
            "실셀 범위를 넘는 <ROW> 가 방출됨: {row_count}"
        );
        assert_eq!(row_count, 400, "실셀이 있는 행은 전부 방출되어야 함");
    }

    // [#2751 회귀] row_count 와 실셀 범위가 일치하는 정상 표는 종전과 동일하게
    // row_count 만큼 <ROW> 를 방출해야 한다 — 과하게 잘라내지 않는다.
    #[test]
    fn normal_table_row_emission_unchanged() {
        let table = table_with_rows(400, 400);

        let xml = serialize_table_to_hml(&table);
        assert_eq!(
            xml.matches("<ROW").count(),
            400,
            "정상 표의 <ROW> 방출 개수가 달라짐"
        );

        // 셀이 하나도 없는 비정상 표도 종전 동작(row_count 만큼 방출)을 유지한다.
        let empty = table_with_rows(3, 0);
        assert_eq!(serialize_table_to_hml(&empty).matches("<ROW").count(), 3);
    }
}