micropdf 0.17.0

A pure Rust PDF library - A pure Rust PDF library with fz_/pdf_ API compatibility
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
//! C FFI for buffer - MicroPDF compatible
//! Safe Rust implementation using handle-based resource management
//!
//! This module includes a buffer pool for efficient memory reuse in hot paths.

use super::{BUFFERS, Handle};
use std::collections::{HashMap, VecDeque};
use std::ffi::{c_char, c_int, c_void};
use std::sync::{LazyLock, Mutex};

// ============================================================================
// Buffer Pool for Memory Reuse
// ============================================================================

/// Common buffer sizes for pooling (in bytes)
const POOL_SIZES: &[usize] = &[
    64,    // Tiny: small strings, names
    256,   // Small: typical text runs
    1024,  // 1KB: page content fragments
    4096,  // 4KB: typical page size
    16384, // 16KB: larger content
    65536, // 64KB: images, streams
];

/// Maximum buffers to keep per size class
const MAX_POOL_SIZE: usize = 32;

/// A pool of pre-allocated buffers for reuse
struct BufferPool {
    /// Pools indexed by size class
    pools: Vec<Mutex<VecDeque<Vec<u8>>>>,
    /// Statistics
    stats: Mutex<PoolStats>,
}

/// Pool statistics for debugging and optimization
#[derive(Debug, Clone, Default)]
pub struct PoolStats {
    /// Number of buffers acquired from pool
    pub hits: u64,
    /// Number of new allocations (pool miss)
    pub misses: u64,
    /// Number of buffers returned to pool
    pub returns: u64,
    /// Number of buffers dropped (pool full)
    pub drops: u64,
    /// Total bytes allocated (cumulative)
    pub total_bytes_allocated: u64,
    /// Total bytes deallocated (cumulative)
    pub total_bytes_deallocated: u64,
    /// Current bytes in use
    pub current_bytes: u64,
    /// Peak bytes in use
    pub peak_bytes: u64,
    /// Total allocations count
    pub total_allocations: u64,
    /// Total deallocations count
    pub total_deallocations: u64,
}

impl BufferPool {
    fn new() -> Self {
        let pools = POOL_SIZES
            .iter()
            .map(|_| Mutex::new(VecDeque::new()))
            .collect();
        Self {
            pools,
            stats: Mutex::new(PoolStats::default()),
        }
    }

    /// Find the size class for a given capacity
    fn size_class(capacity: usize) -> Option<usize> {
        POOL_SIZES.iter().position(|&size| size >= capacity)
    }

    /// Acquire a buffer from the pool or allocate new
    fn acquire(&self, capacity: usize) -> Vec<u8> {
        if let Some(class) = Self::size_class(capacity) {
            if let Ok(mut pool) = self.pools[class].lock() {
                if let Some(mut buf) = pool.pop_front() {
                    let buf_capacity = buf.capacity() as u64;
                    buf.clear();
                    if let Ok(mut stats) = self.stats.lock() {
                        stats.hits += 1;
                        stats.total_allocations += 1;
                        stats.current_bytes += buf_capacity;
                        if stats.current_bytes > stats.peak_bytes {
                            stats.peak_bytes = stats.current_bytes;
                        }
                    }
                    return buf;
                }
            }
        }

        // Pool miss - allocate new
        // Use pool size if it fits, otherwise exact capacity
        let alloc_size = Self::size_class(capacity)
            .map(|class| POOL_SIZES[class])
            .unwrap_or(capacity);

        if let Ok(mut stats) = self.stats.lock() {
            stats.misses += 1;
            stats.total_allocations += 1;
            stats.total_bytes_allocated += alloc_size as u64;
            stats.current_bytes += alloc_size as u64;
            if stats.current_bytes > stats.peak_bytes {
                stats.peak_bytes = stats.current_bytes;
            }
        }

        Vec::with_capacity(alloc_size)
    }

    /// Return a buffer to the pool for reuse
    fn release(&self, mut buf: Vec<u8>) {
        let capacity = buf.capacity() as u64;

        // Update deallocation stats
        if let Ok(mut stats) = self.stats.lock() {
            stats.total_deallocations += 1;
            stats.current_bytes = stats.current_bytes.saturating_sub(capacity);
        }

        if let Some(class) = Self::size_class(capacity as usize) {
            // Only pool if capacity matches a pool size exactly
            if buf.capacity() == POOL_SIZES[class] {
                if let Ok(mut pool) = self.pools[class].lock() {
                    if pool.len() < MAX_POOL_SIZE {
                        buf.clear();
                        pool.push_back(buf);
                        if let Ok(mut stats) = self.stats.lock() {
                            stats.returns += 1;
                        }
                        return;
                    }
                }
            }
        }

        // Pool full or size doesn't match - drop buffer
        if let Ok(mut stats) = self.stats.lock() {
            stats.drops += 1;
            stats.total_bytes_deallocated += capacity;
        }
        drop(buf);
    }

    /// Get pool statistics
    fn get_stats(&self) -> PoolStats {
        self.stats.lock().map(|s| s.clone()).unwrap_or_default()
    }

    /// Clear all pools
    fn clear(&self) {
        for pool in &self.pools {
            if let Ok(mut p) = pool.lock() {
                p.clear();
            }
        }
    }

    /// Get total buffers in pool
    fn pool_count(&self) -> usize {
        self.pools
            .iter()
            .filter_map(|p| p.lock().ok())
            .map(|p| p.len())
            .sum()
    }
}

/// Global buffer pool instance
static BUFFER_POOL: LazyLock<BufferPool> = LazyLock::new(BufferPool::new);

/// Internal buffer state
pub struct Buffer {
    data: Vec<u8>,
    /// Whether this buffer came from the pool
    pooled: bool,
}

impl Buffer {
    /// Create a new buffer with given capacity (uses pool if available)
    pub fn new(capacity: usize) -> Self {
        let data = BUFFER_POOL.acquire(capacity);
        Self { data, pooled: true }
    }

    /// Create a new buffer without using pool
    pub fn new_unpooled(capacity: usize) -> Self {
        Self {
            data: Vec::with_capacity(capacity),
            pooled: false,
        }
    }

    /// Create a buffer from data (copies data, uses pool for allocation)
    pub fn from_data(data: &[u8]) -> Self {
        let mut buf = BUFFER_POOL.acquire(data.len());
        buf.extend_from_slice(data);
        Self {
            data: buf,
            pooled: true,
        }
    }

    /// Create a buffer from data without using pool
    pub fn from_data_unpooled(data: &[u8]) -> Self {
        Self {
            data: data.to_vec(),
            pooled: false,
        }
    }

    /// Take ownership of existing Vec (does not use pool)
    pub fn from_vec(data: Vec<u8>) -> Self {
        Self {
            data,
            pooled: false,
        }
    }

    pub fn len(&self) -> usize {
        self.data.len()
    }

    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    pub fn data(&self) -> &[u8] {
        &self.data
    }

    /// Alias for data() - get immutable slice of buffer
    pub fn as_slice(&self) -> &[u8] {
        &self.data
    }

    pub fn data_mut(&mut self) -> &mut Vec<u8> {
        &mut self.data
    }

    pub fn append(&mut self, data: &[u8]) {
        self.data.extend_from_slice(data);
    }

    pub fn append_byte(&mut self, byte: u8) {
        self.data.push(byte);
    }

    pub fn clear(&mut self) {
        self.data.clear();
    }

    pub fn resize(&mut self, new_size: usize) {
        self.data.resize(new_size, 0);
    }

    pub fn ensure_null_terminated(&mut self) {
        if self.data.is_empty() || self.data.last() != Some(&0) {
            self.data.push(0);
        }
    }

    /// Check if buffer is from pool
    pub fn is_pooled(&self) -> bool {
        self.pooled
    }

    /// Get buffer capacity
    pub fn capacity(&self) -> usize {
        self.data.capacity()
    }

    /// Reserve additional capacity (may reallocate)
    pub fn reserve(&mut self, additional: usize) {
        self.data.reserve(additional);
    }

    /// Reserve exact capacity (may reallocate)
    pub fn reserve_exact(&mut self, additional: usize) {
        self.data.reserve_exact(additional);
    }

    /// Shrink buffer to fit current data
    pub fn shrink_to_fit(&mut self) {
        self.data.shrink_to_fit();
        self.pooled = false; // No longer poolable after shrink
    }

    /// Take the inner Vec, replacing with empty (for transfer)
    pub fn take(&mut self) -> Vec<u8> {
        self.pooled = false;
        std::mem::take(&mut self.data)
    }
}

impl Drop for Buffer {
    fn drop(&mut self) {
        if self.pooled {
            // Return buffer to pool
            let data = std::mem::take(&mut self.data);
            BUFFER_POOL.release(data);
        }
        // Non-pooled buffers drop normally
    }
}

/// Create a new buffer with given capacity
#[unsafe(no_mangle)]
pub extern "C" fn fz_new_buffer(_ctx: Handle, capacity: usize) -> Handle {
    BUFFERS.insert(Buffer::new(capacity))
}

/// Create a buffer from copied data
///
/// # Safety
/// Caller must ensure `data` points to valid memory of at least `size` bytes.
#[unsafe(no_mangle)]
pub extern "C" fn fz_new_buffer_from_copied_data(
    _ctx: Handle,
    data: *const u8,
    size: usize,
) -> Handle {
    if data.is_null() || size == 0 {
        return BUFFERS.insert(Buffer::new(0));
    }

    // SAFETY: Caller guarantees data points to valid memory of `size` bytes
    let data_slice = unsafe { std::slice::from_raw_parts(data, size) };

    BUFFERS.insert(Buffer::from_data(data_slice))
}

/// Keep (increment ref) a buffer - returns same handle
#[unsafe(no_mangle)]
pub extern "C" fn fz_keep_buffer(_ctx: Handle, buf: Handle) -> Handle {
    BUFFERS.keep(buf)
}

/// Drop a buffer reference
#[unsafe(no_mangle)]
pub extern "C" fn fz_drop_buffer(_ctx: Handle, buf: Handle) {
    let _ = BUFFERS.remove(buf);
}

/// Get buffer storage - returns length, optionally fills data pointer
///
/// Note: This function cannot safely return a pointer to internal data
/// because the buffer may be moved or reallocated. For safe access,
/// use fz_buffer_len and copy the data.
#[unsafe(no_mangle)]
pub extern "C" fn fz_buffer_storage(_ctx: Handle, buf: Handle, datap: *mut *mut u8) -> usize {
    let Some(buffer) = BUFFERS.get(buf) else {
        if !datap.is_null() {
            // SAFETY: Caller guarantees datap is valid if non-null
            unsafe {
                *datap = std::ptr::null_mut();
            }
        }
        return 0;
    };

    let guard = buffer.lock().unwrap();
    let len = guard.len();

    if !datap.is_null() {
        // We can't safely return a pointer to internal data
        // because the buffer may be reallocated
        unsafe {
            *datap = std::ptr::null_mut();
        }
    }

    len
}

/// Get pointer to buffer data (Alternative API compatible with MicroPDF)
///
/// Returns a pointer to the buffer's internal data and optionally sets
/// the length pointer if provided. This is compatible with MicroPDF's fz_buffer_data.
///
/// # Safety
/// The returned pointer is only valid until the next operation that might
/// modify the buffer. The caller must copy the data if it needs to be retained.
///
/// # Warning
/// This function returns a direct pointer to internal buffer data. The pointer
/// may be invalidated if the buffer is modified or reallocated.
#[unsafe(no_mangle)]
pub extern "C" fn fz_buffer_data(_ctx: Handle, buf: Handle, len: *mut usize) -> *const u8 {
    let Some(buffer) = BUFFERS.get(buf) else {
        if !len.is_null() {
            unsafe {
                *len = 0;
            }
        }
        return std::ptr::null();
    };

    let guard = buffer.lock().unwrap();
    let data_len = guard.len();

    if !len.is_null() {
        unsafe {
            *len = data_len;
        }
    }

    // Return pointer to internal data
    // SAFETY: The pointer is valid as long as the buffer is not modified
    // and the guard is held. The caller must not hold this pointer
    // after any operation that might modify the buffer.
    guard.data.as_ptr()
}

/// Get buffer contents as a null-terminated C string
///
/// Returns a newly allocated C string containing the buffer's data.
/// The caller is responsible for freeing the returned pointer with
/// `fz_free` or letting it leak (as MuPDF convention).
/// Returns a pointer to a static empty string if the buffer is empty
/// or the data contains interior null bytes.
#[unsafe(no_mangle)]
pub extern "C" fn fz_string_from_buffer(_ctx: Handle, buf: Handle) -> *const c_char {
    if let Some(buffer) = BUFFERS.get(buf) {
        if let Ok(guard) = buffer.lock() {
            let data = guard.data();
            if !data.is_empty() {
                // Build a CString from the buffer data; if the data
                // contains interior nulls, CString::new will fail and
                // we fall through to the empty-string return.
                if let Ok(cstr) = std::ffi::CString::new(data.to_vec()) {
                    return cstr.into_raw() as *const c_char;
                }
            }
        }
    }
    c"".as_ptr()
}

/// Resize buffer to new capacity
#[unsafe(no_mangle)]
pub extern "C" fn fz_resize_buffer(_ctx: Handle, buf: Handle, capacity: usize) {
    if let Some(buffer) = BUFFERS.get(buf) {
        if let Ok(mut guard) = buffer.lock() {
            guard.resize(capacity);
        }
    }
}

/// Grow buffer (double capacity or minimum 256)
#[unsafe(no_mangle)]
pub extern "C" fn fz_grow_buffer(_ctx: Handle, buf: Handle) {
    if let Some(buffer) = BUFFERS.get(buf) {
        if let Ok(mut guard) = buffer.lock() {
            let current_cap = guard.data.capacity();
            let new_cap = (current_cap * 2).max(256);
            guard.data.reserve(new_cap.saturating_sub(current_cap));
        }
    }
}

/// Trim buffer to fit contents
#[unsafe(no_mangle)]
pub extern "C" fn fz_trim_buffer(_ctx: Handle, buf: Handle) {
    if let Some(buffer) = BUFFERS.get(buf) {
        if let Ok(mut guard) = buffer.lock() {
            guard.data.shrink_to_fit();
        }
    }
}

/// Clear buffer contents
#[unsafe(no_mangle)]
pub extern "C" fn fz_clear_buffer(_ctx: Handle, buf: Handle) {
    if let Some(buffer) = BUFFERS.get(buf) {
        if let Ok(mut guard) = buffer.lock() {
            guard.clear();
        }
    }
}

/// Append data to buffer
///
/// # Safety
/// Caller must ensure `data` points to valid memory of at least `len` bytes.
#[unsafe(no_mangle)]
pub extern "C" fn fz_append_data(_ctx: Handle, buf: Handle, data: *const c_void, len: usize) {
    if data.is_null() || len == 0 {
        return;
    }

    if let Some(buffer) = BUFFERS.get(buf) {
        if let Ok(mut guard) = buffer.lock() {
            // SAFETY: Caller guarantees data points to valid memory of `len` bytes
            let slice = unsafe { std::slice::from_raw_parts(data as *const u8, len) };
            guard.append(slice);
        }
    }
}

/// Append C string to buffer
///
/// # Safety
/// Caller must ensure `data` is a valid null-terminated C string.
#[unsafe(no_mangle)]
pub extern "C" fn fz_append_string(_ctx: Handle, buf: Handle, data: *const c_char) {
    if data.is_null() {
        return;
    }

    if let Some(buffer) = BUFFERS.get(buf) {
        if let Ok(mut guard) = buffer.lock() {
            // SAFETY: Caller guarantees data is a valid null-terminated C string
            let c_str = unsafe { std::ffi::CStr::from_ptr(data) };
            guard.append(c_str.to_bytes());
        }
    }
}

/// Append single byte to buffer
#[unsafe(no_mangle)]
pub extern "C" fn fz_append_byte(_ctx: Handle, buf: Handle, c: c_int) {
    if let Some(buffer) = BUFFERS.get(buf) {
        if let Ok(mut guard) = buffer.lock() {
            guard.append_byte(c as u8);
        }
    }
}

/// Null-terminate buffer
#[unsafe(no_mangle)]
pub extern "C" fn fz_terminate_buffer(_ctx: Handle, buf: Handle) {
    if let Some(buffer) = BUFFERS.get(buf) {
        if let Ok(mut guard) = buffer.lock() {
            guard.ensure_null_terminated();
        }
    }
}

/// Compute MD5 digest of buffer contents
///
/// # Safety
/// Caller must ensure `digest` points to valid writable memory of 16 bytes.
#[unsafe(no_mangle)]
pub extern "C" fn fz_md5_buffer(_ctx: Handle, buf: Handle, digest: *mut [u8; 16]) {
    if digest.is_null() {
        return;
    }

    if let Some(buffer) = BUFFERS.get(buf) {
        if let Ok(guard) = buffer.lock() {
            use md5::{Digest, Md5};
            let mut hasher = Md5::new();
            hasher.update(guard.data());
            let result = hasher.finalize();

            // SAFETY: Caller guarantees digest points to valid writable [u8; 16]
            unsafe {
                (*digest).copy_from_slice(&result);
            }
        }
    }
}

/// Clone a buffer
#[unsafe(no_mangle)]
pub extern "C" fn fz_clone_buffer(_ctx: Handle, buf: Handle) -> Handle {
    if let Some(buffer) = BUFFERS.get(buf) {
        if let Ok(guard) = buffer.lock() {
            return BUFFERS.insert(Buffer::from_data(guard.data()));
        }
    }
    0
}

/// Get buffer length
#[unsafe(no_mangle)]
pub extern "C" fn fz_buffer_len(_ctx: Handle, buf: Handle) -> usize {
    if let Some(buffer) = BUFFERS.get(buf) {
        if let Ok(guard) = buffer.lock() {
            return guard.len();
        }
    }
    0
}

// ============================================================================
// Integer Append Functions
// ============================================================================

/// Append 16-bit integer in little-endian format
#[unsafe(no_mangle)]
pub extern "C" fn fz_append_int16_le(_ctx: Handle, buf: Handle, x: i16) {
    if let Some(buffer) = BUFFERS.get(buf) {
        if let Ok(mut guard) = buffer.lock() {
            guard.append(&x.to_le_bytes());
        }
    }
}

/// Append 32-bit integer in little-endian format
#[unsafe(no_mangle)]
pub extern "C" fn fz_append_int32_le(_ctx: Handle, buf: Handle, x: i32) {
    if let Some(buffer) = BUFFERS.get(buf) {
        if let Ok(mut guard) = buffer.lock() {
            guard.append(&x.to_le_bytes());
        }
    }
}

/// Append 16-bit integer in big-endian format
#[unsafe(no_mangle)]
pub extern "C" fn fz_append_int16_be(_ctx: Handle, buf: Handle, x: i16) {
    if let Some(buffer) = BUFFERS.get(buf) {
        if let Ok(mut guard) = buffer.lock() {
            guard.append(&x.to_be_bytes());
        }
    }
}

/// Append 32-bit integer in big-endian format
#[unsafe(no_mangle)]
pub extern "C" fn fz_append_int32_be(_ctx: Handle, buf: Handle, x: i32) {
    if let Some(buffer) = BUFFERS.get(buf) {
        if let Ok(mut guard) = buffer.lock() {
            guard.append(&x.to_be_bytes());
        }
    }
}

// ============================================================================
// Bit Append Functions
// ============================================================================

/// Internal state for bit accumulation
pub struct BitBuffer {
    accumulator: u32,
    bits_in_accumulator: u8,
}

impl BitBuffer {
    pub fn new() -> Self {
        Self {
            accumulator: 0,
            bits_in_accumulator: 0,
        }
    }
}

impl Default for BitBuffer {
    fn default() -> Self {
        Self::new()
    }
}

/// Global bit buffer state for each buffer handle
static BIT_BUFFERS: LazyLock<Mutex<HashMap<Handle, BitBuffer>>> =
    LazyLock::new(|| Mutex::new(HashMap::new()));

/// Append bits to buffer
#[unsafe(no_mangle)]
pub extern "C" fn fz_append_bits(_ctx: Handle, buf: Handle, value: i32, count: i32) {
    if count <= 0 || count > 32 {
        return;
    }

    if let Some(buffer) = BUFFERS.get(buf) {
        if let Ok(mut guard) = buffer.lock() {
            if let Ok(mut bit_map) = BIT_BUFFERS.lock() {
                let bit_buf = bit_map.entry(buf).or_insert_with(BitBuffer::new);

                // Mask to get only the requested bits
                let mask = if count == 32 {
                    u32::MAX
                } else {
                    (1u32 << count) - 1
                };
                let bits = (value as u32) & mask;

                // Add bits to accumulator
                bit_buf.accumulator = (bit_buf.accumulator << count) | bits;
                bit_buf.bits_in_accumulator += count as u8;

                // Flush complete bytes
                while bit_buf.bits_in_accumulator >= 8 {
                    bit_buf.bits_in_accumulator -= 8;
                    let byte = (bit_buf.accumulator >> bit_buf.bits_in_accumulator) as u8;
                    guard.append_byte(byte);
                }
            }
        }
    }
}

/// Append bits and pad to byte boundary
#[unsafe(no_mangle)]
pub extern "C" fn fz_append_bits_pad(_ctx: Handle, buf: Handle) {
    if let Some(buffer) = BUFFERS.get(buf) {
        if let Ok(mut guard) = buffer.lock() {
            if let Ok(mut bit_map) = BIT_BUFFERS.lock() {
                if let Some(bit_buf) = bit_map.get_mut(&buf) {
                    // Flush remaining bits with zero padding
                    if bit_buf.bits_in_accumulator > 0 {
                        let pad_bits = 8 - bit_buf.bits_in_accumulator;
                        let byte = (bit_buf.accumulator << pad_bits) as u8;
                        guard.append_byte(byte);
                        bit_buf.accumulator = 0;
                        bit_buf.bits_in_accumulator = 0;
                    }
                }
            }
        }
    }
}

// ============================================================================
// PDF String Functions
// ============================================================================

/// Append a PDF-escaped string (with parentheses)
///
/// # Safety
/// Caller must ensure `str` is a valid null-terminated C string.
#[unsafe(no_mangle)]
pub extern "C" fn fz_append_pdf_string(_ctx: Handle, buf: Handle, str: *const c_char) {
    if str.is_null() {
        // Append empty string "()"
        if let Some(buffer) = BUFFERS.get(buf) {
            if let Ok(mut guard) = buffer.lock() {
                guard.append(b"()");
            }
        }
        return;
    }

    // SAFETY: Caller guarantees str is a valid null-terminated C string
    let c_str = unsafe { std::ffi::CStr::from_ptr(str) };
    let bytes = c_str.to_bytes();

    if let Some(buffer) = BUFFERS.get(buf) {
        if let Ok(mut guard) = buffer.lock() {
            guard.append_byte(b'(');

            for &byte in bytes {
                match byte {
                    b'(' | b')' | b'\\' => {
                        guard.append_byte(b'\\');
                        guard.append_byte(byte);
                    }
                    b'\n' => {
                        guard.append_byte(b'\\');
                        guard.append_byte(b'n');
                    }
                    b'\r' => {
                        guard.append_byte(b'\\');
                        guard.append_byte(b'r');
                    }
                    b'\t' => {
                        guard.append_byte(b'\\');
                        guard.append_byte(b't');
                    }
                    _ => guard.append_byte(byte),
                }
            }

            guard.append_byte(b')');
        }
    }
}

/// Append another buffer's contents
#[unsafe(no_mangle)]
pub extern "C" fn fz_append_buffer(_ctx: Handle, buf: Handle, src: Handle) {
    // Get source data first
    let src_data = if let Some(src_buffer) = BUFFERS.get(src) {
        if let Ok(guard) = src_buffer.lock() {
            Some(guard.data().to_vec())
        } else {
            None
        }
    } else {
        None
    };

    // Then append to destination
    if let Some(data) = src_data {
        if let Some(buffer) = BUFFERS.get(buf) {
            if let Ok(mut guard) = buffer.lock() {
                guard.append(&data);
            }
        }
    }
}

/// Create a buffer from data with transfer of ownership
///
/// # Safety
/// Caller must ensure `data` points to valid memory of at least `size` bytes.
/// The data will be copied into the buffer (no actual ownership transfer).
#[unsafe(no_mangle)]
pub extern "C" fn fz_new_buffer_from_data(_ctx: Handle, data: *mut u8, size: usize) -> Handle {
    if data.is_null() || size == 0 {
        return BUFFERS.insert(Buffer::new(0));
    }

    // SAFETY: Caller guarantees data points to valid memory of `size` bytes
    let data_slice = unsafe { std::slice::from_raw_parts(data, size) };

    // Copy the data to maintain safety (no actual ownership transfer in Rust FFI)
    BUFFERS.insert(Buffer::from_data(data_slice))
}

/// Create a slice/view of a buffer
///
/// # Safety
/// Caller must ensure buffer handle is valid.
#[unsafe(no_mangle)]
pub extern "C" fn fz_slice_buffer(_ctx: Handle, buf: Handle, offset: usize, len: usize) -> Handle {
    if let Some(buffer) = BUFFERS.get(buf) {
        if let Ok(guard) = buffer.lock() {
            let data = guard.data();
            if offset < data.len() {
                let end = (offset + len).min(data.len());
                let slice = &data[offset..end];
                return BUFFERS.insert(Buffer::from_data(slice));
            }
        }
    }
    0
}

/// Append a Unicode rune (codepoint) to buffer as UTF-8
#[unsafe(no_mangle)]
pub extern "C" fn fz_append_rune(_ctx: Handle, buf: Handle, rune: i32) {
    if let Some(buffer) = BUFFERS.get(buf) {
        if let Ok(mut guard) = buffer.lock() {
            // Convert Unicode codepoint to char and encode as UTF-8
            if let Some(ch) = char::from_u32(rune as u32) {
                let mut utf8_buf = [0u8; 4];
                let utf8_str = ch.encode_utf8(&mut utf8_buf);
                guard.append(utf8_str.as_bytes());
            }
        }
    }
}

/// Append base64 encoded data to buffer
///
/// # Safety
/// Caller must ensure `data` points to valid memory of at least `size` bytes.
#[unsafe(no_mangle)]
pub extern "C" fn fz_append_base64(
    _ctx: Handle,
    buf: Handle,
    data: *const u8,
    size: usize,
    newline: i32,
) {
    if data.is_null() || size == 0 {
        return;
    }

    if let Some(buffer) = BUFFERS.get(buf) {
        if let Ok(mut guard) = buffer.lock() {
            // SAFETY: Caller guarantees data points to valid memory
            let data_slice = unsafe { std::slice::from_raw_parts(data, size) };

            // Simple base64 encoding
            const BASE64_CHARS: &[u8] =
                b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

            let mut line_len = 0;
            let mut i = 0;

            while i + 2 < size {
                let b1 = data_slice[i];
                let b2 = data_slice[i + 1];
                let b3 = data_slice[i + 2];

                guard.append_byte(BASE64_CHARS[((b1 >> 2) & 0x3F) as usize]);
                guard.append_byte(BASE64_CHARS[(((b1 & 0x03) << 4) | ((b2 >> 4) & 0x0F)) as usize]);
                guard.append_byte(BASE64_CHARS[(((b2 & 0x0F) << 2) | ((b3 >> 6) & 0x03)) as usize]);
                guard.append_byte(BASE64_CHARS[(b3 & 0x3F) as usize]);

                line_len += 4;
                if newline != 0 && line_len >= 76 {
                    guard.append_byte(b'\n');
                    line_len = 0;
                }

                i += 3;
            }

            // Handle remaining bytes
            if i < size {
                let b1 = data_slice[i];
                guard.append_byte(BASE64_CHARS[((b1 >> 2) & 0x3F) as usize]);

                if i + 1 < size {
                    let b2 = data_slice[i + 1];
                    guard.append_byte(
                        BASE64_CHARS[(((b1 & 0x03) << 4) | ((b2 >> 4) & 0x0F)) as usize],
                    );
                    guard.append_byte(BASE64_CHARS[((b2 & 0x0F) << 2) as usize]);
                    guard.append_byte(b'=');
                } else {
                    guard.append_byte(BASE64_CHARS[((b1 & 0x03) << 4) as usize]);
                    guard.append_byte(b'=');
                    guard.append_byte(b'=');
                }
            }
        }
    }
}

/// Append an integer formatted as string
#[unsafe(no_mangle)]
pub extern "C" fn fz_append_int(_ctx: Handle, buf: Handle, value: i64) {
    if let Some(buffer) = BUFFERS.get(buf) {
        if let Ok(mut guard) = buffer.lock() {
            let s = format!("{}", value);
            guard.append(s.as_bytes());
        }
    }
}

/// Append float formatted as string
#[unsafe(no_mangle)]
pub extern "C" fn fz_append_float(_ctx: Handle, buf: Handle, value: f32, digits: i32) {
    if let Some(buffer) = BUFFERS.get(buf) {
        if let Ok(mut guard) = buffer.lock() {
            let s = if digits > 0 {
                format!("{:.prec$}", value, prec = digits as usize)
            } else {
                format!("{}", value)
            };
            guard.append(s.as_bytes());
        }
    }
}

/// Append hexadecimal encoded data
///
/// # Safety
/// Caller must ensure `data` points to valid memory of at least `size` bytes.
#[unsafe(no_mangle)]
pub extern "C" fn fz_append_hex(_ctx: Handle, buf: Handle, data: *const u8, size: usize) {
    if data.is_null() || size == 0 {
        return;
    }

    if let Some(buffer) = BUFFERS.get(buf) {
        if let Ok(mut guard) = buffer.lock() {
            // SAFETY: Caller guarantees data points to valid memory of size bytes
            let data_slice = unsafe { std::slice::from_raw_parts(data, size) };

            const HEX_CHARS: &[u8] = b"0123456789abcdef";
            for &byte in data_slice {
                guard.append_byte(HEX_CHARS[(byte >> 4) as usize]);
                guard.append_byte(HEX_CHARS[(byte & 0x0F) as usize]);
            }
        }
    }
}

/// Compare two buffers for equality
#[unsafe(no_mangle)]
pub extern "C" fn fz_buffer_eq(_ctx: Handle, buf1: Handle, buf2: Handle) -> i32 {
    if buf1 == buf2 {
        return 1;
    }

    let data1 = if let Some(b) = BUFFERS.get(buf1) {
        if let Ok(guard) = b.lock() {
            Some(guard.data().to_vec())
        } else {
            None
        }
    } else {
        None
    };

    let data2 = if let Some(b) = BUFFERS.get(buf2) {
        if let Ok(guard) = b.lock() {
            Some(guard.data().to_vec())
        } else {
            None
        }
    } else {
        None
    };

    match (data1, data2) {
        (Some(d1), Some(d2)) => {
            if d1 == d2 {
                1
            } else {
                0
            }
        }
        _ => 0,
    }
}

/// Get buffer storage capacity
#[unsafe(no_mangle)]
pub extern "C" fn fz_buffer_capacity(_ctx: Handle, buf: Handle) -> usize {
    if let Some(buffer) = BUFFERS.get(buf) {
        if let Ok(mut guard) = buffer.lock() {
            return guard.data_mut().capacity();
        }
    }
    0
}

/// Extract data from buffer as new buffer (move semantics)
#[unsafe(no_mangle)]
pub extern "C" fn fz_buffer_extract(_ctx: Handle, buf: Handle) -> Handle {
    if let Some(buffer) = BUFFERS.get(buf) {
        if let Ok(mut guard) = buffer.lock() {
            let data = guard.data().to_vec();
            guard.clear();
            return BUFFERS.insert(Buffer::from_data(&data));
        }
    }
    0
}

// Note: fz_append_printf is not implemented due to variadic function complexity
// in Rust FFI. Users should format strings in their own code and use fz_append_string.
//
// Note: Functions returning raw pointers to internal mutable data (like fz_buffer_data)
// cannot be safely implemented without additional infrastructure due to Rust's
// borrowing rules and the handle-based architecture. Use fz_string_from_buffer for
// read-only access, or work with buffer copies via fz_buffer_extract.

// ============================================================================
// Buffer Pool FFI Functions
// ============================================================================

/// Get buffer pool statistics
///
/// Returns a pointer to a PoolStatsFFI struct that must be freed with fz_free_pool_stats
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct PoolStatsFFI {
    /// Number of buffers acquired from pool (cache hits)
    pub hits: u64,
    /// Number of new allocations (cache misses)
    pub misses: u64,
    /// Number of buffers returned to pool
    pub returns: u64,
    /// Number of buffers dropped (pool full)
    pub drops: u64,
    /// Hit rate (0.0 - 1.0)
    pub hit_rate: f64,
    /// Current number of pooled buffers
    pub pool_count: u64,
    /// Total bytes ever allocated (cumulative)
    pub total_bytes_allocated: u64,
    /// Total bytes deallocated (cumulative)
    pub total_bytes_deallocated: u64,
    /// Current bytes in use
    pub current_bytes: u64,
    /// Peak bytes in use
    pub peak_bytes: u64,
    /// Total allocations count
    pub total_allocations: u64,
    /// Total deallocations count
    pub total_deallocations: u64,
}

/// Get buffer pool statistics
#[unsafe(no_mangle)]
pub extern "C" fn fz_buffer_pool_stats(_ctx: Handle) -> PoolStatsFFI {
    let stats = BUFFER_POOL.get_stats();
    let total = stats.hits + stats.misses;
    let hit_rate = if total > 0 {
        stats.hits as f64 / total as f64
    } else {
        0.0
    };

    PoolStatsFFI {
        hits: stats.hits,
        misses: stats.misses,
        returns: stats.returns,
        drops: stats.drops,
        hit_rate,
        pool_count: BUFFER_POOL.pool_count() as u64,
        total_bytes_allocated: stats.total_bytes_allocated,
        total_bytes_deallocated: stats.total_bytes_deallocated,
        current_bytes: stats.current_bytes,
        peak_bytes: stats.peak_bytes,
        total_allocations: stats.total_allocations,
        total_deallocations: stats.total_deallocations,
    }
}

/// Clear the buffer pool
#[unsafe(no_mangle)]
pub extern "C" fn fz_buffer_pool_clear(_ctx: Handle) {
    BUFFER_POOL.clear();
}

/// Get the number of buffers currently in the pool
#[unsafe(no_mangle)]
pub extern "C" fn fz_buffer_pool_count(_ctx: Handle) -> usize {
    BUFFER_POOL.pool_count()
}

// Note: fz_buffer_capacity already defined below in the file

/// Reserve additional capacity in buffer
#[unsafe(no_mangle)]
pub extern "C" fn fz_buffer_reserve(_ctx: Handle, buf: Handle, additional: usize) {
    if let Some(buffer) = BUFFERS.get(buf) {
        if let Ok(mut guard) = buffer.lock() {
            guard.reserve(additional);
        }
    }
}

/// Shrink buffer capacity to fit current length
#[unsafe(no_mangle)]
pub extern "C" fn fz_buffer_shrink_to_fit(_ctx: Handle, buf: Handle) {
    if let Some(buffer) = BUFFERS.get(buf) {
        if let Ok(mut guard) = buffer.lock() {
            guard.shrink_to_fit();
        }
    }
}

/// Check if buffer is from the pool
#[unsafe(no_mangle)]
pub extern "C" fn fz_buffer_is_pooled(_ctx: Handle, buf: Handle) -> c_int {
    if let Some(buffer) = BUFFERS.get(buf) {
        if let Ok(guard) = buffer.lock() {
            return if guard.is_pooled() { 1 } else { 0 };
        }
    }
    0
}

/// Create a buffer with suggested capacity (uses pool if appropriate)
///
/// This is an optimization hint - the actual capacity may be larger
/// to match a pool size class.
#[unsafe(no_mangle)]
pub extern "C" fn fz_new_buffer_with_capacity(_ctx: Handle, hint: usize) -> Handle {
    BUFFERS.insert(Buffer::new(hint))
}

/// Create a buffer bypassing the pool (for long-lived buffers)
#[unsafe(no_mangle)]
pub extern "C" fn fz_new_buffer_unpooled(_ctx: Handle, capacity: usize) -> Handle {
    BUFFERS.insert(Buffer::new_unpooled(capacity))
}

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

    #[test]
    fn test_buffer_create_and_drop() {
        let handle = fz_new_buffer(0, 100);
        assert_ne!(handle, 0);
        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_buffer_append_byte() {
        let handle = fz_new_buffer(0, 0);
        fz_append_byte(0, handle, b'A' as i32);
        fz_append_byte(0, handle, b'B' as i32);

        let len = fz_buffer_len(0, handle);
        assert_eq!(len, 2);

        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_buffer_clear() {
        let handle = fz_new_buffer(0, 0);
        fz_append_byte(0, handle, b'X' as i32);
        assert_eq!(fz_buffer_len(0, handle), 1);

        fz_clear_buffer(0, handle);
        assert_eq!(fz_buffer_len(0, handle), 0);

        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_buffer_keep() {
        let handle = fz_new_buffer(0, 0);
        let kept = fz_keep_buffer(0, handle);
        assert_eq!(kept, handle);
        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_buffer_resize() {
        let handle = fz_new_buffer(0, 10);
        fz_resize_buffer(0, handle, 100);
        // Resize should succeed
        assert_eq!(fz_buffer_len(0, handle), 100);
        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_buffer_grow() {
        let handle = fz_new_buffer(0, 10);
        fz_grow_buffer(0, handle);
        // Buffer should be able to accommodate growth
        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_buffer_trim() {
        let handle = fz_new_buffer(0, 100);
        fz_append_byte(0, handle, b'A' as i32);
        fz_trim_buffer(0, handle);
        assert_eq!(fz_buffer_len(0, handle), 1);
        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_buffer_clone() {
        let handle1 = fz_new_buffer(0, 0);
        fz_append_byte(0, handle1, b'X' as i32);
        fz_append_byte(0, handle1, b'Y' as i32);

        let handle2 = fz_clone_buffer(0, handle1);
        assert_ne!(handle2, 0);
        assert_eq!(fz_buffer_len(0, handle2), 2);

        // Modify original, clone should be unchanged
        fz_clear_buffer(0, handle1);
        assert_eq!(fz_buffer_len(0, handle1), 0);
        assert_eq!(fz_buffer_len(0, handle2), 2);

        fz_drop_buffer(0, handle1);
        fz_drop_buffer(0, handle2);
    }

    #[test]
    fn test_buffer_len_invalid() {
        let len = fz_buffer_len(0, 0);
        assert_eq!(len, 0);
    }

    #[test]
    fn test_buffer_append_multiple() {
        let handle = fz_new_buffer(0, 0);
        for i in 0..100 {
            fz_append_byte(0, handle, i);
        }
        assert_eq!(fz_buffer_len(0, handle), 100);
        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_buffer_storage() {
        let handle = fz_new_buffer(0, 0);
        fz_append_byte(0, handle, b'H' as i32);
        fz_append_byte(0, handle, b'i' as i32);

        let mut datap: *mut u8 = std::ptr::null_mut();
        let size = fz_buffer_storage(0, handle, &mut datap);

        // Size should be the length of the buffer
        assert_eq!(size, 2);
        // datap will be null because we can't safely return internal pointer
        assert!(datap.is_null());

        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_buffer_internal() {
        let buf = Buffer::new(10);
        assert_eq!(buf.len(), 0);
        assert!(buf.data().is_empty());
    }

    #[test]
    fn test_buffer_from_data() {
        let data = [1u8, 2, 3, 4, 5];
        let buf = Buffer::from_data(&data);
        assert_eq!(buf.len(), 5);
        assert_eq!(buf.data(), &data);
    }

    #[test]
    fn test_buffer_append_internal() {
        let mut buf = Buffer::new(0);
        buf.append_byte(0x42);
        assert_eq!(buf.len(), 1);
        assert_eq!(buf.data(), &[0x42]);
    }

    #[test]
    fn test_buffer_clear_internal() {
        let mut buf = Buffer::from_data(&[1, 2, 3]);
        buf.clear();
        assert_eq!(buf.len(), 0);
    }

    // ============================================================================
    // Additional tests for better coverage
    // ============================================================================

    #[test]
    fn test_buffer_from_copied_data() {
        let data = [1u8, 2, 3, 4, 5];
        let handle = fz_new_buffer_from_copied_data(0, data.as_ptr(), data.len());
        assert_ne!(handle, 0);
        assert_eq!(fz_buffer_len(0, handle), 5);
        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_buffer_from_copied_data_null() {
        let handle = fz_new_buffer_from_copied_data(0, std::ptr::null(), 0);
        assert_ne!(handle, 0);
        assert_eq!(fz_buffer_len(0, handle), 0);
        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_buffer_from_copied_data_null_with_size() {
        // Even with non-zero size, null ptr should return empty buffer
        let handle = fz_new_buffer_from_copied_data(0, std::ptr::null(), 100);
        assert_ne!(handle, 0);
        assert_eq!(fz_buffer_len(0, handle), 0);
        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_buffer_storage_null_datap() {
        let handle = fz_new_buffer(0, 0);
        fz_append_byte(0, handle, b'A' as i32);

        // Pass null pointer for datap
        let size = fz_buffer_storage(0, handle, std::ptr::null_mut());
        assert_eq!(size, 1);

        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_buffer_storage_invalid_handle() {
        let mut datap: *mut u8 = std::ptr::null_mut();
        let size = fz_buffer_storage(0, 99999, &mut datap);
        assert_eq!(size, 0);
        assert!(datap.is_null());
    }

    #[test]
    fn test_fz_string_from_buffer() {
        let handle = fz_new_buffer(0, 0);
        fz_append_byte(0, handle, b'H' as i32);

        let ptr = fz_string_from_buffer(0, handle);
        assert!(!ptr.is_null());

        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_buffer_resize_invalid_handle() {
        // Should not panic
        fz_resize_buffer(0, 99999, 100);
    }

    #[test]
    fn test_buffer_grow_invalid_handle() {
        // Should not panic
        fz_grow_buffer(0, 99999);
    }

    #[test]
    fn test_buffer_trim_invalid_handle() {
        // Should not panic
        fz_trim_buffer(0, 99999);
    }

    #[test]
    fn test_buffer_clear_invalid_handle() {
        // Should not panic
        fz_clear_buffer(0, 99999);
    }

    #[test]
    fn test_fz_append_data() {
        let handle = fz_new_buffer(0, 0);
        let data = [1u8, 2, 3, 4, 5];
        fz_append_data(0, handle, data.as_ptr() as *const c_void, data.len());
        assert_eq!(fz_buffer_len(0, handle), 5);
        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_fz_append_data_null() {
        let handle = fz_new_buffer(0, 0);
        fz_append_data(0, handle, std::ptr::null(), 0);
        assert_eq!(fz_buffer_len(0, handle), 0);
        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_fz_append_data_invalid_handle() {
        let data = [1u8, 2, 3];
        // Should not panic
        fz_append_data(0, 99999, data.as_ptr() as *const c_void, data.len());
    }

    #[test]
    fn test_fz_append_string() {
        let handle = fz_new_buffer(0, 0);
        let s = std::ffi::CString::new("Hello").unwrap();
        fz_append_string(0, handle, s.as_ptr());
        assert_eq!(fz_buffer_len(0, handle), 5);
        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_fz_append_string_null() {
        let handle = fz_new_buffer(0, 0);
        fz_append_string(0, handle, std::ptr::null());
        assert_eq!(fz_buffer_len(0, handle), 0);
        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_fz_append_string_invalid_handle() {
        let s = std::ffi::CString::new("Hello").unwrap();
        // Should not panic
        fz_append_string(0, 99999, s.as_ptr());
    }

    #[test]
    fn test_fz_append_byte_invalid_handle() {
        // Should not panic
        fz_append_byte(0, 99999, b'X' as i32);
    }

    #[test]
    fn test_fz_terminate_buffer() {
        let handle = fz_new_buffer(0, 0);
        fz_append_byte(0, handle, b'H' as i32);
        fz_terminate_buffer(0, handle);
        // After termination, buffer should have a null byte
        assert_eq!(fz_buffer_len(0, handle), 2);
        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_fz_terminate_buffer_invalid_handle() {
        // Should not panic
        fz_terminate_buffer(0, 99999);
    }

    #[test]
    fn test_fz_terminate_buffer_already_terminated() {
        let handle = fz_new_buffer(0, 0);
        fz_append_byte(0, handle, b'H' as i32);
        fz_append_byte(0, handle, 0); // Already has null
        fz_terminate_buffer(0, handle);
        // Should not add another null
        assert_eq!(fz_buffer_len(0, handle), 2);
        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_fz_md5_buffer() {
        let handle = fz_new_buffer(0, 0);
        fz_append_byte(0, handle, b'A' as i32);
        fz_append_byte(0, handle, b'B' as i32);
        fz_append_byte(0, handle, b'C' as i32);

        let mut digest = [0u8; 16];
        fz_md5_buffer(0, handle, &mut digest);

        // MD5("ABC") is known
        assert_ne!(digest, [0u8; 16]);
        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_fz_md5_buffer_null_digest() {
        let handle = fz_new_buffer(0, 0);
        fz_append_byte(0, handle, b'A' as i32);
        // Should not panic
        fz_md5_buffer(0, handle, std::ptr::null_mut());
        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_fz_md5_buffer_invalid_handle() {
        let mut digest = [0u8; 16];
        // Should not panic
        fz_md5_buffer(0, 99999, &mut digest);
    }

    #[test]
    fn test_fz_clone_buffer_invalid_handle() {
        let handle = fz_clone_buffer(0, 99999);
        assert_eq!(handle, 0);
    }

    #[test]
    fn test_buffer_is_empty() {
        let buf = Buffer::new(10);
        assert!(buf.is_empty());

        let buf2 = Buffer::from_data(&[1, 2, 3]);
        assert!(!buf2.is_empty());
    }

    #[test]
    fn test_buffer_data_mut() {
        let mut buf = Buffer::new(0);
        buf.data_mut().push(1);
        buf.data_mut().push(2);
        assert_eq!(buf.len(), 2);
    }

    #[test]
    fn test_buffer_append() {
        let mut buf = Buffer::new(0);
        buf.append(&[1, 2, 3]);
        assert_eq!(buf.len(), 3);
        buf.append(&[4, 5]);
        assert_eq!(buf.len(), 5);
        assert_eq!(buf.data(), &[1, 2, 3, 4, 5]);
    }

    #[test]
    fn test_buffer_resize_internal() {
        let mut buf = Buffer::from_data(&[1, 2, 3]);
        buf.resize(5);
        assert_eq!(buf.len(), 5);
        assert_eq!(&buf.data()[..3], &[1, 2, 3]);
        assert_eq!(&buf.data()[3..], &[0, 0]);
    }

    #[test]
    fn test_buffer_ensure_null_terminated() {
        let mut buf = Buffer::from_data(&[1, 2, 3]);
        buf.ensure_null_terminated();
        assert_eq!(buf.len(), 4);
        assert_eq!(buf.data().last(), Some(&0));

        // Should not add another null
        buf.ensure_null_terminated();
        assert_eq!(buf.len(), 4);
    }

    #[test]
    fn test_buffer_ensure_null_terminated_empty() {
        let mut buf = Buffer::new(0);
        buf.ensure_null_terminated();
        assert_eq!(buf.len(), 1);
        assert_eq!(buf.data(), &[0]);
    }

    // ============================================================================
    // Integer Append Tests
    // ============================================================================

    #[test]
    fn test_fz_append_int16_le() {
        let handle = fz_new_buffer(0, 0);
        fz_append_int16_le(0, handle, 0x0102);
        assert_eq!(fz_buffer_len(0, handle), 2);

        // Check actual bytes (little-endian: 0x02, 0x01)
        if let Some(buffer) = BUFFERS.get(handle) {
            if let Ok(guard) = buffer.lock() {
                assert_eq!(guard.data(), &[0x02, 0x01]);
            }
        }
        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_fz_append_int32_le() {
        let handle = fz_new_buffer(0, 0);
        fz_append_int32_le(0, handle, 0x01020304);
        assert_eq!(fz_buffer_len(0, handle), 4);

        if let Some(buffer) = BUFFERS.get(handle) {
            if let Ok(guard) = buffer.lock() {
                assert_eq!(guard.data(), &[0x04, 0x03, 0x02, 0x01]);
            }
        }
        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_fz_append_int16_be() {
        let handle = fz_new_buffer(0, 0);
        fz_append_int16_be(0, handle, 0x0102);
        assert_eq!(fz_buffer_len(0, handle), 2);

        if let Some(buffer) = BUFFERS.get(handle) {
            if let Ok(guard) = buffer.lock() {
                assert_eq!(guard.data(), &[0x01, 0x02]);
            }
        }
        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_fz_append_int32_be() {
        let handle = fz_new_buffer(0, 0);
        fz_append_int32_be(0, handle, 0x01020304);
        assert_eq!(fz_buffer_len(0, handle), 4);

        if let Some(buffer) = BUFFERS.get(handle) {
            if let Ok(guard) = buffer.lock() {
                assert_eq!(guard.data(), &[0x01, 0x02, 0x03, 0x04]);
            }
        }
        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_fz_append_int_invalid_handle() {
        // Should not panic
        fz_append_int16_le(0, 99999, 0x1234);
        fz_append_int32_le(0, 99999, 0x12345678);
        fz_append_int16_be(0, 99999, 0x1234);
        fz_append_int32_be(0, 99999, 0x12345678);
    }

    // ============================================================================
    // Bit Append Tests
    // ============================================================================

    #[test]
    fn test_fz_append_bits_basic() {
        let handle = fz_new_buffer(0, 0);

        // Append 8 bits at a time - should produce byte
        fz_append_bits(0, handle, 0b10101010, 8);
        assert_eq!(fz_buffer_len(0, handle), 1);

        if let Some(buffer) = BUFFERS.get(handle) {
            if let Ok(guard) = buffer.lock() {
                assert_eq!(guard.data(), &[0b10101010]);
            }
        }
        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_fz_append_bits_multiple() {
        let handle = fz_new_buffer(0, 0);

        // Append 4 bits, then another 4 bits
        fz_append_bits(0, handle, 0b1010, 4);
        fz_append_bits(0, handle, 0b0101, 4);

        assert_eq!(fz_buffer_len(0, handle), 1);

        if let Some(buffer) = BUFFERS.get(handle) {
            if let Ok(guard) = buffer.lock() {
                assert_eq!(guard.data(), &[0b10100101]);
            }
        }
        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_fz_append_bits_pad() {
        let handle = fz_new_buffer(0, 0);

        // Append 5 bits, then pad to byte
        fz_append_bits(0, handle, 0b11111, 5);
        fz_append_bits_pad(0, handle);

        assert_eq!(fz_buffer_len(0, handle), 1);

        if let Some(buffer) = BUFFERS.get(handle) {
            if let Ok(guard) = buffer.lock() {
                // 5 bits of 1s + 3 bits of 0s = 11111000 = 0xF8
                assert_eq!(guard.data(), &[0xF8]);
            }
        }
        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_fz_append_bits_invalid_count() {
        let handle = fz_new_buffer(0, 0);

        // Invalid counts should be ignored
        fz_append_bits(0, handle, 0xFF, 0);
        fz_append_bits(0, handle, 0xFF, -1);
        fz_append_bits(0, handle, 0xFF, 33);

        assert_eq!(fz_buffer_len(0, handle), 0);
        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_fz_append_bits_invalid_handle() {
        // Should not panic
        fz_append_bits(0, 99999, 0xFF, 8);
        fz_append_bits_pad(0, 99999);
    }

    // ============================================================================
    // PDF String Tests
    // ============================================================================

    #[test]
    fn test_fz_append_pdf_string_simple() {
        let handle = fz_new_buffer(0, 0);
        let s = std::ffi::CString::new("Hello").unwrap();
        fz_append_pdf_string(0, handle, s.as_ptr());

        if let Some(buffer) = BUFFERS.get(handle) {
            if let Ok(guard) = buffer.lock() {
                assert_eq!(guard.data(), b"(Hello)");
            }
        }
        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_fz_append_pdf_string_escaping() {
        let handle = fz_new_buffer(0, 0);
        let s = std::ffi::CString::new("Test(with)parens\\backslash").unwrap();
        fz_append_pdf_string(0, handle, s.as_ptr());

        if let Some(buffer) = BUFFERS.get(handle) {
            if let Ok(guard) = buffer.lock() {
                assert_eq!(guard.data(), b"(Test\\(with\\)parens\\\\backslash)");
            }
        }
        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_fz_append_pdf_string_newlines() {
        let handle = fz_new_buffer(0, 0);
        let s = std::ffi::CString::new("Line1\nLine2\rLine3\tTab").unwrap();
        fz_append_pdf_string(0, handle, s.as_ptr());

        if let Some(buffer) = BUFFERS.get(handle) {
            if let Ok(guard) = buffer.lock() {
                assert_eq!(guard.data(), b"(Line1\\nLine2\\rLine3\\tTab)");
            }
        }
        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_fz_append_pdf_string_null() {
        let handle = fz_new_buffer(0, 0);
        fz_append_pdf_string(0, handle, std::ptr::null());

        if let Some(buffer) = BUFFERS.get(handle) {
            if let Ok(guard) = buffer.lock() {
                assert_eq!(guard.data(), b"()");
            }
        }
        fz_drop_buffer(0, handle);
    }

    #[test]
    fn test_fz_append_pdf_string_invalid_handle() {
        let s = std::ffi::CString::new("Test").unwrap();
        // Should not panic
        fz_append_pdf_string(0, 99999, s.as_ptr());
    }

    // ============================================================================
    // Buffer Append Buffer Tests
    // ============================================================================

    #[test]
    fn test_fz_append_buffer() {
        let buf1 = fz_new_buffer(0, 0);
        let buf2 = fz_new_buffer(0, 0);

        fz_append_byte(0, buf1, b'A' as i32);
        fz_append_byte(0, buf1, b'B' as i32);

        fz_append_byte(0, buf2, b'C' as i32);
        fz_append_byte(0, buf2, b'D' as i32);

        fz_append_buffer(0, buf1, buf2);

        assert_eq!(fz_buffer_len(0, buf1), 4);

        if let Some(buffer) = BUFFERS.get(buf1) {
            if let Ok(guard) = buffer.lock() {
                assert_eq!(guard.data(), b"ABCD");
            }
        }

        fz_drop_buffer(0, buf1);
        fz_drop_buffer(0, buf2);
    }

    #[test]
    fn test_fz_append_buffer_invalid() {
        let buf = fz_new_buffer(0, 0);
        fz_append_byte(0, buf, b'X' as i32);

        // Append from invalid handle - should be ignored
        fz_append_buffer(0, buf, 99999);
        assert_eq!(fz_buffer_len(0, buf), 1);

        // Append to invalid handle - should not panic
        fz_append_buffer(0, 99999, buf);

        fz_drop_buffer(0, buf);
    }

    // ============================================================================
    // Buffer Pool Tests
    // ============================================================================

    #[test]
    #[serial]
    fn test_buffer_pool_basic() {
        // Clear pool first for clean state
        fz_buffer_pool_clear(0);

        // Create and drop a poolable buffer
        let buf = fz_new_buffer(0, 256);
        fz_append_byte(0, buf, b'X' as i32);
        assert_eq!(fz_buffer_is_pooled(0, buf), 1);
        fz_drop_buffer(0, buf);

        // Pool should have one buffer now
        let count = fz_buffer_pool_count(0);
        assert!(count >= 1, "Pool should have at least one buffer");
    }

    #[test]
    #[serial]
    fn test_buffer_pool_reuse() {
        // Clear pool
        fz_buffer_pool_clear(0);

        // Create and drop a buffer
        let buf1 = fz_new_buffer(0, 1024);
        let cap1 = fz_buffer_capacity(0, buf1);
        fz_drop_buffer(0, buf1);

        // Get stats before reuse
        let stats_before = fz_buffer_pool_stats(0);

        // Create another buffer of similar size
        let buf2 = fz_new_buffer(0, 512); // Should get 1024 from pool
        let cap2 = fz_buffer_capacity(0, buf2);

        // Check stats after reuse
        let stats_after = fz_buffer_pool_stats(0);

        // Should have reused the buffer (hit)
        assert!(
            stats_after.hits > stats_before.hits || cap2 == cap1,
            "Buffer should be reused from pool"
        );

        fz_drop_buffer(0, buf2);
    }

    #[test]
    #[serial]
    fn test_buffer_pool_stats() {
        fz_buffer_pool_clear(0);

        let stats = fz_buffer_pool_stats(0);
        assert!(stats.hit_rate >= 0.0 && stats.hit_rate <= 1.0);
    }

    #[test]
    fn test_buffer_capacity() {
        let buf = fz_new_buffer(0, 100);

        // Capacity should be at least 100 (may be rounded up to pool size)
        let cap = fz_buffer_capacity(0, buf);
        assert!(cap >= 100, "Capacity should be at least 100");

        // Length should be 0
        assert_eq!(fz_buffer_len(0, buf), 0);

        fz_drop_buffer(0, buf);
    }

    #[test]
    fn test_buffer_reserve() {
        let buf = fz_new_buffer(0, 10);
        let initial_cap = fz_buffer_capacity(0, buf);

        // Reserve much more than current capacity
        fz_buffer_reserve(0, buf, 10000);
        let new_cap = fz_buffer_capacity(0, buf);

        // New capacity should be at least initial + requested
        // (Vec::reserve guarantees at least len + additional)
        assert!(
            new_cap >= initial_cap || new_cap >= 10000,
            "Should have reserved space: initial_cap={}, new_cap={}",
            initial_cap,
            new_cap
        );

        fz_drop_buffer(0, buf);
    }

    #[test]
    fn test_buffer_shrink() {
        let buf = fz_new_buffer(0, 1000);

        // Add some data
        for i in 0..10 {
            fz_append_byte(0, buf, i);
        }

        // Shrink to fit
        fz_buffer_shrink_to_fit(0, buf);

        // Should no longer be pooled
        assert_eq!(fz_buffer_is_pooled(0, buf), 0);

        fz_drop_buffer(0, buf);
    }

    #[test]
    fn test_buffer_unpooled() {
        let buf = fz_new_buffer_unpooled(0, 256);

        // Should not be pooled
        assert_eq!(fz_buffer_is_pooled(0, buf), 0);

        fz_drop_buffer(0, buf);
    }

    #[test]
    fn test_buffer_with_capacity() {
        let buf = fz_new_buffer_with_capacity(0, 500);

        // Should have capacity >= 500 (rounded to pool size)
        let cap = fz_buffer_capacity(0, buf);
        assert!(cap >= 500, "Capacity should be at least 500");

        // Should be pooled
        assert_eq!(fz_buffer_is_pooled(0, buf), 1);

        fz_drop_buffer(0, buf);
    }

    #[test]
    fn test_pool_size_classes() {
        // Test that different sizes get appropriate capacity
        let sizes_and_expected = [
            (10, 64),       // Tiny -> 64
            (100, 256),     // Small -> 256
            (500, 1024),    // Medium -> 1024
            (2000, 4096),   // Page -> 4096
            (10000, 16384), // Large -> 16384
            (50000, 65536), // Very large -> 65536
        ];

        for (requested, expected_min) in sizes_and_expected {
            let buf = fz_new_buffer(0, requested);
            let cap = fz_buffer_capacity(0, buf);
            assert!(
                cap >= expected_min,
                "Buffer for {} bytes should have capacity >= {}, got {}",
                requested,
                expected_min,
                cap
            );
            fz_drop_buffer(0, buf);
        }
    }
}