rhwp 0.9.0

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
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
//! CFB 컨테이너 조립 + 스트림 압축
//!
//! `parser::cfb_reader`의 역방향으로, 직렬화된 스트림을 CFB 컨테이너로 조립한다.
//!
//! 구조:
//! - /FileHeader (256바이트, 비압축)
//! - /DocInfo (레코드 바이트, 조건부 deflate)
//! - /BodyText/Section{N} (레코드 바이트, 조건부 deflate)
//! - /BinData/BIN{XXXX}.{ext} (바이너리 데이터)

use std::io::Write;

use crate::model::bin_data::BinDataContent;
use crate::model::bin_data::{BinData, BinDataType, MAX_BIN_DATA_BYTES};
use crate::model::document::{Document, Preview};
use crate::password_crypto::{encrypt_hwp5_stream, HWP5_ENCRYPT_VERSION};

use super::body_text::serialize_section_for_version;
use super::content_loss::{
    ContentLoss, ContentLossReason, ContentLossReport, SerializedDocument, SerializedFormat,
};
use super::doc_info::{serialize_doc_info, surgical_update_section_count};
use super::header::serialize_file_header;
use super::mini_cfb;
use super::SerializeError;

#[derive(Clone, Copy)]
enum ContentLossWarningMode {
    ReportOnly,
    LegacyStderr,
}

/// Document IR을 HWP 5.0 CFB 바이너리로 직렬화
pub fn serialize_hwp(doc: &Document) -> Result<Vec<u8>, SerializeError> {
    let serialized = serialize_hwp_inner(doc, None, ContentLossWarningMode::LegacyStderr)?;
    Ok(serialized.into_bytes())
}

/// HWP 직렬화 바이트와 바로 그 산출물의 내용 손실을 함께 반환한다 (#4430).
pub fn serialize_hwp_with_report(doc: &Document) -> Result<SerializedDocument, SerializeError> {
    serialize_hwp_inner(doc, None, ContentLossWarningMode::ReportOnly)
}

/// Document IR을 HWP5 EncryptVersion 4 비밀번호 문서로 직렬화한다.
///
/// 암호 적용 범위는 한글의 HWP5 contract에 맞춰 DocInfo, BodyText, BinData,
/// Scripts 및 고아 BinData stream이다. FileHeader와 PrvImage/PrvText는 평문이다.
pub fn serialize_hwp_with_password(
    doc: &Document,
    password: &[u8],
) -> Result<Vec<u8>, SerializeError> {
    let serialized =
        serialize_hwp_inner(doc, Some(password), ContentLossWarningMode::LegacyStderr)?;
    Ok(serialized.into_bytes())
}

/// 비밀번호 HWP 바이트와 바로 그 산출물의 내용 손실을 함께 반환한다 (#4430).
pub fn serialize_hwp_with_password_and_report(
    doc: &Document,
    password: &[u8],
) -> Result<SerializedDocument, SerializeError> {
    serialize_hwp_inner(doc, Some(password), ContentLossWarningMode::ReportOnly)
}

fn serialize_hwp_inner(
    doc: &Document,
    password: Option<&[u8]>,
    warning_mode: ContentLossWarningMode,
) -> Result<SerializedDocument, SerializeError> {
    serialize_hwp_inner_with_storage(
        doc,
        password,
        warning_mode,
        &crate::storage::Unbounded,
        usize::MAX,
    )
}

#[cfg(feature = "pdf-import")]
pub(crate) fn serialize_hwp_with_storage<S: crate::storage::Storage>(
    doc: &Document,
    storage: &S,
    maximum: usize,
) -> Result<Vec<u8>, SerializeError>
where
    S::Error: std::fmt::Display,
{
    Ok(serialize_hwp_inner_with_storage(
        doc,
        None,
        ContentLossWarningMode::LegacyStderr,
        storage,
        maximum,
    )?
    .into_bytes())
}

fn serialize_hwp_inner_with_storage<S: crate::storage::Storage>(
    doc: &Document,
    password: Option<&[u8]>,
    warning_mode: ContentLossWarningMode,
    storage: &S,
    maximum: usize,
) -> Result<SerializedDocument, SerializeError>
where
    S::Error: std::fmt::Display,
{
    crate::model::section_tail::validate_preservation(doc)
        .map_err(SerializeError::UnsupportedInput)?;
    let storage_error = |error| SerializeError::CfbError(format!("{error}"));
    storage
        .bytes(
            doc.header
                .raw_data
                .as_ref()
                .map_or(256, |raw| raw.len().max(256)),
        )
        .map_err(storage_error)?;
    // 1. FileHeader 직렬화
    // [Task #1768] 배포용/암호화 문서 강하: IR 은 이미 복호화된 평문이고 본 직렬화는
    // ViewText/DISTRIBUTE_DOC_DATA 를 생성하지 않으므로, 플래그를 유지하면 산출물
    // 재로드가 "암호 오류: DISTRIBUTE_DOC_DATA 레코드 없음" 으로 실패한다. 일반
    // 문서로 강하(배포용 0x04 · 암호화 0x02 클리어, raw_data 의 플래그와
    // EncryptVersion도 패치).
    let header_bytes = if let Some(_) = password {
        let mut header = doc.header.clone();
        header.distribution = false;
        header.encrypted = true;
        header.flags = (header.flags | 0x02) & !0x04;
        if let Some(raw) = header.raw_data.as_mut() {
            if raw.len() >= 48 {
                raw[36..40].copy_from_slice(&header.flags.to_le_bytes());
                raw[44..48].copy_from_slice(&HWP5_ENCRYPT_VERSION.to_le_bytes());
            }
        }
        let mut bytes = serialize_file_header(&header);
        bytes[36..40].copy_from_slice(&header.flags.to_le_bytes());
        bytes[44..48].copy_from_slice(&HWP5_ENCRYPT_VERSION.to_le_bytes());
        bytes
    } else if doc.header.distribution || doc.header.encrypted {
        let mut header = doc.header.clone();
        header.distribution = false;
        header.encrypted = false;
        header.flags &= !0x06;
        if let Some(raw) = header.raw_data.as_mut() {
            if raw.len() >= 40 {
                let flags = u32::from_le_bytes([raw[36], raw[37], raw[38], raw[39]]) & !0x06u32;
                raw[36..40].copy_from_slice(&flags.to_le_bytes());
            }
            if doc.header.encrypted && raw.len() >= 48 {
                raw[44..48].fill(0);
            }
        }
        serialize_file_header(&header)
    } else {
        serialize_file_header(&doc.header)
    };

    // raw FileHeader가 보존되면 모델의 version과 다를 수 있으므로 실제 출력값을 쓴다.
    let output_version = u32::from_le_bytes(header_bytes[32..36].try_into().unwrap());

    // 3. BodyText 섹션별 직렬화
    //
    // [#5142] HWPX 는 한 section 파일 안에 `<hp:secPr>` 를 여러 개 둘 수 있고,
    // 파서는 이를 IR 구역 하나(문단 중간 SectionDef 컨트롤들)로 읽는다. HWP5 로
    // 그대로 몰아 저장하면 한글이 개방을 거부한다(06544: 63 secPr → Open=false,
    // 0자·1쪽). 한글은 이런 문서를 구역을 나눠 저장하므로, 문단 중간의 SectionDef
    // 경계마다 별도 BodyText/SectionN 스트림으로 가른다. 원본 스트림 재사용이
    // 허용된 구역(HWP5 라운드트립)은 원본 바이트가 이미 한글이 수용한 형상이므로
    // 가르지 않는다. HWP5 출처(네이티브·marker-HWPX)도 가르지 않는다 — 한글은
    // HWP5 단일 스트림 안 다중 secd 를 수용하며(#505 계보), 가르면 rebuild 왕복의
    // IR 형상(구역 수)이 바뀐다. 거부는 순수 HWPX 출처(x2h)에서만 관측됐다.
    let split_multi_sec_pr = doc.layout_profile().hwpx_stored_layout();
    let mut section_bytes_list = Vec::new();
    let mut viewtext_history = Vec::new();
    let mut form_id_allocator = None;
    let memos =
        crate::model::section_tail::collect(&doc.sections, storage).map_err(storage_error)?;
    for (section_idx, section) in doc.sections.iter().enumerate() {
        let tail: &[_] = if section_idx + 1 == doc.sections.len() {
            &memos
        } else {
            &[]
        };
        let split_starts: Vec<usize> =
            if !split_multi_sec_pr || section.raw_provenance_permits_reuse() {
                Vec::new()
            } else {
                section
                    .paragraphs
                    .iter()
                    .enumerate()
                    .skip(1)
                    .filter(|(_, p)| {
                        p.controls
                            .iter()
                            .any(|c| matches!(c, crate::model::control::Control::SectionDef(_)))
                    })
                    .map(|(i, _)| i)
                    .collect()
            };
        if split_starts.is_empty() {
            let prepared =
                super::form_identity::prepare_section(section, doc, &mut form_id_allocator)?;
            let prepared = super::hwpx_lineage_lines::prepare_section(prepared, doc);
            let bytes = super::body_text::try_serialize_section_for_version(
                &prepared,
                output_version,
                tail,
                storage,
            )
            .map_err(storage_error)?;
            if prepared.raw_provenance_permits_reuse() {
                if let Some(visible) =
                    crate::parser::tracked_viewtext::project(&bytes, &doc.doc_info)
                        .map_err(|error| SerializeError::UnsupportedInput(error.to_string()))?
                {
                    // An unedited review stream belongs in ViewText. Reusing it
                    // as BodyText alone loses the distinction between current
                    // content and review history in a Hancom round trip.
                    viewtext_history.push((section_bytes_list.len(), bytes));
                    section_bytes_list.push(visible);
                    continue;
                }
            }
            section_bytes_list.push(bytes);
            continue;
        }
        let mut starts = Vec::with_capacity(split_starts.len() + 1);
        starts.push(0usize);
        starts.extend(split_starts);
        for (k, &start) in starts.iter().enumerate() {
            let end = starts
                .get(k + 1)
                .copied()
                .unwrap_or(section.paragraphs.len());
            let paragraphs = section.paragraphs[start..end].to_vec();
            let section_def = paragraphs
                .first()
                .and_then(|p| {
                    p.controls.iter().find_map(|c| match c {
                        crate::model::control::Control::SectionDef(sd) => Some((**sd).clone()),
                        _ => None,
                    })
                })
                .unwrap_or_else(|| section.section_def.clone());
            let sub = crate::model::document::Section {
                section_def,
                paragraphs,
                trailing_lists: if k + 1 == starts.len() {
                    section.trailing_lists.clone()
                } else {
                    None
                },
                raw_stream: None,
                raw_provenance: None,
            };
            let prepared =
                super::form_identity::prepare_section(&sub, doc, &mut form_id_allocator)?;
            let prepared = super::hwpx_lineage_lines::prepare_section(prepared, doc);
            section_bytes_list.push(
                super::body_text::try_serialize_section_for_version(
                    &prepared,
                    output_version,
                    if k + 1 == starts.len() { tail } else { &[] },
                    storage,
                )
                .map_err(storage_error)?,
            );
        }
    }

    // 2. DocInfo 직렬화 — DOCUMENT_PROPERTIES.section_count 는 **실제로 방출한
    // BodyText/SectionN 스트림 수**로 확정한다 (#6156).
    //
    // 한글은 이 값을 구역 스트림 탐색의 상한으로 읽으므로, 선언값이 실제보다
    // 크면 없는 구역에서 손상 판정을 내고(forceopen 도 실패) 작으면 뒤쪽 구역이
    // 렌더링되지 않는다. 어느 쪽이든 이 값의 권위는 입력 모델이 아니라 이 자리 —
    // "몇 개를 실제로 썼는가" 를 아는 유일한 지점이다.
    //
    // 종전에는 `section_bytes_list.len() != doc.sections.len()` 일 때만 보정해서
    // #5142 분할로 스트림이 늘어난 경우만 잡았고, 입력이 이미 어긋난 경우
    // (선언 2 / IR 구역 1)는 두 값이 같아 원본 선언값이 그대로 실려 나갔다.
    // HWP5 네이티브 왕복은 DOCUMENT_PROPERTIES 를 raw 로 통과시키므로 불일치가
    // 왕복해도 남는다 — 그래서 모델이 아니라 방출 바이트를 고친다.
    let emitted_sections = section_bytes_list.len().min(u16::MAX as usize) as u16;
    let mut doc_info_bytes =
        super::doc_info::try_serialize_doc_info(&doc.doc_info, &doc.doc_properties, storage)
            .map_err(storage_error)?;
    if doc.doc_properties.section_count != emitted_sections {
        // raw 통과(스트림·레코드) 경로에서도 다른 바이트를 건드리지 않도록 국소 패치.
        // 레코드가 없는 병리적 스트림에서만 모델 writer 로 재생성한다.
        if surgical_update_section_count(&mut doc_info_bytes, emitted_sections).is_err() {
            let mut props = doc.doc_properties.clone();
            props.section_count = emitted_sections;
            props.raw_data = None;
            doc_info_bytes =
                super::doc_info::try_serialize_doc_info(&doc.doc_info, &props, storage)
                    .map_err(storage_error)?;
        }
    }

    // 4. 압축 여부 결정
    let compressed = doc.header.compressed;

    // 5. 미리보기 텍스트 보정
    //
    // preview 는 파싱 원본에서 그대로 실려 온다 (원본 보존 우선). 그러나 내장
    // 템플릿에서 만든 새 문서는 템플릿의 placeholder 미리보기("\r\n")를 물고
    // 나가 탐색기·한컴 미리보기에 빈 문서로 보인다. 원본 미리보기가 없거나
    // placeholder 일 때만 본문에서 새로 만든다 — 실문서의 원본 미리보기는 건드리지 않는다.
    let preview = supplement_preview(doc);

    // 6. CFB 컨테이너 조립
    let mut content_loss = ContentLossReport::new(SerializedFormat::Hwp);
    let mut extra_streams = storage
        .clone_record(&doc.extra_streams)
        .map_err(storage_error)?;
    // [#8374] Scripts 는 이 파일의 압축 비트를 따른다 — 원본과 형태가 다르면 맞춘다.
    for (path, bytes) in &mut extra_streams {
        if path.trim_start_matches('/') == "Scripts/DefaultJScript" {
            if let Some(converted) =
                crate::model::form_script::script_stream_for_hwp(doc, bytes, compressed)
                    .map_err(|error| SerializeError::UnsupportedInput(error.to_string()))?
            {
                *bytes = converted;
            }
        }
    }
    extra_streams.retain(|(path, _)| path != crate::model::border_paint::HWP_STREAM);
    if let Some(bytes) = crate::model::border_paint::encode_with_storage(doc, storage)
        .map_err(SerializeError::UnsupportedInput)?
    {
        storage
            .push(
                &mut extra_streams,
                (
                    storage
                        .string(crate::model::border_paint::HWP_STREAM)
                        .map_err(storage_error)?,
                    bytes,
                ),
            )
            .map_err(storage_error)?;
        content_loss
            .record_with_storage(
                crate::model::border_paint::native_editing_loss_with_storage(storage)
                    .map_err(storage_error)?,
                storage,
            )
            .map_err(storage_error)?;
    }
    extra_streams.retain(|(path, _)| path != crate::model::text_clip::HWP_STREAM);
    if let Some(bytes) = crate::model::text_clip::encode_with_storage(doc, storage)
        .map_err(SerializeError::UnsupportedInput)?
    {
        storage
            .push(
                &mut extra_streams,
                (
                    storage
                        .string(crate::model::text_clip::HWP_STREAM)
                        .map_err(storage_error)?,
                    bytes,
                ),
            )
            .map_err(storage_error)?;
        content_loss
            .record_with_storage(
                crate::model::text_clip::native_visibility_loss_with_storage(storage)
                    .map_err(storage_error)?,
                storage,
            )
            .map_err(storage_error)?;
    }
    extra_streams.retain(|(path, _)| path != crate::model::text_paint::HWP_STREAM);
    if let Some(bytes) = crate::model::text_paint::encode_with_storage(doc, storage)
        .map_err(SerializeError::UnsupportedInput)?
    {
        storage
            .push(
                &mut extra_streams,
                (
                    storage
                        .string(crate::model::text_paint::HWP_STREAM)
                        .map_err(storage_error)?,
                    bytes,
                ),
            )
            .map_err(storage_error)?;
        content_loss
            .record_with_storage(
                crate::model::text_paint::native_visibility_loss_with_storage(storage)
                    .map_err(storage_error)?,
                storage,
            )
            .map_err(storage_error)?;
    }
    // HWPX에 보존한 재정렬 요청도 HWP 저장·재열기에서 같은 계약을 유지한다.
    if doc.layout_profile().hwp3_external_realign()
        && !extra_streams
            .iter()
            .any(|(path, _)| path == crate::model::document::HWP3_EXTERNAL_REALIGN_STREAM_PATH)
    {
        extra_streams.push((
            crate::model::document::HWP3_EXTERNAL_REALIGN_STREAM_PATH.to_string(),
            b"1".to_vec(),
        ));
    }
    extra_streams.retain(|(path, _)| path != crate::model::native_font_program::HWP_STREAM);
    if let Some(bytes) = crate::model::native_font_program::encode_with_storage(
        &doc.doc_info,
        &doc_info_bytes,
        storage,
    )
    .map_err(SerializeError::UnsupportedInput)?
    {
        storage
            .push(
                &mut extra_streams,
                (
                    storage
                        .string(crate::model::native_font_program::HWP_STREAM)
                        .map_err(storage_error)?,
                    bytes,
                ),
            )
            .map_err(storage_error)?;
    }
    extra_streams.retain(|(path, _)| path != crate::model::hyperlink_format::HWP_STREAM);
    if let Some(bytes) = crate::model::hyperlink_format::encode_with_storage(doc, storage)
        .map_err(SerializeError::UnsupportedInput)?
    {
        storage
            .push(
                &mut extra_streams,
                (
                    storage
                        .string(crate::model::hyperlink_format::HWP_STREAM)
                        .map_err(storage_error)?,
                    bytes,
                ),
            )
            .map_err(storage_error)?;
    }
    let bytes = write_hwp_cfb_with_storage(
        &header_bytes,
        &doc_info_bytes,
        &section_bytes_list,
        &viewtext_history,
        &doc.doc_info.bin_data_list,
        &doc.bin_data_content,
        &preview,
        &extra_streams,
        compressed,
        password,
        &mut content_loss,
        storage,
        maximum,
    )?;
    if matches!(warning_mode, ContentLossWarningMode::LegacyStderr) {
        content_loss.write_warnings_to_stderr();
    }
    Ok(SerializedDocument::new(bytes, content_loss))
}

/// PrvText 가 비었거나 placeholder 면 본문 텍스트로 채운다.
///
/// 원본 미리보기가 실재하면 그대로 둔다 (라운드트립 보존).
fn supplement_preview(doc: &Document) -> Option<Preview> {
    let has_real_text = doc
        .preview
        .as_ref()
        .and_then(|p| p.text.as_ref())
        .map(|t| !t.trim().is_empty())
        .unwrap_or(false);

    if has_real_text {
        return doc.preview.clone();
    }

    let text = build_preview_text(doc);
    if text.trim().is_empty() {
        return doc.preview.clone();
    }

    Some(Preview {
        image: doc.preview.as_ref().and_then(|p| p.image.clone()),
        text: Some(text),
    })
}

/// 본문 문단에서 미리보기 텍스트를 만든다.
///
/// 한컴은 앞부분 일부만 담는다 (shortcut.hwp 실측 2044B ≈ 1022자).
/// 표/글상자 안 텍스트는 제외하고 본문 문단만 이어 붙인다.
fn build_preview_text(doc: &Document) -> String {
    const MAX_CHARS: usize = 1000;

    let mut out = String::new();
    for section in &doc.sections {
        for para in &section.paragraphs {
            let line = para.text.trim_end_matches('\u{0}');
            if line.is_empty() {
                continue;
            }
            out.push_str(line);
            out.push_str("\r\n");
            if out.chars().count() >= MAX_CHARS {
                return out.chars().take(MAX_CHARS).collect();
            }
        }
    }
    out
}

/// raw deflate 압축 (wbits=-15)
fn compress_stream(data: &[u8]) -> Result<Vec<u8>, SerializeError> {
    compress_stream_with_storage(data, &crate::storage::Unbounded)
}

fn compress_stream_with_storage<S: crate::storage::Storage>(
    data: &[u8],
    storage: &S,
) -> Result<Vec<u8>, SerializeError>
where
    S::Error: std::fmt::Display,
{
    use flate2::write::DeflateEncoder;
    use flate2::Compression;

    let mut encoder = DeflateEncoder::new(
        super::budget_cursor::BudgetCursor::new(storage, usize::MAX),
        Compression::default(),
    );
    encoder
        .write_all(data)
        .map_err(|e| SerializeError::CompressError(e.to_string()))?;
    encoder
        .finish()
        .map(|writer| writer.into_inner())
        .map_err(|e| SerializeError::CompressError(e.to_string()))
}

/// CFB 컨테이너를 인메모리로 생성하여 바이트 배열 반환
fn write_hwp_cfb(
    header_bytes: &[u8],
    doc_info_bytes: &[u8],
    section_bytes_list: &[Vec<u8>],
    viewtext_history: &[(usize, Vec<u8>)],
    bin_data_list: &[BinData],
    bin_data_content: &[BinDataContent],
    preview: &Option<Preview>,
    extra_streams: &[(String, Vec<u8>)],
    compressed: bool,
    password: Option<&[u8]>,
    content_loss: &mut ContentLossReport,
) -> Result<Vec<u8>, SerializeError> {
    write_hwp_cfb_with_storage(
        header_bytes,
        doc_info_bytes,
        section_bytes_list,
        viewtext_history,
        bin_data_list,
        bin_data_content,
        preview,
        extra_streams,
        compressed,
        password,
        content_loss,
        &crate::storage::Unbounded,
        usize::MAX,
    )
}

fn write_hwp_cfb_with_storage<S: crate::storage::Storage>(
    header_bytes: &[u8],
    doc_info_bytes: &[u8],
    section_bytes_list: &[Vec<u8>],
    viewtext_history: &[(usize, Vec<u8>)],
    bin_data_list: &[BinData],
    bin_data_content: &[BinDataContent],
    preview: &Option<Preview>,
    extra_streams: &[(String, Vec<u8>)],
    compressed: bool,
    password: Option<&[u8]>,
    content_loss: &mut ContentLossReport,
    storage: &S,
    maximum: usize,
) -> Result<Vec<u8>, SerializeError>
where
    S::Error: std::fmt::Display,
{
    let storage_error = |error| SerializeError::CfbError(format!("{error}"));
    storage.bytes(0).map_err(storage_error)?;
    // 스트림 목록 수집
    let mut streams: Vec<(String, Vec<u8>)> = Vec::new();

    // 1. /FileHeader (항상 비압축)
    storage
        .push(
            &mut streams,
            (
                storage.string("/FileHeader").map_err(storage_error)?,
                storage.copy_slice(header_bytes).map_err(storage_error)?,
            ),
        )
        .map_err(storage_error)?;

    // 2. /DocInfo (조건부 압축)
    let doc_info_data = if compressed {
        compress_stream_with_storage(doc_info_bytes, storage)?
    } else {
        storage.copy_slice(doc_info_bytes).map_err(storage_error)?
    };
    storage
        .push(
            &mut streams,
            (
                storage.string("/DocInfo").map_err(storage_error)?,
                encrypt_if_password(doc_info_data, password),
            ),
        )
        .map_err(storage_error)?;

    // 3. /BodyText/Section{N} (조건부 압축)
    for (i, section_bytes) in section_bytes_list.iter().enumerate() {
        let path = storage
            .display(&format_args!("/BodyText/Section{}", i))
            .map_err(storage_error)?;
        let data = if compressed {
            compress_stream_with_storage(section_bytes, storage)?
        } else {
            storage.copy_slice(section_bytes).map_err(storage_error)?
        };
        storage
            .push(&mut streams, (path, encrypt_if_password(data, password)))
            .map_err(storage_error)?;
    }
    for (index, bytes) in viewtext_history {
        let data = if compressed {
            compress_stream_with_storage(bytes, storage)?
        } else {
            storage.copy_slice(bytes).map_err(storage_error)?
        };
        storage
            .push(
                &mut streams,
                (
                    storage
                        .display(&format_args!("/ViewText/Section{index}"))
                        .map_err(storage_error)?,
                    encrypt_if_password(data, password),
                ),
            )
            .map_err(storage_error)?;
    }

    // 4. /BinData/BIN{XXXX}.{ext}
    // BinData는 개별 압축 속성에 따라 재압축
    const CFB_MAGIC: [u8; 8] = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];
    for (index, content) in bin_data_content.iter().enumerate() {
        // 연결 레코드 자리 항목은 저장 스트림이 없다.
        if crate::model::bin_data::is_hwp5_link_slot(content, bin_data_list.get(index)) {
            continue;
        }
        let (storage_id, ext, mut should_compress) =
            find_bin_data_info_with_compress(bin_data_list, content, compressed);
        if password.is_some() {
            should_compress = compressed;
        }
        let storage_name = storage
            .display(&format_args!("BIN{:04X}.{}", storage_id, ext))
            .map_err(storage_error)?;
        let path = storage
            .display(&format_args!("/BinData/{}", storage_name))
            .map_err(storage_error)?;

        // 원본 HWP5 에서 바뀌지 않은 항목은 저장된 스트림을 그대로 쓴다. 압축을 풀었다가
        // 다시 압축하는 것과 내용이 같고(OLE 크기 prefix 도 원본 그대로다), 원본 바이트를
        // 보존한다. 편집·추가한 바이트는 저장 형태가 없어 아래 경로로 다시 만든다.
        // 저장 압축 상태가 이 문서가 기대하는 상태와 다르면(암호 저장의 압축 강제 등)
        // 통과시키지 않는다.
        if let Some(stored) = content
            .data
            .load_raw()
            .filter(|stored| stored.compressed == should_compress)
        {
            streams.push((path, encrypt_if_password(stored.bytes, password)));
            continue;
        }

        // [#2550] 압축 해제 상한. 초과 항목(deflate bomb 포함)은 해제 없이 원본
        // 저장 바이트를 그대로 통과시킨다 — 재압축·OLE prefix 복원·매직 판정은
        // 해제된 바이트에만 의미가 있고, 원본 스트림은 이미 그 처리가 끝난
        // 형태이므로 전부 건너뛴다. 정상 대용량 개체는 무손실, 폭탄은 애초에
        // 해제하지 않으므로 OOM 이 없다.
        let bytes = match storage
            .bin_data(&content.data, MAX_BIN_DATA_BYTES)
            .map_err(storage_error)?
        {
            Some(bytes) => bytes,
            None => match content.data.load_raw() {
                // 저장 형태를 그대로 쓰려면 그 압축 상태가 이 문서에서 기대되는
                // 상태와 같아야 한다. 다르면(암호 저장의 압축 강제 등) 읽는 쪽이
                // 압축 바이트를 원본으로 오해해 조용히 깨지므로 통과시키지 않는다.
                Some(stored) if stored.compressed == should_compress => {
                    storage
                        .push(
                            &mut streams,
                            (path, encrypt_if_password(stored.bytes, password)),
                        )
                        .map_err(storage_error)?;
                    continue;
                }
                Some(_) => {
                    // 상한 초과 + 압축 상태 불일치 — 해제(OOM 위험)도, 그대로 쓰기
                    // (오독)도 안 된다. 렌더·클립보드와 같은 placeholder 로 접는다.
                    content_loss
                        .record_with_storage(
                            ContentLoss::binary_content_emptied(
                                storage_id,
                                storage.string(&path).map_err(storage_error)?,
                                ContentLossReason::StoredCompressionMismatch,
                            ),
                            storage,
                        )
                        .map_err(storage_error)?;
                    storage
                        .push(
                            &mut streams,
                            (path, encrypt_if_password(Vec::new(), password)),
                        )
                        .map_err(storage_error)?;
                    continue;
                }
                // HWPX ZIP·인메모리 항목처럼 원본 HWP5 저장 형태가 없는 경우에는
                // 안전한 raw passthrough가 불가능하다. 여기서 `load()`로 되돌아가면
                // HWPX deflate bomb가 다시 무제한 materialize되므로 placeholder로
                // 접는다. 이미 메모리에 있는 `Loaded` 값도 `load_limited()`에서
                // 길이를 확인했으므로 같은 경로를 탄다.
                None => {
                    content_loss
                        .record_with_storage(
                            ContentLoss::binary_content_emptied(
                                storage_id,
                                storage.string(&path).map_err(storage_error)?,
                                ContentLossReason::RawPassthroughUnavailable,
                            ),
                            storage,
                        )
                        .map_err(storage_error)?;
                    storage
                        .push(
                            &mut streams,
                            (path, encrypt_if_password(Vec::new(), password)),
                        )
                        .map_err(storage_error)?;
                    continue;
                }
            },
        };

        // OLE Storage 복원: 파서(`load_bin_data_content`)는 내부 CFB 를 바로 노출하기 위해
        // 선두 4-byte LE size prefix 를 제거(`drain(..4)`)한다. 직렬화 시 이를 다시 붙이지
        // 않으면 한컴이 CFB 매직(D0CF11E0)을 OLE 개체 크기(~3.75GB)로 오인하여
        // "메모리 부족" 오류가 발생한다. 파서의 strip 조건을 그대로 미러링한다.
        let is_ole_storage = bytes.len() >= 8
            && bytes[..8] == CFB_MAGIC
            && bin_data_list
                .iter()
                .any(|bd| bd.data_type == BinDataType::Storage && bd.storage_id == content.id);
        let payload: Vec<u8> = if is_ole_storage {
            let mut v = storage
                .vec(bytes.len().saturating_add(4))
                .map_err(storage_error)?;
            v.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
            v.extend_from_slice(&bytes);
            v
        } else {
            bytes
        };

        let data = if should_compress {
            match compress_stream_with_storage(&payload, storage) {
                Ok(bytes) => bytes,
                Err(_) => {
                    // A request failure must not become ordinary compression fallback.
                    storage.bytes(0).map_err(storage_error)?;
                    storage.copy_slice(&payload).map_err(storage_error)?
                }
            }
        } else {
            payload
        };
        storage
            .push(&mut streams, (path, encrypt_if_password(data, password)))
            .map_err(storage_error)?;
    }

    // 5. 미리보기 데이터 (PrvImage, PrvText)
    if let Some(ref prv) = preview {
        if let Some(ref image) = prv.image {
            storage
                .push(
                    &mut streams,
                    (
                        storage.string("/PrvImage").map_err(storage_error)?,
                        storage.copy_slice(&image.data).map_err(storage_error)?,
                    ),
                )
                .map_err(storage_error)?;
        }
        if let Some(ref text) = prv.text {
            // UTF-16LE로 인코딩
            let utf16 = text.encode_utf16();
            let count = text.encode_utf16().count().saturating_mul(2);
            let mut bytes = storage.vec(count).map_err(storage_error)?;
            for ch in utf16 {
                bytes.extend_from_slice(&ch.to_le_bytes());
            }
            storage
                .push(
                    &mut streams,
                    (storage.string("/PrvText").map_err(storage_error)?, bytes),
                )
                .map_err(storage_error)?;
        }
    }

    // 6. 추가 스트림 (Scripts, DocOptions 등 — 라운드트립 보존)
    for (path, data) in extra_streams {
        let payload = if password.is_some()
            && (path.starts_with("/Scripts/") || path.starts_with("/BinData/"))
        {
            encrypt_if_password(storage.copy_slice(data).map_err(storage_error)?, password)
        } else {
            storage.copy_slice(data).map_err(storage_error)?
        };
        storage
            .push(
                &mut streams,
                (storage.string(path).map_err(storage_error)?, payload),
            )
            .map_err(storage_error)?;
    }

    // mini_cfb로 CFB 컨테이너 조립 (WASM 호환)
    let named_streams = storage
        .collect(
            streams
                .iter()
                .map(|(path, data)| (path.as_str(), data.as_slice())),
        )
        .map_err(storage_error)?;
    mini_cfb::build_cfb_with_storage(&named_streams, [0; 16], storage, maximum)
        .map_err(SerializeError::CfbError)
}

fn encrypt_if_password(data: Vec<u8>, password: Option<&[u8]>) -> Vec<u8> {
    match password {
        Some(value) => encrypt_hwp5_stream(&data, value),
        None => data,
    }
}

/// BinDataContent에 대응하는 BinData 정보(storage_id, extension, should_compress) 찾기
///
/// should_compress: BinData의 압축 속성에 따라 재압축 여부 결정
/// - Default: 문서 전체 compressed 플래그 따름
/// - Compress: 항상 압축
/// - NoCompress: 비압축
fn find_bin_data_info_with_compress<'a>(
    bin_data_list: &'a [BinData],
    content: &'a BinDataContent,
    doc_compressed: bool,
) -> (u16, &'a str, bool) {
    use crate::model::bin_data::BinDataCompression;
    for bd in bin_data_list {
        if matches!(bd.data_type, BinDataType::Embedding | BinDataType::Storage)
            && bd.storage_id == content.id
        {
            let ext = bd.extension.as_deref().unwrap_or("dat");
            let should_compress = match bd.compression {
                BinDataCompression::Default => doc_compressed,
                BinDataCompression::Compress => true,
                BinDataCompression::NoCompress => false,
            };
            return (bd.storage_id, ext, should_compress);
        }
    }
    // 못 찾으면 content에서 직접 추출 (문서 압축 플래그 따름)
    (content.id, &content.extension, doc_compressed)
}

#[cfg(test)]
mod tests;