package gapi-ocaml

  1. Overview
  2. Docs
A simple OCaml client for Google Services

Install

Dune Dependency

Authors

Maintainers

Sources

v0.4.6.tar.gz
sha256=b84b680528a5e050014103a8e7a60a5d43efd5fefc3f838310bd46769775ab48
md5=8ee26acf1f6c6f5e24c7b57fa070a0a2

doc/src/gapi-ocaml.netstring-local/netconversion.ml.html

Source file netconversion.ml

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
(* $Id$
 * ----------------------------------------------------------------------
 *)

open Netsys_types
open Netaux.ArrayAux

exception Malformed_code

exception Cannot_represent of int

let multibyte_limit = (* 6 *) 50;;
  (* The longest multibyte character of all supported encodings,
   * and the longest substitution string.
   *)

let big_slice = (* 3 *) 250;;
  (* The typical length of slices *)


(* Seems to be a good source: ftp://dkuug.dk/i18n/charmaps
 *)

type encoding =
  [  `Enc_utf8       (* UTF-8 *)
  |  `Enc_utf8_opt_bom
  |  `Enc_java
  |  `Enc_utf16      (* UTF-16 with unspecified endianess (restricted usage) *)
  |  `Enc_utf16_le   (* UTF-16 little endian *)
  |  `Enc_utf16_be   (* UTF-16 big endian *)
  |  `Enc_utf32      (* UTF-32 with unspecified endianess (restricted usage) *)
  |  `Enc_utf32_le   (* UTF-32 little endian *)
  |  `Enc_utf32_be   (* UTF-32 big endian *)
  |  `Enc_usascii    (* US-ASCII (only 7 bit) *)
  |  `Enc_iso88591   (* ISO-8859-1 *)
  |  `Enc_iso88592   (* ISO-8859-2 *)
  |  `Enc_iso88593   (* ISO-8859-3 *)
  |  `Enc_iso88594   (* ISO-8859-4 *)
  |  `Enc_iso88595   (* ISO-8859-5 *)
  |  `Enc_iso88596   (* ISO-8859-6 *)
  |  `Enc_iso88597   (* ISO-8859-7 *)
  |  `Enc_iso88598   (* ISO-8859-8 *)
  |  `Enc_iso88599   (* ISO-8859-9 *)
  |  `Enc_iso885910  (* ISO-8859-10 *)
  |  `Enc_iso885911  (* ISO-8859-11 *)
  |  `Enc_iso885913  (* ISO-8859-13 *)
  |  `Enc_iso885914  (* ISO-8859-14 *)
  |  `Enc_iso885915  (* ISO-8859-15 *)
  |  `Enc_iso885916  (* ISO-8859-16 *)
  |  `Enc_koi8r      (* KOI8-R *)   (* http://koi8.pp.ru *)
(*|  `Enc_koi8u      (* KOI8-U *)   (* http://www.net.ua/KOI8-U/index.html *)*)
  |  `Enc_jis0201    (* JIS-X-0201 *)
(*
  |  `Enc_jis0201_roman  (* JIS-X-0201 only roman half *)
  |  `Enc_jis0201_kana   (* JIS-X-0201 katakana half remapped to 0x21..XXX *)
  |  `Enc_jis0208_94x94  (* JIS-X-0208 in ISO-2022-style two byte encoding *)
  |  `Enc_jis0212_94x94  (* JIS-X-0212 in ISO-2022-style two byte encoding *)
*)
  |  `Enc_eucjp      (* EUC-JP *)
  |  `Enc_euckr      (* EUC-KR *)
(* 
  |  `Enc_iso2022 of iso2022_state
  |  `Enc_iso2022jp of iso2022jp_state
*)
    (* Older standards: *)
  |  `Enc_asn1_iso646     (* only the language-neutral subset *)
  |  `Enc_asn1_T61        (* ITU T.61 ("Teletex") *)
  |  `Enc_asn1_printable
    (* Microsoft: *)
  |  `Enc_windows1250  (* WINDOWS-1250 *)
  |  `Enc_windows1251  (* WINDOWS-1251 *)
  |  `Enc_windows1252  (* WINDOWS-1252 *)
  |  `Enc_windows1253  (* WINDOWS-1253 *)
  |  `Enc_windows1254  (* WINDOWS-1254 *)
  |  `Enc_windows1255  (* WINDOWS-1255 *)
  |  `Enc_windows1256  (* WINDOWS-1256 *)
  |  `Enc_windows1257  (* WINDOWS-1257 *)
  |  `Enc_windows1258  (* WINDOWS-1258 *)
    (* IBM, ASCII-based: *)
  |  `Enc_cp437
  |  `Enc_cp737
  |  `Enc_cp775
  |  `Enc_cp850
  |  `Enc_cp852
  |  `Enc_cp855
  |  `Enc_cp856
  |  `Enc_cp857
  |  `Enc_cp860
  |  `Enc_cp861
  |  `Enc_cp862
  |  `Enc_cp863
  |  `Enc_cp864
  |  `Enc_cp865
  |  `Enc_cp866  (* Russian *)
  |  `Enc_cp869
  |  `Enc_cp874
  |  `Enc_cp1006
   (* IBM, EBCDIC-based: *)
  |  `Enc_cp037   (* EBCDIC USA Canada *)
      (* 273: EBCDIC Germany, Austria,
       * 277: Denmark, Norway,
       * 278: Finland, Sweden,
       * 280: Italy,
       * 284: Spain, Latin America,
       * 285: United Kingdom,
       * 297: France,
       * 871: Iceland,
       *)
  |  `Enc_cp424
  |  `Enc_cp500  (* EBCDIC International *)
  |  `Enc_cp875  (* EBCDIC Modern Greek *)
  |  `Enc_cp1026 (* EBCDIC Turkish *)
  |  `Enc_cp1047 (* EBCDIC Latin1, OS 390 System Services *)
   (* Adobe: *)
  |  `Enc_adobe_standard_encoding
  |  `Enc_adobe_symbol_encoding
  |  `Enc_adobe_zapf_dingbats_encoding
   (* Apple: *)
  |  `Enc_macroman
   (* Encoding subset: *)
  |  `Enc_subset of (encoding * (int -> bool))
  |  `Enc_empty
  ]
;;


type charset =
  [  `Set_unicode    (* The full Unicode repertoire *)
  |  `Set_usascii    (* US-ASCII (only 7 bit) *)
  |  `Set_iso88591   (* ISO-8859-1 *)
  |  `Set_iso88592   (* ISO-8859-2 *)
  |  `Set_iso88593   (* ISO-8859-3 *)
  |  `Set_iso88594   (* ISO-8859-4 *)
  |  `Set_iso88595   (* ISO-8859-5 *)
  |  `Set_iso88596   (* ISO-8859-6 *)
  |  `Set_iso88597   (* ISO-8859-7 *)
  |  `Set_iso88598   (* ISO-8859-8 *)
  |  `Set_iso88599   (* ISO-8859-9 *)
  |  `Set_iso885910  (* ISO-8859-10 *)
  |  `Set_iso885911  (* ISO-8859-11 *)
  |  `Set_iso885913  (* ISO-8859-13 *)
  |  `Set_iso885914  (* ISO-8859-14 *)
  |  `Set_iso885915  (* ISO-8859-15 *)
  |  `Set_iso885916  (* ISO-8859-16 *)
  |  `Set_koi8r      (* KOI8-R *)
  |  `Set_jis0201    (* JIS-X-0201 *)
  |  `Set_jis0208    (* JIS-X-0208 *)
  |  `Set_jis0212    (* JIS-X-0212 *)
  |  `Set_ks1001     (* KS-X-1001 *)
  |  `Set_asn1_iso646
  |  `Set_asn1_T61
  |  `Set_asn1_printable
    (* Microsoft: *)
  |  `Set_windows1250  (* WINDOWS-1250 *)
  |  `Set_windows1251  (* WINDOWS-1251 *)
  |  `Set_windows1252  (* WINDOWS-1252 *)
  |  `Set_windows1253  (* WINDOWS-1253 *)
  |  `Set_windows1254  (* WINDOWS-1254 *)
  |  `Set_windows1255  (* WINDOWS-1255 *)
  |  `Set_windows1256  (* WINDOWS-1256 *)
  |  `Set_windows1257  (* WINDOWS-1257 *)
  |  `Set_windows1258  (* WINDOWS-1258 *)
    (* IBM, ASCII-based: *)
  |  `Set_cp437
  |  `Set_cp737
  |  `Set_cp775
  |  `Set_cp850
  |  `Set_cp852
  |  `Set_cp855
  |  `Set_cp856
  |  `Set_cp857
  |  `Set_cp860
  |  `Set_cp861
  |  `Set_cp862
  |  `Set_cp863
  |  `Set_cp864
  |  `Set_cp865
  |  `Set_cp866
  |  `Set_cp869
  |  `Set_cp874
  |  `Set_cp1006
   (* IBM, EBCDIC-based: *)
  |  `Set_cp037
  |  `Set_cp424
  |  `Set_cp500
  |  `Set_cp875
  |  `Set_cp1026
  |  `Set_cp1047
   (* Adobe: *)
  |  `Set_adobe_standard_encoding
  |  `Set_adobe_symbol_encoding
  |  `Set_adobe_zapf_dingbats_encoding
   (* Apple: *)
  |  `Set_macroman
  ]
;;


let ascii_compat_encodings =
  [ `Enc_utf8;  `Enc_utf8_opt_bom; `Enc_java; `Enc_usascii;
    `Enc_iso88591; `Enc_iso88592; `Enc_iso88593; `Enc_iso88594; `Enc_iso88595;
    `Enc_iso88596; `Enc_iso88597; `Enc_iso88598; `Enc_iso88599; `Enc_iso885910;
    `Enc_iso885911; `Enc_iso885913; `Enc_iso885914; `Enc_iso885915;
    `Enc_iso885916;
    `Enc_koi8r;
    `Enc_windows1250; `Enc_windows1251; `Enc_windows1252; `Enc_windows1253;
    `Enc_windows1254; `Enc_windows1255; `Enc_windows1256; `Enc_windows1257;
    `Enc_windows1258;
    `Enc_cp437; `Enc_cp737; `Enc_cp775; `Enc_cp850; `Enc_cp852; `Enc_cp855;
    `Enc_cp856; `Enc_cp857; `Enc_cp860; `Enc_cp861; `Enc_cp862; `Enc_cp863;
    `Enc_cp864; `Enc_cp865; `Enc_cp866; `Enc_cp869; `Enc_cp874; `Enc_cp1006;
    `Enc_eucjp; `Enc_euckr;
    `Enc_macroman;
  ]
;;


let rec is_ascii_compatible = 
  function
    | `Enc_subset(e,_) -> is_ascii_compatible e
    | e -> List.mem e ascii_compat_encodings
;;


let rec is_single_byte =
  function
      `Enc_utf8
    | `Enc_utf8_opt_bom
    | `Enc_java
    | `Enc_utf16
    | `Enc_utf16_le
    | `Enc_utf16_be
    | `Enc_utf32
    | `Enc_utf32_le
    | `Enc_utf32_be -> false
    | `Enc_eucjp -> false
    | `Enc_euckr -> false
    | `Enc_subset(e,_) -> is_single_byte e
    | _ -> true
;;


let punct_re = Netstring_str.regexp "[-_.]";;
let ibm_re = Netstring_str.regexp "^IBM\\([0-9]+\\)$";;
let year_re = Netstring_str.regexp ":[0-9][0-9][0-9][0-9]$";;


let norm_enc_name e =
  (* Removes some punctuation characters from e; uppercase;
   * converts "IBM#" to "CP#"; drops ":YEAR" suffixes 
   *)
  let e1 = STRING_UPPERCASE e in
  let e2 = Netstring_str.global_replace punct_re "" e1 in
  let e3 = Netstring_str.global_replace year_re "" e2 in
  match Netstring_str.string_match ibm_re e3 0 with
      Some r ->
	"CP" ^ Netstring_str.matched_group r 1 e3
    | None ->
	e3
;;


let names =
  (* The first name is the official name, the other are aliases.
   * The aliases must not contain any of the punctuation characters
   * - _ .
   * `Enc_subset is missing in this list, of course.
   *
   * http://www.iana.org/assignments/character-sets
   *
   * A good reference is also:
   * http://www.firstobject.com/character-set-name-alias-code-page.htm
   *)
  [ `Enc_utf16,        [ "UTF-16"; "UTF16"; "UCS2"; "ISO10646UCS2" ];
    `Enc_utf16_be,     [ "UTF-16BE"; "UTF16BE" ];
    `Enc_utf16_le,     [ "UTF-16LE"; "UTF16LE" ];
    `Enc_utf32,        [ "UTF-32"; "UTF32"; "UCS4"; "ISO10646UCS4" ];
    `Enc_utf32_be,     [ "UTF-32BE"; "UTF32BE" ];
    `Enc_utf32_le,     [ "UTF-32LE"; "UTF32LE" ];
    `Enc_utf8,         [ "UTF-8"; "UTF8" ];
    `Enc_utf8_opt_bom, [ "UTF-8"; "UTF8" ];
    `Enc_java,         [ "UTF-8-JAVA"; "UTF8JAVA"; "JAVA" ];
    `Enc_usascii,      [ "US-ASCII"; "USASCII"; "ASCII"; "ISO646US"; "CP367"; 
			 "ISOIR6"; "ANSIX341968" ];
    `Enc_iso88591,     [ "ISO-8859-1"; "ISO88591"; "LATIN1"; "CP819"; 
			 "ISOIR100" ];
    `Enc_iso88592,     [ "ISO-8859-2"; "ISO88592"; "LATIN2"; "ISOIR101";
			 "CP912"
		       ];
    `Enc_iso88593,     [ "ISO-8859-3"; "ISO88593"; "LATIN3"; "ISOIR109" ];
    `Enc_iso88594,     [ "ISO-8859-4"; "ISO88594"; "LATIN4"; "ISOIR110" ];
    `Enc_iso88595,     [ "ISO-8859-5"; "ISO88595"; "CYRILLIC"; "ISOIR144";
			 "CP915"
		       ];
    `Enc_iso88596,     [ "ISO-8859-6"; "ISO88596"; "ARABIC"; "ECMA114"; 
			 "ASMO708"; "ISOIR127"; "CP1089" ];
    `Enc_iso88597,     [ "ISO-8859-7"; "ISO88597"; "GREEK"; "GREEK8"; 
			 "ELOT928"; "ECMA118"; "ISOIR126"; "CP813" ];
    `Enc_iso88598,     [ "ISO-8859-8"; "ISO88598"; "HEBREW"; "ISOIR138";
			 "CP916"
		       ];
    `Enc_iso88599,     [ "ISO-8859-9"; "ISO88599"; "LATIN5"; "ISOIR148";
			 "CP920"
		       ];
    `Enc_iso885910,    [ "ISO-8859-10"; "ISO885910"; "LATIN6"; "ISOIR157" ];
    `Enc_iso885911,    [ "ISO-8859-11"; "ISO885911"; ];
    `Enc_iso885913,    [ "ISO-8859-13"; "ISO885913"; "LATIN7" ];
    `Enc_iso885914,    [ "ISO-8859-14"; "ISO885914"; "LATIN8"; "ISOIR199"; 
			 "ISOCELTIC" ];
    `Enc_iso885915,    [ "ISO-8859-15"; "ISO885915"; "LATIN9"; "ISOIR203" ];
    `Enc_iso885916,    [ "ISO-8859-16"; "ISO885916"; "LATIN10"; "SR14111"; 
			 "ROMANIAN"; "ISOIR226" ];
    `Enc_koi8r,        [ "KOI8-R"; "KOI8R"; "CP878" ];
    `Enc_jis0201,      [ "JIS_X0201"; "JIS0201"; "JISX0201"; "X0201" ];
    `Enc_eucjp,        [ "EUC-JP"; "EUCJP"; ];
    `Enc_euckr,        [ "EUC-KR"; "EUCKR"; ];
    `Enc_windows1250,  [ "WINDOWS-1250"; "WINDOWS1250" ];
    `Enc_windows1251,  [ "WINDOWS-1251"; "WINDOWS1251" ];
    `Enc_windows1252,  [ "WINDOWS-1252"; "WINDOWS1252" ];
    `Enc_windows1253,  [ "WINDOWS-1253"; "WINDOWS1253" ];
    `Enc_windows1254,  [ "WINDOWS-1254"; "WINDOWS1254" ];
    `Enc_windows1255,  [ "WINDOWS-1255"; "WINDOWS1255" ];
    `Enc_windows1256,  [ "WINDOWS-1256"; "WINDOWS1256" ];
    `Enc_windows1257,  [ "WINDOWS-1257"; "WINDOWS1257" ];
    `Enc_windows1258,  [ "WINDOWS-1258"; "WINDOWS1258" ];
    `Enc_cp437,        [ "IBM437"; "CP437" ];
    `Enc_cp737,        [ "IBM737"; "CP737" ];
    `Enc_cp775,        [ "IBM775"; "CP775" ];
    `Enc_cp850,        [ "IBM850"; "CP850" ];
    `Enc_cp852,        [ "IBM852"; "CP852" ];
    `Enc_cp855,        [ "IBM855"; "CP855" ];
    `Enc_cp856,        [ "IBM856"; "CP856" ];
    `Enc_cp857,        [ "IBM857"; "CP857" ];
    `Enc_cp860,        [ "IBM860"; "CP860" ];
    `Enc_cp861,        [ "IBM861"; "CP861"; "CPIS" ];
    `Enc_cp862,        [ "IBM862"; "CP862" ];
    `Enc_cp863,        [ "IBM863"; "CP863" ];
    `Enc_cp864,        [ "IBM864"; "CP864" ];
    `Enc_cp865,        [ "IBM865"; "CP865" ];
    `Enc_cp866,        [ "IBM866"; "CP866" ];
    `Enc_cp869,        [ "IBM869"; "CP869"; "CPGR" ];
    `Enc_cp874,        [ "IBM874"; "CP874" ];
    `Enc_cp1006,       [ "IBM1006"; "CP1006" ];
    `Enc_cp037,        [ "IBM037"; "CP037"; "EBCDICCPUS"; "EBCDICCPCA"; 
			 "EBCDICCPWT"; "EBCDICCPNL" ];
    `Enc_cp424,        [ "IBM424"; "CP424"; "EBCDICCPHE" ];
    `Enc_cp500,        [ "IBM500"; "CP500"; "EBCDICCPBE"; "EBCDICCPCH" ];
    `Enc_cp875,        [ "IBM875"; "CP875" ];
    `Enc_cp1026,       [ "IBM1026"; "CP1026" ];
    `Enc_cp1047,       [ "IBM1047"; "CP1047"; ];
    `Enc_adobe_standard_encoding,       [ "ADOBE-STANDARD-ENCODING"; 
					  "ADOBESTANDARDENCODING" ];
    `Enc_adobe_symbol_encoding,         [ "ADOBE-SYMBOL-ENCODING"; 
					  "ADOBESYMBOLENCODING" ];
    `Enc_adobe_zapf_dingbats_encoding,  [ "ADOBE-ZAPF-DINGBATS-ENCODING"; 
					  "ADOBEZAPFDINGBATSENCODING" ];
    `Enc_macroman,                      [ "MACINTOSH"; "MACINTOSH"; 
					  "MACROMAN"; "MAC" ];

    (* The ASN.1 encodings are intentionally not member of this list *)
  ]
;;


let encoding_of_string e =
  let ne = norm_enc_name e in
  try
    fst
      (List.find
	 (fun (enc, nlist) ->
	    List.mem ne (List.tl nlist))
	 names
      )
  with
      Not_found ->
	failwith "Netconversion.encoding_of_string: unknown encoding"
;;


let rec string_of_encoding (e : encoding) =
  (* If there is a "preferred MIME name", this name is returned (see IANA). *)
  match e with
    | `Enc_subset(e,_) -> string_of_encoding e
    | _ ->
	try
	  let l = List.assoc e names in
	  List.hd l
	with
	    Not_found -> assert false
	      (* Because [names] must be complete *)
;;


let internal_name (cs : charset) =
  (* The name used for netdb lookups *)
  match cs with
    | `Set_unicode -> "unicode"
    | `Set_usascii -> "usascii"
    | `Set_iso88591 -> "iso88591"
    | `Set_iso88592 -> "iso88592"
    | `Set_iso88593 -> "iso88593"
    | `Set_iso88594 -> "iso88594"
    | `Set_iso88595 -> "iso88595"
    | `Set_iso88596 -> "iso88596"
    | `Set_iso88597 -> "iso88597"
    | `Set_iso88598 -> "iso88598"
    | `Set_iso88599 -> "iso88599"
    | `Set_iso885910 -> "iso885910"
    | `Set_iso885911 -> "iso885911"
    | `Set_iso885913 -> "iso885913"
    | `Set_iso885914 -> "iso885914"
    | `Set_iso885915 -> "iso885915"
    | `Set_iso885916 -> "iso885916"
    | `Set_koi8r -> "koi8r"
    | `Set_jis0201 -> "jis0201"
    | `Set_jis0208 -> "jis0208"
    | `Set_jis0212 -> "jis0212"
    | `Set_ks1001 -> "ks1001"
    | `Set_asn1_iso646 -> "asn1_iso646"
    | `Set_asn1_T61 -> "asn1_t61"
    | `Set_asn1_printable -> "asn1_printable"
    | `Set_windows1250 -> "windows1250"
    | `Set_windows1251 -> "windows1251"
    | `Set_windows1252 -> "windows1252"
    | `Set_windows1253 -> "windows1253"
    | `Set_windows1254 -> "windows1254"
    | `Set_windows1255 -> "windows1255"
    | `Set_windows1256 -> "windows1256"    
    | `Set_windows1257 -> "windows1257"
    | `Set_windows1258 -> "windows1258"
    | `Set_cp437 -> "cp437"
    | `Set_cp737 -> "cp737"
    | `Set_cp775 -> "cp775"
    | `Set_cp850 -> "cp850"
    | `Set_cp852 -> "cp852"
    | `Set_cp855 -> "cp855"
    | `Set_cp856 -> "cp856"
    | `Set_cp857 -> "cp857"
    | `Set_cp860 -> "cp860"
    | `Set_cp861 -> "cp861"
    | `Set_cp862 -> "cp862"
    | `Set_cp863 -> "cp863"
    | `Set_cp864 -> "cp864"
    | `Set_cp865 -> "cp865"
    | `Set_cp866 -> "cp866"
    | `Set_cp869 -> "cp869"
    | `Set_cp874 -> "cp874"
    | `Set_cp1006 -> "cp1006"
    | `Set_cp037 -> "cp037"
    | `Set_cp424 -> "cp424"
    | `Set_cp500 -> "cp500"
    | `Set_cp875 -> "cp875"
    | `Set_cp1026 -> "cp1026"
    | `Set_cp1047 -> "cp1047"
    | `Set_adobe_standard_encoding -> "adobe_standard_encoding"
    | `Set_adobe_symbol_encoding -> "adobe_symbol_encoding"
    | `Set_adobe_zapf_dingbats_encoding -> "adobe_zapf_dingbats_encoding"
    | `Set_macroman -> "macroman"
;;


let rec required_charsets (e : encoding) =
  (* The name is a bit misleading. The function returns the charsets that
   * correspond to the conversion tables that are required to support the
   * encoding.
   *)
  match e with
    | `Enc_utf8 | `Enc_utf8_opt_bom | `Enc_java 
    | `Enc_utf16 | `Enc_utf16_le | `Enc_utf16_be
    | `Enc_utf32 | `Enc_utf32_le | `Enc_utf32_be ->
	[]
    | `Enc_usascii -> []
    | `Enc_iso88591 -> []
    | `Enc_iso88592 -> [ `Set_iso88592 ]
    | `Enc_iso88593 -> [ `Set_iso88593 ]
    | `Enc_iso88594 -> [ `Set_iso88594 ]
    | `Enc_iso88595 -> [ `Set_iso88595 ]
    | `Enc_iso88596 -> [ `Set_iso88596 ]
    | `Enc_iso88597 -> [ `Set_iso88597 ]
    | `Enc_iso88598 -> [ `Set_iso88598 ]
    | `Enc_iso88599 -> [ `Set_iso88599 ]
    | `Enc_iso885910 -> [ `Set_iso885910 ]
    | `Enc_iso885911 -> [ `Set_iso885911 ]
    | `Enc_iso885913 -> [ `Set_iso885913 ]
    | `Enc_iso885914 -> [ `Set_iso885914 ]
    | `Enc_iso885915 -> [ `Set_iso885915 ]
    | `Enc_iso885916 -> [ `Set_iso885916 ]
    | `Enc_koi8r -> [ `Set_koi8r ]
    | `Enc_jis0201 -> [ `Set_jis0201 ]
    | `Enc_eucjp -> [ `Set_jis0201; `Set_jis0208; `Set_jis0212 ]
    | `Enc_euckr -> [ `Set_ks1001 ]
    | `Enc_asn1_iso646 -> [ `Set_asn1_iso646 ]
    | `Enc_asn1_T61 -> [ `Set_asn1_T61 ]
    | `Enc_asn1_printable -> [ `Set_asn1_printable ]
    | `Enc_windows1250 -> [ `Set_windows1250 ]
    | `Enc_windows1251 -> [ `Set_windows1251 ]
    | `Enc_windows1252 -> [ `Set_windows1252 ]
    | `Enc_windows1253 -> [ `Set_windows1253 ]
    | `Enc_windows1254 -> [ `Set_windows1254 ]
    | `Enc_windows1255 -> [ `Set_windows1255 ]
    | `Enc_windows1256 -> [ `Set_windows1256 ]    
    | `Enc_windows1257 -> [ `Set_windows1257 ]
    | `Enc_windows1258 -> [ `Set_windows1258 ]
    | `Enc_cp437 -> [ `Set_cp437 ]
    | `Enc_cp737 -> [ `Set_cp737 ]
    | `Enc_cp775 -> [ `Set_cp775 ]
    | `Enc_cp850 -> [ `Set_cp850 ]
    | `Enc_cp852 -> [ `Set_cp852 ]
    | `Enc_cp855 -> [ `Set_cp855 ]
    | `Enc_cp856 -> [ `Set_cp856 ]
    | `Enc_cp857 -> [ `Set_cp857 ]
    | `Enc_cp860 -> [ `Set_cp860 ]
    | `Enc_cp861 -> [ `Set_cp861 ]
    | `Enc_cp862 -> [ `Set_cp862 ]
    | `Enc_cp863 -> [ `Set_cp863 ]
    | `Enc_cp864 -> [ `Set_cp864 ]
    | `Enc_cp865 -> [ `Set_cp865 ]
    | `Enc_cp866 -> [ `Set_cp866 ]
    | `Enc_cp869 -> [ `Set_cp869 ]
    | `Enc_cp874 -> [ `Set_cp874 ]
    | `Enc_cp1006 -> [ `Set_cp1006 ]
    | `Enc_cp037 -> [ `Set_cp037 ]
    | `Enc_cp424 -> [ `Set_cp424 ]
    | `Enc_cp500 -> [ `Set_cp500 ]
    | `Enc_cp875 -> [ `Set_cp875 ]
    | `Enc_cp1026 -> [ `Set_cp1026 ]
    | `Enc_cp1047 -> [ `Set_cp1047 ]
    | `Enc_adobe_standard_encoding -> [ `Set_adobe_standard_encoding ]
    | `Enc_adobe_symbol_encoding -> [ `Set_adobe_symbol_encoding ]
    | `Enc_adobe_zapf_dingbats_encoding -> [ `Set_adobe_zapf_dingbats_encoding ]
    | `Enc_macroman -> [ `Set_macroman ]
    | `Enc_subset(e',_) -> required_charsets e'
    | `Enc_empty -> []
;;


let rec same_encoding e1 e2 =
  match (e1,e2) with
      (`Enc_subset(e1_sub, f1), `Enc_subset(e2_sub, f2)) ->
	same_encoding e1_sub e2_sub && f1 == f2
    | (_,_) ->
	e1 = e2
;;


let rec byte_order_mark =
  function
      `Enc_utf16_le -> "\255\254"
    | `Enc_utf16_be -> "\254\255"
    | `Enc_utf32_le -> "\255\254\000\000"
    | `Enc_utf32_be -> "\000\000\254\255"
    | `Enc_subset(e,_) -> byte_order_mark e
    | _ -> ""
;;



let available_input_encodings() =
  let l = ref [] in
  List.iter
    (fun (e,_) ->
       let charsets = required_charsets e in
       if List.for_all 
	    (fun cs -> Netdb.exists_db ("cmapf." ^ internal_name cs)) charsets
       then
	 l := e :: !l
    )
    names;
  !l
;;


let available_output_encodings() =
  let exclude = [ `Enc_utf16; `Enc_utf32 ] in
  let l = ref [] in
  List.iter
    (fun (e,_) ->
       if not (List.mem e exclude) then begin
	 let charsets = required_charsets e in
	 if List.for_all 
	      (fun cs -> Netdb.exists_db ("cmapr." ^ internal_name cs)) charsets
	 then
	   l := e :: !l
       end
    )
    names;
  !l
;;


let (win32_code_pages : (_ * encoding) list) =
  [  65001, `Enc_utf8;
     1200,  `Enc_utf16_le;
     1201,  `Enc_utf16_be;
     20127, `Enc_usascii;
     28591, `Enc_iso88591;
     28592, `Enc_iso88592;
     28593, `Enc_iso88593;
     28594, `Enc_iso88594;
     28595, `Enc_iso88595;
     28596, `Enc_iso88596;
     28597, `Enc_iso88597;
     28598, `Enc_iso88598;
     28599, `Enc_iso88599;
     (* `Enc_iso885910 *)
     (* `Enc_iso885911 *)
     28603, `Enc_iso885913;
     (* `Enc_iso885914 *)
     28605, `Enc_iso885915;
     (* `Enc_iso885916 *)
     20866, `Enc_koi8r;
     (* `Enc_jis0201 *)
     20932, `Enc_eucjp;
     51949, `Enc_euckr;
     1250, `Enc_windows1250;
     1251, `Enc_windows1251;
     1252, `Enc_windows1252;
     1253, `Enc_windows1253;
     1254, `Enc_windows1254;
     1255, `Enc_windows1255;
     1256, `Enc_windows1256;
     1257, `Enc_windows1257;
     1258, `Enc_windows1258;
     437, `Enc_cp437;
     737, `Enc_cp737;
     775, `Enc_cp775;
     850, `Enc_cp850;
     852, `Enc_cp852;
     855, `Enc_cp855;
     (* `Enc_cp856 *)
     857, `Enc_cp857;
     860, `Enc_cp860;
     861, `Enc_cp861;
     862, `Enc_cp862;
     863, `Enc_cp863;
     864, `Enc_cp864;
     865, `Enc_cp865;
     866, `Enc_cp866;
     869, `Enc_cp869;
     874, `Enc_cp874;
     (* `Enc_cp1006 *)
     37, `Enc_cp037;
     20424, `Enc_cp424;
     500, `Enc_cp500;
     875, `Enc_cp875;
     1026, `Enc_cp1026;
     1047, `Enc_cp1047;
     (* `Enc_adobe_standard_encoding *)
     (* `Enc_adobe_symbol_encoding *)
     (* `Enc_adobe_zapf_dingbats_encoding *)
     10000, `Enc_macroman;
  ]

let user_encoding() =
  match Sys.os_type with
    | "Win32" ->
	let cp = Netsys_win32.get_active_code_page() in
	( try Some(List.assoc cp win32_code_pages)
	  with Not_found -> None
	)
    | _ ->
	( try
	    let codeset = 
	      (Netsys_posix.query_langinfo "").Netsys_posix.nl_CODESET in
	    Some(encoding_of_string codeset)
	  with
	    | _ -> None
	)

(* Internal conversion interface:
 *
 * let (n_char, n_byte, enc') = read_XXX slice_char slice_blen s_in p_in l_in:
 *
 *  - Scans the bytes from position p_in until the slice is decoded, but at
 *    most until the last position p_in+l_in-1 of the input string s_in, and 
 *    decodes the character for the selected encoding.
 *  - "slice_char" is a preallocated array of ints storing the code points
 *    of the characters. It is allowed that "slice_char" is only partially
 *    filled with characters. In this case, there must be a -1 after the
 *    last valid code point.
 *  - "slice_blen" is another "int array" with the same size as "slice_char".
 *    It contains the byte length of every character. It is initialized with
 *    a sequence of ones, so single-byte readers don't have to worry about
 *    this array.
 *  - Returns:
 *      * n_char: the number of decoded characters
 *      * n_byte: the number of scanned bytes ( <= l_in )
 *      * enc': the new encoding
 *  - In the case of multi-byte encodings it is possible that
 *    the last byte to read at position p_in+l_in-1 is the beginning of
 *    a character. This character is excluded from being decoded.
 *  - Errors: If an invalid byte sequence is found, the exception
 *    Malformed_code_read(_,_,_) is raised. The exception returns the
 *    triple (n_char, n_byte, enc') describing how much could be read
 *    before the reader ran into the bad sequence. slice_char and slice_blen
 *    are only partially initialized, with a (-1) at the end of slice_char.
 *
 * let (n_char, n_byte) = 
 *        write_XXX slice_char slice_pos slice_length s_out p_out l_out subst
 *
 *  - Writes the characters found in slice_char to s_out. Only the elements
 *    from slice_pos to slice_pos + slice_length -1 are written. The resulting
 *    bytes are written to s_out from byte position p_out to p_out+l_out-1.
 *  - There must not be a -1 (EOF mark) in the first slice_length characters
 *    of slice_char.
 *  - Only whole characters must be written.
 *  - For code points p that cannot be represented in the output
 *    encoding, the function subst is called. The function must return
 *    the (already encoded) string to substitute. This must be a small string.
 *  - Of course, p >= 0. As special case, p >= 0x110000 may be used to force
 *    that subst is called (it is assumed that max_int can be never
 *    represented).
 *  - Returns:
 *      * n_char: the number of processed characters
 *      * n_byte: the number of written bytes ( <= l_in )
 *
 * let (n_char, n_byte) =
 *        back_XXX s_in range_in range_in_len p_in n_char:
 *
 *  - The substring of s_in beginning at range_in and with length
 *    range_in_len is considered as the valid range
 *  - The cursor is at byte position p_in and goes n_char characters back
 *  - The routine returns:
 *      * n_char: the characters the cursor was actually moved backwards
 *      * n_byte: the bytes the cursor was actually moved backwards
 *  - The validity of the input encoding needs not to be checked
 *)

exception Malformed_code_read of (int * int * encoding);;
  (* not exported! *)

Callback.register_exception "Netconversion.Malformed_code_read"
			    (Malformed_code_read(0,0,`Enc_empty));;
  (* Needed by netaccel_c.c *)




(* UNSAFE_OPT: A number of functions have been optimized by using
 * unsafe features of O'Caml (unsafe_get, unsafe_set, unsafe_chr).
 * These functions have been checked very carefully, and there are
 * a lot of comments arguing about the correctness of the array
 * and string accesses.
 *)

type poly_reader =
    { read : 's . 's Netstring_tstring.tstring_ops -> 
                     int array -> int array -> 's -> int -> int -> 
                     (int * int * encoding)
    }


let read_iso88591 maxcode enc =
  (* UNSAFE_OPT *)
  let read ops slice_char slice_blen s_in p_in l_in =
    let open Netstring_tstring in
    assert(Array.length slice_char = Array.length slice_blen);
    assert(p_in >= 0 && p_in + l_in <= ops.length s_in && l_in >= 0);
    let m = min l_in (Array.length slice_char) in
    let m3 = m/3 in
    for k3 = 0 to m3-1 do
      let k = 3*k3 in
      (* let ch = Char.code s_in.[ p_in + k ] in *)
      let chars = ops.unsafe_get3 s_in (p_in + k) in
      let c0 = chars lsr 16 in
      let c1 = (chars lsr 8) land 0xff in
      let c2 = chars land 0xff in
      if c0 > maxcode then (
        slice_char.(k) <- (-1);
        raise(Malformed_code_read(k,k,enc))
      );
      Array.unsafe_set slice_char k c0;
      if c1 > maxcode then (
        slice_char.(k+1) <- (-1);
        raise(Malformed_code_read(k+1,k+1,enc))
      );
      Array.unsafe_set slice_char (k+1) c1;
      if c2 > maxcode then (
        slice_char.(k+2) <- (-1);
        raise(Malformed_code_read(k+2,k+2,enc))
      );
      Array.unsafe_set slice_char (k+2) c2;
    done;
    for k = 3*m3 to m-1 do
      let c0 = Char.code (ops.unsafe_get s_in (p_in + k)) in
      if c0 > maxcode then (
        slice_char.(k) <- (-1);
        raise(Malformed_code_read(k,k,enc))
      );
      Array.unsafe_set slice_char k c0;
    done;
    if m < Array.length slice_char then (
      slice_char.(m) <- (-1);
    );
    (m,m,enc) in
  { read }
;;


let read_iso88591_ref = ref read_iso88591;;


let get_8bit_to_unicode_map enc =
  let cs = 
    match required_charsets enc with
	[ cs ] -> cs 
      | _ -> failwith "get_8bit_to_unicode_map" in
  let to_unicode = Netmappings.get_to_unicode (internal_name cs) in
  assert(Array.length to_unicode = 256);
  to_unicode
;;


let read_8bit enc =
  let m_to_unicode = get_8bit_to_unicode_map enc in
  (* the 256-byte array mapping the character set to unicode *)

  let read ops slice_char slice_blen s_in p_in l_in =
    (* UNSAFE_OPT *)
    let open Netstring_tstring in
    assert(Array.length slice_char = Array.length slice_blen);
    assert(p_in >= 0 && p_in + l_in <= ops.length s_in && l_in >= 0);
    let m = min l_in (Array.length slice_char) in
    let m3 = m/3 in
    for k3 = 0 to m3-1 do
      let k = 3*k3 in
      let chars = ops.unsafe_get3 s_in k in
      let c0 = chars lsr 16 in
      let c1 = (chars lsr 8) land 0xff in
      let c2 = chars land 0xff in
      let c0_uni = Array.unsafe_get m_to_unicode c0 in
      if c0_uni < 0 then (
	slice_char.(k) <- (-1);
	raise(Malformed_code_read(k,k,enc));
      );
      Array.unsafe_set slice_char k c0_uni;
      let c1_uni = Array.unsafe_get m_to_unicode c1 in
      if c1_uni < 0 then (
	slice_char.(k+1) <- (-1);
	raise(Malformed_code_read(k+1,k+1,enc));
      );
      Array.unsafe_set slice_char (k+1) c1_uni;
      let c2_uni = Array.unsafe_get m_to_unicode c2 in
      if c2_uni < 0 then (
	slice_char.(k+2) <- (-1);
	raise(Malformed_code_read(k+2,k+2,enc));
      );
      Array.unsafe_set slice_char (k+2) c2_uni;
    done;
    for k = 3*m3 to m-1 do
      let c0 = Char.code (ops.get s_in k) in
      let c0_uni = Array.unsafe_get m_to_unicode c0 in
      if c0_uni < 0 then (
	slice_char.(k) <- (-1);
	raise(Malformed_code_read(k,k,enc));
      );
      Array.unsafe_set slice_char k c0_uni;
    done;
    if m < Array.length slice_char then (
      slice_char.(m) <- (-1);
    );
    (m,m,enc) in
  { read }
;;


let read_utf8 is_java =
  (* UNSAFE_OPT *)
  let read ops slice_char slice_blen s_in p_in l_in =
    let open Netstring_tstring in
    assert(Array.length slice_char = Array.length slice_blen);
    assert(p_in >= 0 && p_in + l_in <= ops.length s_in && l_in >= 0);

    (* k: counts the bytes
     * n: counts the characters
     *)

    let p = ref p_in in
    let p_max = p_in + l_in in
    let n = ref 0 in
    let n_ret = ref (-1) in

    let malformed_code() =
      slice_char.( !n ) <- (-1);
      raise(Malformed_code_read(!n, !p - p_in, `Enc_utf8));
    in

    let slice_length = Array.length slice_char in

    while !p < p_max && !n < slice_length do
      let k_inc =
        (* length of the character in bytes; 0 means: stop *)

        (* We know:
         * (1) p_in >= 0 ==> !p >= 0
         * (2) !p < p_max = p_in + l_in <= String.length s_in
         * ==> unsafe get ok
         *)
        (* match s_in.[k_in + k] with *)
        match ops.unsafe_get s_in !p with
            '\000' ->
              if is_java then malformed_code();
              (* slice_char.(n) <- 0; *)
              Array.unsafe_set slice_char !n 0;     (* ok *)
              1
          | ('\001'..'\127' as x) ->
              (* slice_char.(n) <- Char.code x; *)
              Array.unsafe_set slice_char !n (Char.code x);     (* ok *)
              1
          | ('\128'..'\223' as x) ->
              if !p+1 >= p_max then
                0
              else begin
                (* ==> !p+1 < p_max = p_in + l_in <= String.length s_in
                 * ==> unsafe get ok
                 *)
                let n1 = Char.code x in
                let n2 = (* Char.code (s_in.[!p + 1]) *)
                  Char.code(ops.unsafe_get s_in (!p + 1)) in
                if is_java && (n1 = 0x80 && n2 = 0xc0) then begin
                  (* slice_char.(n) <- 0; *)
                  Array.unsafe_set slice_char !n 0;     (* ok *)
                  2
                end
                else begin
                  if n2 < 128 || n2 > 191 then malformed_code();
                  let p = ((n1 land 0b11111) lsl 6) lor (n2 land 0b111111) in
                  if p < 128 then malformed_code();
                  (* slice_char.(n) <- p; *)
                  Array.unsafe_set slice_char !n p;     (* ok *)
                  2
                end
              end
          | ('\224'..'\239' as x) ->
              if !p + 2 >= p_max then
                0
              else begin
                (* ==> !p+2 < p_max = p_in + l_in <= String.length s_in
                 * ==> unsafe get ok
                 *)
                let n1 = Char.code x in
                let n2 = (* Char.code (s_in.[!p + 1]) *)
                  Char.code(ops.unsafe_get s_in (!p + 1)) in
                let n3 = (* Char.code (s_in.[!p + 2]) *)
                  Char.code(ops.unsafe_get s_in (!p + 2)) in
                if n2 < 128 || n2 > 191 then malformed_code();
                if n3 < 128 || n3 > 191 then malformed_code();
                let p =
                  ((n1 land 0b1111) lsl 12) lor
                  ((n2 land 0b111111) lsl 6) lor
                  (n3 land 0b111111)
                in
                if p < 0x800 then malformed_code();
                if (p >= 0xd800 && p < 0xe000) then
                  (* Surrogate pairs are not supported in UTF-8 *)
                  malformed_code();
                if (p >= 0xfffe && p <= 0xffff) then
                  malformed_code();
                (* slice_char.(n) <- p; *)
                Array.unsafe_set slice_char !n p;     (* ok *)
                3
              end
          | ('\240'..'\247' as x) ->
              if !p + 3 >= p_max then
                0
              else begin
                (* ==> !p+3 < p_max = p_in + l_in <= String.length s_in
                 * ==> unsafe get ok
                 *)
                let n1 = Char.code x in
                let chars = ops.unsafe_get3 s_in (!p + 1) in
                let n2 = chars lsr 16 in
                let n3 = (chars lsr 8) land 0xff in
                let n4 = chars land 0xff in
                if n2 < 128 || n2 > 191 then malformed_code();
                if n3 < 128 || n3 > 191 then malformed_code();
                if n4 < 128 || n4 > 191 then malformed_code();
                let p = ((n1 land 0b111) lsl 18) lor
                        ((n2 land 0b111111) lsl 12) lor
                        ((n3 land 0b111111) lsl 6) lor
                        (n4 land 0b111111)
                in
                if p < 0x10000 then malformed_code();
                if p >= 0x110000 then
                  (* These code points are not supported. *)
                  malformed_code();
                (* slice_char.(n) <- p; *)
                Array.unsafe_set slice_char !n p;     (* ok *)
                4
              end
          | _ ->
              (* Outside the valid range of XML characters *)
              malformed_code();
      in
      (* If k_inc = 0, the character was partially outside the processed
       * range of the string, and could not be decoded.
       *)

      if k_inc > 0 then begin
        (* We know:
         * (1) n >= 0, because n starts with 0 and is only increased
         * (2) n < Array.length slice_char = Array.length slice_blen
         * ==> unsafe set ok
         *)
        (* slice_blen.(n) <- k_inc; *)
        Array.unsafe_set slice_blen !n k_inc;
        (* next iteration: *)
        p := !p + k_inc;
        incr n;
      end
      else begin
        (* Stop loop: *)
        n_ret := !n;
        n := slice_length;
      end
    done; 

    if (!n_ret = (-1)) then n_ret := !n;
    if !n_ret < slice_length then (
      (* EOF marker *)
      slice_char.(!n_ret) <- (-1);  
    );
    (!n_ret,!p-p_in,`Enc_utf8) in
  { read }
;;


let read_utf8_ref = ref read_utf8;;


let have_utf8_bom ops s p =
  let open Netstring_tstring in
  let c0 = ops.get s (p + 0) in
  let c1 = ops.get s (p + 1) in
  let c2 = ops.get s (p + 2) in
  c0 = '\xEF' && c1 = '\xBB' && c2 = '\xBF'


let read_utf8_opt_bom expose_bom =
  let read ops slice_char slice_blen s_in p_in l_in =
    let open Netstring_tstring in
    assert(Array.length slice_char = Array.length slice_blen);
    assert(p_in >= 0 && p_in + l_in <= ops.length s_in && l_in >= 0);
    (* Expect a BOM at the beginning of the text *)
    if l_in >= 3 then (
      if have_utf8_bom ops s_in p_in then (
        let p_in1, l_in1 = 
          if expose_bom then p_in, l_in else p_in+3, l_in-3 in
        let (n_ret, p_ret, enc) = 
          (!read_utf8_ref false).read
            ops slice_char slice_blen s_in p_in1 l_in1 in
        let p_ret1 =
          if expose_bom then p_ret else p_ret+3 in
        if expose_bom && n_ret >= 1 then
          slice_char.(0) <- (-3); 
        (n_ret, p_ret1, enc)
      )
      else
        (!read_utf8_ref false).read ops slice_char slice_blen s_in p_in l_in 
    ) else (
      let bom_possible =
        l_in=0 || 
          (l_in=1 && ops.get s_in 0 = '\xEF') ||
            (l_in=2 && ops.get s_in 0 = '\xEF' && ops.get s_in 1 = '\xBB') in
      if bom_possible then
        (0, 0, `Enc_utf8_opt_bom)
      else
        (!read_utf8_ref false).read ops slice_char slice_blen s_in p_in l_in 
    ) in
  { read }
;;


let surrogate_offset = 0x10000 - (0xD800 lsl 10) - 0xDC00;;

let read_utf16_lebe lo hi n_start enc =
  (* lo=0, hi=1: little endian
   * lo=1, hi=0: big endian
   * n_start: First cell in slice to use
   *)
  let read ops slice_char slice_blen s_in p_in l_in =
    let open Netstring_tstring in
    assert(Array.length slice_char = Array.length slice_blen);
    assert(p_in >= 0 && p_in + l_in <= ops.length s_in && l_in >= 0);

    let malformed_code k n =
      slice_char.(n) <- (-1);
      raise(Malformed_code_read(n,k,enc))
    in

    (* k: counts the bytes
     * n: counts the characters
     *)
    let rec put_loop k n =
      if k+1 < l_in && n < Array.length slice_char then begin
        let p = (Char.code (ops.get s_in (p_in + k + lo))) lor 
                ((Char.code (ops.get s_in (p_in + k + hi))) lsl 8) in

        if p >= 0xd800 && p < 0xe000 then begin
          (* This is a surrogate pair. *)
          if k+3 < l_in then begin
            if p <= 0xdbff then begin
              let q = (Char.code (ops.get s_in (p_in + k + 2 + lo))) lor
                      ((Char.code (ops.get s_in (p_in + k + 2 + hi))) lsl 8) in
              if q < 0xdc00 || q > 0xdfff then malformed_code k n;
              let eff_p = (p lsl 10) + q + surrogate_offset in
              slice_char.(n) <- eff_p;
              slice_blen.(n) <- 4;
              put_loop (k+4) (n+1)
            end
            else
              (* Malformed pair: *)
              malformed_code k n;
          end
          else 
            (n,k)
        end
        else
          (* Normal 2-byte character *)
          if p = 0xfffe then 
            (* Wrong byte order mark: It is illegal here *)
            malformed_code k n
          else begin
            (* A regular code point *)
            slice_char.(n) <- p;
            slice_blen.(n) <- 2;
            put_loop (k+2) (n+1)
          end
      end
      else
        (n,k)
    in
    let (n,k) = put_loop 0 n_start in
    if n < Array.length slice_char then (
      (* EOF marker *)
      slice_char.(n) <- (-1);
    );
    (n,k,enc) in
  { read }
;;


let get_endianess ops s_in p_in =
  let open Netstring_tstring in
  let c0 = ops.get s_in (p_in + 0) in
  let c1 = ops.get s_in (p_in + 1) in
  if c0 = '\254' && c1 = '\255' then
    `Big_endian
  else
    if c0 = '\255' && c1 = '\254' then
      `Little_endian
    else
      `No_BOM
;;


(* expose_bom: when true, the BOM is considered as a character and
 * put as value (-3) into slice_char
 *)

let read_utf16 expose_bom =
  let read ops slice_char slice_blen s_in p_in l_in =
    let open Netstring_tstring in
    assert(Array.length slice_char = Array.length slice_blen);
    assert(p_in >= 0 && p_in + l_in <= ops.length s_in && l_in >= 0);
    (* Expect a BOM at the beginning of the text *)
    if l_in >= 2 then begin
      if expose_bom then (
        slice_char.(0) <- (-3); 
        slice_blen.(0) <- 0;  (* Later corrected *)
      );
      match get_endianess ops s_in p_in with
          `Big_endian ->
            let n_start = if expose_bom then 1 else 0 in
            let (n, k, enc') = 
              (read_utf16_lebe 1 0 n_start `Enc_utf16_be).read
                ops slice_char slice_blen s_in (p_in+2) (l_in-2) in
            if n > 0 then slice_blen.(0) <- slice_blen.(0) + 2;
            (n, k+2, enc')
        | `Little_endian ->
            let n_start = if expose_bom then 1 else 0 in
            let (n, k, enc') = 
              (read_utf16_lebe 0 1 n_start `Enc_utf16_le).read
                ops slice_char slice_blen s_in (p_in+2) (l_in-2) in
            if n > 0 then slice_blen.(0) <- slice_blen.(0) + 2;
            (n, k+2, enc')
        | `No_BOM ->
            (* byte order mark missing *)
            slice_char.(0) <- (-1);
            raise(Malformed_code_read(0,0,`Enc_utf16))
    end
    else (
      slice_char.(0) <- (-1);
      (0, 0, `Enc_utf16)
    ) in
  { read }
;;


let read_utf32_lebe little n_start enc =
  (* little: whether little endian
   * n_start: First cell in slice to use
   *)
  let read ops slice_char slice_blen s_in p_in l_in =
    let open Netstring_tstring in
    assert(Array.length slice_char = Array.length slice_blen);
    assert(p_in >= 0 && p_in + l_in <= ops.length s_in && l_in >= 0);

    let malformed_code k n =
      slice_char.(n) <- (-1);
      raise(Malformed_code_read(n,k,enc))
    in

    let b0 = if little then 0 else 3 in
    let b1 = if little then 1 else 2 in
    let b2 = if little then 2 else 1 in
    let b3 = if little then 3 else 0 in

    (* k: counts the bytes
     * n: counts the characters
     *)
    let rec put_loop k n =
      if k+3 < l_in && n < Array.length slice_char then begin
        let p3 = Char.code (ops.get s_in (p_in + k + b3)) in
        if p3 <> 0 then malformed_code k n;
        let p = (Char.code (ops.get s_in (p_in + k + b0))) lor 
                ((Char.code (ops.get s_in (p_in + k + b1))) lsl 8) lor
                ((Char.code (ops.get s_in (p_in + k + b2))) lsl 16) in
        if (p >= 0xD800 && p <= 0xDFFF) || p >= 0x10FFFF then malformed_code k n;
        if p = 0xfffe then 
          (* Wrong byte order mark: It is illegal here *)
          malformed_code k n;
        slice_char.(n) <- p;
        slice_blen.(n) <- 4;
        put_loop (k+4) (n+1)
      end
      else
        (n,k)
    in
    let (n,k) = put_loop 0 n_start in
    if n < Array.length slice_char then (
      (* EOF marker *)
      slice_char.(n) <- (-1);
    );
    (n,k,enc) in
  { read }
;;


let get_endianess32 ops s_in p_in =
  let open Netstring_tstring in
  let c0 = ops.get s_in (p_in + 0) in
  let c1 = ops.get s_in (p_in + 1) in
  let c2 = ops.get s_in (p_in + 2) in
  let c3 = ops.get s_in (p_in + 3) in
  if c0 = '\000' && c1 = '\000' && c2 = '\254' && c3 = '\255' then
    `Big_endian
  else
    if c0 = '\255' && c1 = '\254' && c2 = '\000' && c3 = '\000' then
      `Little_endian
    else
      `No_BOM
;;


let read_utf32 expose_bom =
  let read ops slice_char slice_blen s_in p_in l_in =
    let open Netstring_tstring in
    assert(Array.length slice_char = Array.length slice_blen);
    assert(p_in >= 0 && p_in + l_in <= ops.length s_in && l_in >= 0);
    (* Expect a BOM at the beginning of the text *)
    if l_in >= 4 then begin
      if expose_bom then (
        slice_char.(0) <- (-3); 
        slice_blen.(0) <- 0;  (* Later corrected *)
      );
      match get_endianess32 ops s_in p_in with
          `Big_endian ->
            let n_start = if expose_bom then 1 else 0 in
            let (n, k, enc') = 
              (read_utf32_lebe false n_start `Enc_utf32_be).read
                ops slice_char slice_blen s_in (p_in+4) (l_in-4) in
            if n > 0 then slice_blen.(0) <- slice_blen.(0) + 4;
            (n, k+4, enc')
        | `Little_endian ->
            let n_start = if expose_bom then 1 else 0 in
            let (n, k, enc') = 
              (read_utf32_lebe true n_start `Enc_utf32_le).read
                ops slice_char slice_blen s_in (p_in+4) (l_in-4) in
            if n > 0 then slice_blen.(0) <- slice_blen.(0) + 4;
            (n, k+4, enc')
        | `No_BOM ->
            (* byte order mark missing *)
            slice_char.(0) <- (-1);
            raise(Malformed_code_read(0,0,`Enc_utf32))
    end
    else (
      slice_char.(0) <- (-1);
      (0, 0, `Enc_utf32)
    ) in
  { read }
;;


let read_euc len1 len2 len3 map1 map2 map3 enc =
  (* Code set 0 is US-ASCII.
   * Code sets 1, 2, 3 may be anything. lenX = 0: code set is not supported.
   * lenX is either 0, 1, or 2.
   *)
  (* UNSAFE_OPT *)

  let open Netstring_tstring in
  assert(len1 >= 0 && len1 <= 2);
  assert(len2 >= 0 && len2 <= 2);
  assert(len3 >= 0 && len3 <= 2);

  let read ops slice_char slice_blen s_in p_in l_in =
    assert(Array.length slice_char = Array.length slice_blen);
    assert(p_in >= 0 && p_in + l_in <= ops.length s_in && l_in >= 0);

    (* k: counts the bytes
     * n: counts the characters
     *)

    let p = ref p_in in
    let p_max = p_in + l_in in
    let n = ref 0 in
    let n_ret = ref (-1) in

    let malformed_code() =
      slice_char.( !n ) <- (-1);
      raise(Malformed_code_read(!n, !p - p_in, enc));
    in

    let slice_length = Array.length slice_char in

    while !p < p_max && !n < slice_length do
      let k_inc =
	(* length of the character in bytes; 0 means: stop *)

	(* We know:
	 * (1) p_in >= 0 ==> !p >= 0
	 * (2) !p < p_max = p_in + l_in <= String.length s_in
	 * ==> unsafe get ok
	 *)
	(* match s_in.[k_in + k] with *)
	match ops.unsafe_get s_in !p with
	    '\000'..'\127' as x ->
	      (* US-ASCII *)
	      Array.unsafe_set slice_char !n (Char.code x);     (* ok *)
	      1
	  | '\142' ->
	      (* Code set 2 *)
	      if len2 = 0 then malformed_code();
	      if !p+len2 >= p_max then
		0
	      else begin
		let x1 = Char.code (ops.get s_in (!p + 1)) in
		let x2 = if len2=1 then 256 else
                           Char.code (ops.get s_in (!p + 2)) in
		if x1 < 160 || x2 < 160 then malformed_code();
		let uni = map2 x1 x2 in
		Array.unsafe_set slice_char !n uni;     (* ok *)
		len2+1
	      end
	  | '\143' ->
	      (* Code set 3 *)
	      if len3 = 0 then malformed_code();
	      if !p+len3 >= p_max then
		0
	      else begin
		let x1 = Char.code (ops.get s_in (!p + 1)) in
		let x2 = if len3=1 then 256 else
                           Char.code (ops.get s_in (!p + 2)) in
		if x1 < 160 || x2 < 160 then malformed_code();
		let uni = map3 x1 x2 in
		Array.unsafe_set slice_char !n uni;     (* ok *)
		len3+1
	      end
	  | '\160'..'\255' as x1_code ->
	      (* Code set 1 *)
	      if !p+len1 > p_max then
		0
	      else begin
		let x1 = Char.code x1_code in
		let x2 = if len1=1 then 256 else
                           Char.code (ops.get s_in (!p + 1)) in
		if x2 < 160 then malformed_code();
		let uni = map1 x1 x2 in
		Array.unsafe_set slice_char !n uni;     (* ok *)
		len1
	      end
	  | _ ->
	      (* illegal *)
	      malformed_code()
      in
      (* If k_inc = 0, the character was partially outside the processed
       * range of the string, and could not be decoded.
       *)
      
      if k_inc > 0 then begin
	(* We know:
	 * (1) n >= 0, because n starts with 0 and is only increased
	 * (2) n < Array.length slice_char = Array.length slice_blen
	 * ==> unsafe set ok
	 *)
	(* slice_blen.(n) <- k_inc; *)
	Array.unsafe_set slice_blen !n k_inc;
	(* next iteration: *)
	p := !p + k_inc;
	incr n;
      end
      else begin
	(* Stop loop: *)
	n_ret := !n;
	n := slice_length;
      end
    done; 
    
    if (!n_ret = (-1)) then n_ret := !n;
    if !n_ret < slice_length then (
      (* EOF marker *)
      slice_char.(!n_ret) <- (-1);  
    );
    (!n_ret,!p-p_in,enc) in
  { read }
;;
      

let read_eucjp () =
  let jis0201 = Netmappings.get_to_unicode "jis0201" in
  let jis0208 = Netmappings.get_to_unicode "jis0208" in
  let jis0212 = lazy (Netmappings.get_to_unicode "jis0212") in (* seldom *)
  let map1 x1 x2 =
    jis0208.( (x1-160) * 96 + x2 - 160 ) in
  let map2 x1 _ =
    jis0201.( x1 ) in
  let map3 x1 x2 =
    (Lazy.force jis0212).( (x1-160) * 96 + x2 - 160 ) in
  read_euc 2 1 2 map1 map2 map3 `Enc_eucjp
;;


let read_euckr () =
  let ks1001 = Netmappings.get_to_unicode "ks1001" in
  let map x1 x2 =
    ks1001.( (x1-160) * 96 + x2 - 160 ) in
  read_euc 2 0 0 map map map `Enc_euckr
;;


let read_subset inner_read def =
  let read ops slice_char slice_blen s_in p_in l_in =
    let open Netstring_tstring in
    assert(Array.length slice_char = Array.length slice_blen);
    assert(p_in >= 0 && p_in + l_in <= ops.length s_in && l_in >= 0);

    let (n,k,enc') = inner_read.read ops slice_char slice_blen s_in p_in l_in in

    (* check codepoints: *)
    for j = 0 to n-1 do
      if not(def(slice_char.(j))) then (
        (* raise Malformed_code_read... *)
        (* to get enc'' read again: *)
        let slice_char' = Array.make j (-1) in
        let slice_blen' = Array.make j 1 in
        let (n', k', enc'') = 
          try
            inner_read.read ops slice_char' slice_blen' s_in p_in l_in 
          with
              Malformed_code_read(_,_,_) -> assert false
        in
        assert(n' = j);
        int_blit slice_char' 0 slice_char 0 j;
        int_blit slice_blen' 0 slice_blen 0 j;
        slice_char.(j) <- (-1);
        raise (Malformed_code_read(j, k', enc''))
      );
    done;

    (n,k,enc') in
  { read }
;;

(*
 * let (n_char, b_byte) = 
 *        write_XXX slice_char slice_length s_out p_out l_out subst
 *)

let write_iso88591 maxcode slice_char slice_pos slice_length 
                   s_out p_out l_out subst =
  (* UNSAFE_OPT *)
  (* Use maxcode=255 for ISO-8859-1, and maxcode=127 for US-ASCII,
   * and maxcode=(-1) for `Enc_empty.
   *)
  assert(p_out >= 0 && p_out + l_out <= Bytes.length s_out && l_out >= 0);
  assert(slice_pos >= 0 && slice_pos+slice_length <= Array.length slice_char);
  assert(maxcode <= 255);

  let n = ref slice_pos in     (* index of slice *)
  let n_ret = ref (-1) in      (* returned number of characters *)
  let n_max = slice_pos + slice_length in

  let p = ref p_out in         (* current output position *)
  let p_max = p_out + l_out in (* maximum output position *)

  while ( !n < n_max ) && ( !p < p_max ) do
    (* We know:
     * (1) !n >= 0, because it starts with 0 and is only increased
     * (2) !n < n_max = slice_pos + slice_length <= Array.length slice_char
     * ==> unsafe get ok
     *)
    let ch = Array.unsafe_get slice_char !n in
    if ch >= 0 && ch <= maxcode then begin
      (* Because !p < p_max:
       * !p < p_max = p_out + l_out <= String.length s_out
       * Furthermore, p_out >= 0, !p >= 0.
       * ==> unsafe set ok
       *)
      (* s_out.[ !p ] <- Char.chr ch; *)
      Bytes.unsafe_set s_out !p (Char.unsafe_chr ch);
      incr n;
      incr p;
    end
    else begin
      assert(ch >= 0);
      let replacement = subst ch in
      let l_repl = String.length replacement in
      if l_repl > multibyte_limit then
	failwith "Netconversion.write_iso88591: Substitution string too long";
      if !p + l_repl <= p_max then begin
	(* Enough space to store 'replacement': *)
	Bytes.blit_string replacement 0 s_out !p l_repl;
	p := !p + l_repl;
	incr n
      end
      else begin
	(* Exit whole conversion *)
	n_ret := !n;
	n := n_max;
      end
    end
  done;
  if !n_ret >= 0 then (!n_ret - slice_pos, !p - p_out) 
                 else (!n - slice_pos,     !p - p_out)
;;


let get_8bit_from_unicode_map enc =
  let cs = 
    match required_charsets enc with
	[ cs ] -> cs 
      | _ -> failwith "get_8bit_from_unicode_map" in
  let from_unicode = Netmappings.get_from_unicode (internal_name cs) in
  assert(Array.length from_unicode = 256);
  from_unicode
;;


let write_8bit enc =
  (* UNSAFE_OPT *)

  let m_from_unicode = get_8bit_from_unicode_map enc in
  let m_mask = Array.length m_from_unicode - 1 in

  fun slice_char slice_pos slice_length s_out p_out l_out subst ->
    assert(p_out >= 0 && p_out + l_out <= Bytes.length s_out && l_out >= 0);
    assert(slice_pos >= 0 && slice_pos+slice_length <= Array.length slice_char);

    let n = ref slice_pos in     (* index of slice *)
    let n_max = slice_pos + slice_length in

    let k = ref 0 in             (* written bytes *)
    let n_ret = ref (-1) in      (* returned number of characters *)

    while ( !n < n_max ) && ( !k < l_out ) do
      (* We know:
       * (1) !n >= 0, because it starts with 0 and is only increased
       * (2) !n < n_max = slice_pos + slice_length <= Array.length slice
       * ==> unsafe get ok
       *)
      let p = (* slice_char.( !n ) *) 
              Array.unsafe_get slice_char !n in
      let p' =
	match Array.unsafe_get m_from_unicode (p land m_mask) with
	    Netmappings.U_nil -> -1
	  | Netmappings.U_single (p0,q0) ->
	      if p0 = p then q0 else -1
	  | Netmappings.U_double (p0,q0,p1,q1) ->
	      if p0 = p then q0 else
		if p1 = p then q1 else -1
	  | Netmappings.U_array pq ->
	      let r = ref (-1) in
	      let h = ref 0 in
	      while !r < 0 && !h < Array.length pq do
		if pq.( !h ) = p then
		  r := pq.( !h+1 )
		else
		  h := !h + 2
	      done;
	      !r
      in
      (* If p=-1 ==> p'=-1, because -1 is never mapped to any code point *)

      if p' < 0 then begin
	if p < 0 then
	  assert false   (* EOF mark found *)
	else begin
	  let replacement = subst p in
	  let l_repl =  String.length replacement in
	  if l_repl > multibyte_limit then
	  failwith "Netconversion.write_8bit: Substitution string too long";
	
	  if !k + l_repl <= l_out then begin
	    (* Enough space to store 'replacement': *)
	    Bytes.blit_string replacement 0 s_out (p_out + !k) l_repl;
	    k := !k + l_repl;
	    incr n
	  end
	  else begin
	    (* Exit whole conversion *)
	    n_ret := !n;
	    n := n_max;
	  end
	end
      end
      else begin
	(* Because !k < l_out:
	 * p_out + !k < p_out + l_out <= String.length s_out
	 * Furthermore, p_out >= 0, !k >= 0.
	 * ==> unsafe set ok
	 *)
	(* s_out.[ p_out + !k ] <- Char.chr p'; *)
	Bytes.unsafe_set s_out (p_out + !k) (Char.unsafe_chr(p' land 0xff));
	incr n;
	incr k
      end;
    done;
  if !n_ret >= 0 then (!n_ret - slice_pos, !k) 
                 else (!n - slice_pos,     !k)
;;


let write_utf8 is_java
               slice_char slice_pos slice_length s_out p_out l_out subst =
  (* UNSAFE_OPT *)
  assert(p_out >= 0 && p_out + l_out <= Bytes.length s_out && l_out >= 0);
  assert(slice_pos >= 0 && slice_pos+slice_length <= Array.length slice_char);

  let n = ref slice_pos in     (* index of slice *)
  let n_max = slice_pos + slice_length in

  let k = ref 0 in             (* written bytes *)
  let n_ret = ref (-1) in      (* returned number of characters *)

  while ( !n < n_max ) do
    (* We know:
     * (1) !n >= 0, because it starts with 0 and is only increased
     * (2) !n < n_max = slice_pos + slice_length <= Array.length slice
     * ==> unsafe get ok
     *)
    let p = (* slice.( !n ) *)
            Array.unsafe_get slice_char !n in

    let index = p_out + !k in

    let k_inc =
      (* k_inc: how many bytes are written. (-1) means: stop *)
      if p <= 127 && (not is_java || p <> 0) then begin
	if p < 0 then assert false;  (* EOF mark *)
	if !k < l_out then begin
	  (* (1) index = p_out + !k < p_out + l_out <= 
	   *     String.length s_out
	   * (2) p_out, !n >= 0
	   * ==> unsafe set ok
	   *
	   * 0 <= p <= 127 ==> unsafe_chr ok
	   *)
	  (* s_out.[index] <- Char.chr p; *)
	  Bytes.unsafe_set s_out index (Char.unsafe_chr p);
	  1
	end
	else (-1)
      end
      else if p <= 0x7ff then begin
	if !k + 1 < l_out then begin
	  (* (1) index+1 = p_out + !k + 1 < p_out + l_out <= 
	   *     String.length s_out
	   * (2) p_out, !k >= 0
	   * ==> unsafe set ok
	   *
	   * p <= 0x7ff ==> p lsr 6 <= 0x1f 
	   *            ==> 0xc0 lor (p lsr 6) <= df
	   * p land 0x3f <= 0x3f ==> 0x80 lor (p land 0x3f) <= 0xbf
	   * ==> unsafe_chr ok
	   *)
	  (* s_out.[index]     <- Char.chr (0xc0 lor (p lsr 6)); *)
	  (* s_out.[index + 1] <- Char.chr (0x80 lor (p land 0x3f)); *)
	  Bytes.unsafe_set s_out index 
	    (Char.unsafe_chr (0xc0 lor (p lsr 6)));
	  Bytes.unsafe_set s_out (index+1)
	    (Char.unsafe_chr (0x80 lor (p land 0x3f)));
	  2
	end
	else (-1)
      end
      else if p <= 0xffff then begin
	(* Refuse writing surrogate pairs, and fffe, ffff *)
	if (p >= 0xd800 && p < 0xe000) || (p >= 0xfffe) then
	  failwith "Netconversion.write_utf8";
	if !k + 2 < l_out then begin
	  (* (1) index+2 = p_out + !k + 2 < p_out + l_out <= 
	   *     String.length s_out
	   * (2) p_out, !k >= 0
	   * ==> unsafe set ok
	   *
	   * Well, and it can be proven that unsafe_chr is ok, too...
	   *)
	  (* s_out.[index]     <- Char.chr (0xe0 lor (p lsr 12)); *)
	  (* s_out.[index + 1] <- Char.chr (0x80 lor ((p lsr 6) land 0x3f)); *)
	  (* s_out.[index + 2] <- Char.chr (0x80 lor (p land 0x3f)); *)
	  Bytes.unsafe_set s_out index
	    (Char.unsafe_chr (0xe0 lor (p lsr 12)));
	  Bytes.unsafe_set s_out (index+1)
	    (Char.unsafe_chr (0x80 lor ((p lsr 6) land 0x3f)));
	  Bytes.unsafe_set s_out (index+2)
	    (Char.unsafe_chr (0x80 lor (p land 0x3f)));
	  3
	end
	else (-1)
      end
      else if p <= 0x10ffff then begin
	if !k + 3 < l_out then begin
	  (* No such characters are defined... *)
	  Bytes.set s_out index (Char.chr (0xf0 lor (p lsr 18)));
	  Bytes.set s_out (index + 1) (Char.chr (0x80 lor ((p lsr 12) land 0x3f)));
	  Bytes.set s_out (index + 2) (Char.chr (0x80 lor ((p lsr 6)  land 0x3f)));
	  Bytes.set s_out (index + 3) (Char.chr (0x80 lor (p land 0x3f)));
	  4
	end
	else (-1)
      end
      else begin
	(* Higher code points are not possible in XML; call subst *)
	let replacement = subst p in
	let l_repl =  String.length replacement in
	if l_repl > multibyte_limit then
	  failwith "Netconversion.write_utf8: Substitution string too long";
	if !k + l_repl <= l_out then begin
	  (* Enough space to store 'replacement': *)
	  Bytes.blit_string replacement 0 s_out (p_out + !k) l_repl;
	  l_repl  (* may be 0! *)
	end
	else 
	  (-1) (* Exit whole conversion *)
      end

    in
    if k_inc >= 0 then (
      k := !k + k_inc;
      incr n
    )
    else (
      n_ret := !n;
      n := n_max
    );
  done;
  if !n_ret >= 0 then (!n_ret - slice_pos, !k) 
                 else (!n - slice_pos,     !k)
;;


let write_utf16_lebe lo hi 
                     slice_char slice_pos slice_length s_out p_out l_out subst =
  (* lo=0, hi=1: little endian
   * lo=1, hi=0: big endian
   *)
  assert(p_out >= 0 && p_out + l_out <= Bytes.length s_out && l_out >= 0);
  assert(slice_pos >= 0 && slice_pos+slice_length <= Array.length slice_char);

  let n = ref slice_pos in     (* index of slice *)
  let n_max = slice_pos + slice_length in

  let k = ref 0 in             (* written bytes *)
  let n_ret = ref (-1) in      (* returned number of characters *)

  while ( !n < n_max ) do
    let p = slice_char.( !n ) in

    let index = p_out + !k in

    let k_inc =
      if p >= 0xfffe then begin
	if p <= 0x10ffff then begin
	  if p <= 0xffff then failwith "Netconversion.write_utf16_le";
	  (* Must be written as surrogate pair *)
	  if !k + 3 < l_out then begin
	    let high = ((p - 0x10000) lsr 10) + 0xd800 in
	    let low  = (p land 0x3ff) + 0xdc00 in
	    Bytes.set s_out (index + lo) (Char.chr (high land 0xff));
	    Bytes.set s_out (index + hi) (Char.chr (high lsr 8));
	    Bytes.set s_out (index + 2 + lo) (Char.chr (low land 0xff));
	    Bytes.set s_out (index + 2 + hi) (Char.chr (low lsr 8));
	    4
	  end
	  else (-1)
	end
	else begin
	  (* Higher code points are not possible in XML; call subst *)
	  let replacement = subst p in
	  let l_repl =  String.length replacement in
	  if l_repl > multibyte_limit then
	    failwith "Netconversion.write_utf16_le: Substitution string too long";
	  if !k + l_repl <= l_out then begin
	    (* Enough space to store 'replacement': *)
	    Bytes.blit_string replacement 0 s_out (p_out + !k) l_repl;
	    l_repl  (* may be 0! *)
	  end
	  else 
	    (-1) (* Exit whole conversion *)
	end
      end
      else begin
	(* 2-byte character *)
	if !k + 1 < l_out then begin
	  Bytes.set s_out (index + lo) (Char.unsafe_chr (p land 0xff));
	  Bytes.set s_out (index + hi) (Char.unsafe_chr ((p lsr 8) land 0xff));
	  2
	end
	else (-1)
      end
    in
    if k_inc >= 0 then (
      k := !k + k_inc;
      incr n
    )
    else (
      n_ret := !n;
      n := n_max
    );
  done;
  if !n_ret >= 0 then (!n_ret - slice_pos, !k) 
                 else (!n - slice_pos,     !k)
;;


let write_utf32_lebe little 
                     slice_char slice_pos slice_length s_out p_out l_out subst =
  assert(p_out >= 0 && p_out + l_out <= Bytes.length s_out && l_out >= 0);
  assert(slice_pos >= 0 && slice_pos+slice_length <= Array.length slice_char);

  let n = ref slice_pos in     (* index of slice *)
  let n_max = slice_pos + slice_length in

  let k = ref 0 in             (* written bytes *)
  let n_ret = ref (-1) in      (* returned number of characters *)

  let b0 = if little then 0 else 3 in
  let b1 = if little then 1 else 2 in
  let b2 = if little then 2 else 1 in
  let b3 = if little then 3 else 0 in

  while ( !n < n_max ) do
    let p = slice_char.( !n ) in

    let index = p_out + !k in

    let k_inc =
      if p <= 0x10ffff then (
	if !k + 3 < l_out then (
	  Bytes.set s_out (index + b0) (Char.unsafe_chr (p land 0xff));
	  Bytes.set s_out (index + b1) (Char.unsafe_chr ((p lsr 8) land 0xff));
	  Bytes.set s_out (index + b2) (Char.unsafe_chr ((p lsr 16) land 0xff));
	  Bytes.set s_out (index + b3) (Char.unsafe_chr 0);
	  4
	)
	else (-1)
      ) else (
	  (* Higher code points are not possible in XML; call subst *)
	  let replacement = subst p in
	  let l_repl =  String.length replacement in
	  if l_repl > multibyte_limit then
	    failwith "Netconversion.write_utf32: Substitution string too long";
	  if !k + l_repl <= l_out then begin
	    (* Enough space to store 'replacement': *)
	    Bytes.blit_string replacement 0 s_out (p_out + !k) l_repl;
	    l_repl  (* may be 0! *)
	  end
	  else 
	    (-1) (* Exit whole conversion *)
      ) in
    if k_inc >= 0 then (
      k := !k + k_inc;
      incr n
    )
    else (
      n_ret := !n;
      n := n_max
    );
  done;
  if !n_ret >= 0 then (!n_ret - slice_pos, !k) 
                 else (!n - slice_pos,     !k)
;;


let write_euc map enc =
  (* Code set 0 is US-ASCII.
   * let (set, byte1, byte2) = map unicode:
   *  - set is 1, 2, 3, or 4. 4 means that the code point cannot be mapped.
   *  - byte1 >= 160, <= 255
   *  - byte2 >= 160, <= 255, or byte2=256 meaning that it is not used
   *)
  (* UNSAFE_OPT *)

  fun slice_char slice_pos slice_length s_out p_out l_out subst ->
    assert(p_out >= 0 && p_out + l_out <= Bytes.length s_out && l_out >= 0);
    assert(slice_pos >= 0 && slice_pos+slice_length <= Array.length slice_char);

    let n = ref slice_pos in     (* index of slice *)
    let n_max = slice_pos + slice_length in

    let k = ref 0 in             (* written bytes *)
    let n_ret = ref (-1) in      (* returned number of characters *)

    while ( !n < n_max ) do
      (* We know:
       * (1) !n >= 0, because it starts with 0 and is only increased
       * (2) !n < n_max = slice_pos + slice_length <= Array.length slice
       * ==> unsafe get ok
       *)
      let p = (* slice.( !n ) *)
              Array.unsafe_get slice_char !n in
      assert (p >= 0);

      let index = p_out + !k in

      let (set, b1, b2) = 
	if p <= 127 then (0, p, 256) else map p in

      let k_inc =
	(* k_inc: how many bytes are written *)
	match set with
	    0 ->
	      if !k < l_out then begin
		(* s_out.[index] <- Char.chr p; *)
		Bytes.unsafe_set s_out index (Char.unsafe_chr (b1 land 127));
		1
	      end
	      else (-1)
	  | 1 ->
	      let bl = if b2 = 256 then 1 else 2 in
	      if !k + bl < l_out then begin
		assert(b1 >= 160 && b1 <= 255 && b2 >= 160 && b2 <= 256);
		Bytes.set s_out (index) (Char.chr b1);
		if b2 <> 256 then Bytes.set s_out (index+1) (Char.chr b2);
		bl
	      end
	      else (-1)
	  | 2 ->
	      let bl = if b2 = 256 then 2 else 3 in
	      if !k + bl < l_out then begin
		assert(b1 >= 160 && b1 <= 255 && b2 >= 160 && b2 <= 256);
		Bytes.set s_out index '\142';
		Bytes.set s_out (index+1) (Char.chr b1);
		if b2 <> 256 then Bytes.set s_out (index+2) (Char.chr b2);
		bl
	      end
	      else (-1)
	  | 3 ->
	      let bl = if b2 = 256 then 2 else 3 in
	      if !k + bl < l_out then begin
		assert(b1 >= 160 && b1 <= 255 && b2 >= 160 && b2 <= 256);
		Bytes.set s_out index '\143';
		Bytes.set s_out (index+1) (Char.chr b1);
		if b2 <> 256 then Bytes.set s_out (index+2) (Char.chr b2);
		bl
	      end
	      else (-1)
	  | 4 ->
	      let replacement = subst p in
	      let l_repl =  String.length replacement in
	      if l_repl > multibyte_limit then
		failwith "Netconversion.write_euc: Substitution string too long";
	      if !k + l_repl <= l_out then begin
		(* Enough space to store 'replacement': *)
		Bytes.blit_string replacement 0 s_out (p_out + !k) l_repl;
		l_repl
	      end
	      else 
		(-1) (* Exit whole conversion *)
	  | _ ->
	      assert false
      in
      if k_inc >= 0 then (
	k := !k + k_inc;
	incr n
      )
      else (
	n_ret := !n;
	n := n_max
      );
    done;
    if !n_ret >= 0 then (!n_ret - slice_pos, !k) 
                   else (!n - slice_pos,     !k)
;;


let write_eucjp () =
  let jis0201 = Netmappings.get_from_unicode "jis0201" in
  let jis0208 = Netmappings.get_from_unicode "jis0208" in
  let jis0212 = Netmappings.get_from_unicode "jis0212" in

  let jis0201_mask = Array.length jis0201 - 1 in
  let jis0208_mask = Array.length jis0208 - 1 in
  let jis0212_mask = Array.length jis0212 - 1 in

  let map p =
    (* Try in order: jis0208, jis0201, jis0212 *)
    let map_tbl jistbl jistbl_mask =
      match jistbl.(p land jistbl_mask) with
	  Netmappings.U_nil -> -1
	| Netmappings.U_single (p0,q0) ->
	    if p0 = p then q0 else -1
	| Netmappings.U_double (p0,q0,p1,q1) ->
	    if p0 = p then q0 else
	      if p1 = p then q1 else -1
	| Netmappings.U_array pq ->
	    let r = ref (-1) in
	    let h = ref 0 in
	    while !r < 0 && !h < Array.length pq do
	      if pq.( !h ) = p then
		r := pq.( !h+1 )
	      else
		h := !h + 2
	    done;
	    !r
    in
    let cp_0208 = map_tbl jis0208 jis0208_mask in
    if cp_0208 >= 0 then
      let row = cp_0208 / 96 in
      let col = cp_0208 - row * 96 in
      (1, row + 160, col + 160)
    else
      let cp_0201 = map_tbl jis0201 jis0201_mask in
      if cp_0201 >= 128 then   (* Ignore especially 0x5c, 0x7e *)
	(2, cp_0201, 256)
      else
	let cp_0212 = map_tbl jis0212 jis0212_mask in
	if cp_0212 >= 0 then
	  let row = cp_0212 / 96 in
	  let col = cp_0212 - row * 96 in
	  (3, row + 160, col + 160)
	else
	  (4,256,256)
  in
  write_euc map `Enc_eucjp
;;


let write_euckr () =
  let ks1001 = Netmappings.get_from_unicode "ks1001" in

  let ks1001_mask = Array.length ks1001 - 1 in

  let map p =
    let map_tbl kstbl kstbl_mask =
      match kstbl.(p land kstbl_mask) with
	  Netmappings.U_nil -> -1
	| Netmappings.U_single (p0,q0) ->
	    if p0 = p then q0 else -1
	| Netmappings.U_double (p0,q0,p1,q1) ->
	    if p0 = p then q0 else
	      if p1 = p then q1 else -1
	| Netmappings.U_array pq ->
	    let r = ref (-1) in
	    let h = ref 0 in
	    while !r < 0 && !h < Array.length pq do
	      if pq.( !h ) = p then
		r := pq.( !h+1 )
	      else
		h := !h + 2
	    done;
	    !r
    in
    let cp_1001 = map_tbl ks1001 ks1001_mask in
    if cp_1001 >= 0 then
      let row = cp_1001 / 96 in
      let col = cp_1001 - row * 96 in
      (1, row + 160, col + 160)
    else
      (4,256,256)
  in
  write_euc map `Enc_euckr
;;


let special_cpoint = 0x110000;;


let write_subset inner_writer def 
                 slice_char slice_pos slice_length s_out p_out l_out subst =
  assert(p_out >= 0 && p_out + l_out <= Bytes.length s_out && l_out >= 0);
  assert(slice_pos >= 0 && slice_pos+slice_length <= Array.length slice_char);

  (* Force that the subst' function is called for all undefined code
   * points
   *)

  let slice_char' = Array.sub slice_char slice_pos slice_length in
  for n = 0 to slice_length - 1 do
    let ch = slice_char'.(n) in
    if ch >= special_cpoint || not (def ch) then 
      slice_char'.(n) <- special_cpoint + n
  done;

  let subst' ch =
    if ch >= special_cpoint then
      subst (slice_char.(slice_pos + ch - special_cpoint))
    else
      subst ch
  in

  inner_writer slice_char' 0 slice_length s_out p_out l_out subst'
;;


let back_8bit ops s_in range_in p_in n_char =
  let p_rel = p_in - range_in in
  let n = min p_rel n_char in
  (n,n)
;;


let back_utf8 ops s_in range_in p_in n_char =
  let open Netstring_tstring in
  let n = ref 0 in
  let k = ref 0 in
  let k_out = ref 0 in
  while p_in - !k > range_in && !n < n_char do
    incr k;
    let ch = Char.code (ops.get s_in (p_in - !k)) in
    if ch < 0x80 || ( ch >= 0xc0 && ch <=0xfd) then ( incr n; k_out := !k )
  done;
  ( !n, !k_out )
;;


let back_utf16_lebe lo hi ops s_in range_in p_in n_char =
  (* lo=0, hi=1: little endian
   * lo=1, hi=0: big endian
   *)
  let open Netstring_tstring in
  let n = ref 0 in
  let k = ref 0 in
  let k_out = ref 0 in
  while p_in - !k > range_in + 1 && !n < n_char do
    incr k;
    incr k;
    let ch = (Char.code (ops.get s_in (p_in - !k + lo))) lor 
	     ((Char.code (ops.get s_in (p_in - !k + hi))) lsl 8) in
    if ch < 0xdc00 || ch >= 0xe000 then ( incr n; k_out := !k );
    (* else: ch is the second half of a surrogate pair *)
  done;
  ( !n, !k_out )
;;


let back_utf32 ops s_in range_in p_in n_char =
  let open Netstring_tstring in
  let p_rel = p_in - range_in in
  let n = min p_rel (n_char lsl 2) in
  (n asr 2,n)
;;



let back_euc ops s_in range_in p_in n_char =
  (* Works for 1-byte and 2-byte encodings *)
  let open Netstring_tstring in
  let n = ref 0 in
  let k = ref 0 in
  let k_out = ref 0 in
  while p_in - !k > range_in && !n < n_char do 
    incr k;
    let ch1 = Char.code (ops.get s_in (p_in - !k)) in
    if ch1 < 0x80 then (
      incr n; k_out := !k
    ) 
    else if p_in - !k > range_in then (
      incr k;
      let ch2 = Char.code (ops.get s_in (p_in - !k)) in
      (* ch2 < 0x80: wrong, but we do not report errors here *)
      if ch2 < 0x80 then (
	incr n; k_out := !k
      ) 
      else if ch2 = 142 || ch2 = 143 then (
	incr n; k_out := !k
      )
      else if p_in - !k > range_in then (
	let ch3 = Char.code (ops.get s_in (p_in - !k - 1)) in
	if ch3 = 142 || ch3 = 143 then (
	  incr k; incr n; k_out := !k
	)
	else (
	  incr n; k_out := !k
	)
      )
      else (
	(* At the beginning of the string *)
	incr n; k_out := !k
      )
    )
  done;
  ( !n, !k_out )
;;


let check_unicode p =
  if p < 0 || (p > 0xd7ff && p < 0xe000) || p = 0xfffe || p = 0xffff || p > 0x10ffff then
    raise Malformed_code
;;


let rec to_unicode cs =
  match cs with
      `Set_iso88591 -> (fun p -> 
			  if p < 0 || p > 255 then raise Malformed_code;
			  p)
    | `Set_usascii  -> (fun p -> 
			  if p < 0 || p > 127 then raise Malformed_code;
			  p)
    | `Set_unicode  -> (fun p -> check_unicode p; p)
    | _ -> 
	let m_to_uni = Netmappings.get_to_unicode (internal_name cs) in
	(fun p ->
	   if p < 0 || p >= Array.length m_to_uni then raise Malformed_code;
	   let uni = m_to_uni.(p) in
	   if uni < 0 then raise Malformed_code;
	   uni
	)
;;


let rec from_unicode cs =
  match cs with
      `Set_iso88591 -> (fun p -> 
			  check_unicode p;
			  if p > 255 then raise (Cannot_represent p);
			  p)
    | `Set_usascii  -> (fun p -> 
			  check_unicode p;
			  if p > 127 then raise (Cannot_represent p);
			  p)
    | `Set_unicode  -> (fun p -> check_unicode p; p)
    | _ -> 
	let m_from_unicode = Netmappings.get_from_unicode (internal_name cs) in
	let m_mask = Array.length m_from_unicode - 1 in
	(fun p ->
	   check_unicode p;
	   let p' =
	     match Array.unsafe_get m_from_unicode (p land m_mask) with
		 Netmappings.U_nil -> -1
	       | Netmappings.U_single (p0,q0) ->
		   if p0 = p then q0 else -1
	       | Netmappings.U_double (p0,q0,p1,q1) ->
		   if p0 = p then q0 else
		     if p1 = p then q1 else -1
	       | Netmappings.U_array pq ->
		   let r = ref (-1) in
		   let h = ref 0 in
		   while !r < 0 && !h < Array.length pq do
		     if pq.( !h ) = p then
		       r := pq.( !h+1 )
		     else
		       h := !h + 2
		   done;
		   !r
	   in
	   if p' < 0 then raise(Cannot_represent p);
	   p'
	)
;;


type encoding1 =
  [ encoding | `Enc_utf16_bom | `Enc_utf32_bom | `Enc_utf8_bom ] ;;

  (* `Enc_*_bom considers the BOM as a character with code point -3.
   * This encoding is only internally used.
   *)

let rec get_reader1 (enc : encoding1) =
  (* get_reader1 supports the additional internal encodings of
   * encoding1. get_reader (below) only supports the exported
   * encodings.
   *)
  match enc with
      `Enc_iso88591 -> !read_iso88591_ref 255 `Enc_iso88591
    | `Enc_usascii  -> !read_iso88591_ref 127 `Enc_usascii
    | `Enc_empty    -> !read_iso88591_ref (-1) `Enc_empty
    | `Enc_utf8     -> !read_utf8_ref false
    | `Enc_java     -> !read_utf8_ref true
    | `Enc_utf8_opt_bom -> read_utf8_opt_bom false
    | `Enc_utf8_bom -> read_utf8_opt_bom true
    | `Enc_utf16    -> read_utf16 false
    | `Enc_utf16_bom  -> read_utf16 true
    | `Enc_utf16_le -> read_utf16_lebe 0 1 0 `Enc_utf16_le
    | `Enc_utf16_be -> read_utf16_lebe 1 0 0 `Enc_utf16_be
    | `Enc_utf32    -> read_utf32 false
    | `Enc_utf32_bom -> read_utf32 true
    | `Enc_utf32_le  -> read_utf32_lebe true 0 `Enc_utf32_le
    | `Enc_utf32_be  -> read_utf32_lebe false 0 `Enc_utf32_be
    | `Enc_eucjp    -> read_eucjp ()
    | `Enc_euckr    -> read_euckr ()
    | `Enc_subset(e,def) ->
	let reader' = get_reader1 (e :> encoding1) in
	read_subset reader' def
    | #encoding as e -> 
	read_8bit (e :> encoding)
;;


let get_reader = 
  (get_reader1 : encoding1 -> 'a :> encoding -> 'a);;


let rec get_writer enc =
  match enc with
      `Enc_iso88591 -> write_iso88591 255
    | `Enc_usascii  -> write_iso88591 127
    | `Enc_empty    -> write_iso88591 (-1)
    | `Enc_utf8     -> write_utf8 false
    | `Enc_java     -> write_utf8 true
    | `Enc_utf16    -> failwith "Netconversion: Cannot output text as `Enc_utf16, use `Enc_utf16_le or `Enc_utf16_be"
    | `Enc_utf16_le -> write_utf16_lebe 0 1
    | `Enc_utf16_be -> write_utf16_lebe 1 0
    | `Enc_utf32    -> failwith "Netconversion: Cannot output text as `Enc_utf32, use `Enc_utf32_le or `Enc_utf32_be"
    | `Enc_utf32_le -> write_utf32_lebe true
    | `Enc_utf32_be -> write_utf32_lebe false
    | `Enc_eucjp    -> write_eucjp ()
    | `Enc_euckr    -> write_euckr ()
    | `Enc_subset(e,def) ->
	let writer' = get_writer e in
	write_subset writer' def
    | _ -> 
	write_8bit enc
;;


let rec get_back_fn enc =
  match enc with
    | `Enc_utf8
    | `Enc_java     -> back_utf8
    | `Enc_utf16    -> failwith "Netconversion: Cannot go back in text encoded as `Enc_utf16, use `Enc_utf16_le or `Enc_utf16_be"
    | `Enc_utf16_le -> back_utf16_lebe 0 1
    | `Enc_utf16_be -> back_utf16_lebe 1 0
    | `Enc_utf32
    | `Enc_utf32_le
    | `Enc_utf32_be -> back_utf32
    | `Enc_eucjp    -> back_euc
    | `Enc_euckr    -> back_euc
    | `Enc_subset(e,def) ->
	get_back_fn e
    | _ -> 
	back_8bit
;;


let recode_poly
           ~in_ops
           ~in_enc
           ~in_buf
	   ~in_pos
	   ~in_len
	   ~out_enc
	   ~out_buf
           ~out_pos
	   ~out_len
	   ~max_chars
	   ~subst =
  let open Netstring_tstring in
  if (in_pos < 0  || in_len < 0  || in_pos  + in_len  > in_ops.length in_buf ||
      out_pos < 0 || out_len < 0 || out_pos + out_len > Bytes.length out_buf)
  then
    invalid_arg "Netconversion.recode";

  (* An array with 250 elements can be allocated in the minor heap. *)

  let slice_length = big_slice  in
  let slice_char = Array.make slice_length (-1) in
  let slice_blen = Array.make slice_length 1 in

  let in_k = ref 0 in     (* read bytes *)
  let in_n = ref 0 in     (* read characters *)
  let in_eof = ref (!in_k >= in_len) in
  let out_k = ref 0 in    (* written bytes *)
  let out_n = ref 0 in    (* written characters *)
  let out_eof = ref (!out_k >= out_len || !out_n >= max_chars) in

  let rd_enc = ref in_enc in
  let reader = ref (get_reader in_enc) in
  let writer = get_writer out_enc in

  while not !in_eof && not !out_eof do
    let in_n_inc, in_k_inc, rd_enc' =
      try
	!reader.read in_ops slice_char slice_blen in_buf
                     (in_pos + !in_k) (in_len - !in_k) 
      with
	  Malformed_code_read(in_n_inc, in_k_inc, rd_enc') ->
	    if in_n_inc = 0 then raise Malformed_code;
	    (in_n_inc, in_k_inc, rd_enc')
    in

    let out_n_inc_max = min in_n_inc (max_chars - !out_n) in
        (* do not write more than max_chars *)
    let out_n_inc, out_k_inc =
      if out_n_inc_max > 0 then
	writer 
	  slice_char 0 out_n_inc_max out_buf (out_pos + !out_k) 
	  (out_len - !out_k) subst
      else
	(0,0)
    in

    let in_n_inc', in_k_inc' =
      if in_n_inc > out_n_inc then begin
	(* Not all read characters could be written *)
	let sum = ref 0 in
	for j = 0 to out_n_inc - 1 do
	  sum := !sum + slice_blen.(j)
	done;
	(out_n_inc, !sum)
      end
      else
	(in_n_inc, in_k_inc)
    in

    in_k := !in_k + in_k_inc';
    in_n := !in_n + in_n_inc';
    out_k := !out_k + out_k_inc;
    out_n := !out_n + out_n_inc;

    (* Detect change of input encoding: *)

    if rd_enc' <> !rd_enc then begin
      rd_enc := rd_enc';
      reader := get_reader rd_enc';
      Array.fill slice_blen 0 slice_length 1;
    end;

    (* EOF criteria:
     * - It is possible that !in_k never reaches in_len because there is a
     *   multibyte character at the end that is partially outside the input
     *   range
     * - For the same reason it is possible that !out_k never reaches out_len
     * - It is accepted as reader EOF if not even one character can be
     *   scanned
     * - It is accepted as writer EOF if fewer than in_n_inc characters
     *   could be written
     *)

    in_eof := 
      (!in_k >= in_len || in_n_inc = 0);

    out_eof := 
      (!out_k >= out_len || !out_n >= max_chars || out_n_inc < in_n_inc);

  done;

  ( !in_k, !out_k, !rd_enc )
;;


let recode = recode_poly ~in_ops:Netstring_tstring.string_ops

let recode_bytes = recode_poly ~in_ops:Netstring_tstring.bytes_ops

let recode_tstring ~in_enc ~in_buf ~in_pos ~in_len ~out_enc
                   ~out_buf ~out_pos ~out_len ~max_chars ~subst =
  let f =
    { Netstring_tstring.with_fun =
        (fun in_ops in_buf ->
           recode_poly
             ~in_ops ~in_enc ~in_buf ~in_pos ~in_len ~out_enc
             ~out_buf ~out_pos ~out_len ~max_chars ~subst
        )
    } in
  Netstring_tstring.with_tstring f in_buf


let rec ustring_of_uchar enc =
  let multi_byte writer n p =
    let s = Bytes.create n in
    let _,n_act = writer [|p|] 0 1 s 0 n 
		    (fun _ -> raise (Cannot_represent p)) in
    Bytes.sub_string s 0 n_act
  in
  match enc with
      `Enc_iso88591 -> 
	(fun p ->
	   if p > 255 then raise (Cannot_represent p);
	   String.make 1 (Char.chr p))
    | `Enc_usascii ->
	(fun p ->if p > 127 then raise (Cannot_represent p);
	   String.make 1 (Char.chr p))
    | `Enc_utf8 | `Enc_utf8_opt_bom -> multi_byte (write_utf8 false) 4
    | `Enc_java -> multi_byte (write_utf8 true) 4
    | `Enc_utf16_le -> multi_byte (write_utf16_lebe 0 1) 4
    | `Enc_utf16_be -> multi_byte (write_utf16_lebe 1 0) 4
    | `Enc_utf16 ->
	invalid_arg "Netconversion.ustring_of_uchar: UTF-16 not possible"
    | `Enc_utf32_le -> multi_byte (write_utf32_lebe true) 4
    | `Enc_utf32_be -> multi_byte (write_utf32_lebe false) 4
    | `Enc_utf32 ->
	invalid_arg "Netconversion.ustring_of_uchar: UTF-32 not possible"
    | `Enc_eucjp -> multi_byte (write_eucjp()) 3
    | `Enc_euckr -> multi_byte (write_euckr()) 2
    | `Enc_subset(e,def) ->
	(fun p -> if def p then ustring_of_uchar e p else raise (Cannot_represent p))
    | _ ->
	let writer = write_8bit enc in
	multi_byte writer 1
;;


let makechar enc =
  let us = ustring_of_uchar enc in
  (fun p -> try us p with Cannot_represent _ -> raise Not_found)
;;


(* The following algorithms assume that there is an upper limit of the length
 * of a multibyte character. Currently, UTF8 is the encoding with the longest
 * multibyte characters (6 bytes).
 * Because of this limit, it is allowed to allocate a buffer that is "large
 * enough" in order to ensure that at least one character is recoded in every
 * loop cycle. If the buffer was not large enough, no character would be
 * processed in a cycle, and the algorithm would hang.
 *)

let convert_poly :
      type s t . in_ops:s Netstring_tstring.tstring_ops ->
                 out_kind:t Netstring_tstring.tstring_kind ->
                 ?subst:(int -> string) ->
                 in_enc:encoding ->
                 out_enc:encoding ->
                 ?range_pos:int ->
                 ?range_len:int ->
                 s ->
                   t =
  fun ~in_ops ~out_kind
      ?(subst = (fun p -> raise (Cannot_represent p))) 
      ~in_enc ~out_enc ?(range_pos=0) ?range_len s ->
    let open Netstring_tstring in

    let range_len = 
      match range_len with
          Some l -> l
        | None -> in_ops.length s - range_pos in

    if range_pos < 0 || range_len < 0 || range_pos+range_len > in_ops.length s
    then invalid_arg "Netconversion.convert";

    (* Estimate the size of the output string: 
     * length * 2 is just guessed. It is assumed that this number is usually
     * too large, and to avoid that too much memory is wasted, the buffer is
     * limited by 10000.
     *)
    let size = ref (max multibyte_limit (min 10000 (range_len * 2))) in
    let out_buf = ref (Bytes.create !size) in

    let k_in = ref 0 in
    let k_out = ref 0 in

    while !k_in < range_len do
      let in_len = range_len - !k_in in
      let out_len = !size - !k_out in
      assert (out_len >= multibyte_limit);  (* space for at least one char *)
      let k_in_inc, k_out_inc, in_enc' =
        recode_poly
               ~in_ops
               ~in_enc  ~in_buf:s           ~in_pos:(range_pos + !k_in) ~in_len
               ~out_enc ~out_buf:(!out_buf) ~out_pos:(!k_out)           ~out_len
               ~max_chars:max_int           ~subst in
      if k_in_inc = 0 then raise Malformed_code;
      (* Reasons for k_in_inc = 0:
       * (1) There is not enough space in out_buf to add a single character
       * (2) in_buf ends with a prefix of a multi-byte character
       * Because there is always space for at least one character
       * ( = multibyte_limit ), reason (1) can be excluded. So it must
       * be (2), and we can raise Malformed_code.
       *)
      k_in  := !k_in  + k_in_inc;
      k_out := !k_out + k_out_inc;
      (* double the size of out_buf: *)
      let size' = min Sys.max_string_length (!size + !size) in
      if size' < !size + multibyte_limit then 
        failwith "Netconversion.convert: string too long";
      let out_buf' = Bytes.create size' in
      Bytes.blit !out_buf 0 out_buf' 0 !k_out;
      out_buf := out_buf';
      size := size';
    done;

    match out_kind with
      | Netstring_tstring.String_kind ->
          Bytes.sub_string !out_buf 0 !k_out
      | Netstring_tstring.Bytes_kind ->
          Bytes.sub !out_buf 0 !k_out
      | Netstring_tstring.Memory_kind ->
          let m =
            Bigarray.Array1.create Bigarray.char Bigarray.c_layout !k_out in
          Netsys_mem.blit_bytes_to_memory !out_buf 0 m 0 !k_out;
          m
;;


let convert ?subst ~in_enc ~out_enc ?range_pos ?range_len s =
  convert_poly
    ?subst
    ~in_ops:Netstring_tstring.string_ops
    ~out_kind:Netstring_tstring.String_kind
    ~in_enc ~out_enc ?range_pos ?range_len s

let convert_bytes ?subst ~in_enc ~out_enc ?range_pos ?range_len s =
  convert_poly
    ?subst
    ~in_ops:Netstring_tstring.bytes_ops
    ~out_kind:Netstring_tstring.Bytes_kind
    ~in_enc ~out_enc ?range_pos ?range_len s

let convert_tstring ?subst ~in_enc ~out_enc ~out_kind ?range_pos ?range_len ts =
  let f =
    { Netstring_tstring.with_fun =
        (fun in_ops s ->
           convert_poly
             ?subst
             ~in_ops ~out_kind
             ~in_enc ~out_enc ?range_pos ?range_len s
        )
    } in
  Netstring_tstring.with_tstring f ts


class conversion_pipe ?(subst = (fun p -> raise (Cannot_represent p))) 
                    ~in_enc ~out_enc () =
  let current_in_enc = ref in_enc in
  let conv in_netbuf at_eof out_netbuf =
    if at_eof then
      (* TODO: avoid the extra allocations *)
      let s = convert_bytes
	        ~subst ~in_enc:!current_in_enc ~out_enc
	        (Netbuffer.unsafe_buffer in_netbuf) in
      Netbuffer.add_bytes out_netbuf s
    else
      let in_buf = Netbuffer.unsafe_buffer in_netbuf in
      let in_pos = 0 in
      let in_len = Netbuffer.length in_netbuf in
      let n =
	Netbuffer.add_inplace 
	  out_netbuf
	  (fun out_buf out_pos out_len ->
	     let (in_n,out_n,in_enc') =
	       recode_bytes
	         ~in_enc:!current_in_enc ~in_buf ~in_pos ~in_len
	         ~out_enc ~out_buf ~out_pos ~out_len
	         ~max_chars:out_len
	         ~subst
	     in
	     Netbuffer.delete in_netbuf 0 in_n;
	     current_in_enc := in_enc';
	     out_n
	  )
      in
      if n = 0 && in_len > 0 then begin
	(* To avoid endless loops, ensure here that there is enough space
	 * in out_netbuf
	 *)
	ignore(Netbuffer.add_inplace 
	       ~len:multibyte_limit
		 out_netbuf
		 (fun _ _ _ -> 0));
      end;
      ()
  in
  Netchannels.pipe ~conv ()
;;


(**********************************************************************)
(* Cursors                                                            *)
(**********************************************************************)

(* The "read_*" functions are used to scan the string, and to move
 * the cursor forward. The slice array stores the scanned characters.
 * If the read call raises Malformed_code, the size of the slice
 * is decreased to 1, so the exact position can be calculated.
 *)

(* Notes UTF-8/16/32 with BOM handling:
 * 
 * cursor_enc is updated after the first slice has been read. This
 * usually changes this field to either the big or little endian
 * encoding variant. No update is needed when previous slices are
 * scanned, because the BOM is only allowed at the beginning of the
 * string, so can at most go back to exactly the BOM.
 *
 * cursor_encoding returns `Enc_utf16 when the cursor is over the
 * BOM, and cursor_enc otherwise.
 *)

exception End_of_string;;
exception Cursor_out_of_range;;
exception Partial_character;;
exception Byte_order_mark;;


type 's poly_cursor =
    { (* configuration: *)
      cursor_ops : 's Netstring_tstring.tstring_ops;
      mutable cursor_target : 's;
      mutable cursor_range_pos : int;
      mutable cursor_range_len : int;
      mutable cursor_offset : int;
      mutable cursor_enc : encoding;
        (* `Enc_utf16: Only used if the slice or string is too short to
         *    recognize the endianess. Otherwise, the encoding is set
         *    to the endian-aware variant.
         * `Enc_utf32: same
         *)
      mutable cursor_has_bom : bool;
      (* Whether there is a BOM. Only when initially cursor_enc=`Enc_utf16
         or utf32
       *)
      (* conversion: *)
      mutable cursor_slice_char : int array;
        (* Contains the characters of the slice. Special values:
	 * -1: EOF
	 * -2: Incomplete multi-byte character at end
	 * -3: BOM at the beginning
	 *)
      mutable cursor_slice_blen : int array;
        (* Contains the byte length of the characters.
	 * Recall that this array must contain 1s when single-byte
	 * encodings are scanned, and must not be modified. The
	 * "reader" does not fill this array for single-byte encodings,
	 * so modifications would persist!
	 *)
      mutable cursor_imbchar_len : int;
        (* This is always 0, except in the special case when the first
	 * character of this slice is EOF, and EOF is preceded by an
	 * incomplete multi-byte character (imbchar). In this case,
	 * the length of the imbchar is stored here.
	 *)
      mutable cursor_slice_char_pos : int;
        (* char pos of the beginning of the slice *)
      mutable cursor_slice_byte_pos : int;
        (* byte pos of the beginning of the slice *)
      mutable cursor_slice_length : int;
        (* number of characters *)
      mutable cursor_slice_bytes : int;
        (* number of bytes *)
      (* bookkeeping: *)
      mutable cursor_char_pos : int;
      mutable cursor_byte_pos : int;
      mutable cursor_index : int;     (* index in the slice array *)
      mutable cursor_problem_range_start : int;
      mutable cursor_problem_range_end : int;
      (* The character positions >= range_start and < range_end are
       * considered as problem range. It is known that there is a
       * coding error (Malformed_code), so slices with length 1 must
       * be used.
       *)
      (* methods: *)
      mutable load_next_slice : unit -> unit;   
        (* Precondition: cursor is one char right of the end of the slice
	 * Action: load the next slice
	 * Postcondition: cursor is at the beginning of the new slice
	 *)
      mutable load_prev_slice : unit -> unit;  
        (* Precondition: cursor is at the beginning of current slice 
	 * Action: load the previous slice
	 * Postcondition: the cursor is at the end of the new slice
	 *                or the function raises Cursor_out_of_range
	 * Note that this function actually moves the cursor one character
	 * back (in contrast to load_next_slice that only reloads the
	 * slice array, but does not move the cursor). The function may
	 * choose to allocate a new, shorter slice array.
	 *)
    }
;;


type cursor = string poly_cursor

let cursor_target cs = cs.cursor_target;;

let cursor_range cs = (cs.cursor_range_pos, cs.cursor_range_len);;

let cursor_initial_rel_pos cs = cs.cursor_offset;;

let cursor_char_count cs = cs.cursor_char_pos;;

let cursor_pos cs = cs.cursor_byte_pos;;

let cursor_encoding cs = 
  let enc = cs.cursor_enc in
  match enc with
    ( `Enc_utf16_le | `Enc_utf16_be ) when cs.cursor_has_bom ->
	if cs.cursor_byte_pos = cs.cursor_range_pos then
	  `Enc_utf16
	else
	  enc
    | ( `Enc_utf32_le | `Enc_utf32_be ) when cs.cursor_has_bom ->
	if cs.cursor_byte_pos = cs.cursor_range_pos then
	  `Enc_utf32
	else
	  enc
    | (`Enc_utf8 | `Enc_utf8_opt_bom) when cs.cursor_has_bom ->
	if cs.cursor_byte_pos = cs.cursor_range_pos then
	  `Enc_utf8_opt_bom
	else
	  enc
    | _ ->
	enc
;;


exception Failing_in_Netconversion_uchar_at

let uchar_at cs =
  let ch = cs.cursor_slice_char.(cs.cursor_index) in
  if ch < 0 then
    match ch with
	-1 -> raise End_of_string
      | -2 -> raise Partial_character
      | -3 -> raise Byte_order_mark
      | _  -> (* assert false *) raise Failing_in_Netconversion_uchar_at
	      (* "assert false" isn't inlined! *)
  else
    ch
;;


let cursor_byte_length cs =
  let ch = cs.cursor_slice_char.(cs.cursor_index) in
  if ch = -1 then
    raise End_of_string
  else
    cs.cursor_slice_blen.(cs.cursor_index)
;;



let cursor_at_end cs =
  let ch = cs.cursor_slice_char.(cs.cursor_index) in
  ch = (-1)
;;

let move_right num cs =
  let rec go num =
    let sl = Array.length cs.cursor_slice_char in
    if num >= sl - cs.cursor_index then begin
      (* Case: go at least to the next slice *)

      (* If the current slice is not completely filled, we will be 
       * definitely outside of the valid range
       *)
      if cs.cursor_slice_length < sl then begin
	(* move to rightmost position, and raise the approriate exception *)
	cs.cursor_byte_pos <- cs.cursor_slice_byte_pos + cs.cursor_slice_bytes;
	cs.cursor_char_pos <- cs.cursor_slice_char_pos + cs.cursor_slice_length;
	cs.cursor_index    <- cs.cursor_slice_length;
	assert(cs.cursor_slice_char.(cs.cursor_index) = (-1));
	raise Cursor_out_of_range;
      end;
      assert(cs.cursor_slice_length = sl);
      let n = sl - cs.cursor_index in
      cs.cursor_byte_pos <- cs.cursor_slice_byte_pos + cs.cursor_slice_bytes;
      cs.cursor_char_pos <- cs.cursor_slice_char_pos + cs.cursor_slice_length;
      cs.cursor_index    <- sl;
      cs.load_next_slice();     (* may raise Malformed_code *)
      go (num - n);
    end
    else begin
      (* Case: do not leave this slice *)
      let bl_sum = ref 0 in
      for k = cs.cursor_index to cs.cursor_index + num - 1 do
	let bl = cs.cursor_slice_blen.(k) in
	if k >= cs.cursor_slice_length then begin
	  (* Cursor is beyond EOF *)
	  cs.cursor_byte_pos <- cs.cursor_byte_pos + !bl_sum;
	  cs.cursor_char_pos <- cs.cursor_char_pos + (k - cs.cursor_index);
	  cs.cursor_index    <- k;
	  raise Cursor_out_of_range
	end;
	bl_sum := !bl_sum + bl
      done;
      cs.cursor_byte_pos <- cs.cursor_byte_pos + !bl_sum;
      cs.cursor_char_pos <- cs.cursor_char_pos + num;
      cs.cursor_index    <- cs.cursor_index + num;
    end
  in
  assert(num >= 0);
  try
    go num
  with
      Malformed_code ->
	(* This happens when load_next_slice fails to decode the next slice
	 * of length 1. In this case, load_next_slice keeps the state of
	 * the cursor, so we have the chance to correct it now.
	 *)
	cs.cursor_index    <- cs.cursor_index - 1;
	cs.cursor_char_pos <- cs.cursor_char_pos - 1;
	cs.cursor_byte_pos <- cs.cursor_byte_pos - 
	                      cs.cursor_slice_blen.(cs.cursor_index);
	raise Malformed_code
;;

let move_left num cs =
  let rec go num =
    if num > cs.cursor_index then begin
      let n = cs.cursor_index in
      cs.cursor_byte_pos <- cs.cursor_slice_byte_pos;
      cs.cursor_char_pos <- cs.cursor_slice_char_pos;
      cs.cursor_index    <- 0;
      (* cursor is now at the beginning of the slice *)
      cs.load_prev_slice();   (* go another character back *)
      go (num-n-1)            (* so we went n+1 characters in this round *)
    end
    else begin
      (* num <= cs.cursor_index *)
      let bl_sum = ref 0 in
      let n = cs.cursor_index - num in
      for k = cs.cursor_index - 1 downto n do
	bl_sum := !bl_sum + cs.cursor_slice_blen.(k)
      done;
      cs.cursor_byte_pos <- cs.cursor_byte_pos - !bl_sum;
      cs.cursor_char_pos <- cs.cursor_char_pos - num;
      cs.cursor_index    <- n;
    end
  in
  assert(num < 0);
  go (-num)
;;


let move ?(num = 1) cs =
  if num >= 0 then
    move_right num cs
  else
    move_left num cs
;;


let init_load_slice cs enc =
  let open Netstring_tstring in

  let ops = cs.cursor_ops in
  let reader0 = (get_reader enc).read ops in
  let back0   = lazy(get_back_fn enc ops) in
  (* For most encodings, [reader] and [back] never change.
   * For UTF-16, there may be refinements, however.
   *)

  let reader() =
    match cs.cursor_enc with
      ( `Enc_utf16 | `Enc_utf16_le | `Enc_utf16_be ) when cs.cursor_has_bom ->
	  (* Ensure we use `Enc_utf16_bom when we read the beginning
	   * of the range
	   *)
	  (fun slice_char slice_blen s bp bl ->
	     if bp = cs.cursor_range_pos then
	       (get_reader1 `Enc_utf16_bom).read
                  ops slice_char slice_blen s bp bl
	     else
	       (get_reader cs.cursor_enc).read
                  ops slice_char slice_blen s bp bl
	  )
      | ( `Enc_utf32 | `Enc_utf32_le | `Enc_utf32_be ) when cs.cursor_has_bom ->
	  (* Ensure we use `Enc_utf32_bom when we read the beginning
	   * of the range
	   *)
	  (fun slice_char slice_blen s bp bl ->
	     if bp = cs.cursor_range_pos then
	       (get_reader1 `Enc_utf32_bom).read
                  ops slice_char slice_blen s bp bl
	     else
	       (get_reader cs.cursor_enc).read
                  ops slice_char slice_blen s bp bl
	  )
      | ( `Enc_utf8 | `Enc_utf8_opt_bom ) when cs.cursor_has_bom ->
	  (fun slice_char slice_blen s bp bl ->
	     if bp = cs.cursor_range_pos then
	       (get_reader1 `Enc_utf8_bom).read
                  ops slice_char slice_blen s bp bl
	     else
	       (get_reader cs.cursor_enc).read
                  ops slice_char slice_blen s bp bl
	  )
      | _ ->
	  reader0
  in

  let back() =
    match cs.cursor_enc with
      ( `Enc_utf16 | `Enc_utf16_le | `Enc_utf16_be ) when cs.cursor_has_bom ->
	  get_back_fn cs.cursor_enc ops
      | ( `Enc_utf32 | `Enc_utf32_le | `Enc_utf32_be ) when cs.cursor_has_bom ->
	  get_back_fn cs.cursor_enc ops
      | ( `Enc_utf8 | `Enc_utf8_opt_bom ) when cs.cursor_has_bom ->
	  get_back_fn cs.cursor_enc ops
      | _ ->
	  Lazy.force back0
  in

  let record_imbchar rd_chars rd_bytes scan_bytes =
    (* Put a (-2) at position rd_chars of the current slice *)
    cs.cursor_slice_char.(rd_chars) <- (-2);
    cs.cursor_slice_blen.(rd_chars) <- scan_bytes - rd_bytes;
    if rd_chars+1 < Array.length cs.cursor_slice_char then (
      cs.cursor_slice_char.(rd_chars+1) <- (-1);
    );
    cs.cursor_slice_length <- rd_chars+1;
    cs.cursor_slice_bytes <- scan_bytes;
  in

  let repair_slice slice_size =
    (* When the reader raises Malformed_code, the slice has been
     * modified. This function reloads the old slice again.
     *
     * This function repairs these fields from the other fields:
     * - cursor_slice_char
     * - cursor_slice_blen
     * - cursor_slice_length
     * - cursor_slice_bytes
     *)
    let bp = cs.cursor_slice_byte_pos in
    let ep = cs.cursor_range_pos + cs.cursor_range_len in
    let (slice_char, slice_blen) =
      (Array.make slice_size (-1), Array.make slice_size 1) in
    let rd_chars, rd_bytes, _ =
      try
	reader 
          () slice_char slice_blen cs.cursor_target bp (ep-bp) 
      with
	  (* should not happen: *)
	  Malformed_code_read(_,_,_) -> raise Malformed_code
    in
    cs.cursor_slice_length <- rd_chars;
    cs.cursor_slice_bytes <- rd_bytes;
    cs.cursor_slice_char <- slice_char;
    cs.cursor_slice_blen <- slice_blen;
    (* Check for imbchars: *)
    if rd_chars < slice_size && rd_bytes < ep-bp then (
      record_imbchar rd_chars rd_bytes (ep-bp);
    );
  in

  let load_next_slice() =
    let cp = cs.cursor_char_pos in
    let bp = cs.cursor_byte_pos in
    let ep = cs.cursor_range_pos + cs.cursor_range_len in
    let load slice_size =
      let old_partial_len =
	(* Handle the case that the last character is (-2), and thus the first
	 * character of the next slice will be (-1). Then, cursor_imbchar_len
	 * must be set to the length of the (-2) character.
	 *)
	if cs.cursor_slice_char.(cs.cursor_slice_length-1) = (-2) then
	  cs.cursor_slice_blen.(cs.cursor_slice_length-1)
	else
	  0
      in
      (* Check if the current array can be reused, or if we need new
       * arrays with different sizes
       *)
      let (slice_char, slice_blen) =
	if slice_size = Array.length cs.cursor_slice_char then 
	  (cs.cursor_slice_char, cs.cursor_slice_blen)
	  (* use old arrays again *)
	else
	  (Array.make slice_size (-1), Array.make slice_size 1)
	  (* create new arrays with different size *)
      in
      (* Use the reader to decode the bytes and to put the characters into
       * slice_char. 
       *)
      let rd_chars, rd_bytes, enc' =
	reader () slice_char slice_blen cs.cursor_target bp (ep-bp) in
        (* may raise Malformed_code_read *)
      (* Update cursor record: *)
      cs.cursor_index <- 0;
      cs.cursor_slice_char <- slice_char;
      cs.cursor_slice_blen <- slice_blen;
      cs.cursor_slice_length <- rd_chars;
      cs.cursor_slice_bytes <- rd_bytes;
      cs.cursor_slice_char_pos <- cp;
      cs.cursor_slice_byte_pos <- bp;
      cs.cursor_imbchar_len <- old_partial_len;
      cs.cursor_enc <- enc';
      (* Check for imbchars: *)
      if rd_chars < slice_size && rd_bytes < ep-bp then (
	record_imbchar rd_chars rd_bytes (ep-bp);
      );
    in
    (* Is the cursor positioned in a problem range? If yes, decode only
     * one character. If not, try to decode a block of characters.
     * If the latter fails, the current position turns out to be
     * problematic, and is remembered as such.
     *)
    let old_slice_size = Array.length cs.cursor_slice_char in
    if cp >= cs.cursor_problem_range_start && 
       cp < cs.cursor_problem_range_end then begin
	 try
	   load 1
	 with
	     Malformed_code_read(_,_,_) ->
	       repair_slice old_slice_size; 
	       raise Malformed_code
    end
    else begin
      try load big_slice
      with
	  Malformed_code_read(_,_,_) ->
	    cs.cursor_problem_range_start <- cp;
	    cs.cursor_problem_range_end   <- cp+big_slice;
	    try
	      load 1
	    with
		Malformed_code_read(_,_,_) ->
		  repair_slice old_slice_size; 
		  raise Malformed_code
    end
  in

  let load_prev_slice() =
    let cp = cs.cursor_char_pos in
    let bp = cs.cursor_byte_pos in
    let ep = cs.cursor_range_pos + cs.cursor_range_len in
    let load slice_size =
      (* Check if the current array can be reused, or if we need new
       * arrays with different sizes
       *)
      let (slice_char, slice_blen) =
	if slice_size = Array.length cs.cursor_slice_char then 
	  (cs.cursor_slice_char, cs.cursor_slice_blen)
	  (* use old arrays again *)
	else
	  (Array.make slice_size (-1), Array.make slice_size 1)
	  (* create new arrays with different size *)
      in
      (* Go back 1 character (must always succeed): *)
      if bp = cs.cursor_range_pos then raise Cursor_out_of_range;      
      let bk1_chars, bk1_bytes =
	if cs.cursor_imbchar_len > 0 then
	  (* Special case: the last character of this slice is an imbchar.
	   * Assume imbchar_len 
	   *)
	  (1, cs.cursor_imbchar_len)
	else
	  back 
	    () cs.cursor_target cs.cursor_range_pos bp 1 in
      if bk1_chars = 0 then raise Malformed_code;
      (* bk1_chars = 0: this means there is a multi-byte suffix at the
       * beginning of the range
       * ==> bk1_chars = 1
       *)
      (* Go back further slice_size-1 characters (or less): *)
      let bk_chars, bk_bytes =
	back 
	  () cs.cursor_target cs.cursor_range_pos (bp-bk1_bytes) (slice_size-1) in
      let bp' = bp - bk1_bytes - bk_bytes in
      (* Use the reader to decode the bytes and to put the characters into
       * slice_char. 
       *)
      let rd_chars, rd_bytes, _ =
	reader () slice_char slice_blen cs.cursor_target bp' (ep-bp') in
        (* may raise Malformed_code_read *)
      assert(rd_chars >= bk_chars);
      (* Update cursor record: *)
      cs.cursor_index <- bk_chars;
      cs.cursor_slice_char <- slice_char;
      cs.cursor_slice_blen <- slice_blen;
      cs.cursor_slice_length <- rd_chars;
      cs.cursor_slice_bytes <- rd_bytes;
      cs.cursor_slice_char_pos <- cp - bk_chars - 1;
      cs.cursor_slice_byte_pos <- bp';
      cs.cursor_imbchar_len <- 0; (* Cannot happen *)
      (* Don't need to update cursor_enc! *)
      (* Check for imbchars: *)
      if rd_chars < slice_size && rd_bytes < ep-bp' then (
	record_imbchar rd_chars rd_bytes (ep-bp');
      );
      (* Implicitly go one character back: *)
      cs.cursor_char_pos <- cp - 1;
      cs.cursor_byte_pos <- bp - bk1_bytes;
    in
    (* Is the cursor positioned in a problem range? If yes, decode only
     * one character. If not, try to decode a block of characters.
     * If the latter fails, the current position turns out to be
     * problematic, and is remembered as such.
     *)
    let old_slice_size = Array.length cs.cursor_slice_char in
    if cp > cs.cursor_problem_range_start && 
       cp <= cs.cursor_problem_range_end then begin
	 try
	   load 1
	 with
	     Malformed_code_read(_,_,_) ->
	       repair_slice old_slice_size;
	       raise Malformed_code
    end
    else begin
      try load big_slice
      with
	  Malformed_code_read(_,_,_) ->
	    cs.cursor_problem_range_start <- cp-big_slice;
	    cs.cursor_problem_range_end   <- cp;
	    try
	      load 1
	    with
		Malformed_code_read(_,_,_) ->
		  repair_slice old_slice_size;
		  raise Malformed_code
    end
  in

  (* Important note: These two functions either modify the cursor state
   * as requested, or they raise an exception, and keep the cursor state
   * as before. Considered exceptions are Malformed_code, and
   * Cursor_out_of_range.
   *)

  cs.load_next_slice <- load_next_slice;
  cs.load_prev_slice <- load_prev_slice
;;


let create_poly_cursor
      ?(range_pos = 0) ?range_len ?(initial_rel_pos = 0) enc ops s =
  let open Netstring_tstring in
  if range_pos < 0 || range_pos > ops.length s then
    invalid_arg "Netconversion.create_cursor";
  
  let range_len =
    match range_len with
	Some l -> l
      | None   -> ops.length s - range_pos in
  if range_len < 0 || range_pos + range_len > ops.length s then
    invalid_arg "Netconversion.create_cursor";

  if initial_rel_pos < 0 || initial_rel_pos > range_len then
    invalid_arg "Netconversion.create_cursor";

  if enc = `Enc_utf16 && initial_rel_pos <> 0 then
    failwith "Netconversion.create_cursor: The encoding `Enc_utf16 only supported when initial_rel_pos=0";

  if enc = `Enc_utf32 && initial_rel_pos <> 0 then
    failwith "Netconversion.create_cursor: The encoding `Enc_utf32 only supported when initial_rel_pos=0";

  let cs =
    { cursor_ops = ops;
      cursor_target = s;
      cursor_range_pos = range_pos;
      cursor_range_len = range_len;
      cursor_offset = initial_rel_pos;
      cursor_enc = enc;
      cursor_has_bom =
        (enc = `Enc_utf16 || enc = `Enc_utf32 || enc = `Enc_utf8_opt_bom);
      cursor_slice_char = [| 1 |];
      cursor_slice_blen = [| 1 |];
      cursor_imbchar_len = 0;
      cursor_slice_char_pos = 0;
      cursor_slice_byte_pos = range_pos + initial_rel_pos;
      cursor_slice_length = 1;
      cursor_slice_bytes = 0;
      cursor_char_pos = 0;
      cursor_byte_pos = range_pos + initial_rel_pos;
      cursor_index = 1;
      cursor_problem_range_start = max_int;
      cursor_problem_range_end = max_int;
      load_next_slice = (fun () -> assert false);
      load_prev_slice = (fun () -> assert false);
    } in

  init_load_slice cs enc;
  
  (* load the next slice to do the rest of the initialization: *)
  cs.load_next_slice();

  cs
;;


let create_cursor ?range_pos ?range_len ?initial_rel_pos enc s =
  let ops = Netstring_tstring.string_ops in
  create_poly_cursor ?range_pos ?range_len ?initial_rel_pos enc ops s


type 'a with_cursor_fun =
    { with_cursor_fun : 's . 's Netstring_tstring.tstring_ops ->
                             's poly_cursor ->
                             'a
    }

let with_tstring_cursor ?range_pos ?range_len ?initial_rel_pos enc ts f =
  let f =
    { Netstring_tstring.with_fun =
        (fun ops s ->
           f.with_cursor_fun
             ops
             (create_poly_cursor
                ?range_pos ?range_len ?initial_rel_pos enc ops s)
        )
    } in
  Netstring_tstring.with_tstring f ts


let reinit_cursor ?(range_pos = 0) ?range_len ?(initial_rel_pos = 0) ?enc s cs =
  let open Netstring_tstring in
  let ops = cs.cursor_ops in
  if range_pos < 0 || range_pos > ops.length s then
    invalid_arg "Netconversion.reinit_cursor";
  
  let range_len =
    match range_len with
	Some l -> l
      | None   -> ops.length s - range_pos in
  if range_len < 0 || range_pos + range_len > ops.length s then
    invalid_arg "Netconversion.reinit_cursor";

  if initial_rel_pos < 0 || initial_rel_pos > range_len then
    invalid_arg "Netconversion.reinit_cursor";

  let enc = 
    match enc with
	None -> cs.cursor_enc
      | Some e -> e
  in
  if enc = `Enc_utf16 && initial_rel_pos <> 0 then
    failwith "Netconversion.reinit_cursor: The encoding `Enc_utf16 only supported when initial_rel_pos=0";
  if enc = `Enc_utf32 && initial_rel_pos <> 0 then
    failwith "Netconversion.reinit_cursor: The encoding `Enc_utf32 only supported when initial_rel_pos=0";

  let old_enc = cs.cursor_enc in

  cs.cursor_target <- s;
  cs.cursor_range_pos <- range_pos;
  cs.cursor_range_len <- range_len;
  cs.cursor_offset <- initial_rel_pos;
  cs.cursor_enc <- enc;
  cs.cursor_has_bom <- 
    (enc = `Enc_utf16 || enc = `Enc_utf32 || enc = `Enc_utf8_opt_bom);
  cs.cursor_imbchar_len <- 0;
  cs.cursor_slice_char_pos <- 0;
  cs.cursor_slice_byte_pos <- range_pos + initial_rel_pos;
  cs.cursor_slice_length <- 1;
  cs.cursor_slice_bytes <- 0;
  cs.cursor_char_pos <- 0;
  cs.cursor_byte_pos <- range_pos + initial_rel_pos;
  cs.cursor_index <- 1;
  cs.cursor_problem_range_start <- max_int;
  cs.cursor_problem_range_end <- max_int;
  cs.load_next_slice <- (fun () -> assert false);
  cs.load_prev_slice <- (fun () -> assert false);
  
  cs.cursor_slice_char.(0) <- 1;
  if not (same_encoding enc old_enc) then
    (* slice_blen: It might have happened that the new encoding is an
     * 8 bit charset, but the old was not. Re-initialize this array
     * to ensure it contains only "1" in this case.
     *)
    Array.fill cs.cursor_slice_blen 0 (Array.length cs.cursor_slice_blen) 1;

  init_load_slice cs enc;
  
  (* load the next slice to do the rest of the initialization: *)
  cs.load_next_slice();

;;


let copy_cursor ?enc cs =
  let enc = 
    match enc with
	None -> cs.cursor_enc
      | Some e -> e
  in

  if same_encoding enc cs.cursor_enc then
    { cs with
	cursor_slice_char = Array.copy cs.cursor_slice_char;
	cursor_slice_blen = Array.copy cs.cursor_slice_blen;
    }
  else begin
    if enc = `Enc_utf16 then
      failwith "Netconversion.copy_cursor: The encoding `Enc_utf16 is not supported";
    if enc = `Enc_utf32 then
      failwith "Netconversion.copy_cursor: The encoding `Enc_utf32 is not supported";
    let cs' =
      { cs with
	  cursor_enc = enc;
	  cursor_slice_char = [| 1 |];
	  cursor_slice_blen = [| 1 |];
	  cursor_slice_length = 1;
	  cursor_problem_range_start = max_int;
	  cursor_problem_range_end = max_int;
      } in
    init_load_slice cs' enc;
  
    (* load the next slice to do the rest of the initialization: *)
    cs'.load_next_slice();

    cs'
  end
;;


let cursor_blit_maxlen cs = 
  let l = cs.cursor_slice_length - cs.cursor_index in
  (* Test on special situations: *)
  match cs.cursor_slice_char.(cs.cursor_index) with
      -1 -> (* EOF *) raise End_of_string
    | -3 -> (* BOM *) 0
    | _ ->
	if cs.cursor_slice_char.(cs.cursor_slice_length - 1) = (-2) then
	  (* Partial character *)
	  l-1
	else
	  l
;;


let cursor_blit cs ua pos len =
  if pos < 0 || len < 0 || pos+len > Array.length ua then
    invalid_arg "Netconversion.cursor_blit";
  let cs_len = cursor_blit_maxlen cs in
  let l = min cs_len len in
  int_blit cs.cursor_slice_char cs.cursor_index ua pos l;
  l
;;


let cursor_blit_positions cs ua pos len =
  if pos < 0 || len < 0 || pos+len > Array.length ua then
    invalid_arg "Netconversion.cursor_blit_positions";
  let cs_len = cursor_blit_maxlen cs in
  let l = min cs_len len in
  let p = cs.cursor_byte_pos in
  let blen = cs.cursor_slice_blen in
  let cidx = cs.cursor_index in
  assert(pos+l <= Array.length ua);
  assert(cidx+l <= Array.length cs.cursor_slice_blen);
  Netaux.ArrayAux.int_series blen cidx ua pos l p;
  l
;;


(**********************************************************************)
(* String functions                                                   *)
(**********************************************************************)

(* CHECK
 * - ustring_length: Count imbchars? No!
 *
 * DOC:
 * - imbchar handling (additional exceptions)
 *)


let ustring_length_poly ops enc =
  let open Netstring_tstring in
  if is_single_byte enc then
    fun ?(range_pos=0) ?range_len s ->
      let range_len = 
	match range_len with
	    None -> ops.length s - range_pos
	  | Some l -> l in
      if range_pos < 0 || range_len < 0 || range_pos+range_len > ops.length s
      then invalid_arg "Netconversion.ustring_length";
      range_len
  else
    fun ?range_pos ?range_len s ->
      (* Assumption: There is no string that has more than max_int
       * characters
       *)
      let cs = create_poly_cursor ?range_pos ?range_len enc ops s in
      ( try move ~num:max_int cs with Cursor_out_of_range -> ());
      let n = cursor_char_count cs in
      (* Check that the last char is not an imbchar *)
      ( try
	  move ~num:(-1) cs;
	  let _ = uchar_at cs in ()
	with
	    Cursor_out_of_range -> ()
	  | Partial_character -> raise Malformed_code
      );
      n
;;

let ustring_length enc =
  ustring_length_poly Netstring_tstring.string_ops enc

let ustring_length_ts enc ?range_pos ?range_len ts =
  Netstring_tstring.with_tstring
    { Netstring_tstring.with_fun =
        (fun ops s ->
           ustring_length_poly ops enc ?range_pos ?range_len s
        )
    }
    ts


exception Malformed_code_at of int;;

let verify_poly ops enc ?range_pos ?range_len s =
  let cs = 
    try create_poly_cursor ?range_pos ?range_len enc ops s with
	Malformed_code ->
	  raise (Malformed_code_at 0)
      | _ ->
	  assert false
  in
  ( try move ~num:max_int cs with 
	Cursor_out_of_range -> ()
      | Malformed_code ->
	  (* Now cursor_pos is the byte position of the last valid
	   * character. Add the length of this character.
	   *)
	  let n = cs.cursor_slice_blen.(cs.cursor_index) in
	  raise (Malformed_code_at (cs.cursor_byte_pos + n))
  );
  (* Now we are at EOF. Check this. Furthermore, check whether there is
   * an imbchar just before EOF:
   *)
  ( try
      let _ = uchar_at cs in
      assert false
    with
	End_of_string -> ()
  );
  ( try
      move ~num:(-1) cs;
      let _ = uchar_at cs in
      ()
    with
	Cursor_out_of_range -> ()  (* empty string *)
      | Partial_character ->
	  raise (Malformed_code_at (cs.cursor_byte_pos))
  );
  ()
;;

let verify enc =
  verify_poly Netstring_tstring.string_ops enc

let verify_ts enc ?range_pos ?range_len ts =
  Netstring_tstring.with_tstring
    { Netstring_tstring.with_fun =
        (fun ops s ->
           verify_poly ops enc ?range_pos ?range_len s
        )
    }
    ts

  
  

let ustring_iter_poly ops enc f ?range_pos ?range_len s =
  let cs = create_poly_cursor ?range_pos ?range_len enc ops s in
  try
    while true do
      let ch = uchar_at cs in   (* or End_of_string *)
      f ch;
      move cs
    done;
    assert false
  with
      End_of_string ->
	()
    | Partial_character ->
	raise Malformed_code
;;

let ustring_iter enc =
  ustring_iter_poly Netstring_tstring.string_ops enc

let ustring_iter_ts enc f ?range_pos ?range_len ts =
  Netstring_tstring.with_tstring
    { Netstring_tstring.with_fun =
        (fun ops s ->
           ustring_iter_poly ops enc f ?range_pos ?range_len s
        )
    }
    ts



let ustring_map_poly ops out_kind enc f ?range_pos ?range_len s =
  (* The following algorithm works only if the mapped lists are short:
     let mkch = ustring_of_uchar enc in
     let subst p =
     let p' = f p in
       String.concat "" (List.map mkch p')
     in
     convert ~subst ~in_enc:enc ~out_enc:`Enc_empty ?range_pos ?range_len s
  *)
  let buf = Netbuffer.create 250 in
  ustring_iter_poly
    ops enc
    (fun p ->
       let l = f p in
       Netbuffer.add_string 
	 buf (String.concat "" (List.map (ustring_of_uchar enc) l))
    )
    ?range_pos
    ?range_len
    s;
  Netbuffer.to_tstring_poly buf out_kind
;;


let ustring_map enc =
  ustring_map_poly 
    Netstring_tstring.string_ops
    Netstring_tstring.String_kind
    enc

let ustring_map_ts enc f ?range_pos ?range_len ts =
  Netstring_tstring.with_tstring
    { Netstring_tstring.with_fun =
        (fun ops s ->
           match ts with
             | `String _ ->
                 let kind = Netstring_tstring.String_kind in
                 `String(
                    ustring_map_poly ops kind enc f ?range_pos ?range_len s)
             | `Bytes _ ->
                 let kind = Netstring_tstring.Bytes_kind in
                 `Bytes(
                    ustring_map_poly ops kind enc f ?range_pos ?range_len s)
             | `Memory _ ->
                 let kind = Netstring_tstring.Memory_kind in
                 `Memory(
                    ustring_map_poly ops kind enc f ?range_pos ?range_len s)
        )
    }
    ts


let ustring_to_lower enc ?range_pos ?range_len s =
  let f x = [ Netunichar.to_lower x ] in
  ustring_map enc f ?range_pos ?range_len s ;;

let ustring_to_lower_ts enc ?range_pos ?range_len ts =
  let f x = [ Netunichar.to_lower x ] in
  ustring_map_ts enc f ?range_pos ?range_len ts ;;

let ustring_to_lower_poly ops kind enc ?range_pos ?range_len ts =
  let f x = [ Netunichar.to_lower x ] in
  ustring_map_poly ops kind enc f ?range_pos ?range_len ts ;;


let ustring_to_upper enc ?range_pos ?range_len s =
  let f x = [ Netunichar.to_upper x ] in
  ustring_map enc f ?range_pos ?range_len s ;;

let ustring_to_upper_ts enc ?range_pos ?range_len ts =
  let f x = [ Netunichar.to_upper x ] in
  ustring_map_ts enc f ?range_pos ?range_len ts ;;

let ustring_to_upper_poly ops kind enc ?range_pos ?range_len ts =
  let f x = [ Netunichar.to_upper x ] in
  ustring_map_poly ops kind enc f ?range_pos ?range_len ts ;;


let ustring_to_title enc ?range_pos ?range_len s =
  let f x = [ Netunichar.to_title x ] in
  ustring_map enc f ?range_pos ?range_len s ;;

let ustring_to_title_ts enc ?range_pos ?range_len ts =
  let f x = [ Netunichar.to_title x ] in
  ustring_map_ts enc f ?range_pos ?range_len ts ;;

let ustring_to_title_poly ops kind enc ?range_pos ?range_len s =
  let f x = [ Netunichar.to_title x ] in
  ustring_map_poly ops kind enc f ?range_pos ?range_len s ;;


let ustring_sub_poly ops out_kind enc pos len ?range_pos ?range_len s =
  let open Netstring_tstring in
  try
    if pos < 0 || len < 0 then raise Cursor_out_of_range;
    let cs = create_poly_cursor ?range_pos ?range_len enc ops s in
    move ~num:pos cs;
    let byte_pos_0 = cursor_pos cs in
    move ~num:len cs;
    let byte_pos_1 = cursor_pos cs in
    (* Check: The last character of the string must not be an imbchar *)
    if len > 0 then (
      move ~num:(-1) cs;
      let _ = uchar_at cs in ();  (* or Partial_character *)
    );
    ops.subpoly out_kind s byte_pos_0 (byte_pos_1 - byte_pos_0)
  with
      Cursor_out_of_range -> invalid_arg "Netconversion.ustring_sub"
    | Partial_character -> raise Malformed_code
;;

let ustring_sub enc =
  ustring_sub_poly 
    Netstring_tstring.string_ops
    Netstring_tstring.String_kind
    enc

let ustring_sub_ts enc pos len ?range_pos ?range_len ts =
  Netstring_tstring.with_tstring
    { Netstring_tstring.with_fun =
        (fun ops s ->
           match ts with
             | `String _ ->
                 let kind = Netstring_tstring.String_kind in
                 `String(
                    ustring_sub_poly
                      ops kind enc pos len ?range_pos ?range_len s)
             | `Bytes _ ->
                 let kind = Netstring_tstring.Bytes_kind in
                 `Bytes(
                    ustring_sub_poly
                      ops kind enc pos len ?range_pos ?range_len s)
             | `Memory _ ->
                 let kind = Netstring_tstring.Memory_kind in
                 `Memory(
                    ustring_sub_poly
                      ops kind enc pos len ?range_pos ?range_len s)
        )
    }
    ts


let ustring_compare_poly ops1 ops2
                         enc f ?range_pos:rp1 ?range_len:rl1 s1 
                               ?range_pos:rp2 ?range_len:rl2 s2 =
  let cs1 = create_poly_cursor ?range_pos:rp1 ?range_len:rl1 enc ops1 s1 in
  let cs2 = create_poly_cursor ?range_pos:rp2 ?range_len:rl2 enc ops2 s2 in
  let r = ref 0 in
  try
    while !r = 0 do
      let ch1 = uchar_at cs1 in  (* or End_of_string *)
      let ch2 = uchar_at cs2 in  (* or End_of_string *)
      r := f ch1 ch2
    done;
    !r
  with 
      End_of_string ->
	( match cursor_at_end cs1, cursor_at_end cs2 with
	      true, false -> (-1)
	    | false, true -> 1
	    | true, true -> 0
	    | _ -> assert false
	)
    | Partial_character -> raise Malformed_code
;;


let ustring_compare enc =
  ustring_compare_poly 
    Netstring_tstring.string_ops
    Netstring_tstring.string_ops
    enc


let ustring_compare_ts enc f ?range_pos:rp1 ?range_len:rl1 ts1
                             ?range_pos:rp2 ?range_len:rl2 ts2 =
  Netstring_tstring.with_tstring
    { Netstring_tstring.with_fun =
        (fun ops1 s1 ->
           Netstring_tstring.with_tstring
             { Netstring_tstring.with_fun =
                 (fun ops2 s2 ->
                    ustring_compare_poly
                      ops1 ops2 enc f
                      ?range_pos:rp1 ?range_len:rl1 s1
                      ?range_pos:rp2 ?range_len:rl2 s2
                 )
             }
             ts2
        )
    }
    ts1


let uarray_of_ustring_poly ops enc ?(range_pos=0) ?range_len s =
  let open Netstring_tstring in
  let range_len =
    match range_len with
	Some l -> l
      | None   -> ops.length s - range_pos in

  if range_pos < 0 || range_len < 0 || range_pos+range_len > ops.length s 
  then invalid_arg "Netconversion.uarray_of_ustring";

  let slice_length = big_slice  in
  let slice_char = Array.make slice_length (-1) in
  let slice_blen = Array.make slice_length 1 in

  let k = ref 0 in
  let e = ref enc in
  let reader = ref (get_reader enc) in
  let buf = ref [] in

  while !k < range_len do
    let (n_inc, k_inc, enc') = 
      try
	(!reader).read
          ops slice_char slice_blen s (range_pos + !k) (range_len - !k)
      with
	  Malformed_code_read(_,_,_) -> raise Malformed_code
    in
    
    k := !k + k_inc;
    buf := (Array.sub slice_char 0 n_inc) :: !buf ;

    if enc' <> !e then begin
      e := enc';
      reader := get_reader enc';
      Array.fill slice_blen 0 slice_length 1;
    end;

    if n_inc < slice_length then (
      (* EOF *)
      if !k < range_len then raise Malformed_code; 
                             (* s ends with multi-byte prefix*)
      k := range_len;  
    );

  done;

  Array.concat (List.rev !buf)
;;


let uarray_of_ustring enc =
  uarray_of_ustring_poly Netstring_tstring.string_ops enc

let uarray_of_ustring_ts enc ?range_pos ?range_len ts =
  Netstring_tstring.with_tstring
    { Netstring_tstring.with_fun =
        (fun ops s ->
           uarray_of_ustring_poly ops enc ?range_pos ?range_len s
        )
    }
    ts



let ustring_of_uarray_poly
                      out_kind
                      ?(subst = fun code -> raise (Cannot_represent code)) 
                      enc ?(pos=0) ?len ua =
  let len =
    match len with
	Some l -> l
      | None   -> Array.length ua - pos in

  if pos < 0 || len < 0 || pos+len > Array.length ua then
    invalid_arg "Netconversion.ustring_of_uarray";

  (* Estimate the size of the output string: 
   * length * 2 is just guessed. It is assumed that this number is usually
   * too large, and to avoid that too much memory is wasted, the buffer is
   * limited by 10000.
   *)
  let size = ref (max multibyte_limit (min 10000 (len * 2))) in
  let out_buf = ref (Bytes.create !size) in

  let writer = get_writer enc in

  let k_in = ref 0 in
  let k_out = ref 0 in

  while !k_in < len do
    let k_in_inc, k_out_inc = 
      writer 
	ua (pos + !k_in) (len - !k_in) !out_buf !k_out (!size - !k_out) subst 
    in
    k_in  := !k_in  + k_in_inc;
    k_out := !k_out + k_out_inc;

    (* double the size of out_buf: *)
    let size' = min Sys.max_string_length (!size + !size) in
    if size' < !size + multibyte_limit then 
      failwith "Netconversion.ustring_of_uarray: string too long";
    let out_buf' = Bytes.create size' in
    Bytes.blit !out_buf 0 out_buf' 0 !k_out;
    out_buf := out_buf';
    size := size';
  done;

  Netstring_tstring.bytes_subpoly out_kind !out_buf 0 !k_out
;;

let ustring_of_uarray ?subst =
  ustring_of_uarray_poly
    Netstring_tstring.String_kind
    ?subst

let ustring_of_uarray_ts : type t . t Netstring_tstring.tstring_kind ->
                                    ?subst:(int->string) ->
                                    encoding -> ?pos:int -> ?len:int ->
                                    int array -> tstring =
  fun out_kind ?subst enc ?pos ?len ua ->
    let s = ustring_of_uarray_poly out_kind ?subst enc ?pos ?len ua in
    match out_kind with
      | Netstring_tstring.String_kind -> `String s
      | Netstring_tstring.Bytes_kind -> `Bytes s
      | Netstring_tstring.Memory_kind -> `Memory s


let code_cmp x1 x2 = x1-x2

let ci_code_cmp x1 x2 =
  let x1_lc = Netunichar.to_lower x1 in
  let x2_lc = Netunichar.to_lower x2 in
  x1_lc - x2_lc


OCaml

Innovation. Community. Security.