summaryrefslogtreecommitdiff
path: root/ext/zlib/zlib.c
blob: 03d425502034c40017d531aa29e0e3d6537a0ad9 (plain)
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
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
/*
 * zlib.c - An interface for zlib.
 *
 *   Copyright (C) UENO Katsuhiro 2000-2003
 *
 * $Id$
 */

#include <ruby.h>
#include <zlib.h>
#include <time.h>
#include <ruby/io.h>

#ifdef HAVE_VALGRIND_MEMCHECK_H
# include <valgrind/memcheck.h>
# ifndef VALGRIND_MAKE_MEM_DEFINED
#  define VALGRIND_MAKE_MEM_DEFINED(p, n) VALGRIND_MAKE_READABLE((p), (n))
# endif
# ifndef VALGRIND_MAKE_MEM_UNDEFINED
#  define VALGRIND_MAKE_MEM_UNDEFINED(p, n) VALGRIND_MAKE_WRITABLE((p), (n))
# endif
#else
# define VALGRIND_MAKE_MEM_DEFINED(p, n) /* empty */
# define VALGRIND_MAKE_MEM_UNDEFINED(p, n) /* empty */
#endif

#define RUBY_ZLIB_VERSION  "0.6.0"


#define OBJ_IS_FREED(val)  (RBASIC(val)->flags == 0)

#ifndef GZIP_SUPPORT
#define GZIP_SUPPORT  1
#endif

/* from zutil.h */
#ifndef DEF_MEM_LEVEL
#if MAX_MEM_LEVEL >= 8
#define DEF_MEM_LEVEL  8
#else
#define DEF_MEM_LEVEL  MAX_MEM_LEVEL
#endif
#endif

#if SIZEOF_LONG > SIZEOF_INT
static inline uInt
max_uint(long n)
{
    if (n > UINT_MAX) n = UINT_MAX;
    return (uInt)n;
}
#define MAX_UINT(n) max_uint(n)
#else
#define MAX_UINT(n) (uInt)(n)
#endif

#define sizeof(x) ((int)sizeof(x))

/*--------- Prototypes --------*/

static NORETURN(void raise_zlib_error(int, const char*));
static VALUE rb_zlib_version(VALUE);
static VALUE do_checksum(int, VALUE*, uLong (*)(uLong, const Bytef*, uInt));
static VALUE rb_zlib_adler32(int, VALUE*, VALUE);
static VALUE rb_zlib_crc32(int, VALUE*, VALUE);
static VALUE rb_zlib_crc_table(VALUE);
static voidpf zlib_mem_alloc(voidpf, uInt, uInt);
static void zlib_mem_free(voidpf, voidpf);
static void finalizer_warn(const char*);

struct zstream;
struct zstream_funcs;
static void zstream_init(struct zstream*, const struct zstream_funcs*);
static void zstream_expand_buffer(struct zstream*);
static void zstream_expand_buffer_into(struct zstream*, unsigned long);
static void zstream_append_buffer(struct zstream*, const Bytef*, long);
static VALUE zstream_detach_buffer(struct zstream*);
static VALUE zstream_shift_buffer(struct zstream*, long);
static void zstream_buffer_ungets(struct zstream*, const Bytef*, unsigned long);
static void zstream_buffer_ungetbyte(struct zstream*, int);
static void zstream_append_input(struct zstream*, const Bytef*, long);
static void zstream_discard_input(struct zstream*, long);
static void zstream_reset_input(struct zstream*);
static void zstream_passthrough_input(struct zstream*);
static VALUE zstream_detach_input(struct zstream*);
static void zstream_reset(struct zstream*);
static VALUE zstream_end(struct zstream*);
static void zstream_run(struct zstream*, Bytef*, long, int);
static VALUE zstream_sync(struct zstream*, Bytef*, long);
static void zstream_mark(struct zstream*);
static void zstream_free(struct zstream*);
static VALUE zstream_new(VALUE, const struct zstream_funcs*);
static struct zstream *get_zstream(VALUE);
static void zstream_finalize(struct zstream*);

static VALUE rb_zstream_end(VALUE);
static VALUE rb_zstream_reset(VALUE);
static VALUE rb_zstream_finish(VALUE);
static VALUE rb_zstream_flush_next_in(VALUE);
static VALUE rb_zstream_flush_next_out(VALUE);
static VALUE rb_zstream_avail_out(VALUE);
static VALUE rb_zstream_set_avail_out(VALUE, VALUE);
static VALUE rb_zstream_avail_in(VALUE);
static VALUE rb_zstream_total_in(VALUE);
static VALUE rb_zstream_total_out(VALUE);
static VALUE rb_zstream_data_type(VALUE);
static VALUE rb_zstream_adler(VALUE);
static VALUE rb_zstream_finished_p(VALUE);
static VALUE rb_zstream_closed_p(VALUE);

static VALUE rb_deflate_s_allocate(VALUE);
static VALUE rb_deflate_initialize(int, VALUE*, VALUE);
static VALUE rb_deflate_init_copy(VALUE, VALUE);
static VALUE deflate_run(VALUE);
static VALUE rb_deflate_s_deflate(int, VALUE*, VALUE);
static void do_deflate(struct zstream*, VALUE, int);
static VALUE rb_deflate_deflate(int, VALUE*, VALUE);
static VALUE rb_deflate_addstr(VALUE, VALUE);
static VALUE rb_deflate_flush(int, VALUE*, VALUE);
static VALUE rb_deflate_params(VALUE, VALUE, VALUE);
static VALUE rb_deflate_set_dictionary(VALUE, VALUE);

static VALUE inflate_run(VALUE);
static VALUE rb_inflate_s_allocate(VALUE);
static VALUE rb_inflate_initialize(int, VALUE*, VALUE);
static VALUE rb_inflate_s_inflate(VALUE, VALUE);
static void do_inflate(struct zstream*, VALUE);
static VALUE rb_inflate_inflate(VALUE, VALUE);
static VALUE rb_inflate_addstr(VALUE, VALUE);
static VALUE rb_inflate_sync(VALUE, VALUE);
static VALUE rb_inflate_sync_point_p(VALUE);
static VALUE rb_inflate_set_dictionary(VALUE, VALUE);

#if GZIP_SUPPORT
struct gzfile;
static void gzfile_mark(struct gzfile*);
static void gzfile_free(struct gzfile*);
static VALUE gzfile_new(VALUE, const struct zstream_funcs*, void (*) _((struct gzfile*)));
static void gzfile_reset(struct gzfile*);
static void gzfile_close(struct gzfile*, int);
static void gzfile_write_raw(struct gzfile*);
static VALUE gzfile_read_raw_partial(VALUE);
static VALUE gzfile_read_raw_rescue(VALUE);
static VALUE gzfile_read_raw(struct gzfile*);
static int gzfile_read_raw_ensure(struct gzfile*, long);
static char *gzfile_read_raw_until_zero(struct gzfile*, long);
static unsigned int gzfile_get16(const unsigned char*);
static unsigned long gzfile_get32(const unsigned char*);
static void gzfile_set32(unsigned long n, unsigned char*);
static void gzfile_make_header(struct gzfile*);
static void gzfile_make_footer(struct gzfile*);
static void gzfile_read_header(struct gzfile*);
static void gzfile_check_footer(struct gzfile*);
static void gzfile_write(struct gzfile*, Bytef*, long);
static long gzfile_read_more(struct gzfile*);
static void gzfile_calc_crc(struct gzfile*, VALUE);
static VALUE gzfile_read(struct gzfile*, long);
static VALUE gzfile_read_all(struct gzfile*);
static void gzfile_ungets(struct gzfile*, const Bytef*, long);
static void gzfile_ungetbyte(struct gzfile*, int);
static VALUE gzfile_writer_end_run(VALUE);
static void gzfile_writer_end(struct gzfile*);
static VALUE gzfile_reader_end_run(VALUE);
static void gzfile_reader_end(struct gzfile*);
static void gzfile_reader_rewind(struct gzfile*);
static VALUE gzfile_reader_get_unused(struct gzfile*);
static struct gzfile *get_gzfile(VALUE);
static VALUE gzfile_ensure_close(VALUE);
static VALUE rb_gzfile_s_wrap(int, VALUE*, VALUE);
static VALUE gzfile_s_open(int, VALUE*, VALUE, const char*);
NORETURN(static void gzfile_raise(struct gzfile *, VALUE, const char *));
static VALUE gzfile_error_inspect(VALUE);

static VALUE rb_gzfile_to_io(VALUE);
static VALUE rb_gzfile_crc(VALUE);
static VALUE rb_gzfile_mtime(VALUE);
static VALUE rb_gzfile_level(VALUE);
static VALUE rb_gzfile_os_code(VALUE);
static VALUE rb_gzfile_orig_name(VALUE);
static VALUE rb_gzfile_comment(VALUE);
static VALUE rb_gzfile_lineno(VALUE);
static VALUE rb_gzfile_set_lineno(VALUE, VALUE);
static VALUE rb_gzfile_set_mtime(VALUE, VALUE);
static VALUE rb_gzfile_set_orig_name(VALUE, VALUE);
static VALUE rb_gzfile_set_comment(VALUE, VALUE);
static VALUE rb_gzfile_close(VALUE);
static VALUE rb_gzfile_finish(VALUE);
static VALUE rb_gzfile_closed_p(VALUE);
static VALUE rb_gzfile_eof_p(VALUE);
static VALUE rb_gzfile_sync(VALUE);
static VALUE rb_gzfile_set_sync(VALUE, VALUE);
static VALUE rb_gzfile_total_in(VALUE);
static VALUE rb_gzfile_total_out(VALUE);
static VALUE rb_gzfile_path(VALUE);

static VALUE rb_gzwriter_s_allocate(VALUE);
static VALUE rb_gzwriter_s_open(int, VALUE*, VALUE);
static VALUE rb_gzwriter_initialize(int, VALUE*, VALUE);
static VALUE rb_gzwriter_flush(int, VALUE*, VALUE);
static VALUE rb_gzwriter_write(VALUE, VALUE);
static VALUE rb_gzwriter_putc(VALUE, VALUE);

static VALUE rb_gzreader_s_allocate(VALUE);
static VALUE rb_gzreader_s_open(int, VALUE*, VALUE);
static VALUE rb_gzreader_initialize(int, VALUE*, VALUE);
static VALUE rb_gzreader_rewind(VALUE);
static VALUE rb_gzreader_unused(VALUE);
static VALUE rb_gzreader_read(int, VALUE*, VALUE);
static VALUE rb_gzreader_getc(VALUE);
static VALUE rb_gzreader_readchar(VALUE);
static VALUE rb_gzreader_each_byte(VALUE);
static VALUE rb_gzreader_ungetc(VALUE, VALUE);
static VALUE rb_gzreader_ungetbyte(VALUE, VALUE);
static void gzreader_skip_linebreaks(struct gzfile*);
static VALUE gzreader_gets(int, VALUE*, VALUE);
static VALUE rb_gzreader_gets(int, VALUE*, VALUE);
static VALUE rb_gzreader_readline(int, VALUE*, VALUE);
static VALUE rb_gzreader_each(int, VALUE*, VALUE);
static VALUE rb_gzreader_readlines(int, VALUE*, VALUE);
#endif /* GZIP_SUPPORT */


void Init_zlib(void);

/*--------- Exceptions --------*/

static VALUE cZError, cStreamEnd, cNeedDict;
static VALUE cStreamError, cDataError, cMemError, cBufError, cVersionError;

static void
raise_zlib_error(int err, const char *msg)
{
    VALUE exc;

    if (!msg) {
	msg = zError(err);
    }

    switch(err) {
      case Z_STREAM_END:
	exc = rb_exc_new2(cStreamEnd, msg);
	break;
      case Z_NEED_DICT:
	exc = rb_exc_new2(cNeedDict, msg);
	break;
      case Z_STREAM_ERROR:
	exc = rb_exc_new2(cStreamError, msg);
	break;
      case Z_DATA_ERROR:
	exc = rb_exc_new2(cDataError, msg);
	break;
      case Z_BUF_ERROR:
	exc = rb_exc_new2(cBufError, msg);
	break;
      case Z_VERSION_ERROR:
	exc = rb_exc_new2(cVersionError, msg);
	break;
      case Z_MEM_ERROR:
	exc = rb_exc_new2(cMemError, msg);
	break;
      case Z_ERRNO:
	rb_sys_fail(msg);
	/* no return */
      default:
      {
	  char buf[BUFSIZ];
	  snprintf(buf, BUFSIZ, "unknown zlib error %d: %s", err, msg);
	  exc = rb_exc_new2(cZError, buf);
      }
    }

    rb_exc_raise(exc);
}


/*--- Warning (in finalizer) ---*/

static void
finalizer_warn(const char *msg)
{
    fprintf(stderr, "zlib(finalizer): %s\n", msg);
}


/*-------- module Zlib --------*/

/*
 * Returns the string which represents the version of zlib library.
 */
static VALUE
rb_zlib_version(VALUE klass)
{
    VALUE str;

    str = rb_str_new2(zlibVersion());
    OBJ_TAINT(str);  /* for safe */
    return str;
}

#if SIZEOF_LONG > SIZEOF_INT
static uLong
checksum_long(uLong (*func)(uLong, const Bytef*, uInt), uLong sum, const Bytef *ptr, long len)
{
    if (len > UINT_MAX) {
	do {
	    sum = func(sum, ptr, UINT_MAX);
	    ptr += UINT_MAX;
	    len -= UINT_MAX;
	} while (len >= UINT_MAX);
    }
    if (len > 0) sum = func(sum, ptr, (uInt)len);
    return sum;
}
#else
#define checksum_long(func, sum, ptr, len) (func)((sum), (ptr), (len))
#endif

static VALUE
do_checksum(argc, argv, func)
    int argc;
    VALUE *argv;
    uLong (*func)(uLong, const Bytef*, uInt);
{
    VALUE str, vsum;
    unsigned long sum;

    rb_scan_args(argc, argv, "02", &str, &vsum);

    if (!NIL_P(vsum)) {
	sum = NUM2ULONG(vsum);
    }
    else if (NIL_P(str)) {
	sum = 0;
    }
    else {
	sum = func(0, Z_NULL, 0);
    }

    if (NIL_P(str)) {
	sum = func(sum, Z_NULL, 0);
    }
    else {
	StringValue(str);
	sum = checksum_long(func, sum, (Bytef*)RSTRING_PTR(str), RSTRING_LEN(str));
    }
    return rb_uint2inum(sum);
}

/*
 * call-seq: Zlib.adler32(string, adler)
 *
 * Calculates Adler-32 checksum for +string+, and returns updated value of
 * +adler+. If +string+ is omitted, it returns the Adler-32 initial value. If
 * +adler+ is omitted, it assumes that the initial value is given to +adler+.
 *
 * FIXME: expression.
 */
static VALUE
rb_zlib_adler32(int argc, VALUE *argv, VALUE klass)
{
    return do_checksum(argc, argv, adler32);
}

#ifdef HAVE_ADLER32_COMBINE
/*
 * call-seq: Zlib.adler32_combine(adler1, adler2, len2)
 *
 * Combine two Adler-32 check values in to one.  +alder1+ is the first Adler-32
 * value, +adler2+ is the second Adler-32 value.  +len2+ is the length of the
 * string used to generate +adler2+.
 *
 */
static VALUE
rb_zlib_adler32_combine(VALUE klass, VALUE adler1, VALUE adler2, VALUE len2)
{
  return ULONG2NUM(
	adler32_combine(NUM2ULONG(adler1), NUM2ULONG(adler2), NUM2LONG(len2)));
}
#else
#define rb_zlib_adler32_combine rb_f_notimplement
#endif

/*
 * call-seq: Zlib.crc32(string, adler)
 *
 * Calculates CRC checksum for +string+, and returns updated value of +crc+. If
 * +string+ is omitted, it returns the CRC initial value. If +crc+ is omitted, it
 * assumes that the initial value is given to +crc+.
 *
 * FIXME: expression.
 */
static VALUE
rb_zlib_crc32(int argc, VALUE *argv, VALUE klass)
{
    return do_checksum(argc, argv, crc32);
}

#ifdef HAVE_CRC32_COMBINE
/*
 * call-seq: Zlib.crc32_combine(crc1, crc2, len2)
 *
 * Combine two CRC-32 check values in to one.  +crc1+ is the first CRC-32
 * value, +crc2+ is the second CRC-32 value.  +len2+ is the length of the
 * string used to generate +crc2+.
 *
 */
static VALUE
rb_zlib_crc32_combine(VALUE klass, VALUE crc1, VALUE crc2, VALUE len2)
{
  return ULONG2NUM(
	crc32_combine(NUM2ULONG(crc1), NUM2ULONG(crc2), NUM2LONG(len2)));
}
#else
#define rb_zlib_crc32_combine rb_f_notimplement
#endif

/*
 * Returns the table for calculating CRC checksum as an array.
 */
static VALUE
rb_zlib_crc_table(VALUE obj)
{
    const unsigned long *crctbl;
    VALUE dst;
    int i;

    crctbl = get_crc_table();
    dst = rb_ary_new2(256);

    for (i = 0; i < 256; i++) {
	rb_ary_push(dst, rb_uint2inum(crctbl[i]));
    }
    return dst;
}



/*-------- zstream - internal APIs --------*/

struct zstream {
    unsigned long flags;
    VALUE buf;
    long buf_filled;
    VALUE input;
    z_stream stream;
    const struct zstream_funcs {
	int (*reset)(z_streamp);
	int (*end)(z_streamp);
	int (*run)(z_streamp, int);
    } *func;
};

#define ZSTREAM_FLAG_READY      0x1
#define ZSTREAM_FLAG_IN_STREAM  0x2
#define ZSTREAM_FLAG_FINISHED   0x4
#define ZSTREAM_FLAG_CLOSING    0x8
#define ZSTREAM_FLAG_UNUSED     0x10

#define ZSTREAM_READY(z)       ((z)->flags |= ZSTREAM_FLAG_READY)
#define ZSTREAM_IS_READY(z)    ((z)->flags & ZSTREAM_FLAG_READY)
#define ZSTREAM_IS_FINISHED(z) ((z)->flags & ZSTREAM_FLAG_FINISHED)
#define ZSTREAM_IS_CLOSING(z)  ((z)->flags & ZSTREAM_FLAG_CLOSING)

/* I think that more better value should be found,
   but I gave up finding it. B) */
#define ZSTREAM_INITIAL_BUFSIZE       1024
#define ZSTREAM_AVAIL_OUT_STEP_MAX   16384
#define ZSTREAM_AVAIL_OUT_STEP_MIN    2048

static const struct zstream_funcs deflate_funcs = {
    deflateReset, deflateEnd, deflate,
};

static const struct zstream_funcs inflate_funcs = {
    inflateReset, inflateEnd, inflate,
};


static voidpf
zlib_mem_alloc(voidpf opaque, uInt items, uInt size)
{
    voidpf p = xmalloc(items * size);
    /* zlib FAQ: Valgrind (or some similar memory access checker) says that
       deflate is performing a conditional jump that depends on an
       uninitialized value.  Isn't that a bug?
       http://www.zlib.net/zlib_faq.html#faq36 */
    VALGRIND_MAKE_MEM_DEFINED(p, items * size);
    return p;
}

static void
zlib_mem_free(voidpf opaque, voidpf address)
{
    xfree(address);
}

static void
zstream_init(struct zstream *z, const struct zstream_funcs *func)
{
    z->flags = 0;
    z->buf = Qnil;
    z->buf_filled = 0;
    z->input = Qnil;
    z->stream.zalloc = zlib_mem_alloc;
    z->stream.zfree = zlib_mem_free;
    z->stream.opaque = Z_NULL;
    z->stream.msg = Z_NULL;
    z->stream.next_in = Z_NULL;
    z->stream.avail_in = 0;
    z->stream.next_out = Z_NULL;
    z->stream.avail_out = 0;
    z->func = func;
}

#define zstream_init_deflate(z)   zstream_init((z), &deflate_funcs)
#define zstream_init_inflate(z)   zstream_init((z), &inflate_funcs)

static void
zstream_expand_buffer(struct zstream *z)
{
    long inc;

    if (NIL_P(z->buf)) {
	    /* I uses rb_str_new here not rb_str_buf_new because
	       rb_str_buf_new makes a zero-length string. */
	z->buf = rb_str_new(0, ZSTREAM_INITIAL_BUFSIZE);
	z->buf_filled = 0;
	z->stream.next_out = (Bytef*)RSTRING_PTR(z->buf);
	z->stream.avail_out = ZSTREAM_INITIAL_BUFSIZE;
	RBASIC(z->buf)->klass = 0;
	return;
    }

    if (RSTRING_LEN(z->buf) - z->buf_filled >= ZSTREAM_AVAIL_OUT_STEP_MAX) {
	/* to keep other threads from freezing */
	z->stream.avail_out = ZSTREAM_AVAIL_OUT_STEP_MAX;
    }
    else {
	inc = z->buf_filled / 2;
	if (inc < ZSTREAM_AVAIL_OUT_STEP_MIN) {
	    inc = ZSTREAM_AVAIL_OUT_STEP_MIN;
	}
	rb_str_resize(z->buf, z->buf_filled + inc);
	z->stream.avail_out = (inc < ZSTREAM_AVAIL_OUT_STEP_MAX) ?
	    (int)inc : ZSTREAM_AVAIL_OUT_STEP_MAX;
    }
    z->stream.next_out = (Bytef*)RSTRING_PTR(z->buf) + z->buf_filled;
}

static void
zstream_expand_buffer_into(struct zstream *z, unsigned long size)
{
    if (NIL_P(z->buf)) {
	/* I uses rb_str_new here not rb_str_buf_new because
	   rb_str_buf_new makes a zero-length string. */
	z->buf = rb_str_new(0, size);
	z->buf_filled = 0;
	z->stream.next_out = (Bytef*)RSTRING_PTR(z->buf);
	z->stream.avail_out = MAX_UINT(size);
	RBASIC(z->buf)->klass = 0;
    }
    else if (z->stream.avail_out != size) {
	rb_str_resize(z->buf, z->buf_filled + size);
	z->stream.next_out = (Bytef*)RSTRING_PTR(z->buf) + z->buf_filled;
	z->stream.avail_out = MAX_UINT(size);
    }
}

static void
zstream_append_buffer(struct zstream *z, const Bytef *src, long len)
{
    if (NIL_P(z->buf)) {
	z->buf = rb_str_buf_new(len);
	rb_str_buf_cat(z->buf, (const char*)src, len);
	z->buf_filled = len;
	z->stream.next_out = (Bytef*)RSTRING_PTR(z->buf);
	z->stream.avail_out = 0;
	RBASIC(z->buf)->klass = 0;
	return;
    }

    if (RSTRING_LEN(z->buf) < z->buf_filled + len) {
	rb_str_resize(z->buf, z->buf_filled + len);
	z->stream.avail_out = 0;
    }
    else {
	if (z->stream.avail_out >= (uInt)len) {
	    z->stream.avail_out -= (uInt)len;
	}
	else {
	    z->stream.avail_out = 0;
	}
    }
    memcpy(RSTRING_PTR(z->buf) + z->buf_filled, src, len);
    z->buf_filled += len;
    z->stream.next_out = (Bytef*)RSTRING_PTR(z->buf) + z->buf_filled;
}

#define zstream_append_buffer2(z,v) \
    zstream_append_buffer((z),(Bytef*)RSTRING_PTR(v),RSTRING_LEN(v))

static VALUE
zstream_detach_buffer(struct zstream *z)
{
    VALUE dst;

    if (NIL_P(z->buf)) {
	dst = rb_str_new(0, 0);
    }
    else {
	dst = z->buf;
	rb_str_resize(dst, z->buf_filled);
	RBASIC(dst)->klass = rb_cString;
    }

    z->buf = Qnil;
    z->buf_filled = 0;
    z->stream.next_out = 0;
    z->stream.avail_out = 0;
    return dst;
}

static VALUE
zstream_shift_buffer(struct zstream *z, long len)
{
    VALUE dst;
    long buflen;

    if (z->buf_filled <= len) {
	return zstream_detach_buffer(z);
    }

    dst = rb_str_subseq(z->buf, 0, len);
    RBASIC(dst)->klass = rb_cString;
    z->buf_filled -= len;
    memmove(RSTRING_PTR(z->buf), RSTRING_PTR(z->buf) + len,
	    z->buf_filled);
    z->stream.next_out = (Bytef*)RSTRING_PTR(z->buf) + z->buf_filled;
    buflen = RSTRING_LEN(z->buf) - z->buf_filled;
    if (buflen > ZSTREAM_AVAIL_OUT_STEP_MAX) {
	buflen = ZSTREAM_AVAIL_OUT_STEP_MAX;
    }
    z->stream.avail_out = (uInt)buflen;

    return dst;
}

static void
zstream_buffer_ungets(struct zstream *z, const Bytef *b, unsigned long len)
{
    if (NIL_P(z->buf) || RSTRING_LEN(z->buf) - z->buf_filled == 0) {
	zstream_expand_buffer_into(z, len);
    }

    memmove(RSTRING_PTR(z->buf) + len, RSTRING_PTR(z->buf), z->buf_filled);
    memmove(RSTRING_PTR(z->buf), b, len);
    z->buf_filled+=len;
    if (z->stream.avail_out > 0) {
	if (len > z->stream.avail_out) len = z->stream.avail_out;
	z->stream.next_out+=len;
	z->stream.avail_out-=(uInt)len;
    }
}

static void
zstream_buffer_ungetbyte(struct zstream *z, int c)
{
    if (NIL_P(z->buf) || RSTRING_LEN(z->buf) - z->buf_filled == 0) {
	zstream_expand_buffer(z);
    }

    memmove(RSTRING_PTR(z->buf) + 1, RSTRING_PTR(z->buf), z->buf_filled);
    RSTRING_PTR(z->buf)[0] = (char)c;
    z->buf_filled++;
    if (z->stream.avail_out > 0) {
	z->stream.next_out++;
	z->stream.avail_out--;
    }
}

static void
zstream_append_input(struct zstream *z, const Bytef *src, long len)
{
    if (len <= 0) return;

    if (NIL_P(z->input)) {
	z->input = rb_str_buf_new(len);
	rb_str_buf_cat(z->input, (const char*)src, len);
	RBASIC(z->input)->klass = 0;
    }
    else {
	rb_str_buf_cat(z->input, (const char*)src, len);
    }
}

#define zstream_append_input2(z,v)\
    RB_GC_GUARD(v),\
    zstream_append_input((z), (Bytef*)RSTRING_PTR(v), RSTRING_LEN(v))

static void
zstream_discard_input(struct zstream *z, long len)
{
    if (NIL_P(z->input) || RSTRING_LEN(z->input) <= len) {
	z->input = Qnil;
    }
    else {
	memmove(RSTRING_PTR(z->input), RSTRING_PTR(z->input) + len,
		RSTRING_LEN(z->input) - len);
	rb_str_resize(z->input, RSTRING_LEN(z->input) - len);
    }
}

static void
zstream_reset_input(struct zstream *z)
{
    z->input = Qnil;
}

static void
zstream_passthrough_input(struct zstream *z)
{
    if (!NIL_P(z->input)) {
	zstream_append_buffer2(z, z->input);
	z->input = Qnil;
    }
}

static VALUE
zstream_detach_input(struct zstream *z)
{
    VALUE dst;

    if (NIL_P(z->input)) {
	dst = rb_str_new(0, 0);
    }
    else {
	dst = z->input;
	RBASIC(dst)->klass = rb_cString;
    }
    z->input = Qnil;
    RBASIC(dst)->klass = rb_cString;
    return dst;
}

static void
zstream_reset(struct zstream *z)
{
    int err;

    err = z->func->reset(&z->stream);
    if (err != Z_OK) {
	raise_zlib_error(err, z->stream.msg);
    }
    z->flags = ZSTREAM_FLAG_READY;
    z->buf = Qnil;
    z->buf_filled = 0;
    z->stream.next_out = 0;
    z->stream.avail_out = 0;
    zstream_reset_input(z);
}

static VALUE
zstream_end(struct zstream *z)
{
    int err;

    if (!ZSTREAM_IS_READY(z)) {
	rb_warning("attempt to close uninitialized zstream; ignored.");
	return Qnil;
    }
    if (z->flags & ZSTREAM_FLAG_IN_STREAM) {
	rb_warning("attempt to close unfinished zstream; reset forced.");
	zstream_reset(z);
    }

    zstream_reset_input(z);
    err = z->func->end(&z->stream);
    if (err != Z_OK) {
	raise_zlib_error(err, z->stream.msg);
    }
    z->flags = 0;
    return Qnil;
}

static void
zstream_run(struct zstream *z, Bytef *src, long len, int flush)
{
    uInt n;
    int err;
    volatile VALUE guard = Qnil;

    if (NIL_P(z->input) && len == 0) {
	z->stream.next_in = (Bytef*)"";
	z->stream.avail_in = 0;
    }
    else {
	zstream_append_input(z, src, len);
	z->stream.next_in = (Bytef*)RSTRING_PTR(z->input);
	z->stream.avail_in = MAX_UINT(RSTRING_LEN(z->input));
	/* keep reference to `z->input' so as not to be garbage collected
	   after zstream_reset_input() and prevent `z->stream.next_in'
	   from dangling. */
	guard = z->input;
    }

    if (z->stream.avail_out == 0) {
	zstream_expand_buffer(z);
    }

    for (;;) {
	/* VC allocates err and guard to same address.  accessing err and guard
	   in same scope prevents it. */
	RB_GC_GUARD(guard);
	n = z->stream.avail_out;
	err = z->func->run(&z->stream, flush);
	z->buf_filled += n - z->stream.avail_out;
	rb_thread_schedule();

	if (err == Z_STREAM_END) {
	    z->flags &= ~ZSTREAM_FLAG_IN_STREAM;
	    z->flags |= ZSTREAM_FLAG_FINISHED;
	    break;
	}
	if (err != Z_OK) {
	    if (flush != Z_FINISH && err == Z_BUF_ERROR
		&& z->stream.avail_out > 0) {
		z->flags |= ZSTREAM_FLAG_IN_STREAM;
		break;
	    }
	    zstream_reset_input(z);
	    if (z->stream.avail_in > 0) {
		zstream_append_input(z, z->stream.next_in, z->stream.avail_in);
	    }
	    raise_zlib_error(err, z->stream.msg);
	}
	if (z->stream.avail_out > 0) {
	    z->flags |= ZSTREAM_FLAG_IN_STREAM;
	    break;
	}
	zstream_expand_buffer(z);
    }

    zstream_reset_input(z);
    if (z->stream.avail_in > 0) {
	zstream_append_input(z, z->stream.next_in, z->stream.avail_in);
        guard = Qnil; /* prevent tail call to make guard effective */
    }
}

static VALUE
zstream_sync(struct zstream *z, Bytef *src, long len)
{
    VALUE rest;
    int err;

    if (!NIL_P(z->input)) {
	z->stream.next_in = (Bytef*)RSTRING_PTR(z->input);
	z->stream.avail_in = MAX_UINT(RSTRING_LEN(z->input));
	err = inflateSync(&z->stream);
	if (err == Z_OK) {
	    zstream_discard_input(z,
				  RSTRING_LEN(z->input) - z->stream.avail_in);
	    zstream_append_input(z, src, len);
	    return Qtrue;
	}
	zstream_reset_input(z);
	if (err != Z_DATA_ERROR) {
	    rest = rb_str_new((char*)z->stream.next_in, z->stream.avail_in);
	    raise_zlib_error(err, z->stream.msg);
	}
    }

    if (len <= 0) return Qfalse;

    z->stream.next_in = src;
    z->stream.avail_in = MAX_UINT(len);
    err = inflateSync(&z->stream);
    if (err == Z_OK) {
	zstream_append_input(z, z->stream.next_in, z->stream.avail_in);
	return Qtrue;
    }
    if (err != Z_DATA_ERROR) {
	rest = rb_str_new((char*)z->stream.next_in, z->stream.avail_in);
	raise_zlib_error(err, z->stream.msg);
    }
    return Qfalse;
}

static void
zstream_mark(struct zstream *z)
{
    rb_gc_mark(z->buf);
    rb_gc_mark(z->input);
}

static void
zstream_finalize(struct zstream *z)
{
    int err = z->func->end(&z->stream);
    if (err == Z_STREAM_ERROR)
	finalizer_warn("the stream state was inconsistent.");
    if (err == Z_DATA_ERROR)
	finalizer_warn("the stream was freed prematurely.");
}

static void
zstream_free(struct zstream *z)
{
    if (ZSTREAM_IS_READY(z)) {
	zstream_finalize(z);
    }
    xfree(z);
}

static VALUE
zstream_new(VALUE klass, const struct zstream_funcs *funcs)
{
    VALUE obj;
    struct zstream *z;

    obj = Data_Make_Struct(klass, struct zstream,
			   zstream_mark, zstream_free, z);
    zstream_init(z, funcs);
    return obj;
}

#define zstream_deflate_new(klass)  zstream_new((klass), &deflate_funcs)
#define zstream_inflate_new(klass)  zstream_new((klass), &inflate_funcs)

static struct zstream *
get_zstream(VALUE obj)
{
    struct zstream *z;

    Data_Get_Struct(obj, struct zstream, z);
    if (!ZSTREAM_IS_READY(z)) {
	rb_raise(cZError, "stream is not ready");
    }
    return z;
}


/* ------------------------------------------------------------------------- */

/*
 * Document-class: Zlib::ZStream
 *
 * Zlib::ZStream is the abstract class for the stream which handles the
 * compressed data. The operations are defined in the subclasses:
 * Zlib::Deflate for compression, and Zlib::Inflate for decompression.
 *
 * An instance of Zlib::ZStream has one stream (struct zstream in the source)
 * and two variable-length buffers which associated to the input (next_in) of
 * the stream and the output (next_out) of the stream. In this document,
 * "input buffer" means the buffer for input, and "output buffer" means the
 * buffer for output.
 *
 * Data input into an instance of Zlib::ZStream are temporally stored into
 * the end of input buffer, and then data in input buffer are processed from
 * the beginning of the buffer until no more output from the stream is
 * produced (i.e. until avail_out > 0 after processing).  During processing,
 * output buffer is allocated and expanded automatically to hold all output
 * data.
 *
 * Some particular instance methods consume the data in output buffer and
 * return them as a String.
 *
 * Here is an ascii art for describing above:
 *
 *    +================ an instance of Zlib::ZStream ================+
 *    ||                                                            ||
 *    ||     +--------+          +-------+          +--------+      ||
 *    ||  +--| output |<---------|zstream|<---------| input  |<--+  ||
 *    ||  |  | buffer |  next_out+-------+next_in   | buffer |   |  ||
 *    ||  |  +--------+                             +--------+   |  ||
 *    ||  |                                                      |  ||
 *    +===|======================================================|===+
 *        |                                                      |
 *        v                                                      |
 *    "output data"                                         "input data"
 *
 * If an error occurs during processing input buffer, an exception which is a
 * subclass of Zlib::Error is raised.  At that time, both input and output
 * buffer keep their conditions at the time when the error occurs.
 *
 * == Method Catalogue
 *
 * Many of the methods in this class are fairly low-level and unlikely to be
 * of interest to users.  In fact, users are unlikely to use this class
 * directly; rather they will be interested in Zlib::Inflate and
 * Zlib::Deflate.
 *
 * The higher level methods are listed below.
 *
 * - #total_in
 * - #total_out
 * - #data_type
 * - #adler
 * - #reset
 * - #finish
 * - #finished?
 * - #close
 * - #closed?
 */

/*
 * Closes the stream. All operations on the closed stream will raise an
 * exception.
 */
static VALUE
rb_zstream_end(VALUE obj)
{
    zstream_end(get_zstream(obj));
    return Qnil;
}

/*
 * Resets and initializes the stream. All data in both input and output buffer
 * are discarded.
 */
static VALUE
rb_zstream_reset(VALUE obj)
{
    zstream_reset(get_zstream(obj));
    return Qnil;
}

/*
 * Finishes the stream and flushes output buffer. See Zlib::Deflate#finish and
 * Zlib::Inflate#finish for details of this behavior.
 */
static VALUE
rb_zstream_finish(VALUE obj)
{
    struct zstream *z = get_zstream(obj);
    VALUE dst;

    zstream_run(z, (Bytef*)"", 0, Z_FINISH);
    dst = zstream_detach_buffer(z);

    OBJ_INFECT(dst, obj);
    return dst;
}

/*
 * Flushes input buffer and returns all data in that buffer.
 */
static VALUE
rb_zstream_flush_next_in(VALUE obj)
{
    struct zstream *z;
    VALUE dst;

    Data_Get_Struct(obj, struct zstream, z);
    dst = zstream_detach_input(z);
    OBJ_INFECT(dst, obj);
    return dst;
}

/*
 * Flushes output buffer and returns all data in that buffer.
 */
static VALUE
rb_zstream_flush_next_out(VALUE obj)
{
    struct zstream *z;
    VALUE dst;

    Data_Get_Struct(obj, struct zstream, z);
    dst = zstream_detach_buffer(z);
    OBJ_INFECT(dst, obj);
    return dst;
}

/*
 * Returns number of bytes of free spaces in output buffer.  Because the free
 * space is allocated automatically, this method returns 0 normally.
 */
static VALUE
rb_zstream_avail_out(VALUE obj)
{
    struct zstream *z;
    Data_Get_Struct(obj, struct zstream, z);
    return rb_uint2inum(z->stream.avail_out);
}

/*
 * Allocates +size+ bytes of free space in the output buffer. If there are more
 * than +size+ bytes already in the buffer, the buffer is truncated. Because
 * free space is allocated automatically, you usually don't need to use this
 * method.
 */
static VALUE
rb_zstream_set_avail_out(VALUE obj, VALUE size)
{
    struct zstream *z = get_zstream(obj);

    Check_Type(size, T_FIXNUM);
    zstream_expand_buffer_into(z, FIX2INT(size));
    return size;
}

/*
 * Returns bytes of data in the input buffer. Normally, returns 0.
 */
static VALUE
rb_zstream_avail_in(VALUE obj)
{
    struct zstream *z;
    Data_Get_Struct(obj, struct zstream, z);
    return INT2FIX(NIL_P(z->input) ? 0 : (int)(RSTRING_LEN(z->input)));
}

/*
 * Returns the total bytes of the input data to the stream.  FIXME
 */
static VALUE
rb_zstream_total_in(VALUE obj)
{
    return rb_uint2inum(get_zstream(obj)->stream.total_in);
}

/*
 * Returns the total bytes of the output data from the stream.  FIXME
 */
static VALUE
rb_zstream_total_out(VALUE obj)
{
    return rb_uint2inum(get_zstream(obj)->stream.total_out);
}

/*
 * Guesses the type of the data which have been inputed into the stream. The
 * returned value is either <tt>Zlib::BINARY</tt>, <tt>Zlib::ASCII</tt>, or
 * <tt>Zlib::UNKNOWN</tt>.
 */
static VALUE
rb_zstream_data_type(VALUE obj)
{
    return INT2FIX(get_zstream(obj)->stream.data_type);
}

/*
 * Returns the adler-32 checksum.
 */
static VALUE
rb_zstream_adler(VALUE obj)
{
	return rb_uint2inum(get_zstream(obj)->stream.adler);
}

/*
 * Returns true if the stream is finished.
 */
static VALUE
rb_zstream_finished_p(VALUE obj)
{
    return ZSTREAM_IS_FINISHED(get_zstream(obj)) ? Qtrue : Qfalse;
}

/*
 * Returns true if the stream is closed.
 */
static VALUE
rb_zstream_closed_p(VALUE obj)
{
    struct zstream *z;
    Data_Get_Struct(obj, struct zstream, z);
    return ZSTREAM_IS_READY(z) ? Qfalse : Qtrue;
}


/* ------------------------------------------------------------------------- */

/*
 * Document-class: Zlib::Deflate
 *
 * Zlib::Deflate is the class for compressing data.  See Zlib::Stream for more
 * information.
 */

#define FIXNUMARG(val, ifnil) \
    (NIL_P((val)) ? (ifnil) \
    : ((void)Check_Type((val), T_FIXNUM), FIX2INT((val))))

#define ARG_LEVEL(val)     FIXNUMARG((val), Z_DEFAULT_COMPRESSION)
#define ARG_WBITS(val)     FIXNUMARG((val), MAX_WBITS)
#define ARG_MEMLEVEL(val)  FIXNUMARG((val), DEF_MEM_LEVEL)
#define ARG_STRATEGY(val)  FIXNUMARG((val), Z_DEFAULT_STRATEGY)
#define ARG_FLUSH(val)     FIXNUMARG((val), Z_NO_FLUSH)


static VALUE
rb_deflate_s_allocate(VALUE klass)
{
    return zstream_deflate_new(klass);
}

/*
 * call-seq: Zlib::Deflate.new(level=nil, windowBits=nil, memlevel=nil, strategy=nil)
 *
 * Creates a new deflate stream for compression. See zlib.h for details of
 * each argument. If an argument is nil, the default value of that argument is
 * used.
 *
 * TODO: document better!
 */
static VALUE
rb_deflate_initialize(int argc, VALUE *argv, VALUE obj)
{
    struct zstream *z;
    VALUE level, wbits, memlevel, strategy;
    int err;

    rb_scan_args(argc, argv, "04", &level, &wbits, &memlevel, &strategy);
    Data_Get_Struct(obj, struct zstream, z);

    err = deflateInit2(&z->stream, ARG_LEVEL(level), Z_DEFLATED,
		       ARG_WBITS(wbits), ARG_MEMLEVEL(memlevel),
		       ARG_STRATEGY(strategy));
    if (err != Z_OK) {
	raise_zlib_error(err, z->stream.msg);
    }
    ZSTREAM_READY(z);

    return obj;
}

/*
 * Duplicates the deflate stream.
 */
static VALUE
rb_deflate_init_copy(VALUE self, VALUE orig)
{
    struct zstream *z1, *z2;
    int err;

    Data_Get_Struct(self, struct zstream, z1);
    z2 = get_zstream(orig);

    err = deflateCopy(&z1->stream, &z2->stream);
    if (err != Z_OK) {
	raise_zlib_error(err, 0);
    }
    z1->input = NIL_P(z2->input) ? Qnil : rb_str_dup(z2->input);
    z1->buf   = NIL_P(z2->buf)   ? Qnil : rb_str_dup(z2->buf);
    z1->buf_filled = z2->buf_filled;
    z1->flags = z2->flags;

    return self;
}

static VALUE
deflate_run(VALUE args)
{
    struct zstream *z = (struct zstream*)((VALUE*)args)[0];
    VALUE src = ((VALUE*)args)[1];

    zstream_run(z, (Bytef*)RSTRING_PTR(src), RSTRING_LEN(src), Z_FINISH);
    return zstream_detach_buffer(z);
}

/*
 * call-seq: Zlib.deflate(string[, level])
 *           Zlib::Deflate.deflate(string[, level])
 *
 * Compresses the given +string+. Valid values of level are
 * <tt>Zlib::NO_COMPRESSION</tt>, <tt>Zlib::BEST_SPEED</tt>,
 * <tt>Zlib::BEST_COMPRESSION</tt>, <tt>Zlib::DEFAULT_COMPRESSION</tt>, and an
 * integer from 0 to 9 (the default is 6).
 *
 * This method is almost equivalent to the following code:
 *
 *   def deflate(string, level)
 *     z = Zlib::Deflate.new(level)
 *     dst = z.deflate(string, Zlib::FINISH)
 *     z.close
 *     dst
 *   end
 *
 * See also Zlib.inflate
 *
 */
static VALUE
rb_deflate_s_deflate(int argc, VALUE *argv, VALUE klass)
{
    struct zstream z;
    VALUE src, level, dst, args[2];
    int err, lev;

    rb_scan_args(argc, argv, "11", &src, &level);

    lev = ARG_LEVEL(level);
    StringValue(src);
    zstream_init_deflate(&z);
    err = deflateInit(&z.stream, lev);
    if (err != Z_OK) {
	raise_zlib_error(err, z.stream.msg);
    }
    ZSTREAM_READY(&z);

    args[0] = (VALUE)&z;
    args[1] = src;
    dst = rb_ensure(deflate_run, (VALUE)args, zstream_end, (VALUE)&z);

    OBJ_INFECT(dst, src);
    return dst;
}

static void
do_deflate(struct zstream *z, VALUE src, int flush)
{
    if (NIL_P(src)) {
	zstream_run(z, (Bytef*)"", 0, Z_FINISH);
	return;
    }
    StringValue(src);
    if (flush != Z_NO_FLUSH || RSTRING_LEN(src) > 0) { /* prevent BUF_ERROR */
	zstream_run(z, (Bytef*)RSTRING_PTR(src), RSTRING_LEN(src), flush);
    }
}

/*
 * call-seq: deflate(string[, flush])
 *
 * Inputs +string+ into the deflate stream and returns the output from the
 * stream.  On calling this method, both the input and the output buffers of
 * the stream are flushed. If +string+ is nil, this method finishes the
 * stream, just like Zlib::ZStream#finish.
 *
 * The value of +flush+ should be either <tt>Zlib::NO_FLUSH</tt>,
 * <tt>Zlib::SYNC_FLUSH</tt>, <tt>Zlib::FULL_FLUSH</tt>, or
 * <tt>Zlib::FINISH</tt>. See zlib.h for details.
 *
 * TODO: document better!
 */
static VALUE
rb_deflate_deflate(int argc, VALUE *argv, VALUE obj)
{
    struct zstream *z = get_zstream(obj);
    VALUE src, flush, dst;

    rb_scan_args(argc, argv, "11", &src, &flush);
    OBJ_INFECT(obj, src);
    do_deflate(z, src, ARG_FLUSH(flush));
    dst = zstream_detach_buffer(z);

    OBJ_INFECT(dst, obj);
    return dst;
}

/*
 * call-seq: << string
 *
 * Inputs +string+ into the deflate stream just like Zlib::Deflate#deflate, but
 * returns the Zlib::Deflate object itself.  The output from the stream is
 * preserved in output buffer.
 */
static VALUE
rb_deflate_addstr(VALUE obj, VALUE src)
{
    OBJ_INFECT(obj, src);
    do_deflate(get_zstream(obj), src, Z_NO_FLUSH);
    return obj;
}

/*
 * call-seq: flush(flush)
 *
 * This method is equivalent to <tt>deflate('', flush)</tt>.  If flush is omitted,
 * <tt>Zlib::SYNC_FLUSH</tt> is used as flush.  This method is just provided
 * to improve the readability of your Ruby program.
 *
 * TODO: document better!
 */
static VALUE
rb_deflate_flush(int argc, VALUE *argv, VALUE obj)
{
    struct zstream *z = get_zstream(obj);
    VALUE v_flush, dst;
    int flush;

    rb_scan_args(argc, argv, "01", &v_flush);
    flush = FIXNUMARG(v_flush, Z_SYNC_FLUSH);
    if (flush != Z_NO_FLUSH) {  /* prevent Z_BUF_ERROR */
	zstream_run(z, (Bytef*)"", 0, flush);
    }
    dst = zstream_detach_buffer(z);

    OBJ_INFECT(dst, obj);
    return dst;
}

/*
 * call-seq: params(level, strategy)
 *
 * Changes the parameters of the deflate stream. See zlib.h for details. The
 * output from the stream by changing the params is preserved in output
 * buffer.
 *
 * TODO: document better!
 */
static VALUE
rb_deflate_params(VALUE obj, VALUE v_level, VALUE v_strategy)
{
    struct zstream *z = get_zstream(obj);
    int level, strategy;
    int err;
    uInt n;

    level = ARG_LEVEL(v_level);
    strategy = ARG_STRATEGY(v_strategy);

    n = z->stream.avail_out;
    err = deflateParams(&z->stream, level, strategy);
    z->buf_filled += n - z->stream.avail_out;
    while (err == Z_BUF_ERROR) {
	rb_warning("deflateParams() returned Z_BUF_ERROR");
	zstream_expand_buffer(z);
	n = z->stream.avail_out;
	err = deflateParams(&z->stream, level, strategy);
	z->buf_filled += n - z->stream.avail_out;
    }
    if (err != Z_OK) {
	raise_zlib_error(err, z->stream.msg);
    }

    return Qnil;
}

/*
 * call-seq: set_dictionary(string)
 *
 * Sets the preset dictionary and returns +string+. This method is available
 * just only after Zlib::Deflate.new or Zlib::ZStream#reset method was called.
 * See zlib.h for details.
 *
 * TODO: document better!
 */
static VALUE
rb_deflate_set_dictionary(VALUE obj, VALUE dic)
{
    struct zstream *z = get_zstream(obj);
    VALUE src = dic;
    int err;

    OBJ_INFECT(obj, dic);
    StringValue(src);
    err = deflateSetDictionary(&z->stream,
			       (Bytef*)RSTRING_PTR(src), RSTRING_LENINT(src));
    if (err != Z_OK) {
	raise_zlib_error(err, z->stream.msg);
    }

    return dic;
}


/* ------------------------------------------------------------------------- */

/*
 * Document-class: Zlib::Inflate
 *
 * Zlib:Inflate is the class for decompressing compressed data.  Unlike
 * Zlib::Deflate, an instance of this class is not able to duplicate (clone,
 * dup) itself.
 */



static VALUE
rb_inflate_s_allocate(VALUE klass)
{
    return zstream_inflate_new(klass);
}

/*
 * call-seq: Zlib::Inflate.new(window_bits)
 *
 * Creates a new inflate stream for decompression. See zlib.h for details
 * of the argument.  If +window_bits+ is +nil+, the default value is used.
 *
 * TODO: document better!
 */
static VALUE
rb_inflate_initialize(int argc, VALUE *argv, VALUE obj)
{
    struct zstream *z;
    VALUE wbits;
    int err;

    rb_scan_args(argc, argv, "01", &wbits);
    Data_Get_Struct(obj, struct zstream, z);

    err = inflateInit2(&z->stream, ARG_WBITS(wbits));
    if (err != Z_OK) {
	raise_zlib_error(err, z->stream.msg);
    }
    ZSTREAM_READY(z);

    return obj;
}

static VALUE
inflate_run(VALUE args)
{
    struct zstream *z = (struct zstream*)((VALUE*)args)[0];
    VALUE src = ((VALUE*)args)[1];

    zstream_run(z, (Bytef*)RSTRING_PTR(src), RSTRING_LEN(src), Z_SYNC_FLUSH);
    zstream_run(z, (Bytef*)"", 0, Z_FINISH);  /* for checking errors */
    return zstream_detach_buffer(z);
}

/*
 * call-seq: Zlib.inflate(string)
 *           Zlib::Inflate.inflate(string)
 *
 * Decompresses +string+. Raises a Zlib::NeedDict exception if a preset
 * dictionary is needed for decompression.
 *
 * This method is almost equivalent to the following code:
 *
 *   def inflate(string)
 *     zstream = Zlib::Inflate.new
 *     buf = zstream.inflate(string)
 *     zstream.finish
 *     zstream.close
 *     buf
 *   end
 *
 * See also Zlib.deflate
 *
 */
static VALUE
rb_inflate_s_inflate(VALUE obj, VALUE src)
{
    struct zstream z;
    VALUE dst, args[2];
    int err;

    StringValue(src);
    zstream_init_inflate(&z);
    err = inflateInit(&z.stream);
    if (err != Z_OK) {
	raise_zlib_error(err, z.stream.msg);
    }
    ZSTREAM_READY(&z);

    args[0] = (VALUE)&z;
    args[1] = src;
    dst = rb_ensure(inflate_run, (VALUE)args, zstream_end, (VALUE)&z);

    OBJ_INFECT(dst, src);
    return dst;
}

static void
do_inflate(struct zstream *z, VALUE src)
{
    if (NIL_P(src)) {
	zstream_run(z, (Bytef*)"", 0, Z_FINISH);
	return;
    }
    StringValue(src);
    if (RSTRING_LEN(src) > 0) { /* prevent Z_BUF_ERROR */
	zstream_run(z, (Bytef*)RSTRING_PTR(src), RSTRING_LEN(src), Z_SYNC_FLUSH);
    }
}

/*
 * call-seq: inflate(string)
 *
 * Inputs +string+ into the inflate stream and returns the output from the
 * stream.  Calling this method, both the input and the output buffer of the
 * stream are flushed.  If string is +nil+, this method finishes the stream,
 * just like Zlib::ZStream#finish.
 *
 * Raises a Zlib::NeedDict exception if a preset dictionary is needed to
 * decompress.  Set the dictionary by Zlib::Inflate#set_dictionary and then
 * call this method again with an empty string.  (<i>???</i>)
 *
 * TODO: document better!
 */
static VALUE
rb_inflate_inflate(VALUE obj, VALUE src)
{
    struct zstream *z = get_zstream(obj);
    VALUE dst;

    OBJ_INFECT(obj, src);

    if (ZSTREAM_IS_FINISHED(z)) {
	if (NIL_P(src)) {
	    dst = zstream_detach_buffer(z);
	}
	else {
	    StringValue(src);
	    zstream_append_buffer2(z, src);
	    dst = rb_str_new(0, 0);
	}
    }
    else {
	do_inflate(z, src);
	dst = zstream_detach_buffer(z);
	if (ZSTREAM_IS_FINISHED(z)) {
	    zstream_passthrough_input(z);
	}
    }

    OBJ_INFECT(dst, obj);
    return dst;
}

/*
 * call-seq: << string
 *
 * Inputs +string+ into the inflate stream just like Zlib::Inflate#inflate, but
 * returns the Zlib::Inflate object itself.  The output from the stream is
 * preserved in output buffer.
 */
static VALUE
rb_inflate_addstr(VALUE obj, VALUE src)
{
    struct zstream *z = get_zstream(obj);

    OBJ_INFECT(obj, src);

    if (ZSTREAM_IS_FINISHED(z)) {
	if (!NIL_P(src)) {
	    StringValue(src);
	    zstream_append_buffer2(z, src);
	}
    }
    else {
	do_inflate(z, src);
	if (ZSTREAM_IS_FINISHED(z)) {
	    zstream_passthrough_input(z);
	}
    }

    return obj;
}

/*
 * call-seq: sync(string)
 *
 * Inputs +string+ into the end of input buffer and skips data until a full
 * flush point can be found.  If the point is found in the buffer, this method
 * flushes the buffer and returns false.  Otherwise it returns +true+ and the
 * following data of full flush point is preserved in the buffer.
 */
static VALUE
rb_inflate_sync(VALUE obj, VALUE src)
{
    struct zstream *z = get_zstream(obj);

    OBJ_INFECT(obj, src);
    StringValue(src);
    return zstream_sync(z, (Bytef*)RSTRING_PTR(src), RSTRING_LEN(src));
}

/*
 * Quoted verbatim from original documentation:
 *
 *   What is this?
 *
 * <tt>:)</tt>
 */
static VALUE
rb_inflate_sync_point_p(VALUE obj)
{
    struct zstream *z = get_zstream(obj);
    int err;

    err = inflateSyncPoint(&z->stream);
    if (err == 1) {
	return Qtrue;
    }
    if (err != Z_OK) {
	raise_zlib_error(err, z->stream.msg);
    }
    return Qfalse;
}

/*
 * Sets the preset dictionary and returns +string+.  This method is available just
 * only after a Zlib::NeedDict exception was raised.  See zlib.h for details.
 *
 * TODO: document better!
 */
static VALUE
rb_inflate_set_dictionary(VALUE obj, VALUE dic)
{
    struct zstream *z = get_zstream(obj);
    VALUE src = dic;
    int err;

    OBJ_INFECT(obj, dic);
    StringValue(src);
    err = inflateSetDictionary(&z->stream,
			       (Bytef*)RSTRING_PTR(src), RSTRING_LENINT(src));
    if (err != Z_OK) {
	raise_zlib_error(err, z->stream.msg);
    }

    return dic;
}



#if GZIP_SUPPORT

/* NOTE: Features for gzip files of Ruby/zlib are written from scratch
 *       and using undocumented feature of zlib, negative wbits.
 *       I don't think gzFile APIs of zlib are good for Ruby.
 */

/*------- .gz file header --------*/

#define GZ_MAGIC1             0x1f
#define GZ_MAGIC2             0x8b
#define GZ_METHOD_DEFLATE     8
#define GZ_FLAG_MULTIPART     0x2
#define GZ_FLAG_EXTRA         0x4
#define GZ_FLAG_ORIG_NAME     0x8
#define GZ_FLAG_COMMENT       0x10
#define GZ_FLAG_ENCRYPT       0x20
#define GZ_FLAG_UNKNOWN_MASK  0xc0

#define GZ_EXTRAFLAG_FAST     0x4
#define GZ_EXTRAFLAG_SLOW     0x2

/* from zutil.h */
#define OS_MSDOS    0x00
#define OS_AMIGA    0x01
#define OS_VMS      0x02
#define OS_UNIX     0x03
#define OS_ATARI    0x05
#define OS_OS2      0x06
#define OS_MACOS    0x07
#define OS_TOPS20   0x0a
#define OS_WIN32    0x0b

#define OS_VMCMS    0x04
#define OS_ZSYSTEM  0x08
#define OS_CPM      0x09
#define OS_QDOS     0x0c
#define OS_RISCOS   0x0d
#define OS_UNKNOWN  0xff

#ifndef OS_CODE
#define OS_CODE  OS_UNIX
#endif

static ID id_write, id_read, id_readpartial, id_flush, id_seek, id_close, id_path, id_input;
static VALUE cGzError, cNoFooter, cCRCError, cLengthError;



/*-------- gzfile internal APIs --------*/

struct gzfile {
    struct zstream z;
    VALUE io;
    int level;
    time_t mtime;       /* for header */
    int os_code;        /* for header */
    VALUE orig_name;    /* for header; must be a String */
    VALUE comment;      /* for header; must be a String */
    unsigned long crc;
    int lineno;
    long ungetc;
    void (*end)(struct gzfile *);
    rb_encoding *enc;
    rb_encoding *enc2;
    rb_econv_t *ec;
    int ecflags;
    VALUE ecopts;
    char *cbuf;
    VALUE path;
};
#define GZFILE_CBUF_CAPA 10

#define GZFILE_FLAG_SYNC             ZSTREAM_FLAG_UNUSED
#define GZFILE_FLAG_HEADER_FINISHED  (ZSTREAM_FLAG_UNUSED << 1)
#define GZFILE_FLAG_FOOTER_FINISHED  (ZSTREAM_FLAG_UNUSED << 2)

#define GZFILE_IS_FINISHED(gz) \
    (ZSTREAM_IS_FINISHED(&(gz)->z) && (gz)->z.buf_filled == 0)

#define GZFILE_READ_SIZE  2048


static void
gzfile_mark(struct gzfile *gz)
{
    rb_gc_mark(gz->io);
    rb_gc_mark(gz->orig_name);
    rb_gc_mark(gz->comment);
    zstream_mark(&gz->z);
    rb_gc_mark(gz->ecopts);
    rb_gc_mark(gz->path);
}

static void
gzfile_free(struct gzfile *gz)
{
    struct zstream *z = &gz->z;

    if (ZSTREAM_IS_READY(z)) {
	if (z->func == &deflate_funcs) {
	    finalizer_warn("Zlib::GzipWriter object must be closed explicitly.");
	}
	zstream_finalize(z);
    }
    if (gz->cbuf) {
	xfree(gz->cbuf);
    }
    xfree(gz);
}

static VALUE
gzfile_new(klass, funcs, endfunc)
    VALUE klass;
    const struct zstream_funcs *funcs;
    void (*endfunc)(struct gzfile *);
{
    VALUE obj;
    struct gzfile *gz;

    obj = Data_Make_Struct(klass, struct gzfile, gzfile_mark, gzfile_free, gz);
    zstream_init(&gz->z, funcs);
    gz->io = Qnil;
    gz->level = 0;
    gz->mtime = 0;
    gz->os_code = OS_CODE;
    gz->orig_name = Qnil;
    gz->comment = Qnil;
    gz->crc = crc32(0, Z_NULL, 0);
    gz->lineno = 0;
    gz->ungetc = 0;
    gz->end = endfunc;
    gz->enc = rb_default_external_encoding();
    gz->enc2 = 0;
    gz->ec = NULL;
    gz->ecflags = 0;
    gz->ecopts = Qnil;
    gz->cbuf = 0;
    gz->path = Qnil;

    return obj;
}

#define gzfile_writer_new(gz) gzfile_new((gz),&deflate_funcs,gzfile_writer_end)
#define gzfile_reader_new(gz) gzfile_new((gz),&inflate_funcs,gzfile_reader_end)

static void
gzfile_reset(struct gzfile *gz)
{
    zstream_reset(&gz->z);
    gz->crc = crc32(0, Z_NULL, 0);
    gz->lineno = 0;
    gz->ungetc = 0;
    if (gz->ec) {
	rb_econv_close(gz->ec);
	gz->ec = rb_econv_open_opts(gz->enc2->name, gz->enc->name,
				    gz->ecflags, gz->ecopts);
    }
}

static void
gzfile_close(struct gzfile *gz, int closeflag)
{
    VALUE io = gz->io;

    gz->end(gz);
    gz->io = Qnil;
    gz->orig_name = Qnil;
    gz->comment = Qnil;
    if (closeflag && rb_respond_to(io, id_close)) {
	rb_funcall(io, id_close, 0);
    }
}

static void
gzfile_write_raw(struct gzfile *gz)
{
    VALUE str;

    if (gz->z.buf_filled > 0) {
	str = zstream_detach_buffer(&gz->z);
	OBJ_TAINT(str);  /* for safe */
	rb_funcall(gz->io, id_write, 1, str);
	if ((gz->z.flags & GZFILE_FLAG_SYNC)
	    && rb_respond_to(gz->io, id_flush))
	    rb_funcall(gz->io, id_flush, 0);
    }
}

static VALUE
gzfile_read_raw_partial(VALUE arg)
{
    struct gzfile *gz = (struct gzfile*)arg;
    VALUE str;

    str = rb_funcall(gz->io, id_readpartial, 1, INT2FIX(GZFILE_READ_SIZE));
    Check_Type(str, T_STRING);
    return str;
}

static VALUE
gzfile_read_raw_rescue(VALUE arg)
{
    struct gzfile *gz = (struct gzfile*)arg;
    VALUE str = Qnil;
    if (rb_obj_is_kind_of(rb_errinfo(), rb_eNoMethodError)) {
        str = rb_funcall(gz->io, id_read, 1, INT2FIX(GZFILE_READ_SIZE));
        if (!NIL_P(str)) {
            Check_Type(str, T_STRING);
        }
    }
    return str; /* return nil when EOFError */
}

static VALUE
gzfile_read_raw(struct gzfile *gz)
{
    return rb_rescue2(gzfile_read_raw_partial, (VALUE)gz,
                      gzfile_read_raw_rescue, (VALUE)gz,
                      rb_eEOFError, rb_eNoMethodError, (VALUE)0);
}

static int
gzfile_read_raw_ensure(struct gzfile *gz, long size)
{
    VALUE str;

    while (NIL_P(gz->z.input) || RSTRING_LEN(gz->z.input) < size) {
	str = gzfile_read_raw(gz);
	if (NIL_P(str)) return 0;
	zstream_append_input2(&gz->z, str);
    }
    return 1;
}

static char *
gzfile_read_raw_until_zero(struct gzfile *gz, long offset)
{
    VALUE str;
    char *p;

    for (;;) {
	p = memchr(RSTRING_PTR(gz->z.input) + offset, '\0',
		   RSTRING_LEN(gz->z.input) - offset);
	if (p) break;
	str = gzfile_read_raw(gz);
	if (NIL_P(str)) {
	    rb_raise(cGzError, "unexpected end of file");
	}
	offset = RSTRING_LEN(gz->z.input);
	zstream_append_input2(&gz->z, str);
    }
    return p;
}

static unsigned int
gzfile_get16(const unsigned char *src)
{
    unsigned int n;
    n  = *(src++) & 0xff;
    n |= (*(src++) & 0xff) << 8;
    return n;
}

static unsigned long
gzfile_get32(const unsigned char *src)
{
    unsigned long n;
    n  = *(src++) & 0xff;
    n |= (*(src++) & 0xff) << 8;
    n |= (*(src++) & 0xff) << 16;
    n |= (*(src++) & 0xffU) << 24;
    return n;
}

static void
gzfile_set32(unsigned long n, unsigned char *dst)
{
    *(dst++) = n & 0xff;
    *(dst++) = (n >> 8) & 0xff;
    *(dst++) = (n >> 16) & 0xff;
    *dst     = (n >> 24) & 0xff;
}

static void
gzfile_raise(struct gzfile *gz, VALUE klass, const char *message)
{
    VALUE exc = rb_exc_new2(klass, message);
    if (!NIL_P(gz->z.input)) {
	rb_ivar_set(exc, id_input, rb_str_resurrect(gz->z.input));
    }
    rb_exc_raise(exc);
}

static VALUE
gzfile_error_inspect(VALUE error)
{
    VALUE str = rb_call_super(0, 0);
    VALUE input = rb_attr_get(error, id_input);

    if (!NIL_P(input)) {
	rb_str_resize(str, RSTRING_LEN(str)-1);
	rb_str_cat2(str, ", input=");
	rb_str_append(str, rb_str_inspect(input));
	rb_str_cat2(str, ">");
    }
    return str;
}

static void
gzfile_make_header(struct gzfile *gz)
{
    Bytef buf[10];  /* the size of gzip header */
    unsigned char flags = 0, extraflags = 0;

    if (!NIL_P(gz->orig_name)) {
	flags |= GZ_FLAG_ORIG_NAME;
    }
    if (!NIL_P(gz->comment)) {
	flags |= GZ_FLAG_COMMENT;
    }
    if (gz->mtime == 0) {
	gz->mtime = time(0);
    }

    if (gz->level == Z_BEST_SPEED) {
	extraflags |= GZ_EXTRAFLAG_FAST;
    }
    else if (gz->level == Z_BEST_COMPRESSION) {
	extraflags |= GZ_EXTRAFLAG_SLOW;
    }

    buf[0] = GZ_MAGIC1;
    buf[1] = GZ_MAGIC2;
    buf[2] = GZ_METHOD_DEFLATE;
    buf[3] = flags;
    gzfile_set32((unsigned long)gz->mtime, &buf[4]);
    buf[8] = extraflags;
    buf[9] = gz->os_code;
    zstream_append_buffer(&gz->z, buf, sizeof(buf));

    if (!NIL_P(gz->orig_name)) {
	zstream_append_buffer2(&gz->z, gz->orig_name);
	zstream_append_buffer(&gz->z, (Bytef*)"\0", 1);
    }
    if (!NIL_P(gz->comment)) {
	zstream_append_buffer2(&gz->z, gz->comment);
	zstream_append_buffer(&gz->z, (Bytef*)"\0", 1);
    }

    gz->z.flags |= GZFILE_FLAG_HEADER_FINISHED;
}

static void
gzfile_make_footer(struct gzfile *gz)
{
    Bytef buf[8];  /* 8 is the size of gzip footer */

    gzfile_set32(gz->crc, buf);
    gzfile_set32(gz->z.stream.total_in, &buf[4]);
    zstream_append_buffer(&gz->z, buf, sizeof(buf));
    gz->z.flags |= GZFILE_FLAG_FOOTER_FINISHED;
}

static void
gzfile_read_header(struct gzfile *gz)
{
    const unsigned char *head;
    long len;
    char flags, *p;

    if (!gzfile_read_raw_ensure(gz, 10)) {  /* 10 is the size of gzip header */
	gzfile_raise(gz, cGzError, "not in gzip format");
    }

    head = (unsigned char*)RSTRING_PTR(gz->z.input);

    if (head[0] != GZ_MAGIC1 || head[1] != GZ_MAGIC2) {
	gzfile_raise(gz, cGzError, "not in gzip format");
    }
    if (head[2] != GZ_METHOD_DEFLATE) {
	rb_raise(cGzError, "unsupported compression method %d", head[2]);
    }

    flags = head[3];
    if (flags & GZ_FLAG_MULTIPART) {
	rb_raise(cGzError, "multi-part gzip file is not supported");
    }
    else if (flags & GZ_FLAG_ENCRYPT) {
	rb_raise(cGzError, "encrypted gzip file is not supported");
    }
    else if (flags & GZ_FLAG_UNKNOWN_MASK) {
	rb_raise(cGzError, "unknown flags 0x%02x", flags);
    }

    if (head[8] & GZ_EXTRAFLAG_FAST) {
	gz->level = Z_BEST_SPEED;
    }
    else if (head[8] & GZ_EXTRAFLAG_SLOW) {
	gz->level = Z_BEST_COMPRESSION;
    }
    else {
	gz->level = Z_DEFAULT_COMPRESSION;
    }

    gz->mtime = gzfile_get32(&head[4]);
    gz->os_code = head[9];
    zstream_discard_input(&gz->z, 10);

    if (flags & GZ_FLAG_EXTRA) {
	if (!gzfile_read_raw_ensure(gz, 2)) {
	    rb_raise(cGzError, "unexpected end of file");
	}
	len = gzfile_get16((Bytef*)RSTRING_PTR(gz->z.input));
	if (!gzfile_read_raw_ensure(gz, 2 + len)) {
	    rb_raise(cGzError, "unexpected end of file");
	}
	zstream_discard_input(&gz->z, 2 + len);
    }
    if (flags & GZ_FLAG_ORIG_NAME) {
	p = gzfile_read_raw_until_zero(gz, 0);
	len = p - RSTRING_PTR(gz->z.input);
	gz->orig_name = rb_str_new(RSTRING_PTR(gz->z.input), len);
	OBJ_TAINT(gz->orig_name);  /* for safe */
	zstream_discard_input(&gz->z, len + 1);
    }
    if (flags & GZ_FLAG_COMMENT) {
	p = gzfile_read_raw_until_zero(gz, 0);
	len = p - RSTRING_PTR(gz->z.input);
	gz->comment = rb_str_new(RSTRING_PTR(gz->z.input), len);
	OBJ_TAINT(gz->comment);  /* for safe */
	zstream_discard_input(&gz->z, len + 1);
    }

    if (gz->z.input != Qnil && RSTRING_LEN(gz->z.input) > 0) {
	zstream_run(&gz->z, 0, 0, Z_SYNC_FLUSH);
    }
}

static void
gzfile_check_footer(struct gzfile *gz)
{
    unsigned long crc, length;

    gz->z.flags |= GZFILE_FLAG_FOOTER_FINISHED;

    if (!gzfile_read_raw_ensure(gz, 8)) { /* 8 is the size of gzip footer */
	gzfile_raise(gz, cNoFooter, "footer is not found");
    }

    crc = gzfile_get32((Bytef*)RSTRING_PTR(gz->z.input));
    length = gzfile_get32((Bytef*)RSTRING_PTR(gz->z.input) + 4);

    gz->z.stream.total_in += 8;  /* to rewind correctly */
    zstream_discard_input(&gz->z, 8);

    if (gz->crc != crc) {
	rb_raise(cCRCError, "invalid compressed data -- crc error");
    }
    if ((uint32_t)gz->z.stream.total_out != length) {
	rb_raise(cLengthError, "invalid compressed data -- length error");
    }
}

static void
gzfile_write(struct gzfile *gz, Bytef *str, long len)
{
    if (!(gz->z.flags & GZFILE_FLAG_HEADER_FINISHED)) {
	gzfile_make_header(gz);
    }

    if (len > 0 || (gz->z.flags & GZFILE_FLAG_SYNC)) {
	gz->crc = checksum_long(crc32, gz->crc, str, len);
	zstream_run(&gz->z, str, len, (gz->z.flags & GZFILE_FLAG_SYNC)
		    ? Z_SYNC_FLUSH : Z_NO_FLUSH);
    }
    gzfile_write_raw(gz);
}

static long
gzfile_read_more(struct gzfile *gz)
{
    volatile VALUE str;

    while (!ZSTREAM_IS_FINISHED(&gz->z)) {
	str = gzfile_read_raw(gz);
	if (NIL_P(str)) {
	    if (!ZSTREAM_IS_FINISHED(&gz->z)) {
		rb_raise(cGzError, "unexpected end of file");
	    }
	    break;
	}
	if (RSTRING_LEN(str) > 0) { /* prevent Z_BUF_ERROR */
	    zstream_run(&gz->z, (Bytef*)RSTRING_PTR(str), RSTRING_LEN(str),
			Z_SYNC_FLUSH);
	}
	if (gz->z.buf_filled > 0) break;
    }
    return gz->z.buf_filled;
}

static void
gzfile_calc_crc(struct gzfile *gz, VALUE str)
{
    if (RSTRING_LEN(str) <= gz->ungetc) {
	gz->ungetc -= RSTRING_LEN(str);
    }
    else {
	gz->crc = checksum_long(crc32, gz->crc, (Bytef*)RSTRING_PTR(str) + gz->ungetc,
			RSTRING_LEN(str) - gz->ungetc);
	gz->ungetc = 0;
    }
}

static VALUE
gzfile_newstr(struct gzfile *gz, VALUE str)
{
    if (!gz->enc2) {
	rb_enc_associate(str, gz->enc);
	OBJ_TAINT(str);  /* for safe */
	return str;
    }
    if (gz->ec && rb_enc_dummy_p(gz->enc2)) {
        str = rb_econv_str_convert(gz->ec, str, ECONV_PARTIAL_INPUT);
	rb_enc_associate(str, gz->enc);
	OBJ_TAINT(str);
	return str;
    }
    return rb_str_conv_enc_opts(str, gz->enc2, gz->enc,
				gz->ecflags, gz->ecopts);
}

static long
gzfile_fill(struct gzfile *gz, long len)
{
    if (len < 0)
        rb_raise(rb_eArgError, "negative length %ld given", len);
    if (len == 0)
	return 0;
    while (!ZSTREAM_IS_FINISHED(&gz->z) && gz->z.buf_filled < len) {
	gzfile_read_more(gz);
    }
    if (GZFILE_IS_FINISHED(gz)) {
	if (!(gz->z.flags & GZFILE_FLAG_FOOTER_FINISHED)) {
	    gzfile_check_footer(gz);
	}
	return -1;
    }
    return len < gz->z.buf_filled ? len : gz->z.buf_filled;
}

static VALUE
gzfile_read(struct gzfile *gz, long len)
{
    VALUE dst;

    len = gzfile_fill(gz, len);
    if (len == 0) return rb_str_new(0, 0);
    if (len < 0) return Qnil;
    dst = zstream_shift_buffer(&gz->z, len);
    gzfile_calc_crc(gz, dst);
    return dst;
}

static VALUE
gzfile_readpartial(struct gzfile *gz, long len, VALUE outbuf)
{
    VALUE dst;

    if (len < 0)
        rb_raise(rb_eArgError, "negative length %ld given", len);

    if (!NIL_P(outbuf))
	OBJ_TAINT(outbuf);

    if (len == 0) {
        if (NIL_P(outbuf))
            return rb_str_new(0, 0);
        else {
            rb_str_resize(outbuf, 0);
            return outbuf;
        }
    }
    while (!ZSTREAM_IS_FINISHED(&gz->z) && gz->z.buf_filled == 0) {
	gzfile_read_more(gz);
    }
    if (GZFILE_IS_FINISHED(gz)) {
	if (!(gz->z.flags & GZFILE_FLAG_FOOTER_FINISHED)) {
	    gzfile_check_footer(gz);
	}
        if (!NIL_P(outbuf))
            rb_str_resize(outbuf, 0);
	rb_raise(rb_eEOFError, "end of file reached");
    }

    dst = zstream_shift_buffer(&gz->z, len);
    gzfile_calc_crc(gz, dst);

    if (!NIL_P(outbuf)) {
        rb_str_resize(outbuf, RSTRING_LEN(dst));
        memcpy(RSTRING_PTR(outbuf), RSTRING_PTR(dst), RSTRING_LEN(dst));
	dst = outbuf;
    }
    OBJ_TAINT(dst);  /* for safe */
    return dst;
}

static VALUE
gzfile_read_all(struct gzfile *gz)
{
    VALUE dst;

    while (!ZSTREAM_IS_FINISHED(&gz->z)) {
	gzfile_read_more(gz);
    }
    if (GZFILE_IS_FINISHED(gz)) {
	if (!(gz->z.flags & GZFILE_FLAG_FOOTER_FINISHED)) {
	    gzfile_check_footer(gz);
	}
	return rb_str_new(0, 0);
    }

    dst = zstream_detach_buffer(&gz->z);
    gzfile_calc_crc(gz, dst);
    OBJ_TAINT(dst);
    return gzfile_newstr(gz, dst);
}

static VALUE
gzfile_getc(struct gzfile *gz)
{
    VALUE buf, dst = 0;
    int len;

    len = rb_enc_mbmaxlen(gz->enc);
    while (!ZSTREAM_IS_FINISHED(&gz->z) && gz->z.buf_filled < len) {
	gzfile_read_more(gz);
    }
    if (GZFILE_IS_FINISHED(gz)) {
	if (!(gz->z.flags & GZFILE_FLAG_FOOTER_FINISHED)) {
	    gzfile_check_footer(gz);
	}
	return Qnil;
    }

    if (gz->ec && rb_enc_dummy_p(gz->enc2)) {
	const unsigned char *ss, *sp, *se;
	unsigned char *ds, *dp, *de;
	rb_econv_result_t res;

	if (!gz->cbuf) {
	    gz->cbuf = ALLOC_N(char, GZFILE_CBUF_CAPA);
	}
        ss = sp = (const unsigned char*)RSTRING_PTR(gz->z.buf);
        se = sp + gz->z.buf_filled;
        ds = dp = (unsigned char *)gz->cbuf;
        de = (unsigned char *)ds + GZFILE_CBUF_CAPA;
        res = rb_econv_convert(gz->ec, &sp, se, &dp, de, ECONV_PARTIAL_INPUT|ECONV_AFTER_OUTPUT);
        rb_econv_check_error(gz->ec);
	dst = zstream_shift_buffer(&gz->z, sp - ss);
	gzfile_calc_crc(gz, dst);
	dst = rb_str_new(gz->cbuf, dp - ds);
	rb_enc_associate(dst, gz->enc);
	OBJ_TAINT(dst);
	return dst;
    }
    else {
	buf = gz->z.buf;
	len = rb_enc_mbclen(RSTRING_PTR(buf), RSTRING_END(buf), gz->enc);
	dst = gzfile_read(gz, len);
	return gzfile_newstr(gz, dst);
    }
}

static void
gzfile_ungets(struct gzfile *gz, const Bytef *b, long len)
{
    zstream_buffer_ungets(&gz->z, b, len);
    gz->ungetc+=len;
}

static void
gzfile_ungetbyte(struct gzfile *gz, int c)
{
    zstream_buffer_ungetbyte(&gz->z, c);
    gz->ungetc++;
}

static VALUE
gzfile_writer_end_run(VALUE arg)
{
    struct gzfile *gz = (struct gzfile *)arg;

    if (!(gz->z.flags & GZFILE_FLAG_HEADER_FINISHED)) {
	gzfile_make_header(gz);
    }

    zstream_run(&gz->z, (Bytef*)"", 0, Z_FINISH);
    gzfile_make_footer(gz);
    gzfile_write_raw(gz);

    return Qnil;
}

static void
gzfile_writer_end(struct gzfile *gz)
{
    if (ZSTREAM_IS_CLOSING(&gz->z)) return;
    gz->z.flags |= ZSTREAM_FLAG_CLOSING;

    rb_ensure(gzfile_writer_end_run, (VALUE)gz, zstream_end, (VALUE)&gz->z);
}

static VALUE
gzfile_reader_end_run(VALUE arg)
{
    struct gzfile *gz = (struct gzfile *)arg;

    if (GZFILE_IS_FINISHED(gz)
	&& !(gz->z.flags & GZFILE_FLAG_FOOTER_FINISHED)) {
	gzfile_check_footer(gz);
    }

    return Qnil;
}

static void
gzfile_reader_end(struct gzfile *gz)
{
    if (ZSTREAM_IS_CLOSING(&gz->z)) return;
    gz->z.flags |= ZSTREAM_FLAG_CLOSING;

    rb_ensure(gzfile_reader_end_run, (VALUE)gz, zstream_end, (VALUE)&gz->z);
}

static void
gzfile_reader_rewind(struct gzfile *gz)
{
    long n;

    n = gz->z.stream.total_in;
    if (!NIL_P(gz->z.input)) {
	n += RSTRING_LEN(gz->z.input);
    }

    rb_funcall(gz->io, id_seek, 2, rb_int2inum(-n), INT2FIX(1));
    gzfile_reset(gz);
}

static VALUE
gzfile_reader_get_unused(struct gzfile *gz)
{
    VALUE str;

    if (!ZSTREAM_IS_READY(&gz->z)) return Qnil;
    if (!GZFILE_IS_FINISHED(gz)) return Qnil;
    if (!(gz->z.flags & GZFILE_FLAG_FOOTER_FINISHED)) {
	gzfile_check_footer(gz);
    }
    if (NIL_P(gz->z.input)) return Qnil;

    str = rb_str_resurrect(gz->z.input);
    OBJ_TAINT(str);  /* for safe */
    return str;
}

static struct gzfile *
get_gzfile(VALUE obj)
{
    struct gzfile *gz;

    Data_Get_Struct(obj, struct gzfile, gz);
    if (!ZSTREAM_IS_READY(&gz->z)) {
	rb_raise(cGzError, "closed gzip stream");
    }
    return gz;
}


/* ------------------------------------------------------------------------- */

/*
 * Document-class: Zlib::GzipFile
 *
 * Zlib::GzipFile is an abstract class for handling a gzip formatted
 * compressed file. The operations are defined in the subclasses,
 * Zlib::GzipReader for reading, and Zlib::GzipWriter for writing.
 *
 * GzipReader should be used by associating an IO, or IO-like, object.
 */


typedef struct {
    int argc;
    VALUE *argv;
    VALUE klass;
} new_wrap_arg_t;

static VALUE
new_wrap(VALUE tmp)
{
    new_wrap_arg_t *arg = (new_wrap_arg_t *)tmp;
    return rb_class_new_instance(arg->argc, arg->argv, arg->klass);
}

static VALUE
gzfile_ensure_close(VALUE obj)
{
    struct gzfile *gz;

    Data_Get_Struct(obj, struct gzfile, gz);
    if (ZSTREAM_IS_READY(&gz->z)) {
	gzfile_close(gz, 1);
    }
    return Qnil;
}

static VALUE
gzfile_wrap(int argc, VALUE *argv, VALUE klass, int close_io_on_error)
{
    VALUE obj;

    if (close_io_on_error) {
	int state = 0;
	new_wrap_arg_t arg;
	arg.argc = argc;
	arg.argv = argv;
	arg.klass = klass;
	obj = rb_protect(new_wrap, (VALUE)&arg, &state);
	if (state) {
	    rb_io_close(argv[0]);
	    rb_jump_tag(state);
	}
    }
    else {
	obj = rb_class_new_instance(argc, argv, klass);
    }

    if (rb_block_given_p()) {
	return rb_ensure(rb_yield, obj, gzfile_ensure_close, obj);
    }
    else {
	return obj;
    }
}

/*
 * call-seq: Zlib::GzipFile.wrap(io) { |gz| ... }
 *
 * Creates a GzipFile object associated with +io+, and
 * executes the block with the newly created GzipFile object,
 * just like File.open. The GzipFile object will be closed
 * automatically after executing the block. If you want to keep
 * the associated IO object opening, you may call
 * +Zlib::GzipFile#finish+ method in the block.
 */
static VALUE
rb_gzfile_s_wrap(int argc, VALUE *argv, VALUE klass)
{
    return gzfile_wrap(argc, argv, klass, 0);
}

/*
 * See Zlib::GzipReader#open and Zlib::GzipWriter#open.
 */
static VALUE
gzfile_s_open(int argc, VALUE *argv, VALUE klass, const char *mode)
{
    VALUE io, filename;

    if (argc < 1) {
	rb_raise(rb_eArgError, "wrong number of arguments (0 for 1)");
    }
    filename = argv[0];
    io = rb_file_open_str(filename, mode);
    argv[0] = io;
    return gzfile_wrap(argc, argv, klass, 1);
}

/*
 * Same as IO.
 */
static VALUE
rb_gzfile_to_io(VALUE obj)
{
    return get_gzfile(obj)->io;
}

/*
 * Returns CRC value of the uncompressed data.
 */
static VALUE
rb_gzfile_crc(VALUE obj)
{
    return rb_uint2inum(get_gzfile(obj)->crc);
}

/*
 * Returns last modification time recorded in the gzip file header.
 */
static VALUE
rb_gzfile_mtime(VALUE obj)
{
    return rb_time_new(get_gzfile(obj)->mtime, (time_t)0);
}

/*
 * Returns compression level.
 */
static VALUE
rb_gzfile_level(VALUE obj)
{
    return INT2FIX(get_gzfile(obj)->level);
}

/*
 * Returns OS code number recorded in the gzip file header.
 */
static VALUE
rb_gzfile_os_code(VALUE obj)
{
    return INT2FIX(get_gzfile(obj)->os_code);
}

/*
 * Returns original filename recorded in the gzip file header, or +nil+ if
 * original filename is not present.
 */
static VALUE
rb_gzfile_orig_name(VALUE obj)
{
    VALUE str = get_gzfile(obj)->orig_name;
    if (!NIL_P(str)) {
	str = rb_str_dup(str);
    }
    OBJ_TAINT(str);  /* for safe */
    return str;
}

/*
 * Returns comments recorded in the gzip file header, or nil if the comments
 * is not present.
 */
static VALUE
rb_gzfile_comment(VALUE obj)
{
    VALUE str = get_gzfile(obj)->comment;
    if (!NIL_P(str)) {
	str = rb_str_dup(str);
    }
    OBJ_TAINT(str);  /* for safe */
    return str;
}

/*
 * ???
 */
static VALUE
rb_gzfile_lineno(VALUE obj)
{
    return INT2NUM(get_gzfile(obj)->lineno);
}

/*
 * ???
 */
static VALUE
rb_gzfile_set_lineno(VALUE obj, VALUE lineno)
{
    struct gzfile *gz = get_gzfile(obj);
    gz->lineno = NUM2INT(lineno);
    return lineno;
}

/*
 * ???
 */
static VALUE
rb_gzfile_set_mtime(VALUE obj, VALUE mtime)
{
    struct gzfile *gz = get_gzfile(obj);
    VALUE val;

    if (gz->z.flags & GZFILE_FLAG_HEADER_FINISHED) {
	rb_raise(cGzError, "header is already written");
    }

    if (FIXNUM_P(mtime)) {
	gz->mtime = FIX2INT(mtime);
    }
    else {
	val = rb_Integer(mtime);
	gz->mtime = FIXNUM_P(val) ? FIX2UINT(val) : rb_big2ulong(val);
    }
    return mtime;
}

/*
 * ???
 */
static VALUE
rb_gzfile_set_orig_name(VALUE obj, VALUE str)
{
    struct gzfile *gz = get_gzfile(obj);
    VALUE s;
    char *p;

    if (gz->z.flags & GZFILE_FLAG_HEADER_FINISHED) {
	rb_raise(cGzError, "header is already written");
    }
    s = rb_str_dup(rb_str_to_str(str));
    p = memchr(RSTRING_PTR(s), '\0', RSTRING_LEN(s));
    if (p) {
	rb_str_resize(s, p - RSTRING_PTR(s));
    }
    gz->orig_name = s;
    return str;
}

/*
 * ???
 */
static VALUE
rb_gzfile_set_comment(VALUE obj, VALUE str)
{
    struct gzfile *gz = get_gzfile(obj);
    VALUE s;
    char *p;

    if (gz->z.flags & GZFILE_FLAG_HEADER_FINISHED) {
	rb_raise(cGzError, "header is already written");
    }
    s = rb_str_dup(rb_str_to_str(str));
    p = memchr(RSTRING_PTR(s), '\0', RSTRING_LEN(s));
    if (p) {
	rb_str_resize(s, p - RSTRING_PTR(s));
    }
    gz->comment = s;
    return str;
}

/*
 * Closes the GzipFile object. This method calls close method of the
 * associated IO object. Returns the associated IO object.
 */
static VALUE
rb_gzfile_close(VALUE obj)
{
    struct gzfile *gz = get_gzfile(obj);
    VALUE io;

    io = gz->io;
    gzfile_close(gz, 1);
    return io;
}

/*
 * Closes the GzipFile object. Unlike Zlib::GzipFile#close, this method never
 * calls the close method of the associated IO object. Returns the associated IO
 * object.
 */
static VALUE
rb_gzfile_finish(VALUE obj)
{
    struct gzfile *gz = get_gzfile(obj);
    VALUE io;

    io = gz->io;
    gzfile_close(gz, 0);
    return io;
}

/*
 * Same as IO.
 */
static VALUE
rb_gzfile_closed_p(VALUE obj)
{
    struct gzfile *gz;
    Data_Get_Struct(obj, struct gzfile, gz);
    return NIL_P(gz->io) ? Qtrue : Qfalse;
}

/*
 * ???
 */
static VALUE
rb_gzfile_eof_p(VALUE obj)
{
    struct gzfile *gz = get_gzfile(obj);
    return GZFILE_IS_FINISHED(gz) ? Qtrue : Qfalse;
}

/*
 * Same as IO.
 */
static VALUE
rb_gzfile_sync(VALUE obj)
{
    return (get_gzfile(obj)->z.flags & GZFILE_FLAG_SYNC) ? Qtrue : Qfalse;
}

/*
 * call-seq: sync = flag
 *
 * Same as IO.  If flag is +true+, the associated IO object must respond to the
 * +flush+ method.  While +sync+ mode is +true+, the compression ratio
 * decreases sharply.
 */
static VALUE
rb_gzfile_set_sync(VALUE obj, VALUE mode)
{
    struct gzfile *gz = get_gzfile(obj);

    if (RTEST(mode)) {
	gz->z.flags |= GZFILE_FLAG_SYNC;
    }
    else {
	gz->z.flags &= ~GZFILE_FLAG_SYNC;
    }
    return mode;
}

/*
 * ???
 */
static VALUE
rb_gzfile_total_in(VALUE obj)
{
    return rb_uint2inum(get_gzfile(obj)->z.stream.total_in);
}

/*
 * ???
 */
static VALUE
rb_gzfile_total_out(VALUE obj)
{
    struct gzfile *gz = get_gzfile(obj);
    return rb_uint2inum(gz->z.stream.total_out - gz->z.buf_filled);
}

/*
 * Document-method: path
 *
 * call-seq: path
 *
 * Returns the path string of the associated IO-like object.  This
 * method is only defined when the IO-like object responds to #path().
 */
static VALUE
rb_gzfile_path(VALUE obj)
{
    struct gzfile *gz;
    Data_Get_Struct(obj, struct gzfile, gz);
    return gz->path;
}

static void
rb_gzfile_ecopts(struct gzfile *gz, VALUE opts)
{
    if (!NIL_P(opts)) {
	rb_io_extract_encoding_option(opts, &gz->enc, &gz->enc2, NULL);
    }
    if (gz->enc2) {
	gz->ecflags = rb_econv_prepare_opts(opts, &opts);
	gz->ec = rb_econv_open_opts(gz->enc2->name, gz->enc->name,
				    gz->ecflags, opts);
	gz->ecopts = opts;
    }
}

/* ------------------------------------------------------------------------- */

/*
 * Document-class: Zlib::GzipWriter
 *
 * Zlib::GzipWriter is a class for writing gzipped files.  GzipWriter should
 * be used with an instance of IO, or IO-like, object.
 *
 * Following two example generate the same result.
 *
 *   Zlib::GzipWriter.open('hoge.gz') do |gz|
 *     gz.write 'jugemu jugemu gokou no surikire...'
 *   end
 *
 *   File.open('hoge.gz', 'w') do |f|
 *     gz = Zlib::GzipWriter.new(f)
 *     gz.write 'jugemu jugemu gokou no surikire...'
 *     gz.close
 *   end
 *
 * To make like gzip(1) does, run following:
 *
 *   orig = 'hoge.txt'
 *   Zlib::GzipWriter.open('hoge.gz') do |gz|
 *     gz.mtime = File.mtime(orig)
 *     gz.orig_name = orig
 *     gz.write IO.binread(orig)
 *   end
 *
 * NOTE: Due to the limitation of Ruby's finalizer, you must explicitly close
 * GzipWriter objects by Zlib::GzipWriter#close etc.  Otherwise, GzipWriter
 * will be not able to write the gzip footer and will generate a broken gzip
 * file.
 */

static VALUE
rb_gzwriter_s_allocate(VALUE klass)
{
    return gzfile_writer_new(klass);
}

/*
 * call-seq: Zlib::GzipWriter.open(filename, level=nil, strategy=nil) { |gz| ... }
 *
 * Opens a file specified by +filename+ for writing gzip compressed data, and
 * returns a GzipWriter object associated with that file.  Further details of
 * this method are found in Zlib::GzipWriter.new and Zlib::GzipFile.wrap.
 */
static VALUE
rb_gzwriter_s_open(int argc, VALUE *argv, VALUE klass)
{
    return gzfile_s_open(argc, argv, klass, "wb");
}

/*
 * call-seq: Zlib::GzipWriter.new(io, level, strategy)
 *
 * Creates a GzipWriter object associated with +io+. +level+ and +strategy+
 * should be the same as the arguments of Zlib::Deflate.new.  The GzipWriter
 * object writes gzipped data to +io+.  At least, +io+ must respond to the
 * +write+ method that behaves same as write method in IO class.
 */
static VALUE
rb_gzwriter_initialize(int argc, VALUE *argv, VALUE obj)
{
    struct gzfile *gz;
    VALUE io, level, strategy, opt = Qnil;
    int err;

    if (argc > 1) {
	opt = rb_check_convert_type(argv[argc-1], T_HASH, "Hash", "to_hash");
	if (!NIL_P(opt)) argc--;
    }

    rb_scan_args(argc, argv, "12", &io, &level, &strategy);
    Data_Get_Struct(obj, struct gzfile, gz);

    /* this is undocumented feature of zlib */
    gz->level = ARG_LEVEL(level);
    err = deflateInit2(&gz->z.stream, gz->level, Z_DEFLATED,
		       -MAX_WBITS, DEF_MEM_LEVEL, ARG_STRATEGY(strategy));
    if (err != Z_OK) {
	raise_zlib_error(err, gz->z.stream.msg);
    }
    gz->io = io;
    ZSTREAM_READY(&gz->z);
    rb_gzfile_ecopts(gz, opt);

    if (rb_respond_to(io, id_path)) {
	gz->path = rb_funcall(gz->io, id_path, 0);
	rb_define_singleton_method(obj, "path", rb_gzfile_path, 0);
    }

    return obj;
}

/*
 * call-seq: flush(flush=nil)
 *
 * Flushes all the internal buffers of the GzipWriter object.  The meaning of
 * +flush+ is same as in Zlib::Deflate#deflate.  <tt>Zlib::SYNC_FLUSH</tt> is used if
 * +flush+ is omitted.  It is no use giving flush <tt>Zlib::NO_FLUSH</tt>.
 */
static VALUE
rb_gzwriter_flush(int argc, VALUE *argv, VALUE obj)
{
    struct gzfile *gz = get_gzfile(obj);
    VALUE v_flush;
    int flush;

    rb_scan_args(argc, argv, "01", &v_flush);

    flush = FIXNUMARG(v_flush, Z_SYNC_FLUSH);
    if (flush != Z_NO_FLUSH) {  /* prevent Z_BUF_ERROR */
	zstream_run(&gz->z, (Bytef*)"", 0, flush);
    }

    gzfile_write_raw(gz);
    if (rb_respond_to(gz->io, id_flush)) {
	rb_funcall(gz->io, id_flush, 0);
    }
    return obj;
}

/*
 * Same as IO.
 */
static VALUE
rb_gzwriter_write(VALUE obj, VALUE str)
{
    struct gzfile *gz = get_gzfile(obj);

    if (TYPE(str) != T_STRING)
	str = rb_obj_as_string(str);
    if (gz->enc2 && gz->enc2 != rb_ascii8bit_encoding()) {
	str = rb_str_conv_enc(str, rb_enc_get(str), gz->enc2);
    }
    gzfile_write(gz, (Bytef*)RSTRING_PTR(str), RSTRING_LEN(str));
    return INT2FIX(RSTRING_LEN(str));
}

/*
 * Same as IO.
 */
static VALUE
rb_gzwriter_putc(VALUE obj, VALUE ch)
{
    struct gzfile *gz = get_gzfile(obj);
    char c = NUM2CHR(ch);

    gzfile_write(gz, (Bytef*)&c, 1);
    return ch;
}



/*
 * Document-method: <<
 * Same as IO.
 */
#define rb_gzwriter_addstr  rb_io_addstr
/*
 * Document-method: printf
 * Same as IO.
 */
#define rb_gzwriter_printf  rb_io_printf
/*
 * Document-method: print
 * Same as IO.
 */
#define rb_gzwriter_print  rb_io_print
/*
 * Document-method: puts
 * Same as IO.
 */
#define rb_gzwriter_puts  rb_io_puts


/* ------------------------------------------------------------------------- */

/*
 * Document-class: Zlib::GzipReader
 *
 * Zlib::GzipReader is the class for reading a gzipped file.  GzipReader should
 * be used an IO, or -IO-lie, object.
 *
 *   Zlib::GzipReader.open('hoge.gz') {|gz|
 *     print gz.read
 *   }
 *
 *   File.open('hoge.gz') do |f|
 *     gz = Zlib::GzipReader.new(f)
 *     print gz.read
 *     gz.close
 *   end
 *
 *   # TODO: test these.  Are they equivalent?  Can GzipReader.new take a
 *   # block?
 *
 * == Method Catalogue
 *
 * The following methods in Zlib::GzipReader are just like their counterparts
 * in IO, but they raise Zlib::Error or Zlib::GzipFile::Error exception if an
 * error was found in the gzip file.
 * - #each
 * - #each_line
 * - #each_byte
 * - #gets
 * - #getc
 * - #lineno
 * - #lineno=
 * - #read
 * - #readchar
 * - #readline
 * - #readlines
 * - #ungetc
 *
 * Be careful of the footer of the gzip file. A gzip file has the checksum of
 * pre-compressed data in its footer. GzipReader checks all uncompressed data
 * against that checksum at the following cases, and if it fails, raises
 * <tt>Zlib::GzipFile::NoFooter</tt>, <tt>Zlib::GzipFile::CRCError</tt>, or
 * <tt>Zlib::GzipFile::LengthError</tt> exception.
 *
 * - When an reading request is received beyond the end of file (the end of
 *   compressed data). That is, when Zlib::GzipReader#read,
 *   Zlib::GzipReader#gets, or some other methods for reading returns nil.
 * - When Zlib::GzipFile#close method is called after the object reaches the
 *   end of file.
 * - When Zlib::GzipReader#unused method is called after the object reaches
 *   the end of file.
 *
 * The rest of the methods are adequately described in their own
 * documentation.
 */

static VALUE
rb_gzreader_s_allocate(VALUE klass)
{
    return gzfile_reader_new(klass);
}

/*
 * call-seq: Zlib::GzipReader.open(filename) {|gz| ... }
 *
 * Opens a file specified by +filename+ as a gzipped file, and returns a
 * GzipReader object associated with that file.  Further details of this method
 * are in Zlib::GzipReader.new and ZLib::GzipFile.wrap.
 */
static VALUE
rb_gzreader_s_open(int argc, VALUE *argv, VALUE klass)
{
    return gzfile_s_open(argc, argv, klass, "rb");
}

/*
 * call-seq: Zlib::GzipReader.new(io)
 *
 * Creates a GzipReader object associated with +io+. The GzipReader object reads
 * gzipped data from +io+, and parses/decompresses them.  At least, +io+ must have
 * a +read+ method that behaves same as the +read+ method in IO class.
 *
 * If the gzip file header is incorrect, raises an Zlib::GzipFile::Error
 * exception.
 */
static VALUE
rb_gzreader_initialize(int argc, VALUE *argv, VALUE obj)
{
    VALUE io, opt = Qnil;
    struct gzfile *gz;
    int err;

    Data_Get_Struct(obj, struct gzfile, gz);
    rb_scan_args(argc, argv, "1:", &io, &opt);

    /* this is undocumented feature of zlib */
    err = inflateInit2(&gz->z.stream, -MAX_WBITS);
    if (err != Z_OK) {
	raise_zlib_error(err, gz->z.stream.msg);
    }
    gz->io = io;
    ZSTREAM_READY(&gz->z);
    gzfile_read_header(gz);
    rb_gzfile_ecopts(gz, opt);

    if (rb_respond_to(io, id_path)) {
	gz->path = rb_funcall(gz->io, id_path, 0);
	rb_define_singleton_method(obj, "path", rb_gzfile_path, 0);
    }

    return obj;
}

/*
 * Resets the position of the file pointer to the point created the GzipReader
 * object.  The associated IO object needs to respond to the +seek+ method.
 */
static VALUE
rb_gzreader_rewind(VALUE obj)
{
    struct gzfile *gz = get_gzfile(obj);
    gzfile_reader_rewind(gz);
    return INT2FIX(0);
}

/*
 * Returns the rest of the data which had read for parsing gzip format, or
 * +nil+ if the whole gzip file is not parsed yet.
 */
static VALUE
rb_gzreader_unused(VALUE obj)
{
    struct gzfile *gz;
    Data_Get_Struct(obj, struct gzfile, gz);
    return gzfile_reader_get_unused(gz);
}

/*
 * See Zlib::GzipReader documentation for a description.
 */
static VALUE
rb_gzreader_read(int argc, VALUE *argv, VALUE obj)
{
    struct gzfile *gz = get_gzfile(obj);
    VALUE vlen;
    long len;

    rb_scan_args(argc, argv, "01", &vlen);
    if (NIL_P(vlen)) {
	return gzfile_read_all(gz);
    }

    len = NUM2INT(vlen);
    if (len < 0) {
	rb_raise(rb_eArgError, "negative length %ld given", len);
    }
    return gzfile_read(gz, len);
}

/*
 *  call-seq:
 *     gzipreader.readpartial(maxlen [, outbuf]) => string, outbuf
 *
 *  Reads at most <i>maxlen</i> bytes from the gziped stream but
 *  it blocks only if <em>gzipreader</em> has no data immediately available.
 *  If the optional <i>outbuf</i> argument is present,
 *  it must reference a String, which will receive the data.
 *  It raises <code>EOFError</code> on end of file.
 */
static VALUE
rb_gzreader_readpartial(int argc, VALUE *argv, VALUE obj)
{
    struct gzfile *gz = get_gzfile(obj);
    VALUE vlen, outbuf;
    long len;

    rb_scan_args(argc, argv, "11", &vlen, &outbuf);

    len = NUM2INT(vlen);
    if (len < 0) {
	rb_raise(rb_eArgError, "negative length %ld given", len);
    }
    if (!NIL_P(outbuf))
        Check_Type(outbuf, T_STRING);
    return gzfile_readpartial(gz, len, outbuf);
}

/*
 * See Zlib::GzipReader documentation for a description.
 */
static VALUE
rb_gzreader_getc(VALUE obj)
{
    struct gzfile *gz = get_gzfile(obj);

    return gzfile_getc(gz);
}

/*
 * See Zlib::GzipReader documentation for a description.
 */
static VALUE
rb_gzreader_readchar(VALUE obj)
{
    VALUE dst;
    dst = rb_gzreader_getc(obj);
    if (NIL_P(dst)) {
	rb_raise(rb_eEOFError, "end of file reached");
    }
    return dst;
}

/*
 * See Zlib::GzipReader documentation for a description.
 */
static VALUE
rb_gzreader_getbyte(VALUE obj)
{
    struct gzfile *gz = get_gzfile(obj);
    VALUE dst;

    dst = gzfile_read(gz, 1);
    if (!NIL_P(dst)) {
	dst = INT2FIX((unsigned int)(RSTRING_PTR(dst)[0]) & 0xff);
    }
    return dst;
}

/*
 * See Zlib::GzipReader documentation for a description.
 */
static VALUE
rb_gzreader_readbyte(VALUE obj)
{
    VALUE dst;
    dst = rb_gzreader_getbyte(obj);
    if (NIL_P(dst)) {
	rb_raise(rb_eEOFError, "end of file reached");
    }
    return dst;
}

/*
 * See Zlib::GzipReader documentation for a description.
 */
static VALUE
rb_gzreader_each_char(VALUE obj)
{
    VALUE c;

    RETURN_ENUMERATOR(obj, 0, 0);

    while (!NIL_P(c = rb_gzreader_getc(obj))) {
	rb_yield(c);
    }
    return Qnil;
}

/*
 * See Zlib::GzipReader documentation for a description.
 */
static VALUE
rb_gzreader_each_byte(VALUE obj)
{
    VALUE c;

    RETURN_ENUMERATOR(obj, 0, 0);

    while (!NIL_P(c = rb_gzreader_getbyte(obj))) {
	rb_yield(c);
    }
    return Qnil;
}

/*
 * See Zlib::GzipReader documentation for a description.
 */
static VALUE
rb_gzreader_ungetc(VALUE obj, VALUE s)
{
    struct gzfile *gz;

    if (FIXNUM_P(s))
	return rb_gzreader_ungetbyte(obj, s);
    gz = get_gzfile(obj);
    StringValue(s);
    if (gz->enc2 && gz->enc2 != rb_ascii8bit_encoding()) {
	s = rb_str_conv_enc(s, rb_enc_get(s), gz->enc2);
    }
    gzfile_ungets(gz, (const Bytef*)RSTRING_PTR(s), RSTRING_LEN(s));
    return Qnil;
}

/*
 * See Zlib::GzipReader documentation for a description.
 */
static VALUE
rb_gzreader_ungetbyte(VALUE obj, VALUE ch)
{
    struct gzfile *gz = get_gzfile(obj);
    gzfile_ungetbyte(gz, NUM2CHR(ch));
    return Qnil;
}

static void
gzreader_skip_linebreaks(struct gzfile *gz)
{
    VALUE str;
    char *p;
    int n;

    while (gz->z.buf_filled == 0) {
	if (GZFILE_IS_FINISHED(gz)) return;
	gzfile_read_more(gz);
    }
    n = 0;
    p = RSTRING_PTR(gz->z.buf);

    while (n++, *(p++) == '\n') {
	if (n >= gz->z.buf_filled) {
	    str = zstream_detach_buffer(&gz->z);
	    gzfile_calc_crc(gz, str);
	    while (gz->z.buf_filled == 0) {
		if (GZFILE_IS_FINISHED(gz)) return;
		gzfile_read_more(gz);
	    }
	    n = 0;
	    p = RSTRING_PTR(gz->z.buf);
	}
    }

    str = zstream_shift_buffer(&gz->z, n - 1);
    gzfile_calc_crc(gz, str);
}

static void
rscheck(const char *rsptr, long rslen, VALUE rs)
{
    if (RSTRING_PTR(rs) != rsptr && RSTRING_LEN(rs) != rslen)
	rb_raise(rb_eRuntimeError, "rs modified");
}

static long
gzreader_charboundary(struct gzfile *gz, long n)
{
    char *s = RSTRING_PTR(gz->z.buf);
    char *e = s + gz->z.buf_filled;
    char *p = rb_enc_left_char_head(s, s + n, e, gz->enc);
    long l = p - s;
    if (l < n) {
	n = rb_enc_precise_mbclen(p, e, gz->enc);
	if (MBCLEN_NEEDMORE_P(n)) {
	    if ((l = gzfile_fill(gz, l + MBCLEN_NEEDMORE_LEN(n))) > 0) {
		return l;
	    }
	}
	else if (MBCLEN_CHARFOUND_P(n)) {
	    return l + MBCLEN_CHARFOUND_LEN(n);
	}
    }
    return n;
}

static VALUE
gzreader_gets(int argc, VALUE *argv, VALUE obj)
{
    struct gzfile *gz = get_gzfile(obj);
    volatile VALUE rs;
    VALUE dst;
    const char *rsptr;
    char *p, *res;
    long rslen, n, limit = -1;
    int rspara;
    rb_encoding *enc = gz->enc;
    int maxlen = rb_enc_mbmaxlen(enc);

    if (argc == 0) {
	rs = rb_rs;
    }
    else {
	VALUE lim, tmp;

	rb_scan_args(argc, argv, "11", &rs, &lim);
	if (!NIL_P(lim)) {
	    if (!NIL_P(rs)) StringValue(rs);
	}
	else if (!NIL_P(rs)) {
	    tmp = rb_check_string_type(rs);
	    if (NIL_P(tmp)) {
		lim = rs;
		rs = rb_rs;
	    }
	    else {
		rs = tmp;
	    }
	}
	if (!NIL_P(lim)) {
	    limit = NUM2LONG(lim);
	    if (limit == 0) return rb_str_new(0,0);
	}
    }

    if (NIL_P(rs)) {
	if (limit < 0) {
	    dst = gzfile_read_all(gz);
	    if (RSTRING_LEN(dst) == 0) return Qnil;
	}
	else if ((n = gzfile_fill(gz, limit)) <= 0) {
	    return Qnil;
	}
	else {
	    if (maxlen > 1 && n >= limit && !GZFILE_IS_FINISHED(gz)) {
		n = gzreader_charboundary(gz, n);
	    }
	    else {
		n = limit;
	    }
	    dst = zstream_shift_buffer(&gz->z, n);
	    gzfile_calc_crc(gz, dst);
	    dst = gzfile_newstr(gz, dst);
	}
	gz->lineno++;
	return dst;
    }

    if (RSTRING_LEN(rs) == 0) {
	rsptr = "\n\n";
	rslen = 2;
	rspara = 1;
    } else {
	rsptr = RSTRING_PTR(rs);
	rslen = RSTRING_LEN(rs);
	rspara = 0;
    }

    if (rspara) {
	gzreader_skip_linebreaks(gz);
    }

    while (gz->z.buf_filled < rslen) {
	if (ZSTREAM_IS_FINISHED(&gz->z)) {
	    if (gz->z.buf_filled > 0) gz->lineno++;
	    return gzfile_read(gz, rslen);
	}
	gzfile_read_more(gz);
    }

    p = RSTRING_PTR(gz->z.buf);
    n = rslen;
    for (;;) {
	long filled;
	if (n > gz->z.buf_filled) {
	    if (ZSTREAM_IS_FINISHED(&gz->z)) break;
	    gzfile_read_more(gz);
	    p = RSTRING_PTR(gz->z.buf) + n - rslen;
	}
	if (!rspara) rscheck(rsptr, rslen, rs);
	filled = gz->z.buf_filled;
	if (limit > 0 && filled >= limit) {
	    filled = limit;
	}
	res = memchr(p, rsptr[0], (filled - n + 1));
	if (!res) {
	    n = filled;
	    if (limit > 0 && filled >= limit) break;
	    n++;
	} else {
	    n += (long)(res - p);
	    p = res;
	    if (rslen == 1 || memcmp(p, rsptr, rslen) == 0) break;
	    p++, n++;
	}
    }
    if (maxlen > 1 && n == limit && (gz->z.buf_filled > n || !ZSTREAM_IS_FINISHED(&gz->z))) {
	n = gzreader_charboundary(gz, n);
    }

    gz->lineno++;
    dst = gzfile_read(gz, n);
    if (rspara) {
	gzreader_skip_linebreaks(gz);
    }

    return gzfile_newstr(gz, dst);
}

/*
 * See Zlib::GzipReader documentation for a description.
 */
static VALUE
rb_gzreader_gets(int argc, VALUE *argv, VALUE obj)
{
    VALUE dst;
    dst = gzreader_gets(argc, argv, obj);
    if (!NIL_P(dst)) {
	rb_lastline_set(dst);
    }
    return dst;
}

/*
 * See Zlib::GzipReader documentation for a description.
 */
static VALUE
rb_gzreader_readline(int argc, VALUE *argv, VALUE obj)
{
    VALUE dst;
    dst = rb_gzreader_gets(argc, argv, obj);
    if (NIL_P(dst)) {
	rb_raise(rb_eEOFError, "end of file reached");
    }
    return dst;
}

/*
 * See Zlib::GzipReader documentation for a description.
 */
static VALUE
rb_gzreader_each(int argc, VALUE *argv, VALUE obj)
{
    VALUE str;

    RETURN_ENUMERATOR(obj, 0, 0);

    while (!NIL_P(str = gzreader_gets(argc, argv, obj))) {
	rb_yield(str);
    }
    return obj;
}

/*
 * See Zlib::GzipReader documentation for a description.
 */
static VALUE
rb_gzreader_readlines(int argc, VALUE *argv, VALUE obj)
{
    VALUE str, dst;
    dst = rb_ary_new();
    while (!NIL_P(str = gzreader_gets(argc, argv, obj))) {
	rb_ary_push(dst, str);
    }
    return dst;
}

#endif /* GZIP_SUPPORT */



/*
 * The Zlib module contains several classes for compressing and decompressing
 * streams, and for working with "gzip" files.
 *
 * == Classes
 *
 * Following are the classes that are most likely to be of interest to the
 * user:
 * Zlib::Inflate
 * Zlib::Deflate
 * Zlib::GzipReader
 * Zlib::GzipWriter
 *
 * There are two important base classes for the classes above: Zlib::ZStream
 * and Zlib::GzipFile.  Everything else is an error class.
 *
 * == Constants
 *
 * Here's a list.
 *
 *   Zlib::VERSION
 *       The Ruby/zlib version string.
 *
 *   Zlib::ZLIB_VERSION
 *       The string which represents the version of zlib.h.
 *
 *   Zlib::BINARY
 *   Zlib::ASCII
 *   Zlib::UNKNOWN
 *       The integers representing data types which Zlib::ZStream#data_type
 *       method returns.
 *
 *   Zlib::NO_COMPRESSION
 *   Zlib::BEST_SPEED
 *   Zlib::BEST_COMPRESSION
 *   Zlib::DEFAULT_COMPRESSION
 *       The integers representing compression levels which are an argument
 *       for Zlib::Deflate.new, Zlib::Deflate#deflate, and so on.
 *
 *   Zlib::FILTERED
 *   Zlib::HUFFMAN_ONLY
 *   Zlib::DEFAULT_STRATEGY
 *       The integers representing compression methods which are an argument
 *       for Zlib::Deflate.new and Zlib::Deflate#params.
 *
 *   Zlib::DEF_MEM_LEVEL
 *   Zlib::MAX_MEM_LEVEL
 *       The integers representing memory levels which are an argument for
 *       Zlib::Deflate.new, Zlib::Deflate#params, and so on.
 *
 *   Zlib::MAX_WBITS
 *       The default value of windowBits which is an argument for
 *       Zlib::Deflate.new and Zlib::Inflate.new.
 *
 *   Zlib::NO_FLUSH
 *   Zlib::SYNC_FLUSH
 *   Zlib::FULL_FLUSH
 *   Zlib::FINISH
 *       The integers to control the output of the deflate stream, which are
 *       an argument for Zlib::Deflate#deflate and so on.
 *
 *   Zlib::OS_CODE
 *   Zlib::OS_MSDOS
 *   Zlib::OS_AMIGA
 *   Zlib::OS_VMS
 *   Zlib::OS_UNIX
 *   Zlib::OS_VMCMS
 *   Zlib::OS_ATARI
 *   Zlib::OS_OS2
 *   Zlib::OS_MACOS
 *   Zlib::OS_ZSYSTEM
 *   Zlib::OS_CPM
 *   Zlib::OS_TOPS20
 *   Zlib::OS_WIN32
 *   Zlib::OS_QDOS
 *   Zlib::OS_RISCOS
 *   Zlib::OS_UNKNOWN
 *       The return values of Zlib::GzipFile#os_code method.
 */
void
Init_zlib()
{
    VALUE mZlib, cZStream, cDeflate, cInflate;
#if GZIP_SUPPORT
    VALUE cGzipFile, cGzipWriter, cGzipReader;
#endif

    mZlib = rb_define_module("Zlib");

    cZError = rb_define_class_under(mZlib, "Error", rb_eStandardError);
    cStreamEnd    = rb_define_class_under(mZlib, "StreamEnd", cZError);
    cNeedDict     = rb_define_class_under(mZlib, "NeedDict", cZError);
    cDataError    = rb_define_class_under(mZlib, "DataError", cZError);
    cStreamError  = rb_define_class_under(mZlib, "StreamError", cZError);
    cMemError     = rb_define_class_under(mZlib, "MemError", cZError);
    cBufError     = rb_define_class_under(mZlib, "BufError", cZError);
    cVersionError = rb_define_class_under(mZlib, "VersionError", cZError);

    rb_define_module_function(mZlib, "zlib_version", rb_zlib_version, 0);
    rb_define_module_function(mZlib, "adler32", rb_zlib_adler32, -1);
    rb_define_module_function(mZlib, "adler32_combine", rb_zlib_adler32_combine, 3);
    rb_define_module_function(mZlib, "crc32", rb_zlib_crc32, -1);
    rb_define_module_function(mZlib, "crc32_combine", rb_zlib_crc32_combine, 3);
    rb_define_module_function(mZlib, "crc_table", rb_zlib_crc_table, 0);

    rb_define_const(mZlib, "VERSION", rb_str_new2(RUBY_ZLIB_VERSION));
    rb_define_const(mZlib, "ZLIB_VERSION", rb_str_new2(ZLIB_VERSION));

    cZStream = rb_define_class_under(mZlib, "ZStream", rb_cObject);
    rb_undef_alloc_func(cZStream);
    rb_define_method(cZStream, "avail_out", rb_zstream_avail_out, 0);
    rb_define_method(cZStream, "avail_out=", rb_zstream_set_avail_out, 1);
    rb_define_method(cZStream, "avail_in", rb_zstream_avail_in, 0);
    rb_define_method(cZStream, "total_in", rb_zstream_total_in, 0);
    rb_define_method(cZStream, "total_out", rb_zstream_total_out, 0);
    rb_define_method(cZStream, "data_type", rb_zstream_data_type, 0);
    rb_define_method(cZStream, "adler", rb_zstream_adler, 0);
    rb_define_method(cZStream, "finished?", rb_zstream_finished_p, 0);
    rb_define_method(cZStream, "stream_end?", rb_zstream_finished_p, 0);
    rb_define_method(cZStream, "closed?", rb_zstream_closed_p, 0);
    rb_define_method(cZStream, "ended?", rb_zstream_closed_p, 0);
    rb_define_method(cZStream, "close", rb_zstream_end, 0);
    rb_define_method(cZStream, "end", rb_zstream_end, 0);
    rb_define_method(cZStream, "reset", rb_zstream_reset, 0);
    rb_define_method(cZStream, "finish", rb_zstream_finish, 0);
    rb_define_method(cZStream, "flush_next_in", rb_zstream_flush_next_in, 0);
    rb_define_method(cZStream, "flush_next_out", rb_zstream_flush_next_out, 0);

    rb_define_const(mZlib, "BINARY", INT2FIX(Z_BINARY));
    rb_define_const(mZlib, "ASCII", INT2FIX(Z_ASCII));
    rb_define_const(mZlib, "UNKNOWN", INT2FIX(Z_UNKNOWN));

    cDeflate = rb_define_class_under(mZlib, "Deflate", cZStream);
    rb_define_singleton_method(cDeflate, "deflate", rb_deflate_s_deflate, -1);
    rb_define_singleton_method(mZlib, "deflate", rb_deflate_s_deflate, -1);
    rb_define_alloc_func(cDeflate, rb_deflate_s_allocate);
    rb_define_method(cDeflate, "initialize", rb_deflate_initialize, -1);
    rb_define_method(cDeflate, "initialize_copy", rb_deflate_init_copy, 1);
    rb_define_method(cDeflate, "deflate", rb_deflate_deflate, -1);
    rb_define_method(cDeflate, "<<", rb_deflate_addstr, 1);
    rb_define_method(cDeflate, "flush", rb_deflate_flush, -1);
    rb_define_method(cDeflate, "params", rb_deflate_params, 2);
    rb_define_method(cDeflate, "set_dictionary", rb_deflate_set_dictionary, 1);

    cInflate = rb_define_class_under(mZlib, "Inflate", cZStream);
    rb_define_singleton_method(cInflate, "inflate", rb_inflate_s_inflate, 1);
    rb_define_singleton_method(mZlib, "inflate", rb_inflate_s_inflate, 1);
    rb_define_alloc_func(cInflate, rb_inflate_s_allocate);
    rb_define_method(cInflate, "initialize", rb_inflate_initialize, -1);
    rb_define_method(cInflate, "inflate", rb_inflate_inflate, 1);
    rb_define_method(cInflate, "<<", rb_inflate_addstr, 1);
    rb_define_method(cInflate, "sync", rb_inflate_sync, 1);
    rb_define_method(cInflate, "sync_point?", rb_inflate_sync_point_p, 0);
    rb_define_method(cInflate, "set_dictionary", rb_inflate_set_dictionary, 1);

    rb_define_const(mZlib, "NO_COMPRESSION", INT2FIX(Z_NO_COMPRESSION));
    rb_define_const(mZlib, "BEST_SPEED", INT2FIX(Z_BEST_SPEED));
    rb_define_const(mZlib, "BEST_COMPRESSION", INT2FIX(Z_BEST_COMPRESSION));
    rb_define_const(mZlib, "DEFAULT_COMPRESSION",
		    INT2FIX(Z_DEFAULT_COMPRESSION));

    rb_define_const(mZlib, "FILTERED", INT2FIX(Z_FILTERED));
    rb_define_const(mZlib, "HUFFMAN_ONLY", INT2FIX(Z_HUFFMAN_ONLY));
    rb_define_const(mZlib, "DEFAULT_STRATEGY", INT2FIX(Z_DEFAULT_STRATEGY));

    rb_define_const(mZlib, "MAX_WBITS", INT2FIX(MAX_WBITS));
    rb_define_const(mZlib, "DEF_MEM_LEVEL", INT2FIX(DEF_MEM_LEVEL));
    rb_define_const(mZlib, "MAX_MEM_LEVEL", INT2FIX(MAX_MEM_LEVEL));

    rb_define_const(mZlib, "NO_FLUSH", INT2FIX(Z_NO_FLUSH));
    rb_define_const(mZlib, "SYNC_FLUSH", INT2FIX(Z_SYNC_FLUSH));
    rb_define_const(mZlib, "FULL_FLUSH", INT2FIX(Z_FULL_FLUSH));
    rb_define_const(mZlib, "FINISH", INT2FIX(Z_FINISH));

#if GZIP_SUPPORT
    id_write = rb_intern("write");
    id_read = rb_intern("read");
    id_readpartial = rb_intern("readpartial");
    id_flush = rb_intern("flush");
    id_seek = rb_intern("seek");
    id_close = rb_intern("close");
    id_path = rb_intern("path");
    id_input = rb_intern("@input");

    cGzipFile = rb_define_class_under(mZlib, "GzipFile", rb_cObject);
    cGzError = rb_define_class_under(cGzipFile, "Error", cZError);
    rb_define_attr(cGzError, "input", 1, 0);
    rb_define_method(cGzError, "inspect", gzfile_error_inspect, 0);

    cNoFooter = rb_define_class_under(cGzipFile, "NoFooter", cGzError);
    cCRCError = rb_define_class_under(cGzipFile, "CRCError", cGzError);
    cLengthError = rb_define_class_under(cGzipFile,"LengthError",cGzError);

    cGzipWriter = rb_define_class_under(mZlib, "GzipWriter", cGzipFile);
    cGzipReader = rb_define_class_under(mZlib, "GzipReader", cGzipFile);
    rb_include_module(cGzipReader, rb_mEnumerable);

    rb_define_singleton_method(cGzipFile, "wrap", rb_gzfile_s_wrap, -1);
    rb_undef_alloc_func(cGzipFile);
    rb_define_method(cGzipFile, "to_io", rb_gzfile_to_io, 0);
    rb_define_method(cGzipFile, "crc", rb_gzfile_crc, 0);
    rb_define_method(cGzipFile, "mtime", rb_gzfile_mtime, 0);
    rb_define_method(cGzipFile, "level", rb_gzfile_level, 0);
    rb_define_method(cGzipFile, "os_code", rb_gzfile_os_code, 0);
    rb_define_method(cGzipFile, "orig_name", rb_gzfile_orig_name, 0);
    rb_define_method(cGzipFile, "comment", rb_gzfile_comment, 0);
    rb_define_method(cGzipReader, "lineno", rb_gzfile_lineno, 0);
    rb_define_method(cGzipReader, "lineno=", rb_gzfile_set_lineno, 1);
    rb_define_method(cGzipWriter, "mtime=", rb_gzfile_set_mtime, 1);
    rb_define_method(cGzipWriter, "orig_name=", rb_gzfile_set_orig_name,1);
    rb_define_method(cGzipWriter, "comment=", rb_gzfile_set_comment, 1);
    rb_define_method(cGzipFile, "close", rb_gzfile_close, 0);
    rb_define_method(cGzipFile, "finish", rb_gzfile_finish, 0);
    rb_define_method(cGzipFile, "closed?", rb_gzfile_closed_p, 0);
    rb_define_method(cGzipReader, "eof", rb_gzfile_eof_p, 0);
    rb_define_method(cGzipReader, "eof?", rb_gzfile_eof_p, 0);
    rb_define_method(cGzipFile, "sync", rb_gzfile_sync, 0);
    rb_define_method(cGzipFile, "sync=", rb_gzfile_set_sync, 1);
    rb_define_method(cGzipReader, "pos", rb_gzfile_total_out, 0);
    rb_define_method(cGzipWriter, "pos", rb_gzfile_total_in, 0);
    rb_define_method(cGzipReader, "tell", rb_gzfile_total_out, 0);
    rb_define_method(cGzipWriter, "tell", rb_gzfile_total_in, 0);

    rb_define_singleton_method(cGzipWriter, "open", rb_gzwriter_s_open,-1);
    rb_define_alloc_func(cGzipWriter, rb_gzwriter_s_allocate);
    rb_define_method(cGzipWriter, "initialize", rb_gzwriter_initialize,-1);
    rb_define_method(cGzipWriter, "flush", rb_gzwriter_flush, -1);
    rb_define_method(cGzipWriter, "write", rb_gzwriter_write, 1);
    rb_define_method(cGzipWriter, "putc", rb_gzwriter_putc, 1);
    rb_define_method(cGzipWriter, "<<", rb_gzwriter_addstr, 1);
    rb_define_method(cGzipWriter, "printf", rb_gzwriter_printf, -1);
    rb_define_method(cGzipWriter, "print", rb_gzwriter_print, -1);
    rb_define_method(cGzipWriter, "puts", rb_gzwriter_puts, -1);

    rb_define_singleton_method(cGzipReader, "open", rb_gzreader_s_open,-1);
    rb_define_alloc_func(cGzipReader, rb_gzreader_s_allocate);
    rb_define_method(cGzipReader, "initialize", rb_gzreader_initialize, -1);
    rb_define_method(cGzipReader, "rewind", rb_gzreader_rewind, 0);
    rb_define_method(cGzipReader, "unused", rb_gzreader_unused, 0);
    rb_define_method(cGzipReader, "read", rb_gzreader_read, -1);
    rb_define_method(cGzipReader, "readpartial", rb_gzreader_readpartial, -1);
    rb_define_method(cGzipReader, "getc", rb_gzreader_getc, 0);
    rb_define_method(cGzipReader, "getbyte", rb_gzreader_getbyte, 0);
    rb_define_method(cGzipReader, "readchar", rb_gzreader_readchar, 0);
    rb_define_method(cGzipReader, "readbyte", rb_gzreader_readbyte, 0);
    rb_define_method(cGzipReader, "each_byte", rb_gzreader_each_byte, 0);
    rb_define_method(cGzipReader, "each_char", rb_gzreader_each_char, 0);
    rb_define_method(cGzipReader, "bytes", rb_gzreader_each_byte, 0);
    rb_define_method(cGzipReader, "ungetc", rb_gzreader_ungetc, 1);
    rb_define_method(cGzipReader, "ungetbyte", rb_gzreader_ungetbyte, 1);
    rb_define_method(cGzipReader, "gets", rb_gzreader_gets, -1);
    rb_define_method(cGzipReader, "readline", rb_gzreader_readline, -1);
    rb_define_method(cGzipReader, "each", rb_gzreader_each, -1);
    rb_define_method(cGzipReader, "each_line", rb_gzreader_each, -1);
    rb_define_method(cGzipReader, "lines", rb_gzreader_each, -1);
    rb_define_method(cGzipReader, "readlines", rb_gzreader_readlines, -1);

    rb_define_const(mZlib, "OS_CODE", INT2FIX(OS_CODE));
    rb_define_const(mZlib, "OS_MSDOS", INT2FIX(OS_MSDOS));
    rb_define_const(mZlib, "OS_AMIGA", INT2FIX(OS_AMIGA));
    rb_define_const(mZlib, "OS_VMS", INT2FIX(OS_VMS));
    rb_define_const(mZlib, "OS_UNIX", INT2FIX(OS_UNIX));
    rb_define_const(mZlib, "OS_ATARI", INT2FIX(OS_ATARI));
    rb_define_const(mZlib, "OS_OS2", INT2FIX(OS_OS2));
    rb_define_const(mZlib, "OS_MACOS", INT2FIX(OS_MACOS));
    rb_define_const(mZlib, "OS_TOPS20", INT2FIX(OS_TOPS20));
    rb_define_const(mZlib, "OS_WIN32", INT2FIX(OS_WIN32));

    rb_define_const(mZlib, "OS_VMCMS", INT2FIX(OS_VMCMS));
    rb_define_const(mZlib, "OS_ZSYSTEM", INT2FIX(OS_ZSYSTEM));
    rb_define_const(mZlib, "OS_CPM", INT2FIX(OS_CPM));
    rb_define_const(mZlib, "OS_QDOS", INT2FIX(OS_QDOS));
    rb_define_const(mZlib, "OS_RISCOS", INT2FIX(OS_RISCOS));
    rb_define_const(mZlib, "OS_UNKNOWN", INT2FIX(OS_UNKNOWN));

#endif /* GZIP_SUPPORT */
}

/* Document error classes. */

/*
 * Document-class: Zlib::Error
 *
 * The superclass for all exceptions raised by Ruby/zlib.
 *
 * The following exceptions are defined as subclasses of Zlib::Error. These
 * exceptions are raised when zlib library functions return with an error
 * status.
 *
 * - Zlib::StreamEnd
 * - Zlib::NeedDict
 * - Zlib::DataError
 * - Zlib::StreamError
 * - Zlib::MemError
 * - Zlib::BufError
 * - Zlib::VersionError
 *
 */

/*
 * Document-class: Zlib::GzipFile::Error
 *
 * Base class of errors that occur when processing GZIP files.
 */

/*
 * Document-class: Zlib::GzipFile::NoFooter
 *
 * Raised when gzip file footer is not found.
 */

/*
 * Document-class: Zlib::GzipFile::CRCError
 *
 * Raised when the CRC checksum recorded in gzip file footer is not equivalent
 * to the CRC checksum of the actual uncompressed data.
 */

/*
 * Document-class: Zlib::GzipFile::LengthError
 *
 * Raised when the data length recorded in the gzip file footer is not equivalent
 * to the length of the actual uncompressed data.
 */