summaryrefslogtreecommitdiff
path: root/libguile/ports.c
blob: c25c2070928ecca387dda5a3b28b85026f56cd0a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
/* Copyright 1995-2001,2003-2004,2006-2019,2021
     Free Software Foundation, Inc.

   This file is part of Guile.

   Guile is free software: you can redistribute it and/or modify it
   under the terms of the GNU Lesser General Public License as published
   by the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   Guile is distributed in the hope that it will be useful, but WITHOUT
   ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
   License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with Guile.  If not, see
   <https://www.gnu.org/licenses/>.  */




#define _LARGEFILE64_SOURCE      /* ask for stat64 etc */

#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

#include <assert.h>
#include <assert.h>
#include <errno.h>
#include <fcntl.h>  /* for chsize on mingw */
#include <iconv.h>
#include <poll.h>
#include <stdio.h>
#include <striconveh.h>
#include <string.h>
#include <uniconv.h>
#include <unistd.h>
#include <unistr.h>

#ifdef HAVE_IO_H
#include <io.h>
#endif

#ifdef HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif

#include "alist.h"
#include "async.h"
#include "atomics-internal.h"
#include "boolean.h"
#include "chars.h"
#include "deprecation.h"
#include "dynwind.h"
#include "eq.h"
#include "eval.h"
#include "extensions.h"
#include "finalizers.h"
#include "fluids.h"
#include "fports.h"  /* direct access for seek and truncate */
#include "goops.h"
#include "gsubr.h"
#include "hashtab.h"
#include "keywords.h"
#include "mallocs.h"
#include "modules.h"
#include "numbers.h"
#include "pairs.h"
#include "ports-internal.h"
#include "private-options.h"
#include "procs.h"
#include "smob.h"
#include "strings.h"
#include "symbols.h"
#include "syscalls.h"
#include "variable.h"
#include "vectors.h"
#include "version.h"
#include "weak-set.h"

#include "ports.h"


/* Mingw (version 3.4.5, circa 2006) has ftruncate as an alias for chsize
   already, but have this code here in case that wasn't so in past versions,
   or perhaps to help other minimal DOS environments.

   gnulib ftruncate.c has code using fcntl F_CHSIZE and F_FREESP, which
   might be possibilities if we've got other systems without ftruncate.  */

#if defined HAVE_CHSIZE && ! defined HAVE_FTRUNCATE
#define ftruncate(fd, size) chsize (fd, size)
#undef HAVE_FTRUNCATE
#define HAVE_FTRUNCATE 1
#endif



/* We need these symbols early, before (ice-9 ports) loads in the
   snarfed definitions, so we can't use SCM_SYMBOL.  */
static SCM sym_UTF_8;
static SCM sym_ISO_8859_1;
static SCM sym_UTF_16;
static SCM sym_UTF_16LE;
static SCM sym_UTF_16BE;
static SCM sym_UTF_32;
static SCM sym_UTF_32LE;
static SCM sym_UTF_32BE;

/* Port conversion strategies.  */
static SCM sym_error;
static SCM sym_substitute;
static SCM sym_escape;

/* See scm_port_auxiliary_write_buffer and scm_c_write.  */
static const size_t AUXILIARY_WRITE_BUFFER_SIZE = 256;

/* Maximum number of bytes in a UTF-8 sequence.  */
static const size_t UTF8_BUFFER_SIZE = 4;

/* Maximum number of codepoints to write an escape sequence.  */
static const size_t ESCAPE_BUFFER_SIZE = 9;




/* We have to serialize operations on any given iconv descriptor.  */
static scm_i_pthread_mutex_t iconv_lock = SCM_I_PTHREAD_MUTEX_INITIALIZER;



/* See Unicode 8.0 section 5.22, "Best Practice for U+FFFD
   Substitution".  */
static const scm_t_wchar UNICODE_REPLACEMENT_CHARACTER = 0xFFFD;



static void
release_port (SCM port)
{
  scm_t_port *pt = SCM_PORT (port);

  /* It's possible for two close-port invocations to race, and since
     close-port is defined to be idempotent we need to avoid
     decrementing the refcount past 0.  The normal case is that it's
     open with a refcount of 1 and we're going to change it to 0.
     Otherwise if the refcount is higher we just subtract 1 and we're
     done.  However if the current refcount is 0 then the port has been
     closed or is closing and we just return.  */
  uint32_t cur = 1, next = 0;
  while (!scm_atomic_compare_and_swap_uint32 (&pt->refcount, &cur, next))
    {
      if (cur == 0)
        return;
      next = cur - 1;
    }
  if (cur > 1)
    return;

  /* FIXME: `catch' around the close call?  It could throw an exception,
     and in that case we'd leak the iconv descriptors, if any.  */
  if (SCM_PORT_TYPE (port)->close)
    SCM_PORT_TYPE (port)->close (port);

  scm_i_pthread_mutex_lock (&iconv_lock);
  pt = SCM_PORT (port);
  if (scm_is_true (pt->precise_encoding))
    {
      if (pt->input_cd != (iconv_t) -1)
        iconv_close (pt->input_cd);
      if (pt->output_cd != (iconv_t) -1)
        iconv_close (pt->output_cd);
      pt->precise_encoding = SCM_BOOL_F;
      pt->input_cd = pt->output_cd = (iconv_t) -1;
    }
  scm_i_pthread_mutex_unlock (&iconv_lock);
}

static void
scm_dynwind_acquire_port (SCM port)
{
  scm_t_port *pt = SCM_PORT (port);
  /* We're acquiring a lease on the port so that we only close it when
     no one is using it.  The normal case is that it's open with a
     refcount of 1 and we're going to push it to 2.  Otherwise perhaps
     there is someone else using it; that's fine, we just add our
     refcount.  However if the current refcount is 0 then the port has
     been closed or is closing and we must throw an error.  */
  uint32_t cur = 1, next = 2;
  while (!scm_atomic_compare_and_swap_uint32 (&pt->refcount, &cur, next))
    {
      if (cur == 0)
        scm_wrong_type_arg_msg (NULL, 0, port, "open port");
      next = cur + 1;
    }
  scm_dynwind_unwind_handler_with_scm (release_port, port,
                                       SCM_F_WIND_EXPLICITLY);
}



static SCM trampoline_to_c_read_subr;
static SCM trampoline_to_c_write_subr;

static int
default_random_access_p (SCM port)
{
  return SCM_PORT_TYPE (port)->seek != NULL;
}

static int
default_read_wait_fd (SCM port)
{
  scm_misc_error ("read_wait_fd", "unimplemented", SCM_EOL);
}

static int
default_write_wait_fd (SCM port)
{
  scm_misc_error ("write_wait_fd", "unimplemented", SCM_EOL);
}

scm_t_port_type *
scm_make_port_type (char *name,
                    size_t (*read) (SCM port, SCM dst, size_t start,
                                    size_t count),
                    size_t (*write) (SCM port, SCM src, size_t start,
                                     size_t count))
{
  scm_t_port_type *desc;

  desc = scm_gc_malloc_pointerless (sizeof (*desc), "port-type");
  memset (desc, 0, sizeof (*desc));

  desc->name = name;
  desc->print = scm_port_print;
  desc->c_read = read;
  desc->c_write = write;
  desc->scm_read = read ? trampoline_to_c_read_subr : SCM_BOOL_F;
  desc->scm_write = write ? trampoline_to_c_write_subr : SCM_BOOL_F;
  desc->read_wait_fd = default_read_wait_fd;
  desc->write_wait_fd = default_write_wait_fd;
  desc->random_access_p = default_random_access_p;
  scm_make_port_classes (desc);

  return desc;
}

static SCM
trampoline_to_c_read (SCM port, SCM dst, SCM start, SCM count)
#define FUNC_NAME "port-read"
{
  size_t c_start, c_count, ret;

  SCM_VALIDATE_OPPORT (1, port);
  SCM_VALIDATE_BYTEVECTOR (2, dst);
  c_start = scm_to_size_t (start);
  c_count = scm_to_size_t (count);
  SCM_ASSERT_RANGE (3, start, c_start <= SCM_BYTEVECTOR_LENGTH (dst));
  SCM_ASSERT_RANGE (4, count, c_count <= SCM_BYTEVECTOR_LENGTH (dst) - c_start);

  scm_dynwind_begin (0);
  scm_dynwind_acquire_port (port);
  ret = SCM_PORT_TYPE (port)->c_read (port, dst, c_start, c_count);
  scm_dynwind_end ();

  return ret == (size_t) -1 ? SCM_BOOL_F : scm_from_size_t (ret);
}
#undef FUNC_NAME

static size_t
trampoline_to_scm_read (SCM port, SCM dst, size_t start, size_t count)
{
  SCM ret = scm_call_4 (SCM_PORT_TYPE (port)->scm_read, port, dst,
                        scm_from_size_t (start), scm_from_size_t (count));
  return scm_is_true (ret) ? scm_to_size_t (ret) : (size_t) -1;
}

static SCM
trampoline_to_c_write (SCM port, SCM src, SCM start, SCM count)
#define FUNC_NAME "port-write"
{
  size_t c_start, c_count, ret;

  SCM_VALIDATE_OPPORT (1, port);
  SCM_VALIDATE_BYTEVECTOR (2, src);
  c_start = scm_to_size_t (start);
  c_count = scm_to_size_t (count);
  SCM_ASSERT_RANGE (3, start, c_start <= SCM_BYTEVECTOR_LENGTH (src));
  SCM_ASSERT_RANGE (4, count, c_count <= SCM_BYTEVECTOR_LENGTH (src) - c_start);

  scm_dynwind_begin (0);
  scm_dynwind_acquire_port (port);
  ret = SCM_PORT_TYPE (port)->c_write (port, src, c_start, c_count);
  scm_dynwind_end ();

  return ret == (size_t) -1 ? SCM_BOOL_F : scm_from_size_t (ret);
}
#undef FUNC_NAME

static size_t
trampoline_to_scm_write (SCM port, SCM src, size_t start, size_t count)
{
  SCM ret = scm_call_4 (SCM_PORT_TYPE (port)->scm_write, port, src,
                        scm_from_size_t (start), scm_from_size_t (count));
  return scm_is_true (ret) ? scm_to_size_t (ret) : (size_t) -1;
}

void
scm_set_port_scm_read (scm_t_port_type *ptob, SCM read)
{
  ptob->scm_read = read;
  ptob->c_read = trampoline_to_scm_read;
}

void
scm_set_port_scm_write (scm_t_port_type *ptob, SCM write)
{
  ptob->scm_write = write;
  ptob->c_write = trampoline_to_scm_write;
}

void
scm_set_port_read_wait_fd (scm_t_port_type *ptob, int (*get_fd) (SCM))
{
  ptob->read_wait_fd = get_fd;
}

void
scm_set_port_write_wait_fd (scm_t_port_type *ptob, int (*get_fd) (SCM))
{
  ptob->write_wait_fd = get_fd;
}

void
scm_set_port_print (scm_t_port_type *ptob,
                    int (*print) (SCM exp, SCM port, scm_print_state *pstate))
{
  ptob->print = print;
}

void
scm_set_port_close (scm_t_port_type *ptob, void (*close) (SCM))
{
  ptob->close = close;
}

void
scm_set_port_needs_close_on_gc (scm_t_port_type *ptob, int needs_close_p)
{
  if (needs_close_p)
    ptob->flags |= SCM_PORT_TYPE_NEEDS_CLOSE_ON_GC;
  else
    ptob->flags &= ~SCM_PORT_TYPE_NEEDS_CLOSE_ON_GC;
}

void
scm_set_port_seek (scm_t_port_type *ptob,
                   scm_t_off (*seek) (SCM, scm_t_off, int))
{
  ptob->seek = seek;
}

void
scm_set_port_truncate (scm_t_port_type *ptob, void (*truncate) (SCM, scm_t_off))
{
  ptob->truncate = truncate;
}

void
scm_set_port_input_waiting (scm_t_port_type *ptob, int (*input_waiting) (SCM))
{
  ptob->input_waiting = input_waiting;
}

void
scm_set_port_random_access_p (scm_t_port_type *ptob,
                              int (*random_access_p) (SCM))
{
  ptob->random_access_p = random_access_p;
}

void
scm_set_port_get_natural_buffer_sizes
  (scm_t_port_type *ptob,
   void (*get_natural_buffer_sizes) (SCM, size_t *, size_t *))
{
  ptob->get_natural_buffer_sizes = get_natural_buffer_sizes;
}

static void
scm_i_clear_pending_eof (SCM port)
{
  scm_port_buffer_set_has_eof_p (SCM_PORT (port)->read_buf,
                                 SCM_BOOL_F);
}

SCM_DEFINE (scm_i_port_property, "%port-property", 2, 0, 0,
            (SCM port, SCM key),
            "Return the property of @var{port} associated with @var{key}.")
#define FUNC_NAME s_scm_i_port_property
{
  SCM_VALIDATE_OPPORT (1, port);

  return scm_assq_ref (SCM_PORT (port)->alist, key);
}
#undef FUNC_NAME

SCM_DEFINE (scm_i_set_port_property_x, "%set-port-property!", 3, 0, 0,
            (SCM port, SCM key, SCM value),
            "Set the property of @var{port} associated with @var{key} to @var{value}.")
#define FUNC_NAME s_scm_i_set_port_property_x
{
  scm_t_port *pt;

  SCM_VALIDATE_OPPORT (1, port);

  pt = SCM_PORT (port);
  pt->alist = scm_assq_set_x (pt->alist, key, value);

  return SCM_UNSPECIFIED;
}
#undef FUNC_NAME



/* Standard ports --- current input, output, error, and more(!).  */

static SCM cur_inport_fluid = SCM_BOOL_F;
static SCM cur_outport_fluid = SCM_BOOL_F;
static SCM cur_errport_fluid = SCM_BOOL_F;
static SCM cur_warnport_fluid = SCM_BOOL_F;
static SCM cur_loadport_fluid = SCM_BOOL_F;

SCM_DEFINE (scm_current_input_port, "current-input-port", 0, 0, 0,
	    (void),
	    "Return the current input port.  This is the default port used\n"
	    "by many input procedures.  Initially, @code{current-input-port}\n"
	    "returns the @dfn{standard input} in Unix and C terminology.")
#define FUNC_NAME s_scm_current_input_port
{
  if (scm_is_true (cur_inport_fluid))
    return scm_fluid_ref (cur_inport_fluid);
  else
    return SCM_BOOL_F;
}
#undef FUNC_NAME

SCM_DEFINE (scm_current_output_port, "current-output-port", 0, 0, 0,
	    (void),
            "Return the current output port.  This is the default port used\n"
	    "by many output procedures.  Initially,\n"
	    "@code{current-output-port} returns the @dfn{standard output} in\n"
	    "Unix and C terminology.")
#define FUNC_NAME s_scm_current_output_port
{
  if (scm_is_true (cur_outport_fluid))
    return scm_fluid_ref (cur_outport_fluid);
  else
    return SCM_BOOL_F;
}
#undef FUNC_NAME

SCM_DEFINE (scm_current_error_port, "current-error-port", 0, 0, 0,
            (void),
	    "Return the port to which errors and warnings should be sent (the\n"
	    "@dfn{standard error} in Unix and C terminology).")
#define FUNC_NAME s_scm_current_error_port
{
  if (scm_is_true (cur_errport_fluid))
    return scm_fluid_ref (cur_errport_fluid);
  else
    return SCM_BOOL_F;
}
#undef FUNC_NAME

SCM_DEFINE (scm_current_warning_port, "current-warning-port", 0, 0, 0,
            (void),
	    "Return the port to which diagnostic warnings should be sent.")
#define FUNC_NAME s_scm_current_warning_port
{
  if (scm_is_true (cur_warnport_fluid))
    return scm_fluid_ref (cur_warnport_fluid);
  else
    return SCM_BOOL_F;
}
#undef FUNC_NAME

SCM_DEFINE (scm_current_load_port, "current-load-port", 0, 0, 0,
	    (),
	    "Return the current-load-port.\n"
            "The load port is used internally by @code{primitive-load}.")
#define FUNC_NAME s_scm_current_load_port
{
  return scm_fluid_ref (cur_loadport_fluid);
}
#undef FUNC_NAME

SCM
scm_set_current_input_port (SCM port)
#define FUNC_NAME "set-current-input-port"
{
  SCM oinp = scm_fluid_ref (cur_inport_fluid);
  SCM_VALIDATE_OPINPORT (1, port);
  scm_fluid_set_x (cur_inport_fluid, port);
  return oinp;
}
#undef FUNC_NAME

SCM
scm_set_current_output_port (SCM port)
#define FUNC_NAME "scm-set-current-output-port"
{
  SCM ooutp = scm_fluid_ref (cur_outport_fluid);
  port = SCM_COERCE_OUTPORT (port);
  SCM_VALIDATE_OPOUTPORT (1, port);
  scm_fluid_set_x (cur_outport_fluid, port);
  return ooutp;
}
#undef FUNC_NAME

SCM
scm_set_current_error_port (SCM port)
#define FUNC_NAME "set-current-error-port"
{
  SCM oerrp = scm_fluid_ref (cur_errport_fluid);
  port = SCM_COERCE_OUTPORT (port);
  SCM_VALIDATE_OPOUTPORT (1, port);
  scm_fluid_set_x (cur_errport_fluid, port);
  return oerrp;
}
#undef FUNC_NAME

SCM
scm_set_current_warning_port (SCM port)
#define FUNC_NAME "set-current-warning-port"
{
  SCM owarnp = scm_fluid_ref (cur_warnport_fluid);
  port = SCM_COERCE_OUTPORT (port);
  SCM_VALIDATE_OPOUTPORT (1, port);
  scm_fluid_set_x (cur_warnport_fluid, port);
  return owarnp;
}
#undef FUNC_NAME

void
scm_dynwind_current_input_port (SCM port)
#define FUNC_NAME NULL
{
  SCM_VALIDATE_OPINPORT (1, port);
  scm_dynwind_fluid (cur_inport_fluid, port);
}
#undef FUNC_NAME

void
scm_dynwind_current_output_port (SCM port)
#define FUNC_NAME NULL
{
  port = SCM_COERCE_OUTPORT (port);
  SCM_VALIDATE_OPOUTPORT (1, port);
  scm_dynwind_fluid (cur_outport_fluid, port);
}
#undef FUNC_NAME

void
scm_dynwind_current_error_port (SCM port)
#define FUNC_NAME NULL
{
  port = SCM_COERCE_OUTPORT (port);
  SCM_VALIDATE_OPOUTPORT (1, port);
  scm_dynwind_fluid (cur_errport_fluid, port);
}
#undef FUNC_NAME

void
scm_i_dynwind_current_load_port (SCM port)
{
  scm_dynwind_fluid (cur_loadport_fluid, port);
}




/* Port buffers.  */

static SCM
make_port_buffer (SCM port, size_t size)
{
  SCM ret = scm_c_make_vector (SCM_PORT_BUFFER_FIELD_COUNT, SCM_INUM0);

  SCM_SIMPLE_VECTOR_SET (ret, SCM_PORT_BUFFER_FIELD_BYTEVECTOR,
                         scm_c_make_bytevector (size));
  SCM_SIMPLE_VECTOR_SET (ret, SCM_PORT_BUFFER_FIELD_POSITION,
                         SCM_PORT (port)->position);
  scm_port_buffer_set_has_eof_p (ret, SCM_BOOL_F);

  return ret;
}




/* Retrieving a port's mode.  */

/* Return the flags that characterize a port based on the mode
 * string used to open a file for that port.
 *
 * See PORT FLAGS in scm.h
 */

static long
scm_i_mode_bits_n (SCM modes)
{
  return ((scm_i_string_contains_char (modes, 'r')
	   || scm_i_string_contains_char (modes, '+') ? SCM_RDNG : 0)
	  | (scm_i_string_contains_char (modes, 'w')
	     || scm_i_string_contains_char (modes, 'a')
	     || scm_i_string_contains_char (modes, '+') ? SCM_WRTNG : 0)
	  | (scm_i_string_contains_char (modes, '0') ? SCM_BUF0 : 0)
	  | (scm_i_string_contains_char (modes, 'l') ? SCM_BUFLINE : 0));
}

long
scm_mode_bits (char *modes)
{
  /* Valid characters are rw+a0l.  So, use latin1.  */
  return scm_i_mode_bits (scm_from_latin1_string (modes));
}

long
scm_i_mode_bits (SCM modes)
{
  long bits;

  if (!scm_is_string (modes))
    scm_wrong_type_arg_msg (NULL, 0, modes, "string");

  bits = scm_i_mode_bits_n (modes);
  scm_remember_upto_here_1 (modes);
  return bits;
}

/* Return the mode flags from an open port.
 * Some modes such as "append" are only used when opening
 * a file and are not returned here.  */

SCM_DEFINE (scm_port_mode, "port-mode", 1, 0, 0,
           (SCM port),
	    "Return the port modes associated with the open port @var{port}.\n"
	    "These will not necessarily be identical to the modes used when\n"
	    "the port was opened, since modes such as \"append\" which are\n"
	    "used only during port creation are not retained.")
#define FUNC_NAME s_scm_port_mode
{
  char modes[4];
  modes[0] = '\0';

  port = SCM_COERCE_OUTPORT (port);
  SCM_VALIDATE_OPPORT (1, port);
  if (SCM_CELL_WORD_0 (port) & SCM_RDNG) {
    if (SCM_CELL_WORD_0 (port) & SCM_WRTNG)
      strcpy (modes, "r+");
    else
      strcpy (modes, "r");
  }
  else if (SCM_CELL_WORD_0 (port) & SCM_WRTNG)
    strcpy (modes, "w");
  if (SCM_CELL_WORD_0 (port) & SCM_BUF0)
    strcat (modes, "0");

  return scm_from_latin1_string (modes);
}
#undef FUNC_NAME



/* The port table --- a weak set of all ports.

   We need a global registry of ports to flush them all at exit, and to
   get all the ports matching a file descriptor.  */
SCM scm_i_port_weak_set;




/* Port finalization.  */

static SCM close_port (SCM, int);

static SCM
do_close (void *data)
{
  return close_port (SCM_PACK_POINTER (data), 0);
}

/* Finalize the object (a port) pointed to by PTR.  */
static void
finalize_port (void *ptr, void *data)
{
  SCM port = SCM_PACK_POINTER (ptr);

  if (!SCM_PORTP (port))
    abort ();

  if (SCM_OPENP (port))
    {
      SCM_SET_PORT_FINALIZING (port);
      scm_internal_catch (SCM_BOOL_T, do_close, ptr,
                          scm_handle_by_message_noexit, NULL);
      scm_gc_ports_collected++;
    }
}




/* Default buffer size.  Used if the port type won't supply a value.  */
static const size_t default_buffer_size = 1024;

static void
initialize_port_buffers (SCM port)
{
  scm_t_port *pt = SCM_PORT (port);
  scm_t_port_type *ptob = SCM_PORT_TYPE (port);
  size_t read_buf_size, write_buf_size;

  if (SCM_CELL_WORD_0 (port) & SCM_BUF0)
    read_buf_size = write_buf_size = 1;
  else
    {
      read_buf_size = write_buf_size = default_buffer_size;
      if (ptob->get_natural_buffer_sizes)
        ptob->get_natural_buffer_sizes (port, &read_buf_size, &write_buf_size);
      if (read_buf_size == 0)
        read_buf_size = 1;
      if (write_buf_size == 0)
        write_buf_size = 1;
    }

  if (!SCM_INPUT_PORT_P (port))
    read_buf_size = 1;
  if (!SCM_OUTPUT_PORT_P (port))
    write_buf_size = 1;

  pt->read_buffering = read_buf_size;
  pt->read_buf = make_port_buffer (port, read_buf_size);
  pt->write_buf = make_port_buffer (port, write_buf_size);
  pt->write_buf_aux = SCM_BOOL_F;
}

SCM
scm_c_make_port_with_encoding (scm_t_port_type *ptob, unsigned long mode_bits,
                               SCM encoding, SCM conversion_strategy,
                               scm_t_bits stream)
{
  SCM ret;
  scm_t_port *pt;

  pt = scm_gc_typed_calloc (scm_t_port);

  ret = scm_words (scm_tc7_port | mode_bits | SCM_OPN, 4);
  SCM_SET_CELL_WORD_1 (ret, stream);
  SCM_SET_CELL_WORD_2 (ret, (scm_t_bits) pt);
  SCM_SET_CELL_WORD_3 (ret, (scm_t_bits) ptob);

  pt->encoding = encoding;
  pt->conversion_strategy = conversion_strategy;
  pt->file_name = SCM_BOOL_F;
  pt->position = scm_cons (SCM_INUM0, SCM_INUM0);

  pt->refcount = 1;

  pt->at_stream_start_for_bom_read  = 1;
  pt->at_stream_start_for_bom_write = 1;

  pt->precise_encoding = SCM_BOOL_F;
  pt->input_cd = (iconv_t) -1;
  pt->output_cd = (iconv_t) -1;

  pt->alist = SCM_EOL;

  if (SCM_PORT_TYPE (ret)->flags & SCM_PORT_TYPE_NEEDS_CLOSE_ON_GC)
    {
      scm_i_set_finalizer (SCM2PTR (ret), finalize_port, NULL);
      scm_weak_set_add_x (scm_i_port_weak_set, ret);
    }

  initialize_port_buffers (ret);

  pt->rw_random = ptob->random_access_p (ret);

  return ret;
}

SCM
scm_c_make_port (scm_t_port_type *ptob,
                 unsigned long mode_bits, scm_t_bits stream)
{
  return scm_c_make_port_with_encoding (ptob, mode_bits,
                                        scm_i_default_port_encoding (),
                                        scm_i_default_port_conversion_strategy (),
                                        stream);
}



/* Predicates.  */

SCM_DEFINE (scm_port_p, "port?", 1, 0, 0,
	    (SCM x),
	    "Return a boolean indicating whether @var{x} is a port.\n"
	    "Equivalent to @code{(or (input-port? @var{x}) (output-port?\n"
	    "@var{x}))}.")
#define FUNC_NAME s_scm_port_p
{
  return scm_from_bool (SCM_PORTP (x));
}
#undef FUNC_NAME

SCM_DEFINE (scm_input_port_p, "input-port?", 1, 0, 0,
           (SCM x),
	    "Return @code{#t} if @var{x} is an input port, otherwise return\n"
	    "@code{#f}.  Any object satisfying this predicate also satisfies\n"
	    "@code{port?}.")
#define FUNC_NAME s_scm_input_port_p
{
  return scm_from_bool (SCM_INPUT_PORT_P (x));
}
#undef FUNC_NAME

SCM_DEFINE (scm_output_port_p, "output-port?", 1, 0, 0,
           (SCM x),
	    "Return @code{#t} if @var{x} is an output port, otherwise return\n"
	    "@code{#f}.  Any object satisfying this predicate also satisfies\n"
	    "@code{port?}.")
#define FUNC_NAME s_scm_output_port_p
{
  x = SCM_COERCE_OUTPORT (x);
  return scm_from_bool (SCM_OUTPUT_PORT_P (x));
}
#undef FUNC_NAME

SCM_DEFINE (scm_port_closed_p, "port-closed?", 1, 0, 0,
           (SCM port),
	    "Return @code{#t} if @var{port} is closed or @code{#f} if it is\n"
	    "open.")
#define FUNC_NAME s_scm_port_closed_p
{
  SCM_VALIDATE_PORT (1, port);
  return scm_from_bool (!SCM_OPPORTP (port));
}
#undef FUNC_NAME

SCM_DEFINE (scm_eof_object_p, "eof-object?", 1, 0, 0,
           (SCM x),
	    "Return @code{#t} if @var{x} is an end-of-file object; otherwise\n"
	    "return @code{#f}.")
#define FUNC_NAME s_scm_eof_object_p
{
  return scm_from_bool (SCM_EOF_OBJECT_P (x));
}
#undef FUNC_NAME




/* Closing ports.  */

/* Close PORT.  If EXPLICIT is true, then we are explicitly closing PORT
   with 'close-port'; otherwise PORT is just being GC'd.  */
static SCM
close_port (SCM port, int explicit)
{
  if (SCM_CLOSEDP (port))
    return SCM_BOOL_F;

  /* May throw an exception.  */
  if (SCM_OUTPUT_PORT_P (port))
    scm_flush (port);

  if (explicit && SCM_FPORTP (port))
    /* We're closing PORT explicitly so clear its revealed count so that
       it really gets closed.  */
    SCM_FSTREAM (port)->revealed = 0;

  SCM_CLR_PORT_OPEN_FLAG (port);

  if (SCM_PORT_TYPE (port)->flags & SCM_PORT_TYPE_NEEDS_CLOSE_ON_GC)
    scm_weak_set_remove_x (scm_i_port_weak_set, port);

  release_port (port);

  return SCM_BOOL_T;
}

SCM_DEFINE (scm_close_port, "close-port", 1, 0, 0,
           (SCM port),
	    "Close the specified port object.  Return @code{#t} if it\n"
	    "successfully closes a port or @code{#f} if it was already\n"
	    "closed.  An exception may be raised if an error occurs, for\n"
	    "example when flushing buffered output.  See also @ref{Ports and\n"
	    "File Descriptors, close}, for a procedure which can close file\n"
	    "descriptors.")
#define FUNC_NAME s_scm_close_port
{
  port = SCM_COERCE_OUTPORT (port);
  SCM_VALIDATE_PORT (1, port);

  return close_port (port, 1);
}
#undef FUNC_NAME

SCM_DEFINE (scm_close_input_port, "close-input-port", 1, 0, 0,
           (SCM port),
	    "Close the specified input port object.  The routine has no effect if\n"
	    "the file has already been closed.  An exception may be raised if an\n"
	    "error occurs.  The value returned is unspecified.\n\n"
	    "See also @ref{Ports and File Descriptors, close}, for a procedure\n"
	    "which can close file descriptors.")
#define FUNC_NAME s_scm_close_input_port
{
  SCM_VALIDATE_INPUT_PORT (1, port);
  scm_close_port (port);
  return SCM_UNSPECIFIED;
}
#undef FUNC_NAME

SCM_DEFINE (scm_close_output_port, "close-output-port", 1, 0, 0,
           (SCM port),
	    "Close the specified output port object.  The routine has no effect if\n"
	    "the file has already been closed.  An exception may be raised if an\n"
	    "error occurs.  The value returned is unspecified.\n\n"
	    "See also @ref{Ports and File Descriptors, close}, for a procedure\n"
	    "which can close file descriptors.")
#define FUNC_NAME s_scm_close_output_port
{
  port = SCM_COERCE_OUTPORT (port);
  SCM_VALIDATE_OUTPUT_PORT (1, port);
  scm_close_port (port);
  return SCM_UNSPECIFIED;
}
#undef FUNC_NAME




/* Encoding characters to byte streams, and decoding byte streams to
   characters.  */

/* Port encodings are case-insensitive ASCII strings.  */
static char
ascii_toupper (char c)
{
  return (c < 'a' || c > 'z') ? c : ('A' + (c - 'a'));
}

/* It is only necessary to use this function on encodings that come from
   the user and have not been canonicalized yet.  Encodings that are set
   on ports or in the default encoding fluid are in upper-case, and can
   be compared with strcmp.  */
static int
encoding_matches (const char *enc, SCM upper_symbol)
{
  const char *upper = scm_i_symbol_chars (upper_symbol);

  if (!enc)
    enc = "ISO-8859-1";

  while (*enc)
    if (ascii_toupper (*enc++) != *upper++)
      return 0;

  return !*upper;
}

static SCM
canonicalize_encoding (const char *enc)
{
  char *ret;
  int i;

  if (!enc || encoding_matches (enc, sym_ISO_8859_1))
    return sym_ISO_8859_1;
  if (encoding_matches (enc, sym_UTF_8))
    return sym_UTF_8;

  ret = scm_gc_strdup (enc, "port");

  for (i = 0; ret[i]; i++)
    {
      if (ret[i] > 127)
        /* Restrict to ASCII.  */
        scm_misc_error (NULL, "invalid character encoding ~s",
                        scm_list_1 (scm_from_latin1_string (enc)));
      else
        ret[i] = ascii_toupper (ret[i]);
    }

  return scm_from_latin1_symbol (ret);
}

/* A fluid specifying the default encoding for newly created ports.  If it is
   a string, that is the encoding.  If it is #f, it is in the "native"
   (Latin-1) encoding.  */
static SCM default_port_encoding_var;

/* Use ENCODING as the default encoding for future ports.  */
void
scm_i_set_default_port_encoding (const char *encoding)
{
  if (encoding_matches (encoding, sym_ISO_8859_1))
    scm_fluid_set_x (SCM_VARIABLE_REF (default_port_encoding_var), SCM_BOOL_F);
  else
    scm_fluid_set_x (SCM_VARIABLE_REF (default_port_encoding_var),
                     scm_symbol_to_string (canonicalize_encoding (encoding)));
}

/* Return the name of the default encoding for newly created ports.  */
SCM
scm_i_default_port_encoding (void)
{
  SCM encoding;

  encoding = scm_fluid_ref (SCM_VARIABLE_REF (default_port_encoding_var));
  if (!scm_is_string (encoding))
    return sym_ISO_8859_1;
  else
    return canonicalize_encoding (scm_i_string_chars (encoding));
}

/* A fluid specifying the default conversion handler for newly created
   ports.  Its value should be one of the symbols below.  */
static SCM default_conversion_strategy_var;

/* Return the default failed encoding conversion policy for new created
   ports.  */
SCM
scm_i_default_port_conversion_strategy (void)
{
  SCM value;

  value = scm_fluid_ref (SCM_VARIABLE_REF (default_conversion_strategy_var));

  if (scm_is_eq (sym_substitute, value) || scm_is_eq (sym_escape, value))
    return value;

  /* Default to 'error also when the fluid's value is not one of the
     valid symbols.  */
  return sym_error;
}

/* Use HANDLER as the default conversion strategy for future ports.  */
void
scm_i_set_default_port_conversion_strategy (SCM sym)
{
  if (!scm_is_eq (sym, sym_error)
      && !scm_is_eq (sym, sym_substitute)
      && !scm_is_eq (sym, sym_escape))
    /* Internal error.  */
    abort ();

  scm_fluid_set_x (SCM_VARIABLE_REF (default_conversion_strategy_var), sym);
}

static const unsigned char scm_utf8_bom[3]    = {0xEF, 0xBB, 0xBF};
static const unsigned char scm_utf16be_bom[2] = {0xFE, 0xFF};
static const unsigned char scm_utf16le_bom[2] = {0xFF, 0xFE};
static const unsigned char scm_utf32be_bom[4] = {0x00, 0x00, 0xFE, 0xFF};
static const unsigned char scm_utf32le_bom[4] = {0xFF, 0xFE, 0x00, 0x00};

/* Called with the iconv lock.  Will release the lock before throwing
   any error.  */
static void
prepare_iconv_descriptors (SCM port, SCM precise_encoding)
{
  scm_t_port *pt = SCM_PORT (port);
  iconv_t input_cd, output_cd;
  const char *encoding;
  size_t i;

  /* If the specified encoding is UTF-16 or UTF-32, then default to
     big-endian byte order.  This fallback isn't necessary if you read
     on the port before writing to it, as the read will sniff the BOM if
     any and specialize the encoding; see the manual.  */
  if (scm_is_eq (precise_encoding, sym_UTF_16))
    precise_encoding = sym_UTF_16BE;
  else if (scm_is_eq (precise_encoding, sym_UTF_32))
    precise_encoding = sym_UTF_32BE;

  if (scm_is_eq (pt->precise_encoding, precise_encoding))
    return;

  input_cd = output_cd = (iconv_t) -1;

  if (!scm_is_symbol (precise_encoding))
    goto invalid_encoding;

  encoding = scm_i_symbol_chars (precise_encoding);
  for (i = 0; encoding[i]; i++)
    if (encoding[i] > 127)
      goto invalid_encoding;

  /* Open a iconv conversion descriptors between ENCODING and UTF-8.  We
     choose UTF-8, not UTF-32, because iconv implementations can
     typically convert from anything to UTF-8, but not to UTF-32 (see
     http://lists.gnu.org/archive/html/bug-libunistring/2010-09/msg00007.html,
     for more details).  */

  if (SCM_INPUT_PORT_P (port))
    {
      input_cd = iconv_open ("UTF-8", encoding);
      if (input_cd == (iconv_t) -1)
        goto invalid_encoding;
    }

  if (SCM_OUTPUT_PORT_P (port))
    {
      output_cd = iconv_open (encoding, "UTF-8");
      if (output_cd == (iconv_t) -1)
        {
          if (input_cd != (iconv_t) -1)
            iconv_close (input_cd);
          goto invalid_encoding;
        }
    }

  if (pt->input_cd != (iconv_t) -1)
    iconv_close (pt->input_cd);
  if (pt->output_cd != (iconv_t) -1)
    iconv_close (pt->output_cd);

  pt->precise_encoding = precise_encoding;
  pt->input_cd = input_cd;
  pt->output_cd = output_cd;

  /* Make sure this port has a finalizer.  */
  scm_i_set_finalizer (SCM2PTR (port), finalize_port, NULL);

  return;

 invalid_encoding:
  scm_i_pthread_mutex_unlock (&iconv_lock);
  scm_misc_error ("open_iconv_descriptors",
                  "invalid or unknown character encoding ~s",
                  scm_list_1 (precise_encoding));
}

SCM_INTERNAL SCM scm_specialize_port_encoding_x (SCM port, SCM encoding);
SCM_DEFINE (scm_specialize_port_encoding_x,
            "specialize-port-encoding!", 2, 0, 0,
            (SCM port, SCM encoding),
            "")
#define FUNC_NAME s_scm_specialize_port_encoding_x
{
  SCM_VALIDATE_PORT (1, port);
  SCM_VALIDATE_SYMBOL (2, encoding);

  if (scm_is_eq (SCM_PORT (port)->encoding, sym_UTF_16))
    {
      if (!scm_is_eq (encoding, sym_UTF_16LE)
          && !scm_is_eq (encoding, sym_UTF_16BE))
        SCM_OUT_OF_RANGE (2, encoding);
    }
  else if (scm_is_eq (SCM_PORT (port)->encoding, sym_UTF_32))
    {
      if (!scm_is_eq (encoding, sym_UTF_32LE)
          && !scm_is_eq (encoding, sym_UTF_32BE))
        SCM_OUT_OF_RANGE (2, encoding);
    }
  else
    SCM_OUT_OF_RANGE (2, encoding);

  scm_i_pthread_mutex_lock (&iconv_lock);
  prepare_iconv_descriptors (port, encoding);
  scm_i_pthread_mutex_unlock (&iconv_lock);

  return SCM_UNSPECIFIED;
}
#undef FUNC_NAME

/* Acquire the iconv lock and fill in *INPUT_CD and/or *OUTPUT_CD.  */
void
scm_port_acquire_iconv_descriptors (SCM port, iconv_t *input_cd,
                                    iconv_t *output_cd)
{
  scm_t_port *pt = SCM_PORT (port);

  scm_i_pthread_mutex_lock (&iconv_lock);
  if (scm_is_false (pt->precise_encoding))
    prepare_iconv_descriptors (port, pt->encoding);
  if (input_cd)
    *input_cd = pt->input_cd;
  if (output_cd)
    *output_cd = pt->output_cd;
}

void
scm_port_release_iconv_descriptors (SCM port)
{
  scm_i_pthread_mutex_unlock (&iconv_lock);
}

/* The name of the encoding is itself encoded in ASCII.  */
void
scm_i_set_port_encoding_x (SCM port, const char *encoding)
{
  scm_t_port *pt = SCM_PORT (port);

  /* In order to handle cases where the encoding changes mid-stream
     (e.g. within an HTTP stream, or within a file that is composed of
     segments with different encodings), we consider this to be "stream
     start" for purposes of BOM handling, regardless of our actual file
     position. */
  pt->at_stream_start_for_bom_read  = 1;
  pt->at_stream_start_for_bom_write = 1;
  pt->encoding = canonicalize_encoding (encoding);

  scm_i_pthread_mutex_lock (&iconv_lock);
  if (pt->input_cd != (iconv_t) -1)
    iconv_close (pt->input_cd);
  if (pt->output_cd != (iconv_t) -1)
    iconv_close (pt->output_cd);
  pt->precise_encoding = SCM_BOOL_F;
  pt->input_cd = pt->output_cd = (iconv_t) -1;
  scm_i_pthread_mutex_unlock (&iconv_lock);
}

SCM_DEFINE (scm_sys_port_encoding, "%port-encoding", 1, 0, 0,
	    (SCM port),
	    "Returns, as a symbol, the character encoding that @var{port}\n"
	    "uses to interpret its input and output.\n")
#define FUNC_NAME s_scm_sys_port_encoding
{
  SCM_VALIDATE_OPPORT (1, port);

  return SCM_PORT (port)->encoding;
}
#undef FUNC_NAME

SCM
scm_port_encoding (SCM port)
{
  return scm_symbol_to_string (scm_sys_port_encoding (port));
}

SCM_DEFINE (scm_sys_set_port_encoding_x, "%set-port-encoding!", 2, 0, 0,
	    (SCM port, SCM enc),
	    "Sets the character encoding that will be used to interpret all\n"
	    "port I/O.  New ports are created with the encoding\n"
	    "appropriate for the current locale if @code{setlocale} has \n"
	    "been called or ISO-8859-1 otherwise\n"
	    "and this procedure can be used to modify that encoding.\n")
#define FUNC_NAME s_scm_sys_set_port_encoding_x
{
  SCM_VALIDATE_OPPORT (1, port);
  SCM_VALIDATE_SYMBOL (2, enc);

  scm_i_set_port_encoding_x (port, scm_i_symbol_chars (enc));

  return SCM_UNSPECIFIED;
}
#undef FUNC_NAME

SCM
scm_set_port_encoding_x (SCM port, SCM enc)
{
  return scm_sys_set_port_encoding_x (port, scm_string_to_symbol (enc));
}

scm_t_string_failed_conversion_handler
scm_i_string_failed_conversion_handler (SCM conversion_strategy)
{
  if (scm_is_eq (conversion_strategy, sym_substitute))
    return SCM_FAILED_CONVERSION_QUESTION_MARK;
  if (scm_is_eq (conversion_strategy, sym_escape))
    return SCM_FAILED_CONVERSION_ESCAPE_SEQUENCE;

  /* Default to error.  */
  return SCM_FAILED_CONVERSION_ERROR;
}

SCM_DEFINE (scm_port_conversion_strategy, "port-conversion-strategy",
	    1, 0, 0, (SCM port),
	    "Returns the behavior of the port when handling a character that\n"
	    "is not representable in the port's current encoding.\n"
	    "It returns the symbol @code{error} if unrepresentable characters\n"
	    "should cause exceptions, @code{substitute} if the port should\n"
	    "try to replace unrepresentable characters with question marks or\n"
	    "approximate characters, or @code{escape} if unrepresentable\n"
	    "characters should be converted to string escapes.\n"
	    "\n"
	    "If @var{port} is @code{#f}, then the current default behavior\n"
	    "will be returned.  New ports will have this default behavior\n"
	    "when they are created.\n")
#define FUNC_NAME s_scm_port_conversion_strategy
{
  if (scm_is_false (port))
    return scm_i_default_port_conversion_strategy ();

  SCM_VALIDATE_OPPORT (1, port);
  return SCM_PORT (port)->conversion_strategy;
}
#undef FUNC_NAME

SCM_DEFINE (scm_set_port_conversion_strategy_x, "set-port-conversion-strategy!",
	    2, 0, 0, 
	    (SCM port, SCM sym),
	    "Sets the behavior of the interpreter when outputting a character\n"
	    "that is not representable in the port's current encoding.\n"
	    "@var{sym} can be either @code{'error}, @code{'substitute}, or\n"
	    "@code{'escape}.  If it is @code{'error}, an error will be thrown\n"
	    "when an unconvertible character is encountered.  If it is\n"
	    "@code{'substitute}, then unconvertible characters will \n"
	    "be replaced with approximate characters, or with question marks\n"
	    "if no approximately correct character is available.\n"
	    "If it is @code{'escape},\n"
	    "it will appear as a hex escape when output.\n"
	    "\n"
	    "If @var{port} is an open port, the conversion error behavior\n"
	    "is set for that port.  If it is @code{#f}, it is set as the\n"
	    "default behavior for any future ports that get created in\n"
	    "this thread.\n")
#define FUNC_NAME s_scm_set_port_conversion_strategy_x
{
  if (!scm_is_eq (sym, sym_error)
      && !scm_is_eq (sym, sym_substitute)
      && !scm_is_eq (sym, sym_escape))
    SCM_MISC_ERROR ("unknown conversion strategy ~s", scm_list_1 (sym));

  if (scm_is_false (port))
    scm_i_set_default_port_conversion_strategy (sym);
  else
    {
      SCM_VALIDATE_OPPORT (1, port);
      SCM_PORT (port)->conversion_strategy = sym;
    }

  return SCM_UNSPECIFIED;
}
#undef FUNC_NAME




/* Non-blocking I/O.  */

static int
port_read_wait_fd (SCM port)
{
  scm_t_port_type *ptob = SCM_PORT_TYPE (port);
  return ptob->read_wait_fd (port);
}

static int
port_write_wait_fd (SCM port)
{
  scm_t_port_type *ptob = SCM_PORT_TYPE (port);
  return ptob->write_wait_fd (port);
}

SCM_INTERNAL SCM scm_port_read_wait_fd (SCM);
SCM_DEFINE (scm_port_read_wait_fd, "port-read-wait-fd", 1, 0, 0,
            (SCM port), "")
#define FUNC_NAME s_scm_port_read_wait_fd
{
  int fd;

  port = SCM_COERCE_OUTPORT (port);
  SCM_VALIDATE_OPINPORT (1, port);

  fd = port_read_wait_fd (port);
  return fd < 0 ? SCM_BOOL_F : scm_from_int (fd);
}
#undef FUNC_NAME

SCM_INTERNAL SCM scm_port_write_wait_fd (SCM);
SCM_DEFINE (scm_port_write_wait_fd, "port-write-wait-fd", 1, 0, 0,
            (SCM port), "")
#define FUNC_NAME s_scm_port_write_wait_fd
{
  int fd;

  port = SCM_COERCE_OUTPORT (port);
  SCM_VALIDATE_OPOUTPORT (1, port);

  fd = port_write_wait_fd (port);
  return fd < 0 ? SCM_BOOL_F : scm_from_int (fd);
}
#undef FUNC_NAME

/* Call while having acquired the port.  */
static int
port_poll (SCM port, short events, int timeout)
#define FUNC_NAME "port-poll"
{
  struct pollfd pollfd[2];
  int nfds = 0, rv = 0;

  if (events & POLLIN)
    {
      pollfd[nfds].fd = port_read_wait_fd (port);
      pollfd[nfds].events = events & (POLLIN | POLLPRI);
      pollfd[nfds].revents = 0;
      nfds++;
    }
  if (events & POLLOUT)
    {
      pollfd[nfds].fd = port_write_wait_fd (port);
      pollfd[nfds].events = events & (POLLOUT | POLLPRI);
      pollfd[nfds].revents = 0;
      nfds++;
    }

  if (nfds == 2 && pollfd[0].fd == pollfd[1].fd)
    {
      pollfd[0].events |= pollfd[1].events;
      nfds--;
    }

  SCM_SYSCALL (rv = poll (pollfd, nfds, timeout));
  if (rv < 0)
    SCM_SYSERROR;

  return rv;
}
#undef FUNC_NAME

SCM_INTERNAL SCM scm_port_poll (SCM, SCM, SCM);
SCM_DEFINE (scm_port_poll, "port-poll", 2, 1, 0,
            (SCM port, SCM events, SCM timeout),
            "")
#define FUNC_NAME s_scm_port_poll
{
  short c_events = 0;
  int c_timeout;
  SCM ret;

  port = SCM_COERCE_OUTPORT (port);
  SCM_VALIDATE_PORT (1, port);
  SCM_VALIDATE_STRING (2, events);
  c_timeout = SCM_UNBNDP (timeout) ? -1 : SCM_NUM2INT (3, timeout);

  if (scm_i_string_contains_char (events, 'r'))
    c_events |= POLLIN;
  if (scm_i_string_contains_char (events, '!'))
    c_events |= POLLPRI;
  if (scm_i_string_contains_char (events, 'w'))
    c_events |= POLLOUT;

  scm_dynwind_begin (0);
  scm_dynwind_acquire_port (port);
  ret = scm_from_int (port_poll (port, c_events, c_timeout));
  scm_dynwind_end ();

  return ret;
}
#undef FUNC_NAME




/* Input.  */

static int
get_byte_or_eof (SCM port)
{
  SCM buf = SCM_PORT (port)->read_buf;
  SCM buf_bv, buf_cur, buf_end;
  size_t cur, avail;

  buf_bv = scm_port_buffer_bytevector (buf);
  buf_cur = scm_port_buffer_cur (buf);
  buf_end = scm_port_buffer_end (buf);
  cur = SCM_I_INUM (buf_cur);

  if (SCM_LIKELY (SCM_I_INUMP (buf_cur))
      && SCM_LIKELY (SCM_I_INUMP (buf_end))
      && SCM_LIKELY (cur < SCM_I_INUM (buf_end))
      && SCM_LIKELY (cur < SCM_BYTEVECTOR_LENGTH (buf_bv)))
    {
      uint8_t ret = SCM_BYTEVECTOR_CONTENTS (buf_bv)[cur];
      scm_port_buffer_set_cur (buf, SCM_I_MAKINUM (cur + 1));
      return ret;
    }

  buf = scm_fill_input (port, 0, &cur, &avail);
  buf_bv = scm_port_buffer_bytevector (buf);
  if (avail > 0)
    {
      uint8_t ret = SCM_BYTEVECTOR_CONTENTS (buf_bv)[cur];
      scm_port_buffer_set_cur (buf, SCM_I_MAKINUM (cur + 1));
      return ret;
    }

  /* The next peek or get should cause the read() function to be called
     to see if we still have EOF.  */
  scm_port_buffer_set_has_eof_p (buf, SCM_BOOL_F);
  return EOF;
}

/* Like `scm_get_byte_or_eof' but does not change PORT's `read_pos'.  */
static int
peek_byte_or_eof (SCM port, SCM *buf_out, size_t *cur_out)
{
  SCM buf = SCM_PORT (port)->read_buf;
  SCM buf_bv, buf_cur, buf_end;
  size_t cur, avail;

  buf_bv = scm_port_buffer_bytevector (buf);
  buf_cur = scm_port_buffer_cur (buf);
  buf_end = scm_port_buffer_end (buf);
  cur = scm_to_size_t (buf_cur);
  if (SCM_LIKELY (SCM_I_INUMP (buf_cur))
      && SCM_LIKELY (SCM_I_INUMP (buf_end))
      && SCM_LIKELY (cur < SCM_I_INUM (buf_end))
      && SCM_LIKELY (cur < SCM_BYTEVECTOR_LENGTH (buf_bv)))
    {
      uint8_t ret = SCM_BYTEVECTOR_CONTENTS (buf_bv)[cur];
      *buf_out = buf;
      *cur_out = cur;
      return ret;
    }

  buf = scm_fill_input (port, 0, &cur, &avail);
  buf_bv = scm_port_buffer_bytevector (buf);
  *buf_out = buf;
  *cur_out = cur;
  if (avail > 0)
    {
      uint8_t ret = SCM_BYTEVECTOR_CONTENTS (buf_bv)[cur];
      return ret;
    }

  return EOF;
}

int
scm_get_byte_or_eof (SCM port)
{
  return get_byte_or_eof (port);
}

int
scm_peek_byte_or_eof (SCM port)
{
  SCM buf;
  size_t cur;
  return peek_byte_or_eof (port, &buf, &cur);
}

static size_t
scm_i_read_bytes (SCM port, SCM dst, size_t start, size_t count)
{
  size_t filled;
  scm_t_port_type *ptob = SCM_PORT_TYPE (port);

  assert (count <= SCM_BYTEVECTOR_LENGTH (dst));
  assert (start + count <= SCM_BYTEVECTOR_LENGTH (dst));

  scm_dynwind_begin (0);
  scm_dynwind_acquire_port (port);

 retry:
  filled = ptob->c_read (port, dst, start, count);

  if (filled == (size_t) -1)
    {
      port_poll (port, POLLIN, -1);
      goto retry;
    }

  scm_dynwind_end ();

  assert (filled <= count);

  return filled;
}

/* In text mode, we will slurp a BOM from the beginning of a UTF-8,
   UTF-16, or UTF-32 stream, and write one at the beginning of a UTF-16
   or UTF-32 stream.  In binary mode, we won't.  The mode depends on the
   caller. */
enum bom_io_mode { BOM_IO_TEXT, BOM_IO_BINARY };
static size_t port_clear_stream_start_for_bom_read (SCM, enum bom_io_mode);

/* Used by an application to read arbitrary number of bytes from an SCM
   port.  Same semantics as libc read, except that scm_c_read_bytes only
   returns less than SIZE bytes if at end-of-file.

   Warning: Doesn't update port line and column counts!  */
size_t
scm_c_read_bytes (SCM port, SCM dst, size_t start, size_t count)
#define FUNC_NAME "scm_c_read_bytes"
{
  size_t to_read = count;
  scm_t_port *pt;
  SCM read_buf;
  uint8_t *dst_ptr = (uint8_t *) SCM_BYTEVECTOR_CONTENTS (dst) + start;

  SCM_VALIDATE_OPINPORT (1, port);

  pt = SCM_PORT (port);
  read_buf = pt->read_buf;

  if (pt->rw_random)
    scm_flush (port);

  port_clear_stream_start_for_bom_read (port, BOM_IO_BINARY);

  /* Take bytes first from the port's read buffer. */
  {
    size_t cur, avail, did_read;
    avail = scm_port_buffer_can_take (read_buf, &cur);
    did_read = scm_port_buffer_take (read_buf, dst_ptr, to_read, cur, avail);
    dst_ptr += did_read;
    to_read -= did_read;
  }

  while (to_read)
    {
      size_t did_read;

      /* If the read is smaller than the buffering on the read side of
         this port, then go through the buffer.  Otherwise fill our
         buffer directly.  */
      if (to_read < pt->read_buffering)
        {
          size_t cur, avail;

          read_buf = scm_fill_input (port, 0, &cur, &avail);
          did_read = scm_port_buffer_take (read_buf, dst_ptr, to_read,
                                           cur, avail);
          dst_ptr += did_read;
          to_read -= did_read;
          if (did_read == 0)
            {
              /* Consider that we've read off this EOF.  */
              scm_port_buffer_set_has_eof_p (read_buf, SCM_BOOL_F);
              break;
            }
        }
      else
        {
          did_read = scm_i_read_bytes (port, dst,
                                       start + count - to_read,
                                       to_read);
          to_read -= did_read;
          dst_ptr += did_read;
          if (did_read == 0)
            break;
        }
    }

  return count - to_read;
}
#undef FUNC_NAME

/* Like scm_c_read_bytes, but always proxies reads through the port's
   read buffer.  Used by an application when it wants to read into a
   memory chunk that's not owned by Guile's GC.  */
size_t
scm_c_read (SCM port, void *buffer, size_t size)
#define FUNC_NAME "scm_c_read"
{
  size_t copied = 0;
  scm_t_port *pt;
  SCM read_buf;
  uint8_t *dst = buffer;

  SCM_VALIDATE_OPINPORT (1, port);

  pt = SCM_PORT (port);
  read_buf = pt->read_buf;

  if (pt->rw_random)
    scm_flush (port);

  while (copied < size)
    {
      size_t cur, avail, count;
      read_buf = scm_fill_input (port, 0, &cur, &avail);
      count = scm_port_buffer_take (read_buf, dst + copied, size - copied,
                                    cur, avail);
      copied += count;
      if (count == 0)
        {
          /* Consider that we've read off this EOF.  */
          scm_port_buffer_set_has_eof_p (read_buf, SCM_BOOL_F);
          break;
        }
    }

  return copied;
}
#undef FUNC_NAME

/* Update the line and column number of PORT after consumption of C.  */
static inline void
update_port_position (SCM position, scm_t_wchar c)
{
  int column = scm_to_int (scm_port_position_column (position));

  switch (c)
    {
    case '\a':
    case EOF:
      break;
    case '\b':
      if (column > 0)
        scm_port_position_set_column (position, scm_from_int (column - 1));
      break;
    case '\n':
      {
        long line = scm_to_long (scm_port_position_line (position));
        scm_port_position_set_line (position, scm_from_long (line + 1));
        scm_port_position_set_column (position, SCM_INUM0);
      }
      break;
    case '\r':
      scm_port_position_set_column (position, SCM_INUM0);
      break;
    case '\t':
      scm_port_position_set_column (position,
                                    scm_from_int (column + 8 - column % 8));
      break;
    default:
      scm_port_position_set_column (position, scm_from_int (column + 1));
      break;
    }
}

/* Convert the SIZE-byte UTF-8 sequence in UTF8_BUF to a codepoint.
   UTF8_BUF is assumed to contain a valid UTF-8 sequence.  */
static scm_t_wchar
utf8_to_codepoint (const uint8_t *utf8_buf, size_t size)
{
  scm_t_wchar codepoint;

  if (utf8_buf[0] <= 0x7f)
    {
      assert (size >= 1);
      codepoint = utf8_buf[0];
    }
  else if ((utf8_buf[0] & 0xe0) == 0xc0)
    {
      assert (size >= 2);
      codepoint = ((scm_t_wchar) utf8_buf[0] & 0x1f) << 6UL
	| (utf8_buf[1] & 0x3f);
    }
  else if ((utf8_buf[0] & 0xf0) == 0xe0)
    {
      assert (size >= 3);
      codepoint = ((scm_t_wchar) utf8_buf[0] & 0x0f) << 12UL
	| ((scm_t_wchar) utf8_buf[1] & 0x3f) << 6UL
	| (utf8_buf[2] & 0x3f);
    }
  else
    {
      assert (size >= 4);
      codepoint = ((scm_t_wchar) utf8_buf[0] & 0x07) << 18UL
	| ((scm_t_wchar) utf8_buf[1] & 0x3f) << 12UL
	| ((scm_t_wchar) utf8_buf[2] & 0x3f) << 6UL
	| (utf8_buf[3] & 0x3f);
    }

  return codepoint;
}

/* Peek a UTF-8 sequence from PORT.  On success, return the codepoint
   that was read, and set *LEN to the length in bytes.  If there was a
   decoding error and the port conversion strategy was `substitute',
   then return #\? and set *LEN to the length of the shortest prefix
   that cannot begin a valid UTF-8 sequence.  Otherwise signal an
   error.  */
static scm_t_wchar
peek_utf8_codepoint (SCM port, SCM *buf_out, size_t *cur_out, size_t *len_out)
{
#define DECODING_ERROR(bytes) \
  do { *buf_out = buf; *cur_out = cur; *len_out = bytes; goto decoding_error; } while (0)
#define RETURN(bytes, codepoint) \
  do { *buf_out = buf; *cur_out = cur; *len_out = bytes; return codepoint; } while (0)

  SCM buf;
  size_t cur, avail;
  int first_byte;
  const uint8_t *ptr;

  first_byte = peek_byte_or_eof (port, &buf, &cur);
  if (first_byte == EOF)
    RETURN (0, EOF);
  else if (first_byte < 0x80)
    RETURN (1, first_byte);
  else if (first_byte >= 0xc2 && first_byte <= 0xdf)
    {
      buf = scm_fill_input (port, 2, &cur, &avail);
      ptr = scm_port_buffer_take_pointer (buf, cur);

      if (avail < 2 || (ptr[1] & 0xc0) != 0x80)
        DECODING_ERROR (1);

      RETURN (2, (first_byte & 0x1f) << 6UL | (ptr[1] & 0x3f));
    }
  else if ((first_byte & 0xf0) == 0xe0)
    {
      buf = scm_fill_input (port, 3, &cur, &avail);
      ptr = scm_port_buffer_take_pointer (buf, cur);

      if (avail < 2 || (ptr[1] & 0xc0) != 0x80
          || (ptr[0] == 0xe0 && ptr[1] < 0xa0)
          || (ptr[0] == 0xed && ptr[1] > 0x9f))
        DECODING_ERROR (1);

      if (avail < 3 || (ptr[2] & 0xc0) != 0x80)
        DECODING_ERROR (2);

      RETURN (3,
              ((scm_t_wchar) ptr[0] & 0x0f) << 12UL
              | ((scm_t_wchar) ptr[1] & 0x3f) << 6UL
              | (ptr[2] & 0x3f));
    }
  else if (first_byte >= 0xf0 && first_byte <= 0xf4)
    {
      buf = scm_fill_input (port, 4, &cur, &avail);
      ptr = scm_port_buffer_take_pointer (buf, cur);

      if (avail < 2 || (ptr[1] & 0xc0) != 0x80
          || (ptr[0] == 0xf0 && ptr[1] < 0x90)
          || (ptr[0] == 0xf4 && ptr[1] > 0x8f))
        DECODING_ERROR (1);

      if (avail < 3 || (ptr[2] & 0xc0) != 0x80)
        DECODING_ERROR (2);

      if (avail < 4 || (ptr[3] & 0xc0) != 0x80)
        DECODING_ERROR (3);

      RETURN (4,
              ((scm_t_wchar) ptr[0] & 0x07) << 18UL
              | ((scm_t_wchar) ptr[1] & 0x3f) << 12UL
              | ((scm_t_wchar) ptr[2] & 0x3f) << 6UL
              | (ptr[3] & 0x3f));
    }
  else
    DECODING_ERROR (1);

 decoding_error:
  if (scm_is_eq (SCM_PORT (port)->conversion_strategy, sym_substitute))
    /* *len already set.  */
    return UNICODE_REPLACEMENT_CHARACTER;

  scm_decoding_error ("peek-char", EILSEQ, "input decoding error", port);
  /* Not reached.  */
  return 0;
#undef DECODING_ERROR
#undef RETURN
}

/* Peek an ISO-8859-1 codepoint (a byte) from PORT.  On success, return
   the codepoint, and set *LEN to 1.  Otherwise on EOF set *LEN to 0.  */
static scm_t_wchar
peek_latin1_codepoint (SCM port, SCM *buf, size_t *cur, size_t *len)
{
  scm_t_wchar ret = peek_byte_or_eof (port, buf, cur);

  *len = ret == EOF ? 0 : 1;

  return ret;
}

SCM_INTERNAL SCM scm_port_decode_char (SCM, SCM, SCM, SCM);
SCM_DEFINE (scm_port_decode_char, "port-decode-char", 4, 0, 0,
            (SCM port, SCM bv, SCM start, SCM count),
            "")
#define FUNC_NAME s_scm_port_decode_char
{
  char *input, *output;
  uint8_t utf8_buf[UTF8_BUFFER_SIZE];
  iconv_t input_cd;
  size_t c_start, c_count;
  size_t input_left, output_left, done;

  SCM_VALIDATE_OPINPORT (1, port);
  SCM_VALIDATE_BYTEVECTOR (2, bv);
  c_start = scm_to_size_t (start);
  c_count = scm_to_size_t (count);
  SCM_ASSERT_RANGE (3, start, c_start <= SCM_BYTEVECTOR_LENGTH (bv));
  SCM_ASSERT_RANGE (4, count, c_count <= SCM_BYTEVECTOR_LENGTH (bv) - c_start);

  input = (char *) SCM_BYTEVECTOR_CONTENTS (bv) + c_start;
  input_left = c_count;
  output = (char *) utf8_buf;
  output_left = sizeof (utf8_buf);

  /* FIXME: locking!  */
  scm_port_acquire_iconv_descriptors (port, &input_cd, NULL);
  done = iconv (input_cd, &input, &input_left, &output, &output_left);
  scm_port_release_iconv_descriptors (port);

  if (done == (size_t) -1)
    {
      int err = errno;
      if (err == EINVAL)
        /* The input byte sequence did not form a complete
           character.  Read another byte and try again. */
        return SCM_BOOL_F;
      else if (scm_is_eq (SCM_PORT (port)->conversion_strategy,
                          sym_substitute))
        return SCM_MAKE_CHAR (UNICODE_REPLACEMENT_CHARACTER);
      else
        scm_decoding_error ("decode-char", err, "input decoding error", port);
    }

  {
    size_t output_size = sizeof (utf8_buf) - output_left;
    if (output_size == 0)
      /* iconv consumed some bytes without producing any output.
         Most likely this means that a Unicode byte-order mark
         (BOM) was consumed.  In any case, keep going until we get
         output.  */
      return SCM_BOOL_F;

    return scm_c_make_char (utf8_to_codepoint (utf8_buf, output_size));
  }
}
#undef FUNC_NAME

/* Peek a codepoint from PORT, decoding it through iconv.  On success,
   return the codepoint and set *LEN to the length in bytes.  If there
   was a decoding error and the port conversion strategy was
   `substitute', then return #\? and set *LEN to the length of the
   shortest prefix that cannot begin a valid UTF-8 sequence.  Otherwise
   signal an error.  */
static scm_t_wchar
peek_iconv_codepoint (SCM port, SCM *buf, size_t *cur, size_t *len)
{
  size_t input_size = 0;
  SCM maybe_char = SCM_BOOL_F;

  while (scm_is_false (maybe_char))
    {
      size_t avail;
      *buf = scm_fill_input (port, input_size + 1, cur, &avail);

      if (avail <= input_size)
	{
          *len = input_size;
          if (input_size == 0)
            /* Normal EOF.  */
            return EOF;

          /* EOF found in the middle of a multibyte character. */
          if (scm_is_eq (SCM_PORT (port)->conversion_strategy,
                         sym_substitute))
            return UNICODE_REPLACEMENT_CHARACTER;

          scm_decoding_error ("peek-char", EILSEQ,
                              "input decoding error", port);
          /* Not reached.  */
          return 0;
	}

      input_size++;
      maybe_char = scm_port_decode_char (port,
                                         scm_port_buffer_bytevector (*buf),
                                         SCM_I_MAKINUM (*cur),
                                         SCM_I_MAKINUM (input_size));
    }

  *len = input_size;
  return SCM_CHAR (maybe_char);
}

/* Peek a codepoint from PORT and return it in *CODEPOINT.  Set *LEN to
   the length in bytes of that representation.  Return 0 on success and
   an errno value on error.  */
static SCM_C_INLINE scm_t_wchar
peek_codepoint (SCM port, SCM *buf, size_t *cur, size_t *len)
{
  SCM encoding = SCM_PORT (port)->encoding;

  if (scm_is_eq (encoding, sym_UTF_8))
    return peek_utf8_codepoint (port, buf, cur, len);
  else if (scm_is_eq (encoding, sym_ISO_8859_1))
    return peek_latin1_codepoint (port, buf, cur, len);
  else
    return peek_iconv_codepoint (port, buf, cur, len);
}

/* Read a codepoint from PORT and return it.  */
scm_t_wchar
scm_getc (SCM port)
#define FUNC_NAME "scm_getc"
{
  size_t len = 0;
  size_t cur;
  SCM buf;
  scm_t_wchar codepoint;

  codepoint = peek_codepoint (port, &buf, &cur, &len);
  scm_port_buffer_did_take (buf, cur, len);
  if (codepoint == EOF)
    scm_i_clear_pending_eof (port);
  update_port_position (SCM_PORT (port)->position, codepoint);

  return codepoint;
}
#undef FUNC_NAME

SCM_DEFINE (scm_read_char, "read-char", 0, 1, 0,
           (SCM port),
	    "Return the next character available from @var{port}, updating\n"
	    "@var{port} to point to the following character.  If no more\n"
	    "characters are available, the end-of-file object is returned.\n"
	    "\n"
	    "When @var{port}'s data cannot be decoded according to its\n"
	    "character encoding, a @code{decoding-error} is raised and\n"
	    "@var{port} points past the erroneous byte sequence.\n")
#define FUNC_NAME s_scm_read_char
{
  scm_t_wchar c;
  if (SCM_UNBNDP (port))
    port = scm_current_input_port ();
  SCM_VALIDATE_OPINPORT (1, port);
  c = scm_getc (port);
  if (EOF == c)
    return SCM_EOF_VAL;
  return SCM_MAKE_CHAR (c);
}
#undef FUNC_NAME




/* Pushback.  */



void
scm_unget_bytes (const uint8_t *buf, size_t len, SCM port)
#define FUNC_NAME "scm_unget_bytes"
{
  scm_t_port *pt = SCM_PORT (port);
  SCM read_buf = pt->read_buf;
  size_t cur;

  if (pt->rw_random)
    scm_flush (port);

  cur = scm_port_buffer_can_putback (read_buf);

  if (cur < len)
    {
      /* The bytes don't fit directly in the read_buf.  */
      size_t buffered, size;

      buffered = scm_port_buffer_can_take (read_buf, &cur);
      size = scm_port_buffer_size (read_buf);

      if (len <= size - buffered)
        {
          /* But they would fit if we shift the not-yet-read bytes from
             the read_buf right.  Let's do that.  */
          const uint8_t *to_shift = scm_port_buffer_take_pointer (read_buf, cur);
          scm_port_buffer_reset_end (read_buf);
          scm_port_buffer_putback (read_buf, to_shift, buffered, size);
        }
      else
        {
          /* Bah, have to expand the read_buf for the putback.  */
          while (size < len + buffered)
            size *= 2;
          read_buf = scm_expand_port_read_buffer_x (port,
                                                    scm_from_size_t (size),
                                                    SCM_BOOL_T);
        }

      cur = size - buffered;
    }

  scm_port_buffer_putback (read_buf, buf, len, cur);
}
#undef FUNC_NAME

void
scm_unget_byte (int c, SCM port)
{
  unsigned char byte = c;
  scm_unget_bytes (&byte, 1, port);
}

void
scm_ungetc (scm_t_wchar c, SCM port)
#define FUNC_NAME "scm_ungetc"
{
  scm_t_port *pt = SCM_PORT (port);
  char *result;
  char result_buf[10];
  size_t len;

  len = sizeof (result_buf);

  if (scm_is_eq (pt->encoding, sym_UTF_8))
    {
      if (c < 0x80)
        {
          result_buf[0] = (char) c;
          result = result_buf;
          len = 1;
        }
      else
        result =
          (char *) u32_to_u8 ((uint32_t *) &c, 1, (uint8_t *) result_buf, &len);
    }
  else if (scm_is_eq (pt->encoding, sym_ISO_8859_1) && c <= 0xff)
    {
      result_buf[0] = (char) c;
      result = result_buf;
      len = 1;
    }
  else
    {
      scm_t_string_failed_conversion_handler handler =
        scm_i_string_failed_conversion_handler (pt->conversion_strategy);

      result = u32_conv_to_encoding (scm_i_symbol_chars (pt->encoding),
                                     (enum iconv_ilseq_handler) handler,
                                     (uint32_t *) &c, 1, NULL,
                                     result_buf, &len);
    }

  if (SCM_UNLIKELY (result == NULL || len == 0))
    scm_encoding_error (FUNC_NAME, errno,
			"conversion to port encoding failed",
			port, SCM_MAKE_CHAR (c));

  scm_unget_bytes ((unsigned char *) result, len, port);

  if (SCM_UNLIKELY (result != result_buf))
    free (result);

  {
    long line;
    int column;

    line = scm_to_long (scm_port_position_line (pt->position));
    column = scm_to_int (scm_port_position_column (pt->position));

    if (c == '\n')
      scm_port_position_set_line (pt->position, scm_from_long (line - 1));
    if (column > 0)
      scm_port_position_set_column (pt->position, scm_from_int (column - 1));
  }
}
#undef FUNC_NAME

void 
scm_ungets (const char *s, int n, SCM port)
{
  /* This is simple minded and inefficient, but unreading strings is
   * probably not a common operation, and remember that line and
   * column numbers have to be handled...
   *
   * Please feel free to write an optimized version!
   */
  while (n--)
    scm_ungetc (s[n], port);
}

SCM_DEFINE (scm_peek_char, "peek-char", 0, 1, 0,
           (SCM port),
	    "Return the next character available from @var{port},\n"
	    "@emph{without} updating @var{port} to point to the following\n"
	    "character.  If no more characters are available, the\n"
	    "end-of-file object is returned.\n"
	    "\n"
	    "The value returned by\n"
	    "a call to @code{peek-char} is the same as the value that would\n"
	    "have been returned by a call to @code{read-char} on the same\n"
	    "port.  The only difference is that the very next call to\n"
	    "@code{read-char} or @code{peek-char} on that @var{port} will\n"
	    "return the value returned by the preceding call to\n"
	    "@code{peek-char}.  In particular, a call to @code{peek-char} on\n"
	    "an interactive port will hang waiting for input whenever a call\n"
	    "to @code{read-char} would have hung.\n"
	    "\n"
	    "As for @code{read-char}, a @code{decoding-error} may be raised\n"
	    "if such a situation occurs.  However, unlike with @code{read-char},\n"
	    "@var{port} still points at the beginning of the erroneous byte\n"
	    "sequence when the error is raised.\n")
#define FUNC_NAME s_scm_peek_char
{
  SCM buf;
  scm_t_wchar c;
  size_t cur, len = 0;

  if (SCM_UNBNDP (port))
    port = scm_current_input_port ();
  SCM_VALIDATE_OPINPORT (1, port);

  c = peek_codepoint (port, &buf, &cur, &len);

  return c == EOF ? SCM_EOF_VAL : SCM_MAKE_CHAR (c);
}
#undef FUNC_NAME

SCM_DEFINE (scm_unread_char, "unread-char", 1, 1, 0,
            (SCM cobj, SCM port),
	    "Place character @var{cobj} in @var{port} so that it will be\n"
	    "read by the next read operation.  If called multiple times, the\n"
	    "unread characters will be read again in last-in first-out\n"
	    "order.  If @var{port} is not supplied, the current input port\n"
	    "is used.")
#define FUNC_NAME s_scm_unread_char
{
  int c;

  SCM_VALIDATE_CHAR (1, cobj);
  if (SCM_UNBNDP (port))
    port = scm_current_input_port ();
  SCM_VALIDATE_OPINPORT (2, port);

  c = SCM_CHAR (cobj);

  scm_ungetc (c, port);
  return cobj;
}
#undef FUNC_NAME

SCM_DEFINE (scm_unread_string, "unread-string", 2, 0, 0,
            (SCM str, SCM port),
	    "Place the string @var{str} in @var{port} so that its characters will be\n"
	    "read in subsequent read operations.  If called multiple times, the\n"
	    "unread characters will be read again in last-in first-out order.  If\n"
	    "@var{port} is not supplied, the current-input-port is used.")
#define FUNC_NAME s_scm_unread_string
{
  size_t n;

  SCM_VALIDATE_STRING (1, str);
  if (SCM_UNBNDP (port))
    port = scm_current_input_port ();
  SCM_VALIDATE_OPINPORT (2, port);

  n = scm_i_string_length (str);

  while (n--)
    scm_ungetc (scm_i_string_ref (str, n), port);
  
  return str;
}
#undef FUNC_NAME




/* Manipulating the buffers.  */

SCM_SYMBOL (sym_none, "none");
SCM_SYMBOL (sym_line, "line");
SCM_SYMBOL (sym_block, "block");

SCM_DEFINE (scm_setvbuf, "setvbuf", 2, 1, 0,
            (SCM port, SCM mode, SCM size),
	    "Set the buffering mode for @var{port}.  @var{mode} can be one\n"
            "of the following symbols:\n"
	    "@table @code\n"
	    "@item none\n"
	    "no buffering\n"
	    "@item line\n"
	    "line buffering\n"
	    "@item block\n"
	    "block buffering, using a newly allocated buffer of @var{size} bytes.\n"
	    "If @var{size} is omitted, a default size will be used.\n"
	    "@end table\n\n"
	    "Only certain types of ports are supported, most importantly\n"
	    "file ports.")
#define FUNC_NAME s_scm_setvbuf
{
  long csize;
  scm_t_port *pt;
  scm_t_port_type *ptob;
  scm_t_bits tag_word;
  size_t read_buf_size, write_buf_size, cur, avail;
  SCM saved_read_buf;

  port = SCM_COERCE_OUTPORT (port);

  SCM_VALIDATE_OPENPORT (1, port);
  pt = SCM_PORT (port);
  ptob = SCM_PORT_TYPE (port);
  tag_word = SCM_CELL_WORD_0 (port) & ~(SCM_BUF0 | SCM_BUFLINE);

  if (scm_is_eq (mode, sym_none))
    {
      tag_word |= SCM_BUF0;
      if (!SCM_UNBNDP (size) && !scm_is_eq (size, SCM_INUM0))
	scm_out_of_range (FUNC_NAME, size);
      csize = 0;
    }
  else if (scm_is_eq (mode, sym_line))
    {
      csize = SCM_UNBNDP (size) ? -1 : scm_to_int (size);
      tag_word |= SCM_BUFLINE;
    }
  else if (scm_is_eq (mode, sym_block))
    {
      csize = SCM_UNBNDP (size) ? -1 : scm_to_int (size);
    }
  else
    scm_out_of_range (FUNC_NAME, mode);

  if (!SCM_UNBNDP (size) && csize < 0)
    scm_out_of_range (FUNC_NAME, size);

  if (csize >= 0)
    read_buf_size = write_buf_size = csize;
  else
    {
      read_buf_size = write_buf_size = default_buffer_size;
      scm_dynwind_begin (0);
      scm_dynwind_acquire_port (port);
      if (ptob->get_natural_buffer_sizes)
        ptob->get_natural_buffer_sizes (port, &read_buf_size, &write_buf_size);
      scm_dynwind_end ();
    }

  /* Minimum buffer size is one byte.  */
  if (read_buf_size == 0)
    read_buf_size = 1;
  if (write_buf_size == 0)
    write_buf_size = 1;

  if (SCM_OUTPUT_PORT_P (port))
    scm_flush (port);

  saved_read_buf = pt->read_buf;

  SCM_SET_CELL_WORD_0 (port, tag_word);
  pt->read_buffering = read_buf_size;
  pt->read_buf = make_port_buffer (port, read_buf_size);
  pt->write_buf = make_port_buffer (port, write_buf_size);

  avail = scm_port_buffer_can_take (saved_read_buf, &cur);
  scm_unget_bytes (scm_port_buffer_take_pointer (saved_read_buf, cur), avail,
                   port);
  scm_port_buffer_set_has_eof_p (pt->read_buf,
                                 scm_port_buffer_has_eof_p (saved_read_buf));

  return SCM_UNSPECIFIED;
}
#undef FUNC_NAME

/* Move up to READ_LEN bytes from PORT's read buffer into memory
   starting at DEST.  Return the number of bytes moved.  PORT's
   line/column numbers are left unchanged.  */
size_t
scm_take_from_input_buffers (SCM port, char *dest, size_t read_len)
{
  SCM read_buf = SCM_PORT (port)->read_buf;
  size_t cur, avail;
  avail = scm_port_buffer_can_take (read_buf, &cur);
  return scm_port_buffer_take (read_buf, (uint8_t *) dest, read_len,
                               cur, avail);
}

/* Clear a port's read buffers, returning the contents.  */
SCM_DEFINE (scm_drain_input, "drain-input", 1, 0, 0, 
            (SCM port),
	    "This procedure clears a port's input buffers, similar\n"
	    "to the way that force-output clears the output buffer.  The\n"
	    "contents of the buffers are returned as a single string, e.g.,\n"
	    "\n"
	    "@lisp\n"
	    "(define p (open-input-file ...))\n"
	    "(drain-input p) => empty string, nothing buffered yet.\n"
	    "(unread-char (read-char p) p)\n"
	    "(drain-input p) => initial chars from p, up to the buffer size.\n"
	    "@end lisp\n\n"
	    "Draining the buffers may be useful for cleanly finishing\n"
	    "buffered I/O so that the file descriptor can be used directly\n"
	    "for further input.")
#define FUNC_NAME s_scm_drain_input
{
  SCM read_buf, result;
  size_t avail, cur;

  SCM_VALIDATE_OPINPORT (1, port);
  read_buf = SCM_PORT (port)->read_buf;
  avail = scm_port_buffer_can_take (read_buf, &cur);

  if (avail)
    {
      const uint8_t *ptr = scm_port_buffer_take_pointer (read_buf, cur);
      result = scm_from_port_stringn ((const char *) ptr, avail, port);
      scm_port_buffer_did_take (read_buf, cur, avail);
    }
  else
    result = scm_nullstr;
  
  return result;
}
#undef FUNC_NAME

void
scm_end_input (SCM port)
{
  SCM buf;
  size_t cur, avail;
  scm_t_off offset;

  buf = SCM_PORT (port)->read_buf;
  avail = scm_port_buffer_can_take (buf, &cur);
  scm_port_buffer_did_take (buf, cur, avail);
  offset = - (scm_t_off) avail;

  if (offset != 0)
    {
      scm_dynwind_begin (0);
      scm_dynwind_acquire_port (port);
      SCM_PORT_TYPE (port)->seek (port, offset, SEEK_CUR);
      scm_dynwind_end ();
    }
}

SCM_DEFINE (scm_force_output, "force-output", 0, 1, 0,
           (SCM port),
	    "Flush the specified output port, or the current output port if @var{port}\n"
	    "is omitted.  The current output buffer contents are passed to the\n"
	    "underlying port implementation (e.g., in the case of fports, the\n"
	    "data will be written to the file and the output buffer will be cleared.)\n"
	    "It has no effect on an unbuffered port.\n\n"
	    "The return value is unspecified.")
#define FUNC_NAME s_scm_force_output
{
  if (SCM_UNBNDP (port))
    port = scm_current_output_port ();
  else
    {
      port = SCM_COERCE_OUTPORT (port);
      SCM_VALIDATE_OPOUTPORT (1, port);
    }
  scm_flush (port);
  return SCM_UNSPECIFIED;
}
#undef FUNC_NAME

static void scm_i_write (SCM port, SCM buf);

void
scm_flush (SCM port)
{
  SCM buf = SCM_PORT (port)->write_buf;
  size_t cur;
  if (scm_port_buffer_can_take (buf, &cur))
    scm_i_write (port, buf);
}

/* Return number of bytes consumed, or zero if no BOM was consumed.  */
static size_t
maybe_consume_bom (SCM port, const unsigned char *bom, size_t bom_len)
{
  SCM read_buf;
  const uint8_t *buf;
  size_t cur, avail;

  if (peek_byte_or_eof (port, &read_buf, &cur) != bom[0])
    return 0;

  /* Make sure there's enough space in the buffer for a BOM.  Now that
     we matched the first byte, we know we're going to have to read this
     many bytes anyway.  */
  read_buf = scm_fill_input (port, bom_len, &cur, &avail);
  buf = scm_port_buffer_take_pointer (read_buf, cur);

  if (avail < bom_len)
    return 0;

  if (memcmp (buf, bom, bom_len) != 0)
    return 0;

  scm_port_buffer_did_take (read_buf, cur, bom_len);
  return bom_len;
}

static size_t
port_clear_stream_start_for_bom_read (SCM port, enum bom_io_mode io_mode)
{
  scm_t_port *pt = SCM_PORT (port);

  if (!pt->at_stream_start_for_bom_read)
    return 0;

  /* Maybe slurp off a byte-order marker.  */
  pt->at_stream_start_for_bom_read = 0;
  if (pt->rw_random)
    pt->at_stream_start_for_bom_write = 0;

  if (io_mode == BOM_IO_BINARY)
    return 0;

  if (scm_is_eq (pt->encoding, sym_UTF_8))
    return maybe_consume_bom (port, scm_utf8_bom, sizeof (scm_utf8_bom));

  if (scm_is_eq (pt->encoding, sym_UTF_16))
    {
      if (maybe_consume_bom (port, scm_utf16le_bom, sizeof (scm_utf16le_bom)))
        {
          scm_specialize_port_encoding_x (port, sym_UTF_16LE);
          return 2;
        }
      if (maybe_consume_bom (port, scm_utf16be_bom, sizeof (scm_utf16be_bom)))
        {
          scm_specialize_port_encoding_x (port, sym_UTF_16BE);
          return 2;
        }
      /* Big-endian by default.  */
      scm_specialize_port_encoding_x (port, sym_UTF_16BE);
      return 0;
    }

  if (scm_is_eq (pt->encoding, sym_UTF_32))
    {
      if (maybe_consume_bom (port, scm_utf32le_bom, sizeof (scm_utf32le_bom)))
        {
          /* Big-endian by default.  */
          scm_specialize_port_encoding_x (port, sym_UTF_32LE);
          return 4;
        }
      if (maybe_consume_bom (port, scm_utf32be_bom, sizeof (scm_utf32be_bom)))
        {
          scm_specialize_port_encoding_x (port, sym_UTF_32BE);
          return 4;
        }
      /* Big-endian by default.  */
      scm_specialize_port_encoding_x (port, sym_UTF_32BE);
      return 0;
    }

  return 0;
}

SCM_INTERNAL SCM scm_port_clear_stream_start_for_bom_read (SCM port);
SCM_DEFINE (scm_port_clear_stream_start_for_bom_read,
            "port-clear-stream-start-for-bom-read", 1, 0, 0,
            (SCM port),
            "")
#define FUNC_NAME s_scm_port_clear_stream_start_for_bom_read
{
  scm_t_port *pt;

  SCM_VALIDATE_PORT (1, port);

  pt = SCM_PORT (port);
  if (!pt->at_stream_start_for_bom_read)
    return SCM_BOOL_F;

  /* Maybe slurp off a byte-order marker.  */
  pt->at_stream_start_for_bom_read = 0;
  if (pt->rw_random)
    pt->at_stream_start_for_bom_write = 0;

  return SCM_BOOL_T;
}
#undef FUNC_NAME

SCM_INTERNAL SCM scm_port_clear_stream_start_for_bom_write (SCM, SCM);
SCM_DEFINE (scm_port_clear_stream_start_for_bom_write,
            "port-clear-stream-start-for-bom-write", 1, 1, 0,
            (SCM port, SCM buf),
            "")
#define FUNC_NAME s_scm_port_clear_stream_start_for_bom_write
{
  scm_t_port *pt;

  SCM_VALIDATE_PORT (1, port);

  pt = SCM_PORT (port);
  if (!pt->at_stream_start_for_bom_write)
    return SCM_INUM0;

  pt->at_stream_start_for_bom_write = 0;
  if (pt->rw_random)
    pt->at_stream_start_for_bom_read = 0;

  if (SCM_UNBNDP (buf))
    return SCM_INUM0;

  /* Write a BOM if appropriate.  */
  if (scm_is_eq (pt->encoding, sym_UTF_16))
    {
      SCM precise_encoding;
      size_t end, avail, ret;

      scm_port_acquire_iconv_descriptors (port, NULL, NULL);
      precise_encoding = pt->precise_encoding;
      scm_port_release_iconv_descriptors (port);

      avail = scm_port_buffer_can_put (buf, &end);
      if (scm_is_eq (precise_encoding, sym_UTF_16LE))
        ret = scm_port_buffer_put (buf, scm_utf16le_bom,
                                   sizeof (scm_utf16le_bom), end, avail);
      else
        ret = scm_port_buffer_put (buf, scm_utf16be_bom,
                                   sizeof (scm_utf16be_bom), end, avail);

      return scm_from_size_t (ret);
    }
  else if (scm_is_eq (pt->encoding, sym_UTF_32))
    {
      SCM precise_encoding;
      size_t end, avail, ret;

      scm_port_acquire_iconv_descriptors (port, NULL, NULL);
      precise_encoding = pt->precise_encoding;
      scm_port_release_iconv_descriptors (port);

      avail = scm_port_buffer_can_put (buf, &end);
      if (scm_is_eq (precise_encoding, sym_UTF_32LE))
        ret = scm_port_buffer_put (buf, scm_utf32le_bom,
                                   sizeof (scm_utf32le_bom), end, avail);
      else
        ret = scm_port_buffer_put (buf, scm_utf32be_bom,
                                   sizeof (scm_utf32be_bom), end, avail);

      return scm_from_size_t (ret);
    }

  return SCM_INUM0;
}
#undef FUNC_NAME

SCM
scm_fill_input (SCM port, size_t minimum_size, size_t *cur_out,
                size_t *avail_out)
{
  scm_t_port *pt = SCM_PORT (port);
  SCM read_buf;
  size_t cur, buffered;

  if (minimum_size == 0)
    minimum_size = 1;

  /* The default is BOM_IO_TEXT.  Binary input procedures should
     port_clear_stream_start_for_bom_read with BOM_IO_BINARY before
     filling the input buffers.  */
  port_clear_stream_start_for_bom_read (port, BOM_IO_TEXT);
  read_buf = pt->read_buf;
  buffered = scm_port_buffer_can_take (read_buf, &cur);

  if (buffered >= minimum_size
      || scm_is_true (scm_port_buffer_has_eof_p (read_buf)))
    {
      *cur_out = cur;
      *avail_out = buffered;
      return read_buf;
    }

  if (pt->rw_random)
    scm_flush (port);

  /* Prepare to read.  Make sure there is enough space in the buffer for
     minimum_size, and ensure that cur is zero so that we fill towards
     the end of the buffer.  */
  if (minimum_size > scm_port_buffer_size (read_buf))
    /* Grow the read buffer.  */
    read_buf = scm_expand_port_read_buffer_x (port,
                                              scm_from_size_t (minimum_size),
                                              SCM_BOOL_F);
  else if (buffered == 0)
    scm_port_buffer_reset (read_buf);
  else
    {
      const uint8_t *to_shift;
      to_shift = scm_port_buffer_take_pointer (read_buf, cur);
      scm_port_buffer_reset (read_buf);
      memmove (scm_port_buffer_put_pointer (read_buf, 0), to_shift, buffered);
      scm_port_buffer_did_put (read_buf, 0, buffered);
    }

  while (buffered < minimum_size
         && !scm_is_true (scm_port_buffer_has_eof_p (read_buf)))
    {
      size_t count;
      size_t buffering = pt->read_buffering;
      size_t to_read;

      if (pt->read_buffering < minimum_size)
        buffering = minimum_size;
      to_read = buffering - buffered;

      count = scm_i_read_bytes (port, scm_port_buffer_bytevector (read_buf),
                                buffered, to_read);
      scm_port_buffer_did_put (read_buf, buffered, count);
      buffered += count;
      scm_port_buffer_set_has_eof_p (read_buf, scm_from_bool (count == 0));
    }

  /* We ensured cur was zero.  */
  *cur_out = 0;
  *avail_out = buffered;
  return read_buf;
}

SCM_DEFINE (scm_port_random_access_p, "port-random-access?", 1, 0, 0,
            (SCM port),
	    "Return true if the port is random-access, or false otherwise.")
#define FUNC_NAME s_scm_port_random_access_p
{
  SCM_VALIDATE_OPPORT (1, port);
  return scm_from_bool (SCM_PORT (port)->rw_random);
}
#undef FUNC_NAME

SCM_DEFINE (scm_port_read_buffering, "port-read-buffering", 1, 0, 0,
            (SCM port),
	    "Return the amount of read buffering on a port, in bytes.")
#define FUNC_NAME s_scm_port_read_buffering
{
  SCM_VALIDATE_OPINPORT (1, port);
  return scm_from_size_t (SCM_PORT (port)->read_buffering);
}
#undef FUNC_NAME

SCM_DEFINE (scm_expand_port_read_buffer_x, "expand-port-read-buffer!", 2, 1, 0,
            (SCM port, SCM size, SCM putback_p),
	    "Expand the read buffer of @var{port} to @var{size}.  Copy the\n"
            "old buffered data, if, any, to the beginning of the new\n"
            "buffer, unless @var{putback_p} is true, in which case copy it\n"
            "to the end instead.  Return the new buffer.")
#define FUNC_NAME s_scm_expand_port_read_buffer_x
{
  scm_t_port *pt;
  size_t c_size, cur, avail;
  SCM new_buf;

  SCM_VALIDATE_OPINPORT (1, port);
  pt = SCM_PORT (port);
  c_size = scm_to_size_t (size);
  SCM_ASSERT_RANGE (2, size, c_size > scm_port_buffer_size (pt->read_buf));
  if (SCM_UNBNDP (putback_p))
    putback_p = SCM_BOOL_F;

  new_buf = make_port_buffer (port, c_size);
  scm_port_buffer_set_has_eof_p (new_buf,
                                 scm_port_buffer_has_eof_p (pt->read_buf));
  avail = scm_port_buffer_can_take (pt->read_buf, &cur);

  if (scm_is_true (putback_p))
    {
      scm_port_buffer_reset_end (new_buf);
      scm_port_buffer_putback (new_buf,
                               scm_port_buffer_take_pointer (pt->read_buf, cur),
                               avail, c_size);
    }
  else
    {
      scm_port_buffer_reset (new_buf);
      scm_port_buffer_put (new_buf,
                           scm_port_buffer_take_pointer (pt->read_buf, cur),
                           avail, 0, c_size);
    }
  pt->read_buf = new_buf;

  return new_buf;
}
#undef FUNC_NAME

SCM_DEFINE (scm_port_read, "port-read", 1, 0, 0, (SCM port),
	    "Return the read function for an input port.")
#define FUNC_NAME s_scm_port_read
{
  SCM_VALIDATE_OPINPORT (1, port);
  return SCM_PORT_TYPE (port)->scm_read;
}
#undef FUNC_NAME

SCM_DEFINE (scm_port_write, "port-write", 1, 0, 0,
            (SCM port),
	    "Return the write function for an output port.")
#define FUNC_NAME s_scm_port_write
{
  SCM_VALIDATE_OPOUTPORT (1, port);
  return SCM_PORT_TYPE (port)->scm_write;
}
#undef FUNC_NAME

SCM_DEFINE (scm_port_read_buffer, "port-read-buffer", 1, 0, 0,
            (SCM port),
	    "Return the read buffer for a port.")
#define FUNC_NAME s_scm_port_read_buffer
{
  SCM_VALIDATE_OPPORT (1, port);
  return SCM_PORT (port)->read_buf;
}
#undef FUNC_NAME

SCM_DEFINE (scm_port_write_buffer, "port-write-buffer", 1, 0, 0,
            (SCM port),
	    "Return the write buffer for a port.")
#define FUNC_NAME s_scm_port_write_buffer
{
  SCM_VALIDATE_OPPORT (1, port);
  return SCM_PORT (port)->write_buf;
}
#undef FUNC_NAME

SCM_DEFINE (scm_port_auxiliary_write_buffer, "port-auxiliary-write-buffer",
            1, 0, 0, (SCM port),
	    "Return the auxiliary write buffer for a port.")
#define FUNC_NAME s_scm_port_auxiliary_write_buffer
{
  scm_t_port *pt;

  SCM_VALIDATE_OPPORT (1, port);

  pt = SCM_PORT (port);
  if (scm_is_false (pt->write_buf_aux))
    pt->write_buf_aux = make_port_buffer (port, AUXILIARY_WRITE_BUFFER_SIZE);

  return pt->write_buf_aux;
}
#undef FUNC_NAME

SCM_INTERNAL SCM scm_port_line_buffered_p (SCM);
SCM_DEFINE (scm_port_line_buffered_p, "port-line-buffered?", 1, 0, 0,
            (SCM port),
	    "Return true if the port is line buffered.")
#define FUNC_NAME s_scm_port_line_buffered_p
{
  SCM_VALIDATE_OPPORT (1, port);
  return scm_from_bool (SCM_CELL_WORD_0 (port) & SCM_BUFLINE);
}
#undef FUNC_NAME




/* Output.  */

static void
scm_i_write_bytes (SCM port, SCM src, size_t start, size_t count)
{
  size_t written = 0;
  scm_t_port_type *ptob = SCM_PORT_TYPE (port);

  if (count > SCM_BYTEVECTOR_LENGTH (src))
    fprintf (stderr, "count: %zu %zu\n", count, scm_c_bytevector_length (src));
  assert (count <= SCM_BYTEVECTOR_LENGTH (src));
  assert (start + count <= SCM_BYTEVECTOR_LENGTH (src));

  scm_dynwind_begin (0);
  scm_dynwind_acquire_port (port);

  do
    {
      size_t ret = ptob->c_write (port, src, start + written, count - written);

      if (ret == (size_t) -1)
        {
          if (SCM_PORT_FINALIZING_P (port))
            {
              /* This port is being closed because it became unreachable
                 and was finalized, but it has buffered output, and the
                 resource is not currently writable.  Instead of
                 blocking, discard buffered output and warn.  To avoid
                 this situation, force-output on the port before letting
                 it go!  */
              scm_puts
                ("Warning: Discarding buffered output on non-blocking port\n"
                 "         ",
                 scm_current_warning_port ());
              scm_display (port, scm_current_warning_port());
              scm_puts
                ("\n"
                 "         closed by the garbage collector.  To avoid this\n"
                 "         behavior and this warning, call `force-output' or\n"
                 "         `close-port' on the port before letting go of it.\n",
                 scm_current_warning_port ());
              break;
            }
          else
            port_poll (port, POLLOUT, -1);
        }
      else
        written += ret;
    }
  while (written < count);

  scm_dynwind_end ();

  assert (written == count);
}

static void
scm_i_write (SCM port, SCM buf)
{
  size_t start, count;

  scm_port_clear_stream_start_for_bom_write (port, SCM_UNDEFINED);

  /* Update cursors before attempting to write, assuming that I/O errors
     are sticky.  That way if the write throws an error, causing the
     computation to abort, and possibly causing the port to be collected
     by GC when it's open, any subsequent close-port / force-output
     won't signal *another* error.  */

  count = scm_port_buffer_can_take (buf, &start);
  scm_port_buffer_reset (buf);
  scm_i_write_bytes (port, scm_port_buffer_bytevector (buf), start,
                     count);
}

/* Used by an application to write arbitrary number of bytes to an SCM
   port.  Similar semantics as libc write.  However, unlike libc write,
   scm_c_write writes the requested number of bytes.

   Warning: Doesn't update port line and column counts!  */
void
scm_c_write_bytes (SCM port, SCM src, size_t start, size_t count)
#define FUNC_NAME "scm_c_write_bytes"
{
  scm_t_port *pt;
  SCM write_buf;

  SCM_VALIDATE_OPOUTPORT (1, port);

  pt = SCM_PORT (port);
  write_buf = pt->write_buf;

  if (pt->rw_random)
    scm_end_input (port);

  if (count < scm_port_buffer_size (write_buf))
    {
      size_t cur, end;

      /* Make it so that the write_buf "end" cursor is only nonzero if
         there are buffered bytes already.  */
      if (scm_port_buffer_can_take (write_buf, &cur) == 0)
        {
          scm_port_buffer_reset (write_buf);
          cur = 0;
        }

      /* We buffer writes that are smaller in size than the write
         buffer.  If the buffer is too full to hold the new data, we
         flush it beforehand.  Otherwise it could be that the buffer is
         full after filling it with the new data; if that's the case, we
         flush then instead.  */
      if (scm_port_buffer_can_put (write_buf, &end) < count)
        {
          scm_i_write (port, write_buf);
          end = 0;
        }

      {
        signed char *src_ptr = SCM_BYTEVECTOR_CONTENTS (src) + start;
        scm_port_buffer_put (write_buf, (uint8_t *) src_ptr, count,
                             end, count);
      }

      if (scm_port_buffer_can_put (write_buf, &end) == 0)
        scm_i_write (port, write_buf);
    }
  else
    {
      size_t tmp;

      /* Our write would overflow the buffer.  Flush buffered bytes (if
         needed), then write our bytes with just one syscall.  */
      if (scm_port_buffer_can_take (write_buf, &tmp))
        scm_i_write (port, write_buf);

      scm_i_write_bytes (port, src, start, count);
    }
}
#undef FUNC_NAME

/* Like scm_c_write_bytes, but always writes through the write buffer.
   Used when an application wants to write bytes stored in an area not
   managed by GC.  */
void
scm_c_write (SCM port, const void *ptr, size_t size)
#define FUNC_NAME "scm_c_write"
{
  scm_t_port *pt;
  SCM write_buf;
  size_t end, avail, written = 0;
  int using_aux_buffer = 0;
  const uint8_t *src = ptr;

  SCM_VALIDATE_OPOUTPORT (1, port);

  pt = SCM_PORT (port);

  if (pt->rw_random)
    scm_end_input (port);

  /* Imagine we are writing 40 bytes on an unbuffered port.  If we were
     writing from a bytevector we could pass that write directly to the
     port.  But since we aren't, we need to go through a bytevector, and
     if we went through the port buffer we'd have to make 40 individual
     calls to the write function.  That would be terrible.  Really we
     need an intermediate bytevector.  But, we shouldn't use a trick
     analogous to what we do with expand-port-read-buffer!, because the
     way we use the cur and end cursors doesn't seem to facilitate that.
     So instead we buffer through an auxiliary write buffer if needed.
     To avoid re-allocating this buffer all the time, we store it on the
     port.  It should never be left with buffered data.

     Use of an auxiliary write buffer is triggered if the buffer is
     smaller than the size we would make for an auxiliary write buffer,
     and the write is bigger than the buffer.  */
  write_buf = pt->write_buf;
  if (scm_port_buffer_size (write_buf) < size &&
      scm_port_buffer_size (write_buf) < AUXILIARY_WRITE_BUFFER_SIZE)
    {
      using_aux_buffer = 1;
      write_buf = scm_port_auxiliary_write_buffer (port);
    }

  if (using_aux_buffer)
    {
      end = 0;
      avail = AUXILIARY_WRITE_BUFFER_SIZE;
    }
  else
    avail = scm_port_buffer_can_put (write_buf, &end);

  while (written < size)
    {
      size_t did_put = scm_port_buffer_put (write_buf, src, size - written,
                                            end, avail);
      written += did_put;
      src += did_put;
      if (using_aux_buffer || did_put == avail)
        {
          scm_i_write (port, write_buf);
          end = 0;
          avail = scm_port_buffer_size (write_buf);
        }
    }
}
#undef FUNC_NAME

/* The encoded escape sequence will be written to BUF, and will be valid
   ASCII (so also valid ISO-8859-1 and UTF-8).  Return the number of
   bytes written.  */
static size_t
encode_escape_sequence (scm_t_wchar ch, uint8_t buf[ESCAPE_BUFFER_SIZE])
{
  /* Represent CH using the in-string escape syntax.  */
  static const char hex[] = "0123456789abcdef";
  static const char escapes[7] = "abtnvfr";
  size_t i = 0;

  buf[i++] = '\\';

  if (ch >= 0x07 && ch <= 0x0D && ch != 0x0A)
    /* Use special escapes for some C0 controls.  */
    buf[i++] = escapes[ch - 0x07];
  else if (!SCM_R6RS_ESCAPES_P)
    {
      if (ch <= 0xFF)
        {
          buf[i++] = 'x';
          buf[i++] = hex[ch / 16];
          buf[i++] = hex[ch % 16];
        }
      else if (ch <= 0xFFFF)
        {
          buf[i++] = 'u';
          buf[i++] = hex[(ch & 0xF000) >> 12];
          buf[i++] = hex[(ch & 0xF00) >> 8];
          buf[i++] = hex[(ch & 0xF0) >> 4];
          buf[i++] = hex[(ch & 0xF)];
        }
      else if (ch > 0xFFFF)
        {
          buf[i++] = 'U';
          buf[i++] = hex[(ch & 0xF00000) >> 20];
          buf[i++] = hex[(ch & 0xF0000) >> 16];
          buf[i++] = hex[(ch & 0xF000) >> 12];
          buf[i++] = hex[(ch & 0xF00) >> 8];
          buf[i++] = hex[(ch & 0xF0) >> 4];
          buf[i++] = hex[(ch & 0xF)];
        }
    }
  else
    {
      buf[i++] = 'x';
      if (ch > 0xfffff) buf[i++] = hex[(ch >> 20) & 0xf];
      if (ch > 0x0ffff) buf[i++] = hex[(ch >> 16) & 0xf];
      if (ch > 0x00fff) buf[i++] = hex[(ch >> 12) & 0xf];
      if (ch > 0x000ff) buf[i++] = hex[(ch >> 8) & 0xf];
      if (ch > 0x0000f) buf[i++] = hex[(ch >> 4) & 0xf];
      buf[i++] = hex[ch & 0xf];
      buf[i++] = ';';
    }

  return i;
}

void
scm_c_put_escaped_char (SCM port, scm_t_wchar ch)
{
  uint8_t escape[ESCAPE_BUFFER_SIZE];
  size_t len = encode_escape_sequence (ch, escape);
  scm_c_put_latin1_chars (port, escape, len);
}

/* Convert CODEPOINT to UTF-8 and store the result in UTF8.  Return the
   number of bytes of the UTF-8-encoded string.  */
static size_t
codepoint_to_utf8 (uint32_t codepoint, uint8_t utf8[UTF8_BUFFER_SIZE])
{
  size_t len;

  if (codepoint <= 0x7f)
    {
      len = 1;
      utf8[0] = codepoint;
    }
  else if (codepoint <= 0x7ffUL)
    {
      len = 2;
      utf8[0] = 0xc0 | (codepoint >> 6);
      utf8[1] = 0x80 | (codepoint & 0x3f);
    }
  else if (codepoint <= 0xffffUL)
    {
      len = 3;
      utf8[0] = 0xe0 | (codepoint >> 12);
      utf8[1] = 0x80 | ((codepoint >> 6) & 0x3f);
      utf8[2] = 0x80 | (codepoint & 0x3f);
    }
  else
    {
      len = 4;
      utf8[0] = 0xf0 | (codepoint >> 18);
      utf8[1] = 0x80 | ((codepoint >> 12) & 0x3f);
      utf8[2] = 0x80 | ((codepoint >> 6) & 0x3f);
      utf8[3] = 0x80 | (codepoint & 0x3f);
    }

  return len;
}

static size_t
try_encode_char_to_iconv_buf (SCM port, SCM buf, uint32_t ch)
{
  uint8_t utf8[UTF8_BUFFER_SIZE];
  size_t utf8_len = codepoint_to_utf8 (ch, utf8);
  size_t end;
  size_t can_put = scm_port_buffer_can_put (buf, &end);
  uint8_t *aux = scm_port_buffer_put_pointer (buf, end);
  iconv_t output_cd;
  int saved_errno;

  char *input = (char *) utf8;
  size_t input_left = utf8_len;
  char *output = (char *) aux;
  size_t output_left = can_put;
  size_t res;

  scm_port_acquire_iconv_descriptors (port, NULL, &output_cd);
  res = iconv (output_cd, &input, &input_left, &output, &output_left);
  saved_errno = errno;
  /* Emit bytes needed to get back to initial state, if needed.  */
  iconv (output_cd, NULL, NULL, &output, &output_left);
  scm_port_release_iconv_descriptors (port);

  if (res != (size_t) -1)
    {
      /* Success.  */
      scm_port_buffer_did_put (buf, end, can_put - output_left);
      return 1;
    }

  if (saved_errno == E2BIG)
    /* No space to encode the character; try again next time.  */
    return 0;

  /* Otherwise, re-set the output buffer and try to escape or substitute
     the character, as appropriate.  */
  output = (char *) aux;
  output_left = can_put;

  /* The source buffer is valid UTF-8, so we shouldn't get EILSEQ
     because of the input encoding; if we get EILSEQ, that means the
     codepoint is not accessible in the target encoding.  We have whole
     codepoints in the source buffer, so we shouldn't get EINVAL.  We
     already handled E2BIG.  The descriptor should be valid so we
     shouldn't get EBADF.  In summary, we only need to handle EILSEQ.  */

  if (scm_is_eq (SCM_PORT (port)->conversion_strategy, sym_escape))
    {
      uint8_t escape[ESCAPE_BUFFER_SIZE];
      input = (char *) escape;
      input_left = encode_escape_sequence (ch, escape);
      scm_port_acquire_iconv_descriptors (port, NULL, &output_cd);
      res = iconv (output_cd, &input, &input_left, &output, &output_left);
      saved_errno = errno;
      iconv (output_cd, NULL, NULL, &output, &output_left);
      scm_port_release_iconv_descriptors (port);
    }
  else if (scm_is_eq (SCM_PORT (port)->conversion_strategy, sym_substitute))
    {
      uint8_t substitute[2] = "?";
      input = (char *) substitute;
      input_left = 1;
      scm_port_acquire_iconv_descriptors (port, NULL, &output_cd);
      res = iconv (output_cd, &input, &input_left, &output, &output_left);
      saved_errno = errno;
      iconv (output_cd, NULL, NULL, &output, &output_left);
      scm_port_release_iconv_descriptors (port);
    }

  if (res != (size_t) -1)
    {
      scm_port_buffer_did_put (buf, end, can_put - output_left);
      return 1;
    }

  /* No space to write the substitution or escape, or maybe there was an
     error.  If there are buffered bytes, the caller should flush and
     try again; otherwise the caller should raise an error.  */
  return 0;
}

static size_t
encode_latin1_chars_to_latin1_buf (SCM port, SCM buf,
                                   const uint8_t *chars, size_t count)
{
  size_t end;
  size_t avail = scm_port_buffer_can_put (buf, &end);
  return scm_port_buffer_put (buf, chars, count, end, avail);
}

static size_t
encode_latin1_chars_to_utf8_buf (SCM port, SCM buf,
                                 const uint8_t *chars, size_t count)
{
  size_t end;
  size_t buf_size = scm_port_buffer_can_put (buf, &end);
  uint8_t *dst = scm_port_buffer_put_pointer (buf, end);
  size_t read, written;
  for (read = 0, written = 0;
       read < count && written + UTF8_BUFFER_SIZE < buf_size;
       read++)
    written += codepoint_to_utf8 (chars[read], dst + written);
  scm_port_buffer_did_put (buf, end, written);
  return read;
}

static size_t
encode_latin1_chars_to_iconv_buf (SCM port, SCM buf,
                                  const uint8_t *chars, size_t count)
{
  size_t read;
  for (read = 0; read < count; read++)
    if (!try_encode_char_to_iconv_buf (port, buf, chars[read]))
      break;
  return read;
}

static size_t
encode_latin1_chars (SCM port, SCM buf, const uint8_t *chars, size_t count)
{
  scm_t_port *pt = SCM_PORT (port);
  SCM position;
  size_t ret, i;

  if (scm_is_eq (pt->encoding, sym_ISO_8859_1))
    ret = encode_latin1_chars_to_latin1_buf (port, buf, chars, count);
  else if (scm_is_eq (pt->encoding, sym_UTF_8))
    ret = encode_latin1_chars_to_utf8_buf (port, buf, chars, count);
  else
    ret = encode_latin1_chars_to_iconv_buf (port, buf, chars, count);

  if (ret == 0 && count > 0)
    scm_encoding_error ("put-char", EILSEQ,
                        "conversion to port encoding failed",
                        port, SCM_MAKE_CHAR (chars[0]));

  position = pt->position;
  for (i = 0; i < ret; i++)
    update_port_position (position, chars[i]);

  return ret;
}

static size_t
encode_utf32_chars_to_latin1_buf (SCM port, SCM buf,
                                  const uint32_t *chars, size_t count)
{
  scm_t_port *pt = SCM_PORT (port);
  size_t end;
  size_t buf_size = scm_port_buffer_can_put (buf, &end);
  uint8_t *dst = scm_port_buffer_put_pointer (buf, end);
  size_t read, written;
  for (read = 0, written = 0; read < count && written < buf_size; read++)
    {
      uint32_t ch = chars[read];
      if (ch <= 0xff)
        dst[written++] = ch;
      else if (scm_is_eq (pt->conversion_strategy, sym_substitute))
        dst[written++] = '?';
      else if (scm_is_eq (pt->conversion_strategy, sym_escape))
        {
          uint8_t escape[ESCAPE_BUFFER_SIZE];
          size_t escape_len = encode_escape_sequence (ch, escape);
          if (escape_len > buf_size - written)
            break;
          memcpy (dst + written, escape, escape_len);
          written += escape_len;
        }
      else
        break;
    }
  scm_port_buffer_did_put (buf, end, written);
  return read;
}

static size_t
encode_utf32_chars_to_utf8_buf (SCM port, SCM buf, const uint32_t *chars,
                                size_t count)
{
  size_t end;
  size_t buf_size = scm_port_buffer_can_put (buf, &end);
  uint8_t *dst = scm_port_buffer_put_pointer (buf, end);
  size_t read, written;
  for (read = 0, written = 0;
       read < count && written + UTF8_BUFFER_SIZE < buf_size;
       read++)
    written += codepoint_to_utf8 (chars[read], dst + written);
  scm_port_buffer_did_put (buf, end, written);
  return read;
}

static size_t
encode_utf32_chars_to_iconv_buf (SCM port, SCM buf, const uint32_t *chars,
                                 size_t count)
{
  size_t read;
  for (read = 0; read < count; read++)
    if (!try_encode_char_to_iconv_buf (port, buf, chars[read]))
      break;
  return read;
}

static size_t
encode_utf32_chars (SCM port, SCM buf, const uint32_t *chars, size_t count)
{
  scm_t_port *pt = SCM_PORT (port);
  SCM position;
  size_t ret, i;

  if (scm_is_eq (pt->encoding, sym_ISO_8859_1))
    ret = encode_utf32_chars_to_latin1_buf (port, buf, chars, count);
  else if (scm_is_eq (pt->encoding, sym_UTF_8))
    ret = encode_utf32_chars_to_utf8_buf (port, buf, chars, count);
  else
    ret = encode_utf32_chars_to_iconv_buf (port, buf, chars, count);

  if (ret == 0 && count > 0)
    scm_encoding_error ("put-char", EILSEQ,
                        "conversion to port encoding failed",
                        port, SCM_MAKE_CHAR (chars[0]));

  position = pt->position;
  for (i = 0; i < ret; i++)
    update_port_position (position, chars[i]);

  return ret;
}

static size_t
port_encode_chars (SCM port, SCM buf, SCM str, size_t start, size_t count)
{
  if (count == 0)
    return 0;

  if (scm_i_is_narrow_string (str))
    {
      const char *chars = scm_i_string_chars (str);
      return encode_latin1_chars (port, buf,
                                  ((const uint8_t *) chars) + start,
                                  count);
    }
  else
    {
      const scm_t_wchar *chars = scm_i_string_wide_chars (str);
      return encode_utf32_chars (port, buf,
                                 ((const uint32_t *) chars) + start,
                                 count);
    }
}

SCM scm_port_encode_chars (SCM, SCM, SCM, SCM, SCM);
SCM_DEFINE (scm_port_encode_chars, "port-encode-chars", 5, 0, 0,
            (SCM port, SCM buf, SCM str, SCM start, SCM count),
            "")
#define FUNC_NAME s_scm_port_encode_chars
{
  size_t c_start, c_count, c_len, encoded;

  SCM_VALIDATE_OPOUTPORT (1, port);
  SCM_VALIDATE_VECTOR (2, buf);
  SCM_VALIDATE_STRING (3, str);
  c_len = scm_i_string_length (str);
  SCM_VALIDATE_SIZE_COPY (4, start, c_start);
  SCM_ASSERT_RANGE (4, start, c_start <= c_len);
  SCM_VALIDATE_SIZE_COPY (5, count, c_count);
  SCM_ASSERT_RANGE (5, count, c_count <= c_len - c_start);

  encoded = port_encode_chars (port, buf, str, c_start, c_count);

  return scm_from_size_t (encoded);
}
#undef FUNC_NAME

SCM scm_port_encode_char (SCM, SCM, SCM);
SCM_DEFINE (scm_port_encode_char, "port-encode-char", 3, 0, 0,
            (SCM port, SCM buf, SCM ch),
            "")
#define FUNC_NAME s_scm_port_encode_char
{
  uint32_t codepoint;

  SCM_VALIDATE_OPOUTPORT (1, port);
  SCM_VALIDATE_VECTOR (2, buf);
  SCM_VALIDATE_CHAR (3, ch);

  codepoint = SCM_CHAR (ch);
  encode_utf32_chars (port, buf, &codepoint, 1);

  return SCM_UNSPECIFIED;
}
#undef FUNC_NAME

void
scm_c_put_latin1_chars (SCM port, const uint8_t *chars, size_t len)
{
  SCM aux_buf = scm_port_auxiliary_write_buffer (port);
  SCM aux_bv = scm_port_buffer_bytevector (aux_buf);
  SCM position = SCM_PORT (port)->position;
  SCM saved_line = scm_port_position_line (position);

  scm_port_clear_stream_start_for_bom_write (port, aux_buf);

  while (len)
    {
      size_t encoded = encode_latin1_chars (port, aux_buf, chars, len);
      assert(encoded <= len);
      scm_c_write_bytes (port, aux_bv, 0,
                         scm_to_size_t (scm_port_buffer_end (aux_buf)));
      scm_port_buffer_reset (aux_buf);
      chars += encoded;
      len -= encoded;
    }

  /* Handle line buffering.  */
  if ((SCM_CELL_WORD_0 (port) & SCM_BUFLINE) &&
      !scm_is_eq (saved_line, scm_port_position_line (position)))
    scm_flush (port);
}

void
scm_c_put_utf32_chars (SCM port, const uint32_t *chars, size_t len)
{
  SCM aux_buf = scm_port_auxiliary_write_buffer (port);
  SCM aux_bv = scm_port_buffer_bytevector (aux_buf);
  SCM position = SCM_PORT (port)->position;
  SCM saved_line = scm_port_position_line (position);

  scm_port_clear_stream_start_for_bom_write (port, aux_buf);

  while (len)
    {
      size_t encoded = encode_utf32_chars (port, aux_buf, chars, len);
      assert(encoded <= len);
      scm_c_write_bytes (port, aux_bv, 0,
                         scm_to_size_t (scm_port_buffer_end (aux_buf)));
      scm_port_buffer_reset (aux_buf);
      chars += encoded;
      len -= encoded;
    }

  /* Handle line buffering.  */
  if ((SCM_CELL_WORD_0 (port) & SCM_BUFLINE) &&
      !scm_is_eq (saved_line, scm_port_position_line (position)))
    scm_flush (port);
}

void
scm_c_put_char (SCM port, scm_t_wchar ch)
{
  if (ch <= 0xff)
    {
      uint8_t narrow_ch = ch;
      scm_c_put_latin1_chars (port, &narrow_ch, 1);
    }
  else
    {
      uint32_t wide_ch = ch;
      scm_c_put_utf32_chars (port, &wide_ch, 1);
    }
}

/* Return 0 unless the port can be written out to the port's encoding
   without errors, substitutions, or escapes.  */
int
scm_c_can_put_char (SCM port, scm_t_wchar ch)
{
  SCM encoding = SCM_PORT (port)->encoding;

  if (scm_is_eq (encoding, sym_UTF_8)
      || (scm_is_eq (encoding, sym_ISO_8859_1) && ch <= 0xff)
      || scm_is_eq (encoding, sym_UTF_16)
      || scm_is_eq (encoding, sym_UTF_16LE)
      || scm_is_eq (encoding, sym_UTF_16BE)
      || scm_is_eq (encoding, sym_UTF_32)
      || scm_is_eq (encoding, sym_UTF_32LE)
      || scm_is_eq (encoding, sym_UTF_32BE))
    return 1;

  {
    SCM bv = scm_port_buffer_bytevector (scm_port_auxiliary_write_buffer (port));
    uint8_t buf[UTF8_BUFFER_SIZE];
    char *input = (char *) buf;
    size_t input_len;
    char *output = (char *) SCM_BYTEVECTOR_CONTENTS (bv);
    size_t output_len = SCM_BYTEVECTOR_LENGTH (bv);
    size_t result;
    iconv_t output_cd;

    input_len = codepoint_to_utf8 (ch, buf);

    scm_port_acquire_iconv_descriptors (port, NULL, &output_cd);
    iconv (output_cd, NULL, NULL, &output, &output_len);
    result = iconv (output_cd, &input, &input_len, &output, &output_len);
    iconv (output_cd, NULL, NULL, &output, &output_len);
    scm_port_release_iconv_descriptors (port);

    return result != (size_t) -1;
  }
}

void
scm_c_put_string (SCM port, SCM string, size_t start, size_t count)
{
  if (scm_i_is_narrow_string (string))
    {
      const char *ptr = scm_i_string_chars (string);
      scm_c_put_latin1_chars (port, ((const uint8_t *) ptr) + start, count);
    }
  else
    {
      const scm_t_wchar *ptr = scm_i_string_wide_chars (string);
      scm_c_put_utf32_chars (port, ((const uint32_t *) ptr) + start, count);
    }
}

SCM_DEFINE (scm_put_char, "put-char", 2, 0, 0, (SCM port, SCM ch),
            "Encode @var{ch} to bytes, and send those bytes to @var{port}.")
#define FUNC_NAME s_scm_put_char
{
  SCM_VALIDATE_OPOUTPORT (1, port);
  SCM_VALIDATE_CHAR (2, ch);

  scm_c_put_char (port, SCM_CHAR (ch));

  return SCM_UNSPECIFIED;
}
#undef FUNC_NAME

SCM_DEFINE (scm_put_string, "put-string", 2, 2, 0,
            (SCM port, SCM string, SCM start, SCM count),
            "Display the @var{count} characters from @var{string} to\n"
            "@var{port}, starting with the character at index @var{start}.\n"
            "@var{start} defaults to 0, and @var{count} defaults to\n"
            "displaying all characters until the end of the string.\n\n"
            "Calling @code{put-string} is equivalent in all respects to\n"
            "calling @code{put-char} on the relevant sequence of characters,\n"
            "except that it will attempt to write multiple characters to\n"
            "the port at a time, even if the port is unbuffered.")
#define FUNC_NAME s_scm_put_string
{
  size_t c_start, c_count, c_len;

  SCM_VALIDATE_OPOUTPORT (1, port);
  SCM_VALIDATE_STRING (2, string);
  c_len = scm_i_string_length (string);
  c_start = SCM_UNBNDP (start) ? 0 : scm_to_size_t (start);
  SCM_ASSERT_RANGE (3, start, c_start <= c_len);
  c_count = SCM_UNBNDP (count) ? c_len - c_start : scm_to_size_t (count);
  SCM_ASSERT_RANGE (4, count, c_count <= c_len - c_start);

  scm_c_put_string (port, string, c_start, c_count);

  return SCM_UNSPECIFIED;
}
#undef FUNC_NAME

void
scm_putc (char c, SCM port)
{
  SCM_ASSERT_TYPE (SCM_OPOUTPORTP (port), port, 0, NULL, "output port");
  scm_c_put_char (port, (uint8_t) c);
}

void
scm_puts (const char *s, SCM port)
{
  SCM_ASSERT_TYPE (SCM_OPOUTPORTP (port), port, 0, NULL, "output port");
  scm_c_put_latin1_chars (port, (const uint8_t *) s, strlen (s));
}

/* scm_lfwrite
 *
 * This function differs from scm_c_write; it updates port line and
 * column, flushing line-buffered ports when appropriate. */
void
scm_lfwrite (const char *ptr, size_t size, SCM port)
{
  scm_c_put_latin1_chars (port, (const uint8_t *) ptr, size);
}

/* Write STR to PORT from START inclusive to END exclusive.  */
void
scm_lfwrite_substr (SCM str, size_t start, size_t end, SCM port)
{
  if (end == (size_t) -1)
    end = scm_i_string_length (str);

  scm_c_put_string (port, str, start, end - start);
}




/* Querying and setting positions, and character availability.  */

SCM_DEFINE (scm_char_ready_p, "char-ready?", 0, 1, 0, 
	    (SCM port),
	    "Return @code{#t} if a character is ready on input @var{port}\n"
	    "and return @code{#f} otherwise.  If @code{char-ready?} returns\n"
	    "@code{#t} then the next @code{read-char} operation on\n"
	    "@var{port} is guaranteed not to hang.  If @var{port} is a file\n"
	    "port at end of file then @code{char-ready?} returns @code{#t}.\n"
	    "\n"
	    "@code{char-ready?} exists to make it possible for a\n"
	    "program to accept characters from interactive ports without\n"
	    "getting stuck waiting for input.  Any input editors associated\n"
	    "with such ports must make sure that characters whose existence\n"
	    "has been asserted by @code{char-ready?} cannot be rubbed out.\n"
	    "If @code{char-ready?} were to return @code{#f} at end of file,\n"
	    "a port at end of file would be indistinguishable from an\n"
	    "interactive port that has no ready characters.")
#define FUNC_NAME s_scm_char_ready_p
{
  SCM read_buf;
  size_t tmp;

  if (SCM_UNBNDP (port))
    port = scm_current_input_port ();
  /* It's possible to close the current input port, so validate even in
     this case. */
  SCM_VALIDATE_OPINPORT (1, port);

  read_buf = SCM_PORT (port)->read_buf;

  if (scm_port_buffer_can_take (read_buf, &tmp) ||
      scm_is_true (scm_port_buffer_has_eof_p (read_buf)))
    /* FIXME: Verify that a whole character is available?  */
    return SCM_BOOL_T;
  else
    {
      scm_t_port_type *ptob = SCM_PORT_TYPE (port);
      
      if (ptob->input_waiting)
        {
          SCM ret;
          scm_dynwind_begin (0);
          scm_dynwind_acquire_port (port);
          ret = scm_from_bool (ptob->input_waiting (port));
          scm_dynwind_end ();
          return ret;
        }
      else
	return SCM_BOOL_T;
    }
}
#undef FUNC_NAME

SCM_DEFINE (scm_seek, "seek", 3, 0, 0,
            (SCM fd_port, SCM offset, SCM whence),
	    "Sets the current position of @var{fd_port} to the integer\n"
	    "@var{offset}, which is interpreted according to the value of\n"
	    "@var{whence}.\n"
	    "\n"
	    "One of the following variables should be supplied for\n"
	    "@var{whence}:\n"
	    "@defvar SEEK_SET\n"
	    "Seek from the beginning of the file.\n"
	    "@end defvar\n"
	    "@defvar SEEK_CUR\n"
	    "Seek from the current position.\n"
	    "@end defvar\n"
	    "@defvar SEEK_END\n"
	    "Seek from the end of the file.\n"
	    "@end defvar\n"
	    "If @var{fd_port} is a file descriptor, the underlying system\n"
	    "call is @code{lseek}.  @var{port} may be a string port.\n"
	    "\n"
	    "The value returned is the new position in the file.  This means\n"
	    "that the current position of a port can be obtained using:\n"
	    "@lisp\n"
	    "(seek port 0 SEEK_CUR)\n"
	    "@end lisp")
#define FUNC_NAME s_scm_seek
{
  int how;

  fd_port = SCM_COERCE_OUTPORT (fd_port);

  how = scm_to_int (whence);
  if (how != SEEK_SET && how != SEEK_CUR && how != SEEK_END)
    SCM_OUT_OF_RANGE (3, whence);

  if (SCM_OPPORTP (fd_port))
    {
      scm_t_port *pt = SCM_PORT (fd_port);
      scm_t_port_type *ptob = SCM_PORT_TYPE (fd_port);
      scm_t_off off = scm_to_off_t (offset);
      scm_t_off rv;

      if (ptob->seek && how == SEEK_CUR && off == 0)
        {
          size_t tmp;
          /* If we are just querying the current position, avoid
             flushing buffers.  We don't even need to require that the
             port supports random access.  */
          scm_dynwind_begin (0);
          scm_dynwind_acquire_port (fd_port);
          rv = ptob->seek (fd_port, off, how);
          scm_dynwind_end ();
          rv -= scm_port_buffer_can_take (pt->read_buf, &tmp);
          rv += scm_port_buffer_can_take (pt->write_buf, &tmp);
          return scm_from_off_t (rv);
        }

      if (!ptob->seek || !pt->rw_random)
	SCM_MISC_ERROR ("port is not seekable", 
                        scm_cons (fd_port, SCM_EOL));

      scm_end_input (fd_port);
      scm_flush (fd_port);

      scm_dynwind_begin (0);
      scm_dynwind_acquire_port (fd_port);
      rv = ptob->seek (fd_port, off, how);
      scm_dynwind_end ();

      /* Set stream-start flags according to new position. */
      pt->at_stream_start_for_bom_read  = (rv == 0);
      pt->at_stream_start_for_bom_write = (rv == 0);

      scm_i_clear_pending_eof (fd_port);

      return scm_from_off_t (rv);
    }
  else /* file descriptor?.  */
    {
      off_t_or_off64_t off = scm_to_off_t_or_off64_t (offset);
      off_t_or_off64_t rv;
      rv = lseek_or_lseek64 (scm_to_int (fd_port), off, how);
      if (rv == -1)
	SCM_SYSERROR;
      return scm_from_off_t_or_off64_t (rv);
    }
}
#undef FUNC_NAME

#ifndef O_BINARY
#define O_BINARY 0
#endif

/* Mingw has ftruncate(), perhaps implemented above using chsize, but
   doesn't have the filename version truncate(), hence this code.  */
#if HAVE_FTRUNCATE && ! HAVE_TRUNCATE
static int
truncate (const char *file, off_t length)
{
  int ret, fdes;

  fdes = open (file, O_BINARY | O_WRONLY);
  if (fdes == -1)
    return -1;

  ret = ftruncate (fdes, length);
  if (ret == -1)
    {
      int save_errno = errno;
      close (fdes);
      errno = save_errno;
      return -1;
    }

  return close (fdes);
}
#endif /* HAVE_FTRUNCATE && ! HAVE_TRUNCATE */

SCM_DEFINE (scm_truncate_file, "truncate-file", 1, 1, 0,
            (SCM object, SCM length),
	    "Truncate file @var{object} to @var{length} bytes.  @var{object}\n"
	    "can be a filename string, a port object, or an integer file\n"
	    "descriptor.\n"
	    "The return value is unspecified.\n"
	    "\n"
	    "For a port or file descriptor @var{length} can be omitted, in\n"
	    "which case the file is truncated at the current position (per\n"
	    "@code{ftell} above).\n"
	    "\n"
	    "On most systems a file can be extended by giving a length\n"
	    "greater than the current size, but this is not mandatory in the\n"
	    "POSIX standard.")
#define FUNC_NAME s_scm_truncate_file
{
  int rv;

  /* "object" can be a port, fdes or filename.

     Negative "length" makes no sense, but it's left to truncate() or
     ftruncate() to give back an error for that (normally EINVAL).
     */

  if (SCM_UNBNDP (length))
    {
      /* must supply length if object is a filename.  */
      if (scm_is_string (object))
        SCM_MISC_ERROR("must supply length if OBJECT is a filename", SCM_EOL);
      
      length = scm_seek (object, SCM_INUM0, scm_from_int (SEEK_CUR));
    }

  object = SCM_COERCE_OUTPORT (object);
  if (scm_is_integer (object))
    {
      off_t_or_off64_t c_length = scm_to_off_t_or_off64_t (length);
      SCM_SYSCALL (rv = ftruncate_or_ftruncate64 (scm_to_int (object),
                                                  c_length));
    }
  else if (SCM_OPOUTPORTP (object))
    {
      scm_t_off c_length = scm_to_off_t (length);
      scm_t_port_type *ptob = SCM_PORT_TYPE (object);

      if (!ptob->truncate)
	SCM_MISC_ERROR ("port is not truncatable", SCM_EOL);

      scm_i_clear_pending_eof (object);

      if (SCM_INPUT_PORT_P (object)
          && SCM_PORT (object)->rw_random)
        scm_end_input (object);
      scm_flush (object);

      scm_dynwind_begin (0);
      scm_dynwind_acquire_port (object);
      ptob->truncate (object, c_length);
      scm_dynwind_end ();
      rv = 0;
    }
  else
    {
      off_t_or_off64_t c_length = scm_to_off_t_or_off64_t (length);
      char *str = scm_to_locale_string (object);
      int eno;
      SCM_SYSCALL (rv = truncate_or_truncate64 (str, c_length));
      eno = errno;
      free (str);
      errno = eno;
    }
  if (rv == -1)
    SCM_SYSERROR;
  return SCM_UNSPECIFIED;
}
#undef FUNC_NAME

SCM_DEFINE (scm_port_line, "port-line", 1, 0, 0,
            (SCM port),
	    "Return the current line number for @var{port}.\n"
	    "\n"
	    "The first line of a file is 0.  But you might want to add 1\n"
	    "when printing line numbers, since starting from 1 is\n"
	    "traditional in error messages, and likely to be more natural to\n"
	    "non-programmers.")
#define FUNC_NAME s_scm_port_line
{
  port = SCM_COERCE_OUTPORT (port);
  SCM_VALIDATE_OPENPORT (1, port);
  return scm_port_position_line (SCM_PORT (port)->position);
}
#undef FUNC_NAME

SCM_DEFINE (scm_set_port_line_x, "set-port-line!", 2, 0, 0,
            (SCM port, SCM line),
	    "Set the current line number for @var{port} to @var{line}.  The\n"
	    "first line of a file is 0.")
#define FUNC_NAME s_scm_set_port_line_x
{
  port = SCM_COERCE_OUTPORT (port);
  SCM_VALIDATE_OPENPORT (1, port);
  scm_to_long (line);
  scm_port_position_set_line (SCM_PORT (port)->position, line);
  return SCM_UNSPECIFIED;
}
#undef FUNC_NAME

SCM_DEFINE (scm_port_column, "port-column", 1, 0, 0,
            (SCM port),
	    "Return the current column number of @var{port}.\n"
	    "If the number is\n"
	    "unknown, the result is #f.  Otherwise, the result is a 0-origin integer\n"
	    "- i.e. the first character of the first line is line 0, column 0.\n"
	    "(However, when you display a file position, for example in an error\n"
	    "message, we recommend you add 1 to get 1-origin integers.  This is\n"
	    "because lines and column numbers traditionally start with 1, and that is\n"
	    "what non-programmers will find most natural.)")
#define FUNC_NAME s_scm_port_column
{
  port = SCM_COERCE_OUTPORT (port);
  SCM_VALIDATE_OPENPORT (1, port);
  return scm_port_position_column (SCM_PORT (port)->position);
}
#undef FUNC_NAME

SCM_DEFINE (scm_set_port_column_x, "set-port-column!", 2, 0, 0,
            (SCM port, SCM column),
	    "Set the current column of @var{port}.  Before reading the first\n"
	    "character on a line the column should be 0.")
#define FUNC_NAME s_scm_set_port_column_x
{
  port = SCM_COERCE_OUTPORT (port);
  SCM_VALIDATE_OPENPORT (1, port);
  scm_to_int (column);
  scm_port_position_set_column (SCM_PORT (port)->position, column);
  return SCM_UNSPECIFIED;
}
#undef FUNC_NAME

SCM_DEFINE (scm_port_filename, "port-filename", 1, 0, 0,
            (SCM port),
	    "Return the filename associated with @var{port}, or @code{#f}\n"
	    "if no filename is associated with the port.")
#define FUNC_NAME s_scm_port_filename
{
  port = SCM_COERCE_OUTPORT (port);
  SCM_VALIDATE_OPENPORT (1, port);
  return SCM_FILENAME (port);
}
#undef FUNC_NAME

SCM_DEFINE (scm_set_port_filename_x, "set-port-filename!", 2, 0, 0,
            (SCM port, SCM filename),
	    "Change the filename associated with @var{port}, using the current input\n"
	    "port if none is specified.  Note that this does not change the port's\n"
	    "source of data, but only the value that is returned by\n"
	    "@code{port-filename} and reported in diagnostic output.")
#define FUNC_NAME s_scm_set_port_filename_x
{
  port = SCM_COERCE_OUTPORT (port);
  SCM_VALIDATE_OPENPORT (1, port);
  /* We allow the user to set the filename to whatever he likes.  */
  SCM_SET_FILENAME (port, filename);
  return SCM_UNSPECIFIED;
}
#undef FUNC_NAME




/* Implementation helpers for port printing functions.  */

void
scm_print_port_mode (SCM exp, SCM port)
{
  scm_puts (SCM_CLOSEDP (exp)
	    ? "closed: "
	    : (SCM_RDNG & SCM_CELL_WORD_0 (exp)
	       ? (SCM_WRTNG & SCM_CELL_WORD_0 (exp)
		  ? "input-output: "
		  : "input: ")
	       : (SCM_WRTNG & SCM_CELL_WORD_0 (exp)
		  ? "output: "
		  : "bogus: ")),
	    port);
}

int
scm_port_print (SCM exp, SCM port, scm_print_state *pstate SCM_UNUSED)
{
  char *type = SCM_PORT_TYPE (port)->name;
  if (!type)
    type = "port";
  scm_puts ("#<", port);
  scm_print_port_mode (exp, port);
  scm_puts (type, port);
  scm_putc (' ', port);
  scm_uintprint ((scm_t_bits) SCM_PORT (exp), 16, port);
  scm_putc ('>', port);
  return 1;
}




/* Iterating over all ports.  */

struct for_each_data 
{
  void (*proc) (void *data, SCM p);
  void *data;
};

static SCM
for_each_trampoline (void *data, SCM port, SCM result)
{
  struct for_each_data *d = data;
  
  d->proc (d->data, port);

  return result;
}

void
scm_c_port_for_each (void (*proc)(void *data, SCM p), void *data)
{
  struct for_each_data d;
  
  d.proc = proc;
  d.data = data;

  scm_c_weak_set_fold (for_each_trampoline, &d, SCM_EOL,
                       scm_i_port_weak_set);
}

static void
scm_for_each_trampoline (void *data, SCM port)
{
  scm_call_1 (SCM_PACK_POINTER (data), port);
}

SCM_DEFINE (scm_port_for_each, "port-for-each", 1, 0, 0,
	    (SCM proc),
	    "Apply @var{proc} to each port in the Guile port table\n"
	    "in turn.  The return value is unspecified.  More specifically,\n"
	    "@var{proc} is applied exactly once to every port that exists\n"
	    "in the system at the time @code{port-for-each} is invoked.\n"
	    "Changes to the port table while @code{port-for-each} is running\n"
	    "have no effect as far as @code{port-for-each} is concerned.") 
#define FUNC_NAME s_scm_port_for_each
{
  SCM_VALIDATE_PROC (1, proc);

  scm_c_port_for_each (scm_for_each_trampoline, SCM_UNPACK_POINTER (proc));
  
  return SCM_UNSPECIFIED;
}
#undef FUNC_NAME

static void
flush_output_port (void *closure, SCM port)
{
  if (SCM_OPOUTPORTP (port))
    scm_flush (port);
}

SCM_DEFINE (scm_flush_all_ports, "flush-all-ports", 0, 0, 0,
            (),
	    "Equivalent to calling @code{force-output} on\n"
	    "all open output ports.  The return value is unspecified.")
#define FUNC_NAME s_scm_flush_all_ports
{
  scm_c_port_for_each (&flush_output_port, NULL);
  return SCM_UNSPECIFIED;
}
#undef FUNC_NAME




/* Void ports.   */

scm_t_port_type *scm_void_port_type = 0;

static size_t
void_port_read (SCM port, SCM dst, size_t start, size_t count)
{
  return 0;
}

static size_t
void_port_write (SCM port, SCM src, size_t start, size_t count)
{
  return count;
}

static SCM
scm_i_void_port (long mode_bits)
{
  return scm_c_make_port (scm_void_port_type, mode_bits, 0);
}

SCM
scm_void_port (char *mode_str)
{
  return scm_i_void_port (scm_mode_bits (mode_str));
}

SCM_DEFINE (scm_sys_make_void_port, "%make-void-port", 1, 0, 0,
            (SCM mode),
	    "Create and return a new void port.  A void port acts like\n"
	    "@file{/dev/null}.  The @var{mode} argument\n"
	    "specifies the input/output modes for this port: see the\n"
	    "documentation for @code{open-file} in @ref{File Ports}.")
#define FUNC_NAME s_scm_sys_make_void_port
{
  return scm_i_void_port (scm_i_mode_bits (mode));
}
#undef FUNC_NAME




/* Initialization.  */

static void
scm_init_ice_9_ports (void)
{
#include "ports.x"

  scm_c_define ("the-eof-object", SCM_EOF_VAL);

  /* lseek() symbols.  */
  scm_c_define ("SEEK_SET", scm_from_int (SEEK_SET));
  scm_c_define ("SEEK_CUR", scm_from_int (SEEK_CUR));
  scm_c_define ("SEEK_END", scm_from_int (SEEK_END));

  scm_c_define ("%current-input-port-fluid", cur_inport_fluid);
  scm_c_define ("%current-output-port-fluid", cur_outport_fluid);
  scm_c_define ("%current-error-port-fluid", cur_errport_fluid);
  scm_c_define ("%current-warning-port-fluid", cur_warnport_fluid);
}

void
scm_init_ports (void)
{
  sym_UTF_8 = scm_from_latin1_symbol ("UTF-8");
  sym_ISO_8859_1 = scm_from_latin1_symbol ("ISO-8859-1");
  sym_UTF_16 = scm_from_latin1_symbol ("UTF-16");
  sym_UTF_16LE = scm_from_latin1_symbol ("UTF-16LE");
  sym_UTF_16BE = scm_from_latin1_symbol ("UTF-16BE");
  sym_UTF_32 = scm_from_latin1_symbol ("UTF-32");
  sym_UTF_32LE = scm_from_latin1_symbol ("UTF-32LE");
  sym_UTF_32BE = scm_from_latin1_symbol ("UTF-32BE");

  sym_substitute = scm_from_latin1_symbol ("substitute");
  sym_escape = scm_from_latin1_symbol ("escape");
  sym_error = scm_from_latin1_symbol ("error");

  trampoline_to_c_read_subr =
    scm_c_make_gsubr ("port-read", 4, 0, 0,
                      (scm_t_subr) trampoline_to_c_read);
  trampoline_to_c_write_subr =
    scm_c_make_gsubr ("port-write", 4, 0, 0,
                      (scm_t_subr) trampoline_to_c_write);

  scm_void_port_type = scm_make_port_type ("void", void_port_read,
					   void_port_write);

  scm_i_port_weak_set = scm_c_make_weak_set (31);

  cur_inport_fluid = scm_make_fluid ();
  cur_outport_fluid = scm_make_fluid ();
  cur_errport_fluid = scm_make_fluid ();
  cur_warnport_fluid = scm_make_fluid ();
  cur_loadport_fluid = scm_make_fluid ();

  default_port_encoding_var =
    scm_c_define ("%default-port-encoding",
                  scm_make_fluid_with_default (SCM_BOOL_F));
  default_conversion_strategy_var =
    scm_c_define ("%default-port-conversion-strategy",
                  scm_make_fluid_with_default (sym_substitute));
  /* Use the locale as the default port encoding.  */
  scm_i_set_default_port_encoding (locale_charset ());

  scm_c_register_extension ("libguile-" SCM_EFFECTIVE_VERSION,
                            "scm_init_ice_9_ports",
			    (scm_t_extension_init_func) scm_init_ice_9_ports,
			    NULL);

  /* The following bindings are used early in boot-9.scm.  */

  /* Used by `include'.  */
  scm_c_define_gsubr ("set-port-encoding!", 2, 0, 0,
                      (scm_t_subr) scm_set_port_encoding_x);
  scm_c_define_gsubr (s_scm_eof_object_p, 1, 0, 0,
                      (scm_t_subr) scm_eof_object_p);

  /* Used by a number of error/warning-printing routines.  */
  scm_c_define_gsubr (s_scm_force_output, 0, 1, 0,
                      (scm_t_subr) scm_force_output);

  /* Used by `file-exists?' and related functions if `stat' is
     unavailable.  */
  scm_c_define_gsubr (s_scm_close_port, 1, 0, 0,
                      (scm_t_subr) scm_close_port);

  /* Used by error routines.  */
  scm_c_define_gsubr (s_scm_current_error_port, 0, 0, 0,
                      (scm_t_subr) scm_current_error_port);
  scm_c_define_gsubr (s_scm_current_warning_port, 0, 0, 0,
                      (scm_t_subr) scm_current_warning_port);
}