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
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
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
//! CFB (Compound File Binary) 컨테이너 읽기
//!
//! HWP 파일의 OLE/CFB 컨테이너를 열고 스트림을 추출한다.
//! - FileHeader: 256바이트, 비압축
//! - DocInfo: 레코드 스트림, 압축 가능
//! - BodyText/Section{N}: 레코드 스트림, 압축 가능
//! - ViewText/Section{N}: 배포용 문서 (암호화 + 압축)
//! - BinData/BIN{XXXX}.{ext}: 바이너리 데이터

use std::io::{Cursor, Read};

/// CFB 컨테이너 리더
pub struct CfbReader {
    compound: cfb::CompoundFile<Cursor<Vec<u8>>>,
}

/// CFB 리더 에러
#[derive(Debug)]
pub enum CfbError {
    /// OLE 컨테이너 열기 실패
    OpenError(String),
    /// 스트림 읽기 실패
    StreamError(String),
    /// 스트림을 찾을 수 없음
    StreamNotFound(String),
    /// 압축 해제 실패
    DecompressError(String),
    /// 스트림 또는 압축 해제 결과가 호출부 상한을 초과함
    LimitExceeded(usize),
}

impl std::fmt::Display for CfbError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CfbError::OpenError(e) => write!(f, "CFB 열기 실패: {}", e),
            CfbError::StreamError(e) => write!(f, "스트림 읽기 실패: {}", e),
            CfbError::StreamNotFound(name) => write!(f, "스트림 없음: {}", name),
            CfbError::DecompressError(e) => write!(f, "압축 해제 실패: {}", e),
            CfbError::LimitExceeded(limit) => {
                write!(f, "스트림이 {} 바이트 상한을 초과했습니다", limit)
            }
        }
    }
}

impl std::error::Error for CfbError {}

impl CfbReader {
    /// 바이트 데이터에서 CFB 컨테이너 열기
    pub fn open(data: &[u8]) -> Result<Self, CfbError> {
        let cursor = Cursor::new(data.to_vec());
        let compound =
            cfb::CompoundFile::open(cursor).map_err(|e| CfbError::OpenError(e.to_string()))?;

        Ok(CfbReader { compound })
    }

    /// 스트림 존재 여부 확인
    pub fn has_stream(&self, path: &str) -> bool {
        self.compound.is_stream(path)
    }

    /// 스트림 원본 데이터 읽기 (압축 해제 없이)
    pub fn read_stream_raw(&mut self, path: &str) -> Result<Vec<u8>, CfbError> {
        if !self.compound.is_stream(path) {
            return Err(CfbError::StreamNotFound(path.to_string()));
        }

        let mut stream = self
            .compound
            .open_stream(path)
            .map_err(|e| CfbError::StreamError(format!("{}: {}", path, e)))?;

        let mut data = Vec::new();
        stream
            .read_to_end(&mut data)
            .map_err(|e| CfbError::StreamError(format!("{}: {}", path, e)))?;

        Ok(data)
    }

    /// 스트림 원본을 `max_bytes` 바이트까지만 읽는다.
    ///
    /// 상한을 선택하지 않는 CFB 기계 API다. 원본 스트림을 직접 소비하는 caller는
    /// 자신의 자원 정책을 명시적으로 전달해야 한다.
    pub fn read_stream_raw_limited(
        &mut self,
        path: &str,
        max_bytes: usize,
    ) -> Result<Vec<u8>, CfbError> {
        if !self.compound.is_stream(path) {
            return Err(CfbError::StreamNotFound(path.to_string()));
        }

        let mut stream = self
            .compound
            .open_stream(path)
            .map_err(|e| CfbError::StreamError(format!("{}: {}", path, e)))?;

        let mut data = Vec::new();
        stream
            .by_ref()
            .take((max_bytes as u64).saturating_add(1))
            .read_to_end(&mut data)
            .map_err(|e| CfbError::StreamError(format!("{}: {}", path, e)))?;
        if data.len() > max_bytes {
            return Err(CfbError::LimitExceeded(max_bytes));
        }

        Ok(data)
    }

    /// FileHeader 스트림 읽기 (256바이트, 항상 비압축)
    pub fn read_file_header(&mut self) -> Result<Vec<u8>, CfbError> {
        self.read_stream_raw("/FileHeader")
    }

    /// DocInfo 스트림 읽기 (압축 가능)
    pub fn read_doc_info(&mut self, compressed: bool) -> Result<Vec<u8>, CfbError> {
        decode_stream(self.read_stream_raw("/DocInfo")?, compressed)
    }

    /// DocInfo 스트림을 압축 해제 결과 기준 `max_bytes` 바이트까지만 읽는다.
    pub fn read_doc_info_limited(
        &mut self,
        compressed: bool,
        max_bytes: usize,
    ) -> Result<Vec<u8>, CfbError> {
        decode_stream_limited(self.read_stream_raw("/DocInfo")?, compressed, max_bytes)
    }

    /// 본문 섹션 스트림 읽기
    ///
    /// 배포용 문서의 경우 ViewText/Section{N}에서 읽는다.
    /// 일반 문서는 BodyText/Section{N}에서 읽는다.
    /// 반환값은 압축 해제된 레코드 데이터.
    ///
    /// 배포용 문서의 경우, 이 함수는 raw 암호화 데이터를 반환한다.
    /// 호출자가 별도로 복호화를 수행해야 한다.
    pub fn read_body_text_section(
        &mut self,
        index: u32,
        compressed: bool,
        distribution: bool,
    ) -> Result<Vec<u8>, CfbError> {
        if distribution {
            // 배포용 문서: ViewText 스트림 (암호화됨 → 호출자가 복호화)
            let viewtext_path = format!("/ViewText/Section{}", index);
            if self.has_stream(&viewtext_path) {
                return self.read_stream_raw(&viewtext_path);
            }
        }

        decode_stream(self.read_body_text_section_raw(index)?, compressed)
    }

    /// 일반 BodyText 섹션을 압축 해제 결과 기준 `max_bytes` 바이트까지만 읽는다.
    ///
    /// 배포용 ViewText는 암호화된 raw 스트림이므로 이 메서드의 대상이 아니다.
    pub fn read_body_text_section_limited(
        &mut self,
        index: u32,
        compressed: bool,
        max_bytes: usize,
    ) -> Result<Vec<u8>, CfbError> {
        let raw = self.read_body_text_section_raw(index)?;

        decode_stream_limited(raw, compressed, max_bytes)
    }

    /// 일반 BodyText 섹션의 원본 바이트를 반환한다.
    ///
    /// 비밀번호 암호 문서는 이 경로로 암호문을 가져온 뒤, 호출자가 복호화 결과에
    /// 열린 문서의 예산을 적용한다.
    pub(crate) fn read_body_text_section_raw(&mut self, index: u32) -> Result<Vec<u8>, CfbError> {
        let bodytext_path = format!("/BodyText/Section{}", index);
        if self.has_stream(&bodytext_path) {
            return self.read_stream_raw(&bodytext_path);
        }

        let section_path = format!("/Section{}", index);
        if !self.has_stream(&section_path) {
            return Err(CfbError::StreamNotFound(format!("Section{}", index)));
        }
        self.read_stream_raw(&section_path)
    }

    /// 일반 BodyText 섹션의 원본을 caller 제공 상한까지 읽는다.
    ///
    /// 이 API는 압축 해제를 하지 않는다. raw 암호문을 직접 소비하는 CLI 같은 caller는
    /// 이 명시적 bound를 사용한 뒤 자신의 crypto `_limited` 호출에 별도 출력 상한을 준다.
    pub fn read_body_text_section_raw_limited(
        &mut self,
        index: u32,
        max_bytes: usize,
    ) -> Result<Vec<u8>, CfbError> {
        let bodytext_path = format!("/BodyText/Section{}", index);
        if self.has_stream(&bodytext_path) {
            return self.read_stream_raw_limited(&bodytext_path, max_bytes);
        }

        let section_path = format!("/Section{}", index);
        if !self.has_stream(&section_path) {
            return Err(CfbError::StreamNotFound(format!("Section{}", index)));
        }
        self.read_stream_raw_limited(&section_path, max_bytes)
    }

    /// 배포용 ViewText 섹션의 암호문 원본을 반환한다.
    ///
    /// 배포용 문서 열기 경계는 이 바이트를 crypto의 명시적 상한 경로로 전달한다.
    /// ViewText가 없을 때 BodyText로 대체하지 않는다. 그 대체는 배포 플래그가 켜진
    /// 손상 입력에서 일반 본문을 무제한 압축 해제할 수 있기 때문이다.
    pub(crate) fn read_viewtext_section_raw(&mut self, index: u32) -> Result<Vec<u8>, CfbError> {
        let path = format!("/ViewText/Section{}", index);
        self.read_stream_raw(&path)
    }

    /// 배포용 ViewText 암호문 원본을 caller 제공 상한까지 읽는다.
    pub(crate) fn read_viewtext_section_raw_limited(
        &mut self,
        index: u32,
        max_bytes: usize,
    ) -> Result<Vec<u8>, CfbError> {
        let path = format!("/ViewText/Section{}", index);
        self.read_stream_raw_limited(&path, max_bytes)
    }

    /// BinData 스트림 읽기 (BinData/BIN{XXXX}.{ext})
    pub fn read_bin_data(&mut self, storage_name: &str) -> Result<Vec<u8>, CfbError> {
        let path = format!("/BinData/{}", storage_name);
        self.read_stream_raw(&path)
    }

    /// BinData 스트림을 `max_bytes` 바이트까지만 읽는다.
    pub fn read_bin_data_limited(
        &mut self,
        storage_name: &str,
        max_bytes: usize,
    ) -> Result<Vec<u8>, CfbError> {
        let path = format!("/BinData/{}", storage_name);
        if !self.compound.is_stream(&path) {
            return Err(CfbError::StreamNotFound(path));
        }
        let mut stream = self
            .compound
            .open_stream(&path)
            .map_err(|error| CfbError::StreamError(format!("{}: {}", path, error)))?;
        let mut data = Vec::new();
        stream
            .by_ref()
            .take((max_bytes as u64).saturating_add(1))
            .read_to_end(&mut data)
            .map_err(|error| CfbError::StreamError(format!("{}: {}", path, error)))?;
        if data.len() > max_bytes {
            return Err(CfbError::LimitExceeded(max_bytes));
        }
        Ok(data)
    }

    /// 본문 섹션 수 계산
    pub fn section_count(&self) -> u32 {
        let mut count = 0;
        loop {
            let has_body = self
                .compound
                .is_stream(&format!("/BodyText/Section{}", count));
            let has_view = self
                .compound
                .is_stream(&format!("/ViewText/Section{}", count));
            let has_root = self.compound.is_stream(&format!("/Section{}", count));

            if has_body || has_view || has_root {
                count += 1;
            } else {
                break;
            }
        }
        count
    }

    /// BinData 스토리지의 스트림 이름 목록
    pub fn list_bin_data(&self) -> Vec<String> {
        let mut names = Vec::new();
        // cfb 크레이트의 walk API로 BinData 하위 항목 탐색
        for entry in self.compound.walk() {
            let path = entry.path().to_string_lossy().replace('\\', "/");
            if path.starts_with("/BinData/") && entry.is_stream() {
                if let Some(name) = path.strip_prefix("/BinData/") {
                    names.push(name.to_string());
                }
            }
        }
        names
    }

    /// 모든 스트림 경로 목록
    pub fn list_streams(&self) -> Vec<String> {
        let mut paths = Vec::new();
        for entry in self.compound.walk() {
            if entry.is_stream() {
                paths.push(entry.path().to_string_lossy().replace('\\', "/"));
            }
        }
        paths
    }

    /// 모든 엔트리(스트림 + 스토리지) 경로와 크기 목록
    pub fn list_all_entries(&self) -> Vec<(String, u64, bool)> {
        let mut entries = Vec::new();
        for entry in self.compound.walk() {
            let path = entry.path().to_string_lossy().replace('\\', "/");
            let size = entry.len();
            let is_stream = entry.is_stream();
            entries.push((path, size, is_stream));
        }
        entries
    }

    /// 미리보기 이미지 스트림 읽기 (PrvImage)
    ///
    /// BMP 또는 GIF 형식의 썸네일 이미지를 반환한다.
    /// 스트림이 없으면 None을 반환한다.
    pub fn read_preview_image(&mut self) -> Option<Vec<u8>> {
        if self.has_stream("/PrvImage") {
            self.read_stream_raw("/PrvImage").ok()
        } else {
            None
        }
    }

    /// 미리보기 이미지 스트림을 `max_bytes` 바이트까지만 읽는다.
    ///
    /// 호출자가 정한 상한에 대해, 디렉터리의 선언 크기와 실제 stream read 양쪽을
    /// 확인한다.
    pub fn read_preview_image_limited(&mut self, max_bytes: usize) -> Option<Vec<u8>> {
        let declared_size = usize::try_from(self.compound.entry("/PrvImage").ok()?.len()).ok()?;
        if declared_size == 0 || declared_size > max_bytes {
            return None;
        }

        let mut stream = self.compound.open_stream("/PrvImage").ok()?;
        let mut data = Vec::new();
        stream
            .by_ref()
            .take((max_bytes as u64).saturating_add(1))
            .read_to_end(&mut data)
            .ok()?;
        (data.len() == declared_size).then_some(data)
    }

    /// 미리보기 텍스트 스트림 읽기 (PrvText)
    ///
    /// UTF-16LE 인코딩된 미리보기 텍스트를 반환한다.
    /// 스트림이 없으면 None을 반환한다.
    pub fn read_preview_text(&mut self) -> Option<String> {
        if !self.has_stream("/PrvText") {
            return None;
        }

        let data = self.read_stream_raw("/PrvText").ok()?;

        // UTF-16LE 디코딩
        if data.len() < 2 {
            return None;
        }

        let text: String = data
            .chunks(2)
            .filter_map(|chunk| {
                if chunk.len() == 2 {
                    let code = u16::from_le_bytes([chunk[0], chunk[1]]);
                    char::from_u32(code as u32)
                } else {
                    None
                }
            })
            .collect();

        if text.is_empty() {
            None
        } else {
            Some(text)
        }
    }

    /// [Task #1001] HWP3 → HWP5 변환본 식별 (휴리스틱).
    ///
    /// HwpSummaryInformation stream 의 text properties 안에 HWP3 시대 (1990-2003)
    /// 의 년 (예: "1998년") 이 포함되어 있으면 변환본으로 판정. 한컴이 HWP3 →
    /// HWP5 변환 시 원본 작성일 / 메모 등을 HwpSummary 의 string field 에 보존
    /// 하는 패턴을 활용.
    ///
    /// 변환본은 ParaShape spacing/margin 값이 HWP3 원본의 2배로 저장되어 있어
    /// 한컴 viewer 가 표시 시 1/2 보정 (HwpUnitChar 단위) 한다. rhwp 도 동일
    /// 보정을 위해 본 식별 신호 사용.
    ///
    /// Misid risk: HwpSummary 의 다른 field 가 우연히 HWP3 시대 년 포함 시
    /// false positive. 그러나 변환본이 아닌 일반 HWP5 의 ParaShape spacing 은
    /// 대부분 0 이라 1/2 보정 영향이 미미함 (시각 회귀 안전).
    pub fn detect_hwp3_variant(&mut self) -> bool {
        // HwpSummaryInformation stream 시도 (다양한 경로)
        let raw = self
            .read_stream_raw("/\u{0005}HwpSummaryInformation")
            .or_else(|_| self.read_stream_raw("\u{0005}HwpSummaryInformation"))
            .or_else(|_| self.read_stream_raw("HwpSummaryInformation"))
            .unwrap_or_default();
        hwp_summary_indicates_hwp3_era(&raw)
    }
}

/// Lenient CFB 리더 (FAT 검증 무시)
///
/// HWP 프로그램이 생성하는 일부 CFB 파일은 표준 cfb 크레이트의
/// FAT 검증("sector 0 pointed to twice")을 통과하지 못한다.
/// 이 구현체는 FAT 중복을 무시하고 스트림을 추출한다.
pub struct LenientCfbReader {
    data: Vec<u8>,
    sector_size: usize,
    /// Directory entries: (name, start_sector, size, obj_type)
    entries: Vec<(String, u32, u64, u8)>,
    /// 원본 directory ID를 보존한 엔트리. 경로가 중요한 ViewText는 이 트리를 따라
    /// 찾아야 `BodyText/SectionN`과 이름만 같은 스트림을 혼동하지 않는다.
    directory_entries: Vec<LenientDirectoryEntry>,
    /// FAT table
    fat: Vec<u32>,
    /// Mini-stream data
    mini_stream: Vec<u8>,
    /// Mini-FAT table
    mini_fat: Vec<u32>,
    /// Mini-stream cutoff size
    mini_stream_cutoff: u32,
}

#[derive(Debug)]
struct LenientDirectoryEntry {
    name: String,
    left_sibling: u32,
    right_sibling: u32,
    child: u32,
    start_sector: u32,
    size: u64,
    obj_type: u8,
}

impl LenientCfbReader {
    const END_OF_CHAIN: u32 = 0xFFFFFFFE;
    const FREE_SECT: u32 = 0xFFFFFFFF;

    pub fn open(data: &[u8]) -> Result<Self, CfbError> {
        if data.len() < 512 {
            return Err(CfbError::OpenError("파일이 너무 작음".into()));
        }
        // Magic number 확인
        if &data[0..8] != b"\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1" {
            return Err(CfbError::OpenError("CFB 매직 넘버 불일치".into()));
        }

        // 섹터 크기 지수는 파일에서 온 값(0~65535)이라 검증 없이 shift 하면 안 된다.
        // - power >= 64(wasm32 에서는 >= 32): `1usize << power` 가 shift overflow.
        //   debug 는 패닉, release 는 마스킹돼 엉뚱한 sector_size 가 된다.
        // - power 가 0·1 이면 sector_size 가 1·2 라 아래 DIFAT 순회의
        //   `sector_size / 4 - 1` 이 언더플로한다(debug 패닉, release 는 usize::MAX 로
        //   감싸져 곧바로 슬라이스 범위 초과 패닉).
        // CFB 사양상 섹터 크기는 512B(9) 또는 4096B(12)이므로 그 범위를 벗어나면
        // 해석을 포기하고 Err 를 돌려준다. 패닉은 WASM 모듈 전체를 죽여 편집 중인
        // 다른 문서까지 잃게 하므로, 열기 실패로 처리하는 편이 언제나 낫다.
        let sector_size_power = u16::from_le_bytes([data[30], data[31]]) as usize;
        if !(9..=12).contains(&sector_size_power) {
            return Err(CfbError::OpenError(format!(
                "CFB 섹터 크기 지수가 사양 범위를 벗어남: {sector_size_power}"
            )));
        }
        let sector_size = 1usize << sector_size_power;
        let mini_sector_size_power = u16::from_le_bytes([data[32], data[33]]) as usize;
        if mini_sector_size_power >= usize::BITS as usize {
            return Err(CfbError::OpenError(format!(
                "CFB 미니 섹터 크기 지수가 사양 범위를 벗어남: {mini_sector_size_power}"
            )));
        }
        let _mini_sector_size = 1usize << mini_sector_size_power;

        let fat_sectors_count =
            u32::from_le_bytes([data[44], data[45], data[46], data[47]]) as usize;
        let first_dir_sector = u32::from_le_bytes([data[48], data[49], data[50], data[51]]);
        let mini_stream_cutoff = u32::from_le_bytes([data[56], data[57], data[58], data[59]]);
        let first_mini_fat_sector = u32::from_le_bytes([data[60], data[61], data[62], data[63]]);
        let mini_fat_sectors_count =
            u32::from_le_bytes([data[64], data[65], data[66], data[67]]) as usize;
        let first_difat_sector = u32::from_le_bytes([data[68], data[69], data[70], data[71]]);
        let difat_sectors_count =
            u32::from_le_bytes([data[72], data[73], data[74], data[75]]) as usize;

        // DIFAT 읽기: 헤더의 109개 + 추가 DIFAT 섹터
        //
        // [정적분석] 유효한 CFB 파일은 각 FAT 섹터 id 를 DIFAT 에 한 번만 기재한다
        // (섹터마다 파일의 서로 다른 영역을 담당하므로). 이 불변식을 검증 없이 신뢰하면,
        // 조작된 파일이 같은 id 를 반복 기재해 물리 섹터 1개만으로 FAT 벡터를
        // 반복 횟수에 비례해(최대 DIFAT 섹터 수 × 섹터당 엔트리 수) 부풀릴 수 있다
        // (#3181 순환 미탐지와 같은 클래스 — "카운트 필드를 무검증으로 반복 사용"하는
        // DoS 증폭). visited_fat_sids 로 중복 id 를 조용히 건너뛴다.
        let mut fat_sector_ids = Vec::new();
        let mut visited_fat_sids = std::collections::HashSet::new();
        for i in 0..109.min(fat_sectors_count) {
            let off = 76 + i * 4;
            let sid = u32::from_le_bytes([data[off], data[off + 1], data[off + 2], data[off + 3]]);
            if sid != Self::FREE_SECT && sid != Self::END_OF_CHAIN && visited_fat_sids.insert(sid) {
                fat_sector_ids.push(sid);
            }
        }
        // 추가 DIFAT 섹터 체인
        if difat_sectors_count > 0 && first_difat_sector != Self::END_OF_CHAIN {
            let mut dsid = first_difat_sector;
            // difat_sectors_count 는 파일 헤더에서 그대로 읽은 값(공격자 통제 가능)이라,
            // 실제 섹터 체인이 짧은 순환을 이뤄도 최대 u32::MAX 번 순회할 수 있다.
            // FAT/미니FAT 체인 순회(read_chain_static)처럼 방문 집합으로 순환을 조기 차단한다.
            let mut visited_difat = std::collections::HashSet::new();
            for _ in 0..difat_sectors_count {
                if !visited_difat.insert(dsid) {
                    break;
                }
                let off = 512 + dsid as usize * sector_size;
                if off + sector_size > data.len() {
                    break;
                }
                let entries_per = sector_size / 4 - 1;
                for i in 0..entries_per {
                    let eoff = off + i * 4;
                    let sid = u32::from_le_bytes([
                        data[eoff],
                        data[eoff + 1],
                        data[eoff + 2],
                        data[eoff + 3],
                    ]);
                    if sid != Self::FREE_SECT
                        && sid != Self::END_OF_CHAIN
                        && visited_fat_sids.insert(sid)
                    {
                        fat_sector_ids.push(sid);
                    }
                }
                // 다음 DIFAT 섹터
                let next_off = off + entries_per * 4;
                dsid = u32::from_le_bytes([
                    data[next_off],
                    data[next_off + 1],
                    data[next_off + 2],
                    data[next_off + 3],
                ]);
                if dsid == Self::END_OF_CHAIN || dsid == Self::FREE_SECT {
                    break;
                }
            }
        }

        // FAT 빌드
        let mut fat = Vec::new();
        for &fsid in &fat_sector_ids {
            let off = 512 + fsid as usize * sector_size;
            if off + sector_size > data.len() {
                continue;
            }
            let entries = sector_size / 4;
            for i in 0..entries {
                let eoff = off + i * 4;
                fat.push(u32::from_le_bytes([
                    data[eoff],
                    data[eoff + 1],
                    data[eoff + 2],
                    data[eoff + 3],
                ]));
            }
        }

        // Directory entries 읽기
        let dir_data = Self::read_chain_static(data, &fat, first_dir_sector, sector_size);
        let mut entries = Vec::new();
        let mut directory_entries = Vec::new();
        let entry_size = 128;
        let n_entries = dir_data.len() / entry_size;
        for i in 0..n_entries {
            let eoff = i * entry_size;
            // name_len 도 파일에서 온 값(0~65535)이다. 이름 필드는 엔트리 선두 64바이트이므로
            // 그보다 큰 값은 손상으로 보고 잘라낸다. 잘라내지 않으면 아래 슬라이스가
            // dir_data(= n_entries * 128 바이트) 범위를 넘어 패닉한다 — 슬라이스 경계 검사는
            // release 에서도 켜져 있어 배포 WASM 에서도 그대로 터진다.
            let name_len =
                (u16::from_le_bytes([dir_data[eoff + 64], dir_data[eoff + 65]]) as usize).min(64);
            let name = if name_len > 2 {
                let name_bytes = &dir_data[eoff..eoff + name_len - 2]; // UTF-16LE, exclude null
                String::from_utf16_lossy(
                    &name_bytes
                        .chunks(2)
                        .map(|c| u16::from_le_bytes([c[0], c.get(1).copied().unwrap_or(0)]))
                        .collect::<Vec<_>>(),
                )
            } else {
                String::new()
            };
            let obj_type = dir_data[eoff + 66];
            let left_sibling = u32::from_le_bytes([
                dir_data[eoff + 68],
                dir_data[eoff + 69],
                dir_data[eoff + 70],
                dir_data[eoff + 71],
            ]);
            let right_sibling = u32::from_le_bytes([
                dir_data[eoff + 72],
                dir_data[eoff + 73],
                dir_data[eoff + 74],
                dir_data[eoff + 75],
            ]);
            let child = u32::from_le_bytes([
                dir_data[eoff + 76],
                dir_data[eoff + 77],
                dir_data[eoff + 78],
                dir_data[eoff + 79],
            ]);
            let start_sector = u32::from_le_bytes([
                dir_data[eoff + 116],
                dir_data[eoff + 117],
                dir_data[eoff + 118],
                dir_data[eoff + 119],
            ]);
            let size = u64::from_le_bytes([
                dir_data[eoff + 120],
                dir_data[eoff + 121],
                dir_data[eoff + 122],
                dir_data[eoff + 123],
                dir_data[eoff + 124],
                dir_data[eoff + 125],
                dir_data[eoff + 126],
                dir_data[eoff + 127],
            ]);

            directory_entries.push(LenientDirectoryEntry {
                name: name.clone(),
                left_sibling,
                right_sibling,
                child,
                start_sector,
                size,
                obj_type,
            });

            if obj_type == 1 || obj_type == 2 || obj_type == 5 {
                entries.push((name, start_sector, size, obj_type));
            }
        }

        // Mini-FAT 빌드
        let mut mini_fat = Vec::new();
        if mini_fat_sectors_count > 0 && first_mini_fat_sector != Self::END_OF_CHAIN {
            let mfat_data = Self::read_chain_static(data, &fat, first_mini_fat_sector, sector_size);
            for chunk in mfat_data.chunks(4) {
                if chunk.len() == 4 {
                    mini_fat.push(u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
                }
            }
        }

        // Mini-stream: Root entry의 스트림 데이터
        let mini_stream = directory_entries
            .iter()
            .find(|entry| entry.obj_type == 5)
            .map(|root| Self::read_chain_static(data, &fat, root.start_sector, sector_size))
            .unwrap_or_default();

        Ok(LenientCfbReader {
            data: data.to_vec(),
            sector_size,
            entries,
            directory_entries,
            fat,
            mini_stream,
            mini_fat,
            mini_stream_cutoff,
        })
    }

    fn read_chain_static(data: &[u8], fat: &[u32], start: u32, sector_size: usize) -> Vec<u8> {
        let mut result = Vec::new();
        let mut sid = start;
        let mut visited = std::collections::HashSet::new();
        while sid != Self::END_OF_CHAIN && sid != Self::FREE_SECT {
            if !visited.insert(sid) {
                break;
            } // 순환 방지
            let off = 512 + sid as usize * sector_size;
            if off + sector_size > data.len() {
                break;
            }
            result.extend_from_slice(&data[off..off + sector_size]);
            if (sid as usize) < fat.len() {
                sid = fat[sid as usize];
            } else {
                break;
            }
        }
        result
    }

    /// 선언된 스트림 길이까지만 FAT 체인을 읽는다.
    ///
    /// lenient 경로는 손상된 체인도 최대한 복구하려 하지만, 완전 문서 열기에서
    /// 원시 스트림 상한을 우회해서 전체 체인을 `Vec`로 만들면 안 된다.
    fn read_chain_static_sized(
        data: &[u8],
        fat: &[u32],
        start: u32,
        sector_size: usize,
        size: usize,
    ) -> Vec<u8> {
        let mut result = Vec::with_capacity(size.min(sector_size));
        let mut sid = start;
        let mut visited = std::collections::HashSet::new();
        while result.len() < size && sid != Self::END_OF_CHAIN && sid != Self::FREE_SECT {
            if !visited.insert(sid) {
                break;
            }
            let off = 512 + sid as usize * sector_size;
            if off + sector_size > data.len() {
                break;
            }
            let remaining = size - result.len();
            let take = remaining.min(sector_size);
            result.extend_from_slice(&data[off..off + take]);
            if (sid as usize) < fat.len() {
                sid = fat[sid as usize];
            } else {
                break;
            }
        }
        result
    }

    fn read_mini_stream(&self, start: u32, size: u64) -> Vec<u8> {
        let mini_sector_size = 64usize;
        let mut result = Vec::new();
        let mut sid = start;
        let mut visited = std::collections::HashSet::new();
        while sid != Self::END_OF_CHAIN && sid != Self::FREE_SECT {
            if !visited.insert(sid) {
                break;
            }
            let off = sid as usize * mini_sector_size;
            if off + mini_sector_size > self.mini_stream.len() {
                break;
            }
            result.extend_from_slice(&self.mini_stream[off..off + mini_sector_size]);
            if (sid as usize) < self.mini_fat.len() {
                sid = self.mini_fat[sid as usize];
            } else {
                break;
            }
        }
        result.truncate(size as usize);
        result
    }

    /// 선언된 mini-stream 길이까지만 읽는다.
    fn read_mini_stream_sized(&self, start: u32, size: usize) -> Vec<u8> {
        const MINI_SECTOR_SIZE: usize = 64;

        let mut result = Vec::with_capacity(size.min(MINI_SECTOR_SIZE));
        let mut sid = start;
        let mut visited = std::collections::HashSet::new();
        while result.len() < size && sid != Self::END_OF_CHAIN && sid != Self::FREE_SECT {
            if !visited.insert(sid) {
                break;
            }
            let off = sid as usize * MINI_SECTOR_SIZE;
            if off + MINI_SECTOR_SIZE > self.mini_stream.len() {
                break;
            }
            let remaining = size - result.len();
            let take = remaining.min(MINI_SECTOR_SIZE);
            result.extend_from_slice(&self.mini_stream[off..off + take]);
            if (sid as usize) < self.mini_fat.len() {
                sid = self.mini_fat[sid as usize];
            } else {
                break;
            }
        }
        result
    }

    /// 디렉토리 경로로 엔트리 id(= `directory_entries` 인덱스)를 찾는다.
    /// 경로 형식: "FileHeader", "/DocInfo", "/BodyText/Section0" 등
    ///
    /// 스토리지를 실제로 따라간다. 이름만 비교하면 `BodyText/Section0` 과
    /// `ViewText/Section0` 처럼 **이름이 같은 스트림**을 가진 문서에서 디렉터리에
    /// 먼저 나오는 쪽이 잡힌다(변경 추적 문서 등에서 실제로 발생).
    fn find_entry_id(&self, path: &str) -> Option<usize> {
        let parts: Vec<&str> = path
            .trim_start_matches('/')
            .split('/')
            .filter(|segment| !segment.is_empty())
            .collect();
        let (last, parents) = parts.split_last()?;

        // 1) 정상 CFB: 루트에서 세그먼트마다 자식으로 내려간다.
        if let Some(root_id) = self
            .directory_entries
            .iter()
            .position(|entry| entry.obj_type == 5)
        {
            let mut current = Some(root_id);
            for segment in parents {
                current = current
                    .and_then(|id| self.find_child_entry_by_name(id, segment))
                    .filter(|&id| self.directory_entries[id].obj_type == 1);
            }
            // 손상된 링크가 이름만 남은 삭제 슬롯을 가리킬 수 있다.
            // 무효 entry는 채택하지 않고 아래의 유일 이름 복구를 시도한다.
            if let Some(id) = current
                .and_then(|id| self.find_child_entry_by_name(id, last))
                .filter(|&id| matches!(self.directory_entries[id].obj_type, 1 | 2 | 5))
            {
                return Some(id);
            }
        }

        // 2) lenient 폴백: 디렉터리 트리가 깨진 입력은 이름으로 찾는다.
        //    단 같은 이름이 둘 이상이면 어느 쪽이 맞는지 알 수 없으므로 고르지 않는다
        //    (잘못된 스트림을 조용히 읽느니 없다고 답한다).
        let mut found = None;
        for (id, entry) in self.directory_entries.iter().enumerate() {
            if entry.name == *last && matches!(entry.obj_type, 1 | 2 | 5) {
                if found.is_some() {
                    return None;
                }
                found = Some(id);
            }
        }
        found
    }

    /// 본문 섹션 스트림 경로. strict `CfbReader::read_body_text_section_raw` 와 같은 규칙.
    fn body_text_section_path(&self, index: u32) -> String {
        let bodytext_path = format!("/BodyText/Section{}", index);
        if self.has_stream(&bodytext_path) {
            return bodytext_path;
        }
        format!("/Section{}", index)
    }

    fn find_child_entry_by_name(&self, parent_id: usize, name: &str) -> Option<usize> {
        let first_child = self.directory_entries.get(parent_id)?.child;
        let mut pending = vec![first_child];
        let mut visited = std::collections::HashSet::new();

        while let Some(entry_id) = pending.pop() {
            if entry_id == Self::END_OF_CHAIN || entry_id == Self::FREE_SECT {
                continue;
            }
            let entry_id = entry_id as usize;
            if !visited.insert(entry_id) {
                continue;
            }
            let Some(entry) = self.directory_entries.get(entry_id) else {
                continue;
            };
            if entry.name == name {
                return Some(entry_id);
            }
            pending.push(entry.left_sibling);
            pending.push(entry.right_sibling);
        }

        None
    }

    fn read_directory_stream(&self, entry_id: usize, path: &str) -> Result<Vec<u8>, CfbError> {
        let entry = self
            .directory_entries
            .get(entry_id)
            .ok_or_else(|| CfbError::StreamNotFound(path.to_string()))?;
        if entry.obj_type != 2 {
            return Err(CfbError::StreamError(format!(
                "{}: 스트림이 아님 (type={})",
                path, entry.obj_type
            )));
        }

        if entry.size < self.mini_stream_cutoff as u64 {
            Ok(self.read_mini_stream(entry.start_sector, entry.size))
        } else {
            let mut data = Self::read_chain_static(
                &self.data,
                &self.fat,
                entry.start_sector,
                self.sector_size,
            );
            data.truncate(entry.size as usize);
            Ok(data)
        }
    }

    fn read_directory_stream_limited(
        &self,
        entry_id: usize,
        path: &str,
        max_bytes: usize,
    ) -> Result<Vec<u8>, CfbError> {
        let entry = self
            .directory_entries
            .get(entry_id)
            .ok_or_else(|| CfbError::StreamNotFound(path.to_string()))?;
        if entry.obj_type != 2 {
            return Err(CfbError::StreamError(format!(
                "{}: 스트림이 아님 (type={})",
                path, entry.obj_type
            )));
        }
        if entry.size > max_bytes as u64 {
            return Err(CfbError::LimitExceeded(max_bytes));
        }
        let size = entry.size as usize;
        if entry.size < self.mini_stream_cutoff as u64 {
            Ok(self.read_mini_stream_sized(entry.start_sector, size))
        } else {
            Ok(Self::read_chain_static_sized(
                &self.data,
                &self.fat,
                entry.start_sector,
                self.sector_size,
                size,
            ))
        }
    }

    pub fn read_stream(&self, path: &str) -> Result<Vec<u8>, CfbError> {
        let entry_id = self
            .find_entry_id(path)
            .ok_or_else(|| CfbError::StreamNotFound(path.to_string()))?;
        self.read_directory_stream(entry_id, path)
    }

    /// 원시 스트림을 caller 제공 상한 안에서 읽는다.
    ///
    /// 선언 크기를 먼저 검증하고 FAT/mini-FAT 체인도 선언 크기까지만 순회하므로,
    /// lenient fallback이 손상된 체인의 뒷부분을 불필요하게 materialize하지 않는다.
    pub fn read_stream_raw_limited(
        &self,
        path: &str,
        max_bytes: usize,
    ) -> Result<Vec<u8>, CfbError> {
        let entry_id = self
            .find_entry_id(path)
            .ok_or_else(|| CfbError::StreamNotFound(path.to_string()))?;
        self.read_directory_stream_limited(entry_id, path, max_bytes)
    }

    pub fn has_stream(&self, path: &str) -> bool {
        self.find_entry_id(path).is_some()
    }

    pub fn read_doc_info(&self, compressed: bool) -> Result<Vec<u8>, CfbError> {
        decode_stream(self.read_stream("DocInfo")?, compressed)
    }

    pub fn read_doc_info_limited(
        &self,
        compressed: bool,
        max_bytes: usize,
    ) -> Result<Vec<u8>, CfbError> {
        decode_stream_limited(self.read_stream("DocInfo")?, compressed, max_bytes)
    }

    pub fn read_body_text_section(
        &self,
        index: u32,
        compressed: bool,
    ) -> Result<Vec<u8>, CfbError> {
        let path = self.body_text_section_path(index);
        decode_stream(self.read_stream(&path)?, compressed)
    }

    pub fn list_entries(&self) -> &[(String, u32, u64, u8)] {
        &self.entries
    }

    /// FileHeader 스트림 읽기 (256바이트, 항상 비압축)
    pub fn read_file_header(&self) -> Result<Vec<u8>, CfbError> {
        self.read_stream("FileHeader")
    }

    /// 본문 섹션 스트림 읽기 (배포용 ViewText 지원)
    pub fn read_body_text_section_full(
        &self,
        index: u32,
        compressed: bool,
        distribution: bool,
    ) -> Result<Vec<u8>, CfbError> {
        if distribution {
            let viewtext_path = format!("/ViewText/Section{}", index);
            // ViewText 하위 스트림 탐색
            if self.has_stream(&viewtext_path) {
                return self.read_stream(&viewtext_path);
            }
        }

        let path = self.body_text_section_path(index);
        decode_stream(self.read_stream(&path)?, compressed)
    }

    /// 배포용 ViewText 섹션의 암호문 원본을 반환한다.
    ///
    /// Lenient complete-open 경계는 이 값을 crypto의 명시적 상한 경로로 전달한다.
    /// 손상된 배포 플래그에서 BodyText fallback을 하지 않는다.
    pub(crate) fn read_viewtext_section_raw(&self, index: u32) -> Result<Vec<u8>, CfbError> {
        let path = format!("ViewText/Section{}", index);
        let root_id = self
            .directory_entries
            .iter()
            .position(|entry| entry.obj_type == 5)
            .ok_or_else(|| CfbError::StreamNotFound(path.clone()))?;
        let viewtext_id = self
            .find_child_entry_by_name(root_id, "ViewText")
            .filter(|entry_id| self.directory_entries[*entry_id].obj_type == 1)
            .ok_or_else(|| CfbError::StreamNotFound(path.clone()))?;
        let section_name = format!("Section{}", index);
        let section_id = self
            .find_child_entry_by_name(viewtext_id, &section_name)
            .filter(|entry_id| self.directory_entries[*entry_id].obj_type == 2)
            .ok_or_else(|| CfbError::StreamNotFound(path.clone()))?;
        self.read_directory_stream(section_id, &path)
    }

    /// 배포용 ViewText 암호문 원본을 caller 제공 상한까지 읽는다.
    pub(crate) fn read_viewtext_section_raw_limited(
        &self,
        index: u32,
        max_bytes: usize,
    ) -> Result<Vec<u8>, CfbError> {
        let path = format!("ViewText/Section{}", index);
        let root_id = self
            .directory_entries
            .iter()
            .position(|entry| entry.obj_type == 5)
            .ok_or_else(|| CfbError::StreamNotFound(path.clone()))?;
        let viewtext_id = self
            .find_child_entry_by_name(root_id, "ViewText")
            .filter(|entry_id| self.directory_entries[*entry_id].obj_type == 1)
            .ok_or_else(|| CfbError::StreamNotFound(path.clone()))?;
        let section_name = format!("Section{}", index);
        let section_id = self
            .find_child_entry_by_name(viewtext_id, &section_name)
            .filter(|entry_id| self.directory_entries[*entry_id].obj_type == 2)
            .ok_or_else(|| CfbError::StreamNotFound(path.clone()))?;
        self.read_directory_stream_limited(section_id, &path, max_bytes)
    }

    pub fn read_body_text_section_limited(
        &self,
        index: u32,
        compressed: bool,
        max_bytes: usize,
    ) -> Result<Vec<u8>, CfbError> {
        let path = self.body_text_section_path(index);
        decode_stream_limited(self.read_stream(&path)?, compressed, max_bytes)
    }

    /// 일반 BodyText 섹션의 원본을 caller 제공 상한까지 읽는다.
    /// strict `CfbReader::read_body_text_section_raw_limited` 와 같은 경로 규칙.
    pub fn read_body_text_section_raw_limited(
        &self,
        index: u32,
        max_bytes: usize,
    ) -> Result<Vec<u8>, CfbError> {
        let path = self.body_text_section_path(index);
        self.read_stream_raw_limited(&path, max_bytes)
    }

    /// 본문 섹션 수 계산
    pub fn section_count(&self) -> u32 {
        let mut count = 0u32;
        loop {
            let name = format!("Section{}", count);
            if self.entries.iter().any(|(n, _, _, _)| n == &name) {
                count += 1;
            } else {
                break;
            }
        }
        count
    }
}

/// CFB 루트 디렉터리 엔트리의 CLSID(오프셋 +80, 16바이트)를 읽는다. (#4097)
///
/// OLE 개체는 이 값으로 서버를 식별한다. 재포장할 때 보존하지 않으면 한컴이 개체를 알아보지
/// 못해 틀과 선택 핸들만 그리고 내용을 비운다(2026-08-05 실측). 짝이 되는 쓰기측은
/// `serializer::mini_cfb::build_cfb_with_root_clsid` 다.
///
/// 전체 파싱을 하지 않는다 — 헤더 두 필드만 본다. `_uSectorShift`(0x1E)로 섹터 크기를,
/// `_sectDirStart`(0x30)로 첫 디렉터리 섹터 SID 를 구한다. 헤더가 앞 512바이트를 차지하므로
/// 섹터 SID `n` 의 파일 오프셋은 `512 + n * sector_size` 이고, 루트는 그 섹터의 0번 엔트리다.
/// 헤더 크기는 CFB v3/v4 모두 512바이트다. 따라서 v3(512B sector)에서는
/// `(n + 1) * sector_size` 와 우연히 같지만, v4(4096B sector)에서는 반드시 헤더 512바이트를
/// 별도로 더해야 한다.
///
/// 형식이 어긋나면 `None` 을 돌려주고 패닉하지 않는다. 패닉은 WASM 모듈 전체를 죽여 편집 중인
/// 다른 문서까지 잃게 하므로, `LenientCfbReader::open` 의 섹터 지수 검증과 같은 근거로 전 구간에
/// 바운드 검사를 건다.
pub fn root_clsid(cfb: &[u8]) -> Option<[u8; 16]> {
    if cfb.len() < 512 || cfb[0..8] != *b"\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1" {
        return None;
    }
    // 섹터 크기 지수는 파일에서 온 값(0~65535)이라 검증 없이 shift 하면 안 된다.
    // wasm32(usize=32bit)에서 `1usize << 32` 는 debug 패닉 / release 마스킹이다.
    let sector_shift = u16::from_le_bytes([cfb[0x1E], cfb[0x1F]]) as usize;
    if !(9..=12).contains(&sector_shift) {
        return None;
    }
    let sector_size = 1usize << sector_shift;
    let dir_start = u32::from_le_bytes(cfb[0x30..0x34].try_into().ok()?) as usize;
    // ENDOFCHAIN(0xFFFFFFFE) 같은 특수값과 거대 SID 는 checked 연산이 걸러낸다.
    // wasm32 에서는 usize 가 32비트라 곱셈이 실제로 넘칠 수 있어 checked_mul 이 필수다.
    let at = 512usize
        .checked_add(dir_start.checked_mul(sector_size)?)?
        .checked_add(80)?;
    let end = at.checked_add(16)?;
    if end > cfb.len() {
        return None;
    }
    cfb[at..end].try_into().ok()
}

/// zlib/deflate 압축 해제
///
/// HWP는 raw deflate (wbits=-15) 사용. 실패 시 표준 zlib도 시도.
/// 문서 입력을 여는 경로는 이 함수 대신 [`decompress_stream_limited`]를 사용한다.
pub fn decompress_stream(data: &[u8]) -> Result<Vec<u8>, CfbError> {
    // raw deflate (wbits=-15) 시도
    use flate2::read::DeflateDecoder;
    let mut decoder = DeflateDecoder::new(data);
    let mut decompressed = Vec::new();
    match decoder.read_to_end(&mut decompressed) {
        Ok(_) => return Ok(decompressed),
        Err(_) => {}
    }

    // 표준 zlib 시도
    use flate2::read::ZlibDecoder;
    let mut decoder = ZlibDecoder::new(data);
    let mut decompressed = Vec::new();
    match decoder.read_to_end(&mut decompressed) {
        Ok(_) => Ok(decompressed),
        Err(e) => Err(CfbError::DecompressError(e.to_string())),
    }
}

/// zlib/raw-deflate 데이터를 `max_bytes` 바이트까지만 압축 해제한다.
pub fn decompress_stream_limited(data: &[u8], max_bytes: usize) -> Result<Vec<u8>, CfbError> {
    fn decode_limited<R: Read>(reader: R, max_bytes: usize) -> Result<Vec<u8>, CfbError> {
        let mut output = Vec::new();
        reader
            .take((max_bytes as u64).saturating_add(1))
            .read_to_end(&mut output)
            .map_err(|error| CfbError::DecompressError(error.to_string()))?;
        if output.len() > max_bytes {
            return Err(CfbError::LimitExceeded(max_bytes));
        }
        Ok(output)
    }

    let raw_result = decode_limited(flate2::read::DeflateDecoder::new(data), max_bytes);
    if let Ok(output) = raw_result {
        return Ok(output);
    }
    let raw_exceeded = matches!(raw_result, Err(CfbError::LimitExceeded(_)));

    match decode_limited(flate2::read::ZlibDecoder::new(data), max_bytes) {
        Ok(output) => Ok(output),
        Err(CfbError::LimitExceeded(_)) => Err(CfbError::LimitExceeded(max_bytes)),
        Err(_) if raw_exceeded => Err(CfbError::LimitExceeded(max_bytes)),
        Err(error) => Err(error),
    }
}

fn decode_stream(raw: Vec<u8>, compressed: bool) -> Result<Vec<u8>, CfbError> {
    if compressed {
        decompress_stream(&raw)
    } else {
        Ok(raw)
    }
}

pub(crate) fn decode_stream_limited(
    raw: Vec<u8>,
    compressed: bool,
    max_bytes: usize,
) -> Result<Vec<u8>, CfbError> {
    if compressed {
        decompress_stream_limited(&raw, max_bytes)
    } else if raw.len() > max_bytes {
        Err(CfbError::LimitExceeded(max_bytes))
    } else {
        Ok(raw)
    }
}

/// 압축 해제 결과의 **길이만** 센다. 출력을 버퍼에 쌓지 않으므로 메모리 O(1)이다.
///
/// [#2550] `len()`/`is_empty()` 류 질의가 크기를 재려고 전체를 materialize 하지
/// 않도록 한다. `decompress_stream_limited` 와 같은 순서(raw deflate → zlib)와
/// 같은 `LimitExceeded` 우선순위를 따른다. `cap` 초과 시 `LimitExceeded`.
pub fn decompressed_len_capped(data: &[u8], cap: usize) -> Result<usize, CfbError> {
    fn count_limited<R: Read>(reader: R, cap: usize) -> Result<usize, CfbError> {
        let mut limited = reader.take((cap as u64).saturating_add(1));
        let copied = std::io::copy(&mut limited, &mut std::io::sink())
            .map_err(|error| CfbError::DecompressError(error.to_string()))?;
        if copied > cap as u64 {
            return Err(CfbError::LimitExceeded(cap));
        }
        Ok(copied as usize)
    }

    let raw_result = count_limited(flate2::read::DeflateDecoder::new(data), cap);
    if let Ok(len) = raw_result {
        return Ok(len);
    }
    let raw_exceeded = matches!(raw_result, Err(CfbError::LimitExceeded(_)));

    match count_limited(flate2::read::ZlibDecoder::new(data), cap) {
        Ok(len) => Ok(len),
        Err(CfbError::LimitExceeded(_)) => Err(CfbError::LimitExceeded(cap)),
        Err(_) if raw_exceeded => Err(CfbError::LimitExceeded(cap)),
        Err(error) => Err(error),
    }
}

/// 압축 해제 결과의 **선두 `n` 바이트까지만** 얻는다. 이후가 더 있어도 오류가 아니다.
///
/// [#2550] OLE size prefix 판정(12바이트)이나 빈 항목 판정(1바이트)처럼 아주 짧은
/// 프리픽스만 필요할 때, 전체 해제나 `LimitExceeded` 없이 안전하게 읽는 경로다.
pub fn decompress_stream_prefix(data: &[u8], n: usize) -> Result<Vec<u8>, CfbError> {
    fn prefix<R: Read>(reader: R, n: usize) -> Result<Vec<u8>, CfbError> {
        let mut output = Vec::new();
        reader
            .take(n as u64)
            .read_to_end(&mut output)
            .map_err(|error| CfbError::DecompressError(error.to_string()))?;
        Ok(output)
    }

    if let Ok(output) = prefix(flate2::read::DeflateDecoder::new(data), n) {
        return Ok(output);
    }
    prefix(flate2::read::ZlibDecoder::new(data), n)
}

/// [#7035] `HwpSummaryInformation` 원문에서 HWP3 시대(1990~2003) 년 표기를 찾는다.
///
/// 같은 판정을 정상 `CfbReader` 와 lenient 경로가 함께 쓰도록 바이트 단위로 뽑았다 —
/// 한쪽만 이 신호를 갖고 다른 쪽이 비율 휴리스틱만 쓰면 같은 문서가 파싱 경로에 따라
/// 다른 조판 예산을 받는다.
pub fn hwp_summary_indicates_hwp3_era(raw: &[u8]) -> bool {
    if raw.len() < 16 {
        return false;
    }
    // UTF-16LE 디코딩
    let utf16: Vec<u16> = raw
        .chunks_exact(2)
        .map(|c| u16::from_le_bytes([c[0], c[1]]))
        .collect();
    let text = String::from_utf16_lossy(&utf16);
    // HWP3 시대 (1990-2003) 의 년 검출 — HWP5 도입 (2007년) 이전
    (1990..=2003).any(|y| text.contains(&format!("{}년", y)))
}

#[cfg(test)]
mod tests {
    use super::*;

    // ── LenientCfbReader 헤더 필드 검증 ──────────────────────────────────
    //
    // LenientCfbReader 는 엄격 파서가 실패한 뒤에만 쓰인다(parser/mod.rs). 즉 입력 모집단이
    // "이미 손상이 확인된 파일"이라, 헤더 필드에 쓰레기 값이 들어있을 확률이 가장 높은
    // 자리다. 그런데 파일에서 온 값을 검증 없이 shift/슬라이스에 쓰고 있었다.
    // WASM 에서 패닉은 모듈 전체를 트랩시켜 편집 중이던 다른 문서까지 잃게 하므로,
    // 해석 불가한 헤더는 패닉이 아니라 Err 로 돌려줘야 한다.

    /// 최소 CFB 헤더(512B). 섹터 크기 512B, DIFAT/디렉터리 없음.
    fn minimal_header() -> Vec<u8> {
        let mut d = vec![0u8; 512];
        d[0..8].copy_from_slice(&[0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]);
        d[30..32].copy_from_slice(&9u16.to_le_bytes()); // sector size = 1 << 9
        d[32..34].copy_from_slice(&6u16.to_le_bytes()); // mini sector size = 1 << 6
        d[68..72].copy_from_slice(&0xFFFF_FFFEu32.to_le_bytes()); // first DIFAT = EOC
        d
    }

    #[test]
    fn root_clsid_reads_v4_directory_after_fixed_header() {
        // CFB v4도 헤더는 512B이며 첫 섹터는 그 직후에 시작한다. SID=1인 디렉터리는
        // 512 + 1 * 4096에 있으므로 `(SID + 1) * 4096`로 계산하면 다른 위치를 읽는다.
        const CLSID: [u8; 16] = [
            0x37, 0xa1, 0x3d, 0x4c, 0x90, 0xdc, 0xb9, 0x47, 0x9b, 0xed, 0x59, 0xda, 0xe3, 0x52,
            0xa2, 0x80,
        ];
        const SECTOR_SIZE: usize = 4096;
        const DIRECTORY_SID: usize = 1;

        let mut d = minimal_header();
        d[30..32].copy_from_slice(&12u16.to_le_bytes());
        d[48..52].copy_from_slice(&(DIRECTORY_SID as u32).to_le_bytes());
        d.resize(512 + (DIRECTORY_SID + 1) * SECTOR_SIZE, 0);
        let directory = 512 + DIRECTORY_SID * SECTOR_SIZE;
        d[directory + 80..directory + 96].copy_from_slice(&CLSID);

        assert_eq!(root_clsid(&d), Some(CLSID));
    }

    #[test]
    fn lenient_open_rejects_out_of_range_sector_size_power() {
        // power >= 64 는 `1usize << power` 가 shift overflow(debug 패닉 / release 마스킹).
        let mut d = minimal_header();
        d[30..32].copy_from_slice(&64u16.to_le_bytes());
        assert!(
            LenientCfbReader::open(&d).is_err(),
            "shift overflow 대신 Err 이어야 함"
        );

        // power 0·1 은 sector_size 가 1·2 라 DIFAT 순회의 `sector_size / 4 - 1` 이 언더플로.
        for bad in [0u16, 1u16] {
            let mut d = minimal_header();
            d[30..32].copy_from_slice(&bad.to_le_bytes());
            d[68..72].copy_from_slice(&0u32.to_le_bytes()); // DIFAT 체인 진입
            d[72..76].copy_from_slice(&1u32.to_le_bytes());
            assert!(
                LenientCfbReader::open(&d).is_err(),
                "sector_size_power={bad} 에서 언더플로 대신 Err 이어야 함"
            );
        }
    }

    #[test]
    fn lenient_open_rejects_out_of_range_mini_sector_size_power() {
        let mut d = minimal_header();
        d[32..34].copy_from_slice(&64u16.to_le_bytes());
        assert!(
            LenientCfbReader::open(&d).is_err(),
            "shift overflow 대신 Err 이어야 함"
        );
    }

    #[test]
    fn lenient_open_survives_oversized_directory_entry_name_len() {
        // 디렉터리 섹터까지 도달하는 최소 컨테이너.
        // 레이아웃: [0]=헤더 512B, [512]=FAT 섹터, [1024]=디렉터리 섹터
        let mut d = minimal_header();
        d[44..48].copy_from_slice(&1u32.to_le_bytes()); // FAT 섹터 1개
        d[48..52].copy_from_slice(&1u32.to_le_bytes()); // 디렉터리 시작 = 섹터 1
        d[76..80].copy_from_slice(&0u32.to_le_bytes()); // DIFAT[0] = FAT 은 섹터 0
        d.resize(512 * 3, 0);

        // FAT(섹터 0): 엔트리 1 = END_OF_CHAIN → 디렉터리 체인은 한 섹터로 끝난다.
        d[512 + 4..512 + 8].copy_from_slice(&0xFFFF_FFFEu32.to_le_bytes());

        // 디렉터리(섹터 1)의 첫 엔트리 name_len 을 최대값으로 손상시킨다.
        // 잘라내지 않으면 dir_data(512B) 범위를 한참 넘겨 슬라이스해 패닉한다.
        d[1024 + 64..1024 + 66].copy_from_slice(&0xFFFFu16.to_le_bytes());

        let r = LenientCfbReader::open(&d);
        assert!(r.is_ok(), "손상된 name_len 에서 패닉 없이 열려야 함");
    }

    #[test]
    fn lenient_open_terminates_on_cyclic_difat_chain() {
        // DIFAT 확장 체인은 header 의 difat_sectors_count(공격자 통제 가능한 4바이트) 만큼
        // 순회하되, FAT 체인 순회(read_chain_static)와 달리 방문 집합이 없다. 두 DIFAT
        // 섹터가 서로를 가리키는 순환을 만들고 difat_sectors_count 를 u32::MAX 로 두면,
        // 실제 체인 길이(2)와 무관하게 최대 40억 회 넘게 순회해 사실상 멈추지 않는다 —
        // 단일 스레드 WASM 에서는 탭 전체가 응답 없음 상태가 된다.
        let mut d = minimal_header();
        d[44..48].copy_from_slice(&0u32.to_le_bytes()); // fat_sectors_count = 0
        d[68..72].copy_from_slice(&0u32.to_le_bytes()); // first_difat_sector = 섹터 0
        d[72..76].copy_from_slice(&u32::MAX.to_le_bytes()); // difat_sectors_count: 공격자 제어

        // 헤더(512B) 뒤에 DIFAT 섹터 2개(섹터 0, 섹터 1)를 배치.
        d.resize(512 + 512 * 2, 0);
        let entries_per = 512 / 4 - 1; // 127
                                       // 모든 FAT-포인터 엔트리는 FREE_SECT 로 채워 fat_sector_ids 가 자라지 않게 한다
                                       // (순환 자체와 무관한 메모리 팽창을 피하기 위함).
        for sector_idx in 0..2usize {
            let base = 512 + sector_idx * 512;
            for i in 0..entries_per {
                let eoff = base + i * 4;
                d[eoff..eoff + 4].copy_from_slice(&0xFFFF_FFFFu32.to_le_bytes());
            }
        }
        // 섹터 0 의 "다음 DIFAT" 포인터 = 섹터 1
        let next0 = 512 + entries_per * 4;
        d[next0..next0 + 4].copy_from_slice(&1u32.to_le_bytes());
        // 섹터 1 의 "다음 DIFAT" 포인터 = 섹터 0 (순환!)
        let next1 = 512 + 512 + entries_per * 4;
        d[next1..next1 + 4].copy_from_slice(&0u32.to_le_bytes());

        let (tx, rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let _ = LenientCfbReader::open(&d);
            let _ = tx.send(());
        });
        assert!(
            rx.recv_timeout(std::time::Duration::from_secs(3)).is_ok(),
            "순환 DIFAT 체인에서 방문 집합 없이 difat_sectors_count 만큼 순회해 반환하지 않음"
        );
    }

    #[test]
    fn lenient_open_deduplicates_fat_sector_id_from_difat() {
        // Header DIFAT과 추가 DIFAT가 같은 FAT sector 0을 가리키는 손상 CFB.
        // 물리 FAT은 한 섹터이므로 결과 fat도 512 / 4 엔트리여야 한다.
        let mut d = minimal_header();
        d[44..48].copy_from_slice(&1u32.to_le_bytes()); // FAT sector 수
        d[48..52].copy_from_slice(&0xFFFF_FFFEu32.to_le_bytes()); // directory = EOC
        d[68..72].copy_from_slice(&1u32.to_le_bytes()); // 추가 DIFAT = sector 1
        d[72..76].copy_from_slice(&1u32.to_le_bytes());
        d[76..80].copy_from_slice(&0u32.to_le_bytes()); // header FAT = sector 0
        d.resize(512 + 512 * 2, 0);

        let difat_off = 512 + 512;
        let entries_per = 512 / 4 - 1;
        for i in 0..entries_per {
            let off = difat_off + i * 4;
            d[off..off + 4].copy_from_slice(&0xFFFF_FFFFu32.to_le_bytes());
        }
        d[difat_off..difat_off + 4].copy_from_slice(&0u32.to_le_bytes()); // duplicate FAT
        let next_difat = difat_off + entries_per * 4;
        d[next_difat..next_difat + 4].copy_from_slice(&0xFFFF_FFFEu32.to_le_bytes());

        let reader = LenientCfbReader::open(&d).expect("손상 CFB도 lenient reader가 열어야 함");
        assert_eq!(
            reader.fat.len(),
            512 / 4,
            "중복 FAT sector를 한 번만 읽어야 함"
        );
    }

    #[test]
    fn test_decompress_empty() {
        // 빈 deflate 스트림 (0x03, 0x00 = final empty block)
        let compressed = [0x03, 0x00];
        let result = decompress_stream(&compressed);
        assert!(result.is_ok());
        assert!(result.unwrap().is_empty());
    }

    #[test]
    fn test_decompress_invalid_data() {
        let result = decompress_stream(&[0xFF, 0xFF, 0xFF]);
        assert!(result.is_err());
    }

    #[test]
    fn test_decompress_real_data() {
        // flate2로 직접 압축한 데이터 검증
        use flate2::write::DeflateEncoder;
        use flate2::Compression;
        use std::io::Write;

        let original = b"Hello, HWP World! This is a test string for compression.";
        let mut encoder = DeflateEncoder::new(Vec::new(), Compression::default());
        encoder.write_all(original).unwrap();
        let compressed = encoder.finish().unwrap();

        let decompressed = decompress_stream(&compressed).unwrap();
        assert_eq!(decompressed, original);
    }

    #[test]
    fn test_limited_decompression_rejects_compact_oversized_output() {
        use flate2::write::DeflateEncoder;
        use flate2::Compression;
        use std::io::Write;

        let original = vec![b'A'; 4096];
        let mut encoder = DeflateEncoder::new(Vec::new(), Compression::best());
        encoder.write_all(&original).unwrap();
        let compressed = encoder.finish().unwrap();
        assert!(compressed.len() < 1024);

        assert!(matches!(
            decompress_stream_limited(&compressed, 1024),
            Err(CfbError::LimitExceeded(1024))
        ));
        assert_eq!(
            decompress_stream_limited(&compressed, original.len()).unwrap(),
            original
        );
    }

    #[test]
    fn open_decompression_stream_readers_enforce_limit() {
        use flate2::write::DeflateEncoder;
        use flate2::Compression;
        use std::io::Write;

        let plain = vec![b'A'; 4096];
        let mut encoder = DeflateEncoder::new(Vec::new(), Compression::best());
        encoder.write_all(&plain).unwrap();
        let compressed = encoder.finish().unwrap();
        let cfb = crate::serializer::mini_cfb::build_cfb(&[
            ("/DocInfo", compressed.as_slice()),
            ("/BodyText/Section0", compressed.as_slice()),
        ])
        .unwrap();

        let mut strict = CfbReader::open(&cfb).unwrap();
        assert_eq!(
            strict.read_body_text_section_raw(0).unwrap(),
            compressed,
            "암호 경로는 raw ciphertext를 먼저 가져와 복호화 결과에만 별도 상한을 적용한다"
        );
        assert!(matches!(
            strict.read_doc_info_limited(true, 1024),
            Err(CfbError::LimitExceeded(1024))
        ));
        assert!(matches!(
            strict.read_body_text_section_limited(0, true, 1024),
            Err(CfbError::LimitExceeded(1024))
        ));
        assert_eq!(
            strict.read_doc_info_limited(true, plain.len()).unwrap(),
            plain
        );
        assert!(matches!(
            strict.read_stream_raw_limited("/DocInfo", compressed.len() - 1),
            Err(CfbError::LimitExceeded(limit)) if limit == compressed.len() - 1
        ));

        let lenient = LenientCfbReader::open(&cfb).unwrap();
        assert!(matches!(
            lenient.read_doc_info_limited(true, 1024),
            Err(CfbError::LimitExceeded(1024))
        ));
        assert!(matches!(
            lenient.read_body_text_section_limited(0, true, 1024),
            Err(CfbError::LimitExceeded(1024))
        ));
        assert_eq!(
            lenient
                .read_body_text_section_limited(0, true, plain.len())
                .unwrap(),
            plain
        );
        assert!(matches!(
            lenient.read_stream_raw_limited("DocInfo", compressed.len() - 1),
            Err(CfbError::LimitExceeded(limit)) if limit == compressed.len() - 1
        ));
    }

    #[test]
    fn test_compare_cfb_streams_cli_vs_browser() {
        use std::collections::BTreeMap;

        let cli_path = "samples/20250130-hongbo_saved.hwp";
        let browser_path = "samples/honbo-save.hwp";

        let cli_data = std::fs::read(cli_path)
            .unwrap_or_else(|e| panic!("CLI 파일 읽기 실패: {} - {}", cli_path, e));
        let browser_data = std::fs::read(browser_path)
            .unwrap_or_else(|e| panic!("Browser 파일 읽기 실패: {} - {}", browser_path, e));

        println!("\n{}", "=".repeat(60));
        println!("  CFB Stream Structure Comparison");
        println!(
            "  CLI-saved (works):   {} ({} bytes)",
            cli_path,
            cli_data.len()
        );
        println!(
            "  Browser-saved (bad): {} ({} bytes)",
            browser_path,
            browser_data.len()
        );
        println!("{}\n", "=".repeat(60));

        let cli_cfb = CfbReader::open(&cli_data).expect("CLI CFB 열기 실패");
        let browser_cfb = CfbReader::open(&browser_data).expect("Browser CFB 열기 실패");

        // Collect all entries with sizes
        let cli_entries: BTreeMap<String, (u64, bool)> = cli_cfb
            .list_all_entries()
            .into_iter()
            .map(|(path, size, is_stream)| (path, (size, is_stream)))
            .collect();

        let browser_entries: BTreeMap<String, (u64, bool)> = browser_cfb
            .list_all_entries()
            .into_iter()
            .map(|(path, size, is_stream)| (path, (size, is_stream)))
            .collect();

        // Print CLI streams
        println!("--- CLI-saved streams (works in Hancom) ---");
        println!("{:<45} {:>10} {:>10}", "Path", "Size", "Type");
        println!("{:-<67}", "");
        for (path, (size, is_stream)) in &cli_entries {
            let type_str = if *is_stream { "stream" } else { "storage" };
            println!("{:<45} {:>10} {:>10}", path, size, type_str);
        }

        println!("\n--- Browser-saved streams (corrupted in Hancom) ---");
        println!("{:<45} {:>10} {:>10}", "Path", "Size", "Type");
        println!("{:-<67}", "");
        for (path, (size, is_stream)) in &browser_entries {
            let type_str = if *is_stream { "stream" } else { "storage" };
            println!("{:<45} {:>10} {:>10}", path, size, type_str);
        }

        // Compare: find differences
        println!("\n--- DIFFERENCES ---");
        println!();

        // Streams only in CLI
        let cli_only: Vec<_> = cli_entries
            .keys()
            .filter(|k| !browser_entries.contains_key(*k))
            .collect();
        if !cli_only.is_empty() {
            println!("Streams ONLY in CLI-saved (missing from browser-saved):");
            for path in &cli_only {
                let (size, _) = cli_entries[*path];
                println!("  [MISSING] {:<40} (size: {})", path, size);
            }
            println!();
        }

        // Streams only in Browser
        let browser_only: Vec<_> = browser_entries
            .keys()
            .filter(|k| !cli_entries.contains_key(*k))
            .collect();
        if !browser_only.is_empty() {
            println!("Streams ONLY in Browser-saved (extra, not in CLI-saved):");
            for path in &browser_only {
                let (size, _) = browser_entries[*path];
                println!("  [EXTRA]   {:<40} (size: {})", path, size);
            }
            println!();
        }

        // Streams with different sizes
        println!("Streams with SIZE differences:");
        let mut size_diffs = 0;
        for (path, (cli_size, cli_is_stream)) in &cli_entries {
            if let Some((browser_size, _)) = browser_entries.get(path) {
                if cli_size != browser_size && *cli_is_stream {
                    let diff = *browser_size as i64 - *cli_size as i64;
                    let sign = if diff > 0 { "+" } else { "" };
                    println!(
                        "  {:<40} CLI: {:>8}  Browser: {:>8}  ({}{})",
                        path, cli_size, browser_size, sign, diff
                    );
                    size_diffs += 1;
                }
            }
        }
        if size_diffs == 0 {
            println!("  (none)");
        }

        // Specifically analyze BinData streams
        println!("\n--- BinData Stream Analysis ---");
        println!();
        let cli_bins: Vec<_> = cli_entries
            .keys()
            .filter(|k| k.starts_with("/BinData/"))
            .collect();
        let browser_bins: Vec<_> = browser_entries
            .keys()
            .filter(|k| k.starts_with("/BinData/"))
            .collect();

        println!("CLI-saved BinData streams ({} total):", cli_bins.len());
        for path in &cli_bins {
            let (size, _) = cli_entries[*path];
            println!("  {:<45} size: {}", path, size);
        }

        println!(
            "\nBrowser-saved BinData streams ({} total):",
            browser_bins.len()
        );
        for path in &browser_bins {
            let (size, _) = browser_entries[*path];
            println!("  {:<45} size: {}", path, size);
        }

        // Check naming pattern
        println!("\nBinData naming pattern check:");
        for path in cli_bins.iter().chain(browser_bins.iter()) {
            if let Some(name) = path.strip_prefix("/BinData/") {
                if name.starts_with("BIN") {
                    // Extract the numeric part
                    let num_part: String = name
                        .chars()
                        .skip(3)
                        .take_while(|c| c.is_ascii_digit())
                        .collect();
                    let ext_part: String = name.chars().skip(3 + num_part.len()).collect();
                    let source =
                        if cli_entries.contains_key(*path) && browser_entries.contains_key(*path) {
                            "BOTH"
                        } else if cli_entries.contains_key(*path) {
                            "CLI-ONLY"
                        } else {
                            "BROWSER-ONLY"
                        };
                    println!(
                        "  {} => prefix=BIN, num='{}' (digits={}), ext='{}' [{}]",
                        name,
                        num_part,
                        num_part.len(),
                        ext_part,
                        source
                    );
                }
            }
        }

        // Summary
        println!("\n--- SUMMARY ---");
        println!(
            "CLI-saved:     {} total entries ({} streams)",
            cli_entries.len(),
            cli_entries.values().filter(|(_, is)| *is).count()
        );
        println!(
            "Browser-saved: {} total entries ({} streams)",
            browser_entries.len(),
            browser_entries.values().filter(|(_, is)| *is).count()
        );
        println!("Only in CLI:     {}", cli_only.len());
        println!("Only in Browser: {}", browser_only.len());
        println!("Size differences: {}", size_diffs);

        // Helper functions for record parsing
        fn parse_records(data: &[u8]) -> Vec<(u32, u32, u32, usize)> {
            // Returns: (tag_id, level, size, offset)
            let mut records = Vec::new();
            let mut pos = 0;
            while pos + 4 <= data.len() {
                let header =
                    u32::from_le_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]);
                let tag_id = header & 0x3FF;
                let level = (header >> 10) & 0x3FF;
                let size_field = (header >> 20) & 0xFFF;
                let mut size = size_field as u32;
                let mut data_offset = pos + 4;
                if size_field == 0xFFF {
                    if pos + 8 > data.len() {
                        break;
                    }
                    size = u32::from_le_bytes([
                        data[pos + 4],
                        data[pos + 5],
                        data[pos + 6],
                        data[pos + 7],
                    ]);
                    data_offset = pos + 8;
                }
                records.push((tag_id, level, size, pos));
                pos = data_offset + size as usize;
            }
            records
        }

        fn tag_name(tag_id: u32) -> &'static str {
            match tag_id {
                66 => "PARA_HEADER",
                67 => "PARA_TEXT",
                68 => "PARA_CHAR_SHAPE",
                69 => "PARA_LINE_SEG",
                70 => "PARA_RANGE_TAG",
                71 => "CTRL_HEADER",
                72 => "LIST_HEADER",
                73 => "PAGE_DEF",
                74 => "FOOTNOTE_SHAPE",
                75 => "PAGE_BORDER_FILL",
                76 => "SHAPE_COMPONENT",
                77 => "TABLE",
                78 => "SHAPE_LINE",
                79 => "SHAPE_RECT",
                80 => "SHAPE_ELLIPSE",
                81 => "SHAPE_ARC",
                82 => "SHAPE_POLYGON",
                83 => "SHAPE_CURVE",
                84 => "SHAPE_OLE",
                85 => "SHAPE_PICTURE",
                86 => "SHAPE_CONTAINER",
                87 => "CTRL_DATA",
                88 => "EQEDIT",
                99 => "SHAPE_TEXTART",
                102 => "FORM_OBJECT",
                103 => "MEMO_SHAPE",
                104 => "MEMO_LIST",
                _ => "UNKNOWN",
            }
        }

        // Compare BodyText/Section0 records
        println!("\n--- BodyText/Section0 Record-level Comparison ---");

        let mut cli_cfb3 = CfbReader::open(&cli_data).unwrap();
        let mut browser_cfb3 = CfbReader::open(&browser_data).unwrap();
        let cli_section = cli_cfb3.read_body_text_section(0, true, false).unwrap();
        let browser_section = browser_cfb3.read_body_text_section(0, true, false).unwrap();

        println!(
            "CLI Section0 decompressed size:     {} bytes",
            cli_section.len()
        );
        println!(
            "Browser Section0 decompressed size: {} bytes",
            browser_section.len()
        );

        let cli_records = parse_records(&cli_section);
        let browser_records = parse_records(&browser_section);

        println!("\nCLI records: {} total", cli_records.len());
        println!("Browser records: {} total", browser_records.len());

        // Print all records side by side (only show differences and nearby context)
        let max_records = std::cmp::max(cli_records.len(), browser_records.len());
        println!(
            "\n{:<5} {:<30} {:>4} {:>6}  |  {:<30} {:>4} {:>6}  | Match",
            "#", "CLI Tag", "Lvl", "Size", "Browser Tag", "Lvl", "Size"
        );
        println!("{:-<120}", "");

        for i in 0..max_records {
            let cli_str = if i < cli_records.len() {
                let (tag, lvl, sz, _) = cli_records[i];
                format!(
                    "{:<30} {:>4} {:>6}",
                    format!("{} ({})", tag_name(tag), tag),
                    lvl,
                    sz
                )
            } else {
                format!("{:<30} {:>4} {:>6}", "---", "", "")
            };

            let browser_str = if i < browser_records.len() {
                let (tag, lvl, sz, _) = browser_records[i];
                format!(
                    "{:<30} {:>4} {:>6}",
                    format!("{} ({})", tag_name(tag), tag),
                    lvl,
                    sz
                )
            } else {
                format!("{:<30} {:>4} {:>6}", "---", "", "")
            };

            let match_str = if i < cli_records.len() && i < browser_records.len() {
                let (ct, cl, cs, co) = cli_records[i];
                let (bt, bl, bs, bo) = browser_records[i];
                if ct == bt && cl == bl && cs == bs {
                    let cli_data_start = if cs == 0xFFF { co + 8 } else { co + 4 };
                    let browser_data_start = if bs == 0xFFF { bo + 8 } else { bo + 4 };
                    let cli_slice = &cli_section[cli_data_start..cli_data_start + cs as usize];
                    let browser_slice =
                        &browser_section[browser_data_start..browser_data_start + bs as usize];
                    if cli_slice == browser_slice {
                        "OK"
                    } else {
                        "DATA DIFF"
                    }
                } else if ct == bt && cl == bl {
                    "SIZE DIFF"
                } else {
                    "MISMATCH"
                }
            } else {
                "MISSING"
            };

            // Only print non-OK records and some context
            if match_str != "OK" {
                println!("{:<5} {}  |  {}  | {}", i, cli_str, browser_str, match_str);
            }
        }

        // Hex dump of key differing records
        println!("\n--- Hex Dump of Key Differing Records ---");
        for idx in [19usize, 20, 21, 32, 33, 34, 225, 226, 227] {
            if idx >= cli_records.len() && idx >= browser_records.len() {
                continue;
            }
            println!("\n=== Record #{} ===", idx);
            if idx < cli_records.len() {
                let (tag, lvl, sz, off) = cli_records[idx];
                let data_start = if sz >= 0xFFF { off + 8 } else { off + 4 };
                let data_end = data_start + sz as usize;
                println!(
                    "CLI: tag={} ({}) level={} size={} offset={:#x}",
                    tag_name(tag),
                    tag,
                    lvl,
                    sz,
                    off
                );
                if data_end <= cli_section.len() {
                    let bytes = &cli_section[data_start..data_end];
                    let show_len = std::cmp::min(bytes.len(), 80);
                    print!("  hex: ");
                    for b in &bytes[..show_len] {
                        print!("{:02x} ", b);
                    }
                    if bytes.len() > show_len {
                        print!("...({} more bytes)", bytes.len() - show_len);
                    }
                    println!();
                }
            }
            if idx < browser_records.len() {
                let (tag, lvl, sz, off) = browser_records[idx];
                let data_start = if sz >= 0xFFF { off + 8 } else { off + 4 };
                let data_end = data_start + sz as usize;
                println!(
                    "Browser: tag={} ({}) level={} size={} offset={:#x}",
                    tag_name(tag),
                    tag,
                    lvl,
                    sz,
                    off
                );
                if data_end <= browser_section.len() {
                    let bytes = &browser_section[data_start..data_end];
                    let show_len = std::cmp::min(bytes.len(), 80);
                    print!("  hex: ");
                    for b in &bytes[..show_len] {
                        print!("{:02x} ", b);
                    }
                    if bytes.len() > show_len {
                        print!("...({} more bytes)", bytes.len() - show_len);
                    }
                    println!();
                }
            }
        }

        // Record count analysis
        println!("\n--- Record Count Analysis ---");
        println!("CLI:     {} records, {} CTRL_HEADER, {} SHAPE_COMPONENT, {} SHAPE_PICTURE, {} CTRL_DATA, {} LIST_HEADER",
            cli_records.len(),
            cli_records.iter().filter(|(t,_,_,_)| *t == 71).count(),
            cli_records.iter().filter(|(t,_,_,_)| *t == 76).count(),
            cli_records.iter().filter(|(t,_,_,_)| *t == 85).count(),
            cli_records.iter().filter(|(t,_,_,_)| *t == 87).count(),
            cli_records.iter().filter(|(t,_,_,_)| *t == 72).count());
        println!("Browser: {} records, {} CTRL_HEADER, {} SHAPE_COMPONENT, {} SHAPE_PICTURE, {} CTRL_DATA, {} LIST_HEADER",
            browser_records.len(),
            browser_records.iter().filter(|(t,_,_,_)| *t == 71).count(),
            browser_records.iter().filter(|(t,_,_,_)| *t == 76).count(),
            browser_records.iter().filter(|(t,_,_,_)| *t == 85).count(),
            browser_records.iter().filter(|(t,_,_,_)| *t == 87).count(),
            browser_records.iter().filter(|(t,_,_,_)| *t == 72).count());

        // CTRL_HEADER sizes
        println!("\n--- All CTRL_HEADER (71) sizes ---");
        let cli_ctrl: Vec<_> = cli_records
            .iter()
            .enumerate()
            .filter(|(_, (t, _, _, _))| *t == 71)
            .collect();
        let browser_ctrl: Vec<_> = browser_records
            .iter()
            .enumerate()
            .filter(|(_, (t, _, _, _))| *t == 71)
            .collect();
        println!(
            "CLI:     {:?}",
            cli_ctrl
                .iter()
                .map(|(i, (_, l, s, _))| format!("#{}: lvl={} sz={}", i, l, s))
                .collect::<Vec<_>>()
        );
        println!(
            "Browser: {:?}",
            browser_ctrl
                .iter()
                .map(|(i, (_, l, s, _))| format!("#{}: lvl={} sz={}", i, l, s))
                .collect::<Vec<_>>()
        );

        // SHAPE_COMPONENT sizes
        println!("\n--- All SHAPE_COMPONENT (76) sizes ---");
        let cli_shape: Vec<_> = cli_records
            .iter()
            .enumerate()
            .filter(|(_, (t, _, _, _))| *t == 76)
            .collect();
        let browser_shape: Vec<_> = browser_records
            .iter()
            .enumerate()
            .filter(|(_, (t, _, _, _))| *t == 76)
            .collect();
        println!(
            "CLI:     {:?}",
            cli_shape
                .iter()
                .map(|(i, (_, l, s, _))| format!("#{}: lvl={} sz={}", i, l, s))
                .collect::<Vec<_>>()
        );
        println!(
            "Browser: {:?}",
            browser_shape
                .iter()
                .map(|(i, (_, l, s, _))| format!("#{}: lvl={} sz={}", i, l, s))
                .collect::<Vec<_>>()
        );

        // Compare FileHeader bytes
        println!("\n--- FileHeader Comparison ---");
        let mut cli_cfb2 = CfbReader::open(&cli_data).unwrap();
        let mut browser_cfb2 = CfbReader::open(&browser_data).unwrap();

        let cli_header = cli_cfb2.read_file_header().unwrap();
        let browser_header = browser_cfb2.read_file_header().unwrap();

        println!("CLI FileHeader size: {} bytes", cli_header.len());
        println!("Browser FileHeader size: {} bytes", browser_header.len());

        if cli_header == browser_header {
            println!("FileHeaders are IDENTICAL.");
        } else {
            println!("FileHeaders DIFFER at these byte offsets:");
            let max_len = std::cmp::max(cli_header.len(), browser_header.len());
            let mut diff_count = 0;
            for i in 0..max_len {
                let cli_byte = cli_header.get(i).copied();
                let browser_byte = browser_header.get(i).copied();
                if cli_byte != browser_byte {
                    println!(
                        "  offset {:#06x}: CLI={:?} Browser={:?}",
                        i,
                        cli_byte.map(|b| format!("{:#04x}", b)),
                        browser_byte.map(|b| format!("{:#04x}", b))
                    );
                    diff_count += 1;
                    if diff_count > 20 {
                        println!("  ... (truncated, more differences exist)");
                        break;
                    }
                }
            }
        }
    }
}