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
|
/**********************************************************************
io_buffer.c
Copyright (C) 2021 Samuel Grant Dawson Williams
**********************************************************************/
#include "ruby/io.h"
#include "ruby/io/buffer.h"
#include "ruby/fiber/scheduler.h"
#include "internal.h"
#include "internal/array.h"
#include "internal/bits.h"
#include "internal/error.h"
#include "internal/numeric.h"
#include "internal/string.h"
#include "internal/thread.h"
VALUE rb_cIOBuffer;
VALUE rb_eIOBufferLockedError;
VALUE rb_eIOBufferAllocationError;
VALUE rb_eIOBufferAccessError;
VALUE rb_eIOBufferInvalidatedError;
VALUE rb_eIOBufferMaskError;
size_t RUBY_IO_BUFFER_PAGE_SIZE;
size_t RUBY_IO_BUFFER_DEFAULT_SIZE;
#ifdef _WIN32
#else
#include <unistd.h>
#include <sys/mman.h>
#endif
struct rb_io_buffer {
void *base;
size_t size;
enum rb_io_buffer_flags flags;
#if defined(_WIN32)
HANDLE mapping;
#endif
VALUE source;
};
static inline void *
io_buffer_map_memory(size_t size, int flags)
{
#if defined(_WIN32)
void * base = VirtualAlloc(0, size, MEM_COMMIT, PAGE_READWRITE);
if (!base) {
rb_sys_fail("io_buffer_map_memory:VirtualAlloc");
}
#else
int mmap_flags = MAP_ANONYMOUS;
if (flags & RB_IO_BUFFER_SHARED) {
mmap_flags |= MAP_SHARED;
}
else {
mmap_flags |= MAP_PRIVATE;
}
void * base = mmap(NULL, size, PROT_READ | PROT_WRITE, mmap_flags, -1, 0);
if (base == MAP_FAILED) {
rb_sys_fail("io_buffer_map_memory:mmap");
}
#endif
return base;
}
static void
io_buffer_map_file(struct rb_io_buffer *data, int descriptor, size_t size, rb_off_t offset, enum rb_io_buffer_flags flags)
{
#if defined(_WIN32)
HANDLE file = (HANDLE)_get_osfhandle(descriptor);
if (!file) rb_sys_fail("io_buffer_map_descriptor:_get_osfhandle");
DWORD protect = PAGE_READONLY, access = FILE_MAP_READ;
if (flags & RB_IO_BUFFER_READONLY) {
data->flags |= RB_IO_BUFFER_READONLY;
}
else {
protect = PAGE_READWRITE;
access = FILE_MAP_WRITE;
}
HANDLE mapping = CreateFileMapping(file, NULL, protect, 0, 0, NULL);
if (!mapping) rb_sys_fail("io_buffer_map_descriptor:CreateFileMapping");
if (flags & RB_IO_BUFFER_PRIVATE) {
access |= FILE_MAP_COPY;
data->flags |= RB_IO_BUFFER_PRIVATE;
}
else {
// This buffer refers to external data.
data->flags |= RB_IO_BUFFER_EXTERNAL;
data->flags |= RB_IO_BUFFER_SHARED;
}
void *base = MapViewOfFile(mapping, access, (DWORD)(offset >> 32), (DWORD)(offset & 0xFFFFFFFF), size);
if (!base) {
CloseHandle(mapping);
rb_sys_fail("io_buffer_map_file:MapViewOfFile");
}
data->mapping = mapping;
#else
int protect = PROT_READ, access = 0;
if (flags & RB_IO_BUFFER_READONLY) {
data->flags |= RB_IO_BUFFER_READONLY;
}
else {
protect |= PROT_WRITE;
}
if (flags & RB_IO_BUFFER_PRIVATE) {
data->flags |= RB_IO_BUFFER_PRIVATE;
}
else {
// This buffer refers to external data.
data->flags |= RB_IO_BUFFER_EXTERNAL;
data->flags |= RB_IO_BUFFER_SHARED;
access |= MAP_SHARED;
}
void *base = mmap(NULL, size, protect, access, descriptor, offset);
if (base == MAP_FAILED) {
rb_sys_fail("io_buffer_map_file:mmap");
}
#endif
data->base = base;
data->size = size;
data->flags |= RB_IO_BUFFER_MAPPED;
}
static inline void
io_buffer_unmap(void* base, size_t size)
{
#ifdef _WIN32
VirtualFree(base, 0, MEM_RELEASE);
#else
munmap(base, size);
#endif
}
static void
io_buffer_experimental(void)
{
static int warned = 0;
if (warned) return;
warned = 1;
if (rb_warning_category_enabled_p(RB_WARN_CATEGORY_EXPERIMENTAL)) {
rb_category_warn(RB_WARN_CATEGORY_EXPERIMENTAL,
"IO::Buffer is experimental and both the Ruby and C interface may change in the future!"
);
}
}
static void
io_buffer_zero(struct rb_io_buffer *data)
{
data->base = NULL;
data->size = 0;
#if defined(_WIN32)
data->mapping = NULL;
#endif
data->source = Qnil;
}
static void
io_buffer_initialize(struct rb_io_buffer *data, void *base, size_t size, enum rb_io_buffer_flags flags, VALUE source)
{
if (base) {
// If we are provided a pointer, we use it.
}
else if (size) {
// If we are provided a non-zero size, we allocate it:
if (flags & RB_IO_BUFFER_INTERNAL) {
base = calloc(size, 1);
}
else if (flags & RB_IO_BUFFER_MAPPED) {
base = io_buffer_map_memory(size, flags);
}
if (!base) {
rb_raise(rb_eIOBufferAllocationError, "Could not allocate buffer!");
}
}
else {
// Otherwise we don't do anything.
return;
}
data->base = base;
data->size = size;
data->flags = flags;
data->source = source;
}
static int
io_buffer_free(struct rb_io_buffer *data)
{
if (data->base) {
if (data->flags & RB_IO_BUFFER_INTERNAL) {
free(data->base);
}
if (data->flags & RB_IO_BUFFER_MAPPED) {
io_buffer_unmap(data->base, data->size);
}
// Previously we had this, but we found out due to the way GC works, we
// can't refer to any other Ruby objects here.
// if (RB_TYPE_P(data->source, T_STRING)) {
// rb_str_unlocktmp(data->source);
// }
data->base = NULL;
#if defined(_WIN32)
if (data->mapping) {
CloseHandle(data->mapping);
data->mapping = NULL;
}
#endif
data->size = 0;
data->flags = 0;
data->source = Qnil;
return 1;
}
return 0;
}
void
rb_io_buffer_type_mark(void *_data)
{
struct rb_io_buffer *data = _data;
rb_gc_mark(data->source);
}
void
rb_io_buffer_type_free(void *_data)
{
struct rb_io_buffer *data = _data;
io_buffer_free(data);
free(data);
}
size_t
rb_io_buffer_type_size(const void *_data)
{
const struct rb_io_buffer *data = _data;
size_t total = sizeof(struct rb_io_buffer);
if (data->flags) {
total += data->size;
}
return total;
}
static const rb_data_type_t rb_io_buffer_type = {
.wrap_struct_name = "IO::Buffer",
.function = {
.dmark = rb_io_buffer_type_mark,
.dfree = rb_io_buffer_type_free,
.dsize = rb_io_buffer_type_size,
},
.data = NULL,
.flags = RUBY_TYPED_FREE_IMMEDIATELY,
};
VALUE
rb_io_buffer_type_allocate(VALUE self)
{
struct rb_io_buffer *data = NULL;
VALUE instance = TypedData_Make_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
io_buffer_zero(data);
return instance;
}
static VALUE
io_buffer_for_make_instance(VALUE klass, VALUE string)
{
VALUE instance = rb_io_buffer_type_allocate(klass);
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(instance, struct rb_io_buffer, &rb_io_buffer_type, data);
enum rb_io_buffer_flags flags = RB_IO_BUFFER_EXTERNAL;
if (RB_OBJ_FROZEN(string))
flags |= RB_IO_BUFFER_READONLY;
io_buffer_initialize(data, RSTRING_PTR(string), RSTRING_LEN(string), flags, string);
return instance;
}
struct io_buffer_for_yield_instance_arguments {
VALUE klass;
VALUE string;
VALUE instance;
};
static VALUE
io_buffer_for_yield_instance(VALUE _arguments)
{
struct io_buffer_for_yield_instance_arguments *arguments = (struct io_buffer_for_yield_instance_arguments *)_arguments;
rb_str_locktmp(arguments->string);
arguments->instance = io_buffer_for_make_instance(arguments->klass, arguments->string);
return rb_yield(arguments->instance);
}
static VALUE
io_buffer_for_yield_instance_ensure(VALUE _arguments)
{
struct io_buffer_for_yield_instance_arguments *arguments = (struct io_buffer_for_yield_instance_arguments *)_arguments;
if (arguments->instance != Qnil) {
rb_io_buffer_free(arguments->instance);
}
rb_str_unlocktmp(arguments->string);
return Qnil;
}
/*
* call-seq:
* IO::Buffer.for(string) -> readonly io_buffer
* IO::Buffer.for(string) {|io_buffer| ... read/write io_buffer ...}
*
* Creates a IO::Buffer from the given string's memory. Without a block a
* frozen internal copy of the string is created efficiently and used as the
* buffer source. When a block is provided, the buffer is associated directly
* with the string's internal data and updating the buffer will update the
* string.
*
* Until #free is invoked on the buffer, either explicitly or via the garbage
* collector, the source string will be locked and cannot be modified.
*
* If the string is frozen, it will create a read-only buffer which cannot be
* modified.
*
* string = 'test'
* buffer = IO::Buffer.for(string)
* buffer.external? #=> true
*
* buffer.get_string(0, 1)
* # => "t"
* string
* # => "best"
*
* buffer.resize(100)
* # in `resize': Cannot resize external buffer! (IO::Buffer::AccessError)
*
* IO::Buffer.for(string) do |buffer|
* buffer.set_string("T")
* string
* # => "Test"
* end
*/
VALUE
rb_io_buffer_type_for(VALUE klass, VALUE string)
{
StringValue(string);
// If the string is frozen, both code paths are okay.
// If the string is not frozen, if a block is not given, it must be frozen.
if (rb_block_given_p()) {
struct io_buffer_for_yield_instance_arguments arguments = {
.klass = klass,
.string = string,
.instance = Qnil,
};
return rb_ensure(io_buffer_for_yield_instance, (VALUE)&arguments, io_buffer_for_yield_instance_ensure, (VALUE)&arguments);
}
else {
// This internally returns the source string if it's already frozen.
string = rb_str_tmp_frozen_acquire(string);
return io_buffer_for_make_instance(klass, string);
}
}
/*
* call-seq:
* IO::Buffer.string(length) {|io_buffer| ... read/write io_buffer ...} -> string
*
* Creates a new string of the given length and yields a IO::Buffer instance
* to the block which uses the string as a source. The block is expected to
* write to the buffer and the string will be returned.
*
* IO::Buffer.string(4) do |buffer|
* buffer.set_string("Ruby")
* end
* # => "Ruby"
*/
VALUE
rb_io_buffer_type_string(VALUE klass, VALUE length)
{
VALUE string = rb_str_new(NULL, RB_NUM2LONG(length));
struct io_buffer_for_yield_instance_arguments arguments = {
.klass = klass,
.string = string,
.instance = Qnil,
};
rb_ensure(io_buffer_for_yield_instance, (VALUE)&arguments, io_buffer_for_yield_instance_ensure, (VALUE)&arguments);
return string;
}
VALUE
rb_io_buffer_new(void *base, size_t size, enum rb_io_buffer_flags flags)
{
VALUE instance = rb_io_buffer_type_allocate(rb_cIOBuffer);
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(instance, struct rb_io_buffer, &rb_io_buffer_type, data);
io_buffer_initialize(data, base, size, flags, Qnil);
return instance;
}
VALUE
rb_io_buffer_map(VALUE io, size_t size, rb_off_t offset, enum rb_io_buffer_flags flags)
{
io_buffer_experimental();
VALUE instance = rb_io_buffer_type_allocate(rb_cIOBuffer);
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(instance, struct rb_io_buffer, &rb_io_buffer_type, data);
int descriptor = rb_io_descriptor(io);
io_buffer_map_file(data, descriptor, size, offset, flags);
return instance;
}
/*
* call-seq: IO::Buffer.map(file, [size, [offset, [flags]]]) -> io_buffer
*
* Create an IO::Buffer for reading from +file+ by memory-mapping the file.
* +file_io+ should be a +File+ instance, opened for reading.
*
* Optional +size+ and +offset+ of mapping can be specified.
*
* By default, the buffer would be immutable (read only); to create a writable
* mapping, you need to open a file in read-write mode, and explicitly pass
* +flags+ argument without IO::Buffer::IMMUTABLE.
*
* Example:
*
* File.write('test.txt', 'test')
*
* buffer = IO::Buffer.map(File.open('test.txt'), nil, 0, IO::Buffer::READONLY)
* # => #<IO::Buffer 0x00000001014a0000+4 MAPPED READONLY>
*
* buffer.readonly? # => true
*
* buffer.get_string
* # => "test"
*
* buffer.set_string('b', 0)
* # `set_string': Buffer is not writable! (IO::Buffer::AccessError)
*
* # create read/write mapping: length 4 bytes, offset 0, flags 0
* buffer = IO::Buffer.map(File.open('test.txt', 'r+'), 4, 0)
* buffer.set_string('b', 0)
* # => 1
*
* # Check it
* File.read('test.txt')
* # => "best"
*
* Note that some operating systems may not have cache coherency between mapped
* buffers and file reads.
*/
static VALUE
io_buffer_map(int argc, VALUE *argv, VALUE klass)
{
rb_check_arity(argc, 1, 4);
// We might like to handle a string path?
VALUE io = argv[0];
size_t size;
if (argc >= 2 && !RB_NIL_P(argv[1])) {
size = RB_NUM2SIZE(argv[1]);
}
else {
rb_off_t file_size = rb_file_size(io);
// Compiler can confirm that we handled file_size < 0 case:
if (file_size < 0) {
rb_raise(rb_eArgError, "Invalid negative file size!");
}
// Here, we assume that file_size is positive:
else if ((uintmax_t)file_size > SIZE_MAX) {
rb_raise(rb_eArgError, "File larger than address space!");
}
else {
// This conversion should be safe:
size = (size_t)file_size;
}
}
rb_off_t offset = 0;
if (argc >= 3) {
offset = NUM2OFFT(argv[2]);
}
enum rb_io_buffer_flags flags = 0;
if (argc >= 4) {
flags = RB_NUM2UINT(argv[3]);
}
return rb_io_buffer_map(io, size, offset, flags);
}
// Compute the optimal allocation flags for a buffer of the given size.
static inline enum rb_io_buffer_flags
io_flags_for_size(size_t size)
{
if (size >= RUBY_IO_BUFFER_PAGE_SIZE) {
return RB_IO_BUFFER_MAPPED;
}
return RB_IO_BUFFER_INTERNAL;
}
/*
* call-seq: IO::Buffer.new([size = DEFAULT_SIZE, [flags = 0]]) -> io_buffer
*
* Create a new zero-filled IO::Buffer of +size+ bytes.
* By default, the buffer will be _internal_: directly allocated chunk
* of the memory. But if the requested +size+ is more than OS-specific
* IO::Buffer::PAGE_SIZE, the buffer would be allocated using the
* virtual memory mechanism (anonymous +mmap+ on Unix, +VirtualAlloc+
* on Windows). The behavior can be forced by passing IO::Buffer::MAPPED
* as a second parameter.
*
* Examples
*
* buffer = IO::Buffer.new(4)
* # =>
* # #<IO::Buffer 0x000055b34497ea10+4 INTERNAL>
* # 0x00000000 00 00 00 00 ....
*
* buffer.get_string(0, 1) # => "\x00"
*
* buffer.set_string("test")
* buffer
* # =>
* # #<IO::Buffer 0x000055b34497ea10+4 INTERNAL>
* # 0x00000000 74 65 73 74 test
*/
VALUE
rb_io_buffer_initialize(int argc, VALUE *argv, VALUE self)
{
io_buffer_experimental();
rb_check_arity(argc, 0, 2);
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
size_t size;
if (argc > 0) {
size = RB_NUM2SIZE(argv[0]);
}
else {
size = RUBY_IO_BUFFER_DEFAULT_SIZE;
}
enum rb_io_buffer_flags flags = 0;
if (argc >= 2) {
flags = RB_NUM2UINT(argv[1]);
}
else {
flags |= io_flags_for_size(size);
}
io_buffer_initialize(data, NULL, size, flags, Qnil);
return self;
}
static int
io_buffer_validate_slice(VALUE source, void *base, size_t size)
{
void *source_base = NULL;
size_t source_size = 0;
if (RB_TYPE_P(source, T_STRING)) {
RSTRING_GETMEM(source, source_base, source_size);
}
else {
rb_io_buffer_get_bytes(source, &source_base, &source_size);
}
// Source is invalid:
if (source_base == NULL) return 0;
// Base is out of range:
if (base < source_base) return 0;
const void *source_end = (char*)source_base + source_size;
const void *end = (char*)base + size;
// End is out of range:
if (end > source_end) return 0;
// It seems okay:
return 1;
}
static int
io_buffer_validate(struct rb_io_buffer *data)
{
if (data->source != Qnil) {
// Only slices incur this overhead, unfortunately... better safe than sorry!
return io_buffer_validate_slice(data->source, data->base, data->size);
}
else {
return 1;
}
}
/*
* call-seq: to_s -> string
*
* Short representation of the buffer. It includes the address, size and
* symbolic flags. This format is subject to change.
*
* puts IO::Buffer.new(4) # uses to_s internally
* # #<IO::Buffer 0x000055769f41b1a0+4 INTERNAL>
*/
VALUE
rb_io_buffer_to_s(VALUE self)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
VALUE result = rb_str_new_cstr("#<");
rb_str_append(result, rb_class_name(CLASS_OF(self)));
rb_str_catf(result, " %p+%"PRIdSIZE, data->base, data->size);
if (data->base == NULL) {
rb_str_cat2(result, " NULL");
}
if (data->flags & RB_IO_BUFFER_EXTERNAL) {
rb_str_cat2(result, " EXTERNAL");
}
if (data->flags & RB_IO_BUFFER_INTERNAL) {
rb_str_cat2(result, " INTERNAL");
}
if (data->flags & RB_IO_BUFFER_MAPPED) {
rb_str_cat2(result, " MAPPED");
}
if (data->flags & RB_IO_BUFFER_SHARED) {
rb_str_cat2(result, " SHARED");
}
if (data->flags & RB_IO_BUFFER_LOCKED) {
rb_str_cat2(result, " LOCKED");
}
if (data->flags & RB_IO_BUFFER_READONLY) {
rb_str_cat2(result, " READONLY");
}
if (data->source != Qnil) {
rb_str_cat2(result, " SLICE");
}
if (!io_buffer_validate(data)) {
rb_str_cat2(result, " INVALID");
}
return rb_str_cat2(result, ">");
}
static VALUE
io_buffer_hexdump(VALUE string, size_t width, char *base, size_t size, int first)
{
char *text = alloca(width+1);
text[width] = '\0';
for (size_t offset = 0; offset < size; offset += width) {
memset(text, '\0', width);
if (first) {
rb_str_catf(string, "0x%08" PRIxSIZE " ", offset);
first = 0;
}
else {
rb_str_catf(string, "\n0x%08" PRIxSIZE " ", offset);
}
for (size_t i = 0; i < width; i += 1) {
if (offset+i < size) {
unsigned char value = ((unsigned char*)base)[offset+i];
if (value < 127 && isprint(value)) {
text[i] = (char)value;
}
else {
text[i] = '.';
}
rb_str_catf(string, " %02x", value);
}
else {
rb_str_cat2(string, " ");
}
}
rb_str_catf(string, " %s", text);
}
return string;
}
static VALUE
rb_io_buffer_hexdump(VALUE self)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
VALUE result = Qnil;
if (io_buffer_validate(data) && data->base) {
result = rb_str_buf_new(data->size*3 + (data->size/16)*12 + 1);
io_buffer_hexdump(result, 16, data->base, data->size, 1);
}
return result;
}
VALUE
rb_io_buffer_inspect(VALUE self)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
VALUE result = rb_io_buffer_to_s(self);
if (io_buffer_validate(data)) {
// Limit the maximum size generated by inspect.
if (data->size <= 256) {
io_buffer_hexdump(result, 16, data->base, data->size, 0);
}
}
return result;
}
/*
* call-seq: size -> integer
*
* Returns the size of the buffer that was explicitly set (on creation with ::new
* or on #resize), or deduced on buffer's creation from string or file.
*/
VALUE
rb_io_buffer_size(VALUE self)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
return SIZET2NUM(data->size);
}
/*
* call-seq: valid? -> true or false
*
* Returns whether the buffer data is accessible.
*
* A buffer becomes invalid if it is a slice of another buffer which has been
* freed.
*/
static VALUE
rb_io_buffer_valid_p(VALUE self)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
return RBOOL(io_buffer_validate(data));
}
/*
* call-seq: null? -> true or false
*
* If the buffer was freed with #free or was never allocated in the first
* place.
*/
static VALUE
rb_io_buffer_null_p(VALUE self)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
return RBOOL(data->base == NULL);
}
/*
* call-seq: empty? -> true or false
*
* If the buffer has 0 size: it is created by ::new with size 0, or with ::for
* from an empty string. (Note that empty files can't be mapped, so the buffer
* created with ::map will never be empty.)
*/
static VALUE
rb_io_buffer_empty_p(VALUE self)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
return RBOOL(data->size == 0);
}
/*
* call-seq: external? -> true or false
*
* The buffer is _external_ if it references the memory which is not
* allocated or mapped by the buffer itself.
*
* A buffer created using ::for has an external reference to the string's
* memory.
*
* External buffer can't be resized.
*/
static VALUE
rb_io_buffer_external_p(VALUE self)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
return RBOOL(data->flags & RB_IO_BUFFER_EXTERNAL);
}
/*
* call-seq: internal? -> true or false
*
* If the buffer is _internal_, meaning it references memory allocated by the
* buffer itself.
*
* An internal buffer is not associated with any external memory (e.g. string)
* or file mapping.
*
* Internal buffers are created using ::new and is the default when the
* requested size is less than the IO::Buffer::PAGE_SIZE and it was not
* requested to be mapped on creation.
*
* Internal buffers can be resized, and such an operation will typically
* invalidate all slices, but not always.
*/
static VALUE
rb_io_buffer_internal_p(VALUE self)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
return RBOOL(data->flags & RB_IO_BUFFER_INTERNAL);
}
/*
* call-seq: mapped? -> true or false
*
* If the buffer is _mapped_, meaning it references memory mapped by the
* buffer.
*
* Mapped buffers are either anonymous, if created by ::new with the
* IO::Buffer::MAPPED flag or if the size was at least IO::Buffer::PAGE_SIZE,
* or backed by a file if created with ::map.
*
* Mapped buffers can usually be resized, and such an operation will typically
* invalidate all slices, but not always.
*/
static VALUE
rb_io_buffer_mapped_p(VALUE self)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
return RBOOL(data->flags & RB_IO_BUFFER_MAPPED);
}
/*
* call-seq: shared? -> true or false
*
* If the buffer is _shared_, meaning it references memory that can be shared
* with other processes (and thus might change without being modified
* locally).
*/
static VALUE
rb_io_buffer_shared_p(VALUE self)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
return RBOOL(data->flags & RB_IO_BUFFER_SHARED);
}
/*
* call-seq: locked? -> true or false
*
* If the buffer is _locked_, meaning it is inside #locked block execution.
* Locked buffer can't be resized or freed, and another lock can't be acquired
* on it.
*
* Locking is not thread safe, but is a semantic used to ensure buffers don't
* move while being used by a system call.
*
* Example:
*
* buffer.locked do
* buffer.write(io) # theoretical system call interface
* end
*/
static VALUE
rb_io_buffer_locked_p(VALUE self)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
return RBOOL(data->flags & RB_IO_BUFFER_LOCKED);
}
int
rb_io_buffer_readonly_p(VALUE self)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
return data->flags & RB_IO_BUFFER_READONLY;
}
/*
* call-seq: readonly? -> true or false
*
* If the buffer is <i>read only</i>, meaning the buffer cannot be modified using
* #set_value, #set_string or #copy and similar.
*
* Frozen strings and read-only files create read-only buffers.
*/
static VALUE
io_buffer_readonly_p(VALUE self)
{
return RBOOL(rb_io_buffer_readonly_p(self));
}
VALUE
rb_io_buffer_lock(VALUE self)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
if (data->flags & RB_IO_BUFFER_LOCKED) {
rb_raise(rb_eIOBufferLockedError, "Buffer already locked!");
}
data->flags |= RB_IO_BUFFER_LOCKED;
return self;
}
static void
io_buffer_unlock(struct rb_io_buffer *data)
{
if (!(data->flags & RB_IO_BUFFER_LOCKED)) {
rb_raise(rb_eIOBufferLockedError, "Buffer not locked!");
}
data->flags &= ~RB_IO_BUFFER_LOCKED;
}
VALUE
rb_io_buffer_unlock(VALUE self)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
io_buffer_unlock(data);
return self;
}
int
rb_io_buffer_try_unlock(VALUE self)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
if (data->flags & RB_IO_BUFFER_LOCKED) {
data->flags &= ~RB_IO_BUFFER_LOCKED;
return 1;
}
return 0;
}
/*
* call-seq: locked { ... }
*
* Allows to process a buffer in exclusive way, for concurrency-safety. While
* the block is performed, the buffer is considered locked, and no other code
* can enter the lock. Also, locked buffer can't be changed with #resize or
* #free.
*
* The following operations acquire a lock: #resize, #free.
*
* Locking is not thread safe. It is designed as a safety net around
* non-blocking system calls. You can only share a buffer between threads with
* appropriate synchronisation techniques.
*
* Example:
*
* buffer = IO::Buffer.new(4)
* buffer.locked? #=> false
*
* Fiber.schedule do
* buffer.locked do
* buffer.write(io) # theoretical system call interface
* end
* end
*
* Fiber.schedule do
* # in `locked': Buffer already locked! (IO::Buffer::LockedError)
* buffer.locked do
* buffer.set_string("test", 0)
* end
* end
*/
VALUE
rb_io_buffer_locked(VALUE self)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
if (data->flags & RB_IO_BUFFER_LOCKED) {
rb_raise(rb_eIOBufferLockedError, "Buffer already locked!");
}
data->flags |= RB_IO_BUFFER_LOCKED;
VALUE result = rb_yield(self);
data->flags &= ~RB_IO_BUFFER_LOCKED;
return result;
}
/*
* call-seq: free -> self
*
* If the buffer references memory, release it back to the operating system.
* * for a _mapped_ buffer (e.g. from file): unmap.
* * for a buffer created from scratch: free memory.
* * for a buffer created from string: undo the association.
*
* After the buffer is freed, no further operations can't be performed on it.
*
* You can resize a freed buffer to re-allocate it.
*
* Example:
*
* buffer = IO::Buffer.for('test')
* buffer.free
* # => #<IO::Buffer 0x0000000000000000+0 NULL>
*
* buffer.get_value(:U8, 0)
* # in `get_value': The buffer is not allocated! (IO::Buffer::AllocationError)
*
* buffer.get_string
* # in `get_string': The buffer is not allocated! (IO::Buffer::AllocationError)
*
* buffer.null?
* # => true
*/
VALUE
rb_io_buffer_free(VALUE self)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
if (data->flags & RB_IO_BUFFER_LOCKED) {
rb_raise(rb_eIOBufferLockedError, "Buffer is locked!");
}
io_buffer_free(data);
return self;
}
VALUE rb_io_buffer_free_locked(VALUE self)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
io_buffer_unlock(data);
io_buffer_free(data);
return self;
}
// Validate that access to the buffer is within bounds, assuming you want to
// access length bytes from the specified offset.
static inline void
io_buffer_validate_range(struct rb_io_buffer *data, size_t offset, size_t length)
{
if (offset + length > data->size) {
rb_raise(rb_eArgError, "Specified offset+length exceeds data size!");
}
}
static VALUE
rb_io_buffer_slice(struct rb_io_buffer *data, VALUE self, size_t offset, size_t length)
{
io_buffer_validate_range(data, offset, length);
VALUE instance = rb_io_buffer_type_allocate(rb_class_of(self));
struct rb_io_buffer *slice = NULL;
TypedData_Get_Struct(instance, struct rb_io_buffer, &rb_io_buffer_type, slice);
slice->base = (char*)data->base + offset;
slice->size = length;
// The source should be the root buffer:
if (data->source != Qnil)
slice->source = data->source;
else
slice->source = self;
return instance;
}
/*
* call-seq: slice([offset = 0, [length]]) -> io_buffer
*
* Produce another IO::Buffer which is a slice (or view into) the current one
* starting at +offset+ bytes and going for +length+ bytes.
*
* The slicing happens without copying of memory, and the slice keeps being
* associated with the original buffer's source (string, or file), if any.
*
* If the offset is not given, it will be zero. If the offset is negative, it
* will raise an ArgumentError.
*
* If the length is not given, the slice will be as long as the original
* buffer minus the specified offset. If the length is negative, it will raise
* an ArgumentError.
*
* Raises RuntimeError if the <tt>offset+length</tt> is out of the current
* buffer's bounds.
*
* Example:
*
* string = 'test'
* buffer = IO::Buffer.for(string)
*
* slice = buffer.slice
* # =>
* # #<IO::Buffer 0x0000000108338e68+4 SLICE>
* # 0x00000000 74 65 73 74 test
*
* buffer.slice(2)
* # =>
* # #<IO::Buffer 0x0000000108338e6a+2 SLICE>
* # 0x00000000 73 74 st
*
* slice = buffer.slice(1, 2)
* # =>
* # #<IO::Buffer 0x00007fc3d34ebc49+2 SLICE>
* # 0x00000000 65 73 es
*
* # Put "o" into 0s position of the slice
* slice.set_string('o', 0)
* slice
* # =>
* # #<IO::Buffer 0x00007fc3d34ebc49+2 SLICE>
* # 0x00000000 6f 73 os
*
* # it is also visible at position 1 of the original buffer
* buffer
* # =>
* # #<IO::Buffer 0x00007fc3d31e2d80+4 SLICE>
* # 0x00000000 74 6f 73 74 tost
*
* # ...and original string
* string
* # => tost
*/
static VALUE
io_buffer_slice(int argc, VALUE *argv, VALUE self)
{
rb_check_arity(argc, 0, 2);
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
size_t offset = 0, length = 0;
if (argc > 0) {
if (rb_int_negative_p(argv[0])) {
rb_raise(rb_eArgError, "Offset can't be negative!");
}
offset = NUM2SIZET(argv[0]);
}
if (argc > 1) {
if (rb_int_negative_p(argv[1])) {
rb_raise(rb_eArgError, "Length can't be negative!");
}
length = NUM2SIZET(argv[1]);
}
else {
length = data->size - offset;
}
return rb_io_buffer_slice(data, self, offset, length);
}
int
rb_io_buffer_get_bytes(VALUE self, void **base, size_t *size)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
if (io_buffer_validate(data)) {
if (data->base) {
*base = data->base;
*size = data->size;
return data->flags;
}
}
*base = NULL;
*size = 0;
return 0;
}
static inline void
io_buffer_get_bytes_for_writing(struct rb_io_buffer *data, void **base, size_t *size)
{
if (data->flags & RB_IO_BUFFER_READONLY) {
rb_raise(rb_eIOBufferAccessError, "Buffer is not writable!");
}
if (!io_buffer_validate(data)) {
rb_raise(rb_eIOBufferInvalidatedError, "Buffer is invalid!");
}
if (data->base) {
*base = data->base;
*size = data->size;
return;
}
rb_raise(rb_eIOBufferAllocationError, "The buffer is not allocated!");
}
void
rb_io_buffer_get_bytes_for_writing(VALUE self, void **base, size_t *size)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
io_buffer_get_bytes_for_writing(data, base, size);
}
static void
io_buffer_get_bytes_for_reading(struct rb_io_buffer *data, const void **base, size_t *size)
{
if (!io_buffer_validate(data)) {
rb_raise(rb_eIOBufferInvalidatedError, "Buffer has been invalidated!");
}
if (data->base) {
*base = data->base;
*size = data->size;
return;
}
rb_raise(rb_eIOBufferAllocationError, "The buffer is not allocated!");
}
void
rb_io_buffer_get_bytes_for_reading(VALUE self, const void **base, size_t *size)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
io_buffer_get_bytes_for_reading(data, base, size);
}
/*
* call-seq: transfer -> new_io_buffer
*
* Transfers ownership to a new buffer, deallocating the current one.
*
* Example:
*
* buffer = IO::Buffer.new('test')
* other = buffer.transfer
* other
* # =>
* # #<IO::Buffer 0x00007f136a15f7b0+4 SLICE>
* # 0x00000000 74 65 73 74 test
* buffer
* # =>
* # #<IO::Buffer 0x0000000000000000+0 NULL>
* buffer.null?
* # => true
*/
VALUE
rb_io_buffer_transfer(VALUE self)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
if (data->flags & RB_IO_BUFFER_LOCKED) {
rb_raise(rb_eIOBufferLockedError, "Cannot transfer ownership of locked buffer!");
}
VALUE instance = rb_io_buffer_type_allocate(rb_class_of(self));
struct rb_io_buffer *transferred;
TypedData_Get_Struct(instance, struct rb_io_buffer, &rb_io_buffer_type, transferred);
*transferred = *data;
io_buffer_zero(data);
return instance;
}
static void
io_buffer_resize_clear(struct rb_io_buffer *data, void* base, size_t size)
{
if (size > data->size) {
memset((unsigned char*)base+data->size, 0, size - data->size);
}
}
static void
io_buffer_resize_copy(struct rb_io_buffer *data, size_t size)
{
// Slow path:
struct rb_io_buffer resized;
io_buffer_initialize(&resized, NULL, size, io_flags_for_size(size), Qnil);
if (data->base) {
size_t preserve = data->size;
if (preserve > size) preserve = size;
memcpy(resized.base, data->base, preserve);
io_buffer_resize_clear(data, resized.base, size);
}
io_buffer_free(data);
*data = resized;
}
void
rb_io_buffer_resize(VALUE self, size_t size)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
if (data->flags & RB_IO_BUFFER_LOCKED) {
rb_raise(rb_eIOBufferLockedError, "Cannot resize locked buffer!");
}
if (data->base == NULL) {
io_buffer_initialize(data, NULL, size, io_flags_for_size(size), Qnil);
return;
}
if (data->flags & RB_IO_BUFFER_EXTERNAL) {
rb_raise(rb_eIOBufferAccessError, "Cannot resize external buffer!");
}
#if defined(HAVE_MREMAP) && defined(MREMAP_MAYMOVE)
if (data->flags & RB_IO_BUFFER_MAPPED) {
void *base = mremap(data->base, data->size, size, MREMAP_MAYMOVE);
if (base == MAP_FAILED) {
rb_sys_fail("rb_io_buffer_resize:mremap");
}
io_buffer_resize_clear(data, base, size);
data->base = base;
data->size = size;
return;
}
#endif
if (data->flags & RB_IO_BUFFER_INTERNAL) {
if (size == 0) {
io_buffer_free(data);
return;
}
void *base = realloc(data->base, size);
if (!base) {
rb_sys_fail("rb_io_buffer_resize:realloc");
}
io_buffer_resize_clear(data, base, size);
data->base = base;
data->size = size;
return;
}
io_buffer_resize_copy(data, size);
}
/*
* call-seq: resize(new_size) -> self
*
* Resizes a buffer to a +new_size+ bytes, preserving its content.
* Depending on the old and new size, the memory area associated with
* the buffer might be either extended, or rellocated at different
* address with content being copied.
*
* buffer = IO::Buffer.new(4)
* buffer.set_string("test", 0)
* buffer.resize(8) # resize to 8 bytes
* # =>
* # #<IO::Buffer 0x0000555f5d1a1630+8 INTERNAL>
* # 0x00000000 74 65 73 74 00 00 00 00 test....
*
* External buffer (created with ::for), and locked buffer
* can not be resized.
*/
static VALUE
io_buffer_resize(VALUE self, VALUE size)
{
rb_io_buffer_resize(self, NUM2SIZET(size));
return self;
}
/*
* call-seq: <=>(other) -> true or false
*
* Buffers are compared by size and exact contents of the memory they are
* referencing using +memcmp+.
*/
static VALUE
rb_io_buffer_compare(VALUE self, VALUE other)
{
const void *ptr1, *ptr2;
size_t size1, size2;
rb_io_buffer_get_bytes_for_reading(self, &ptr1, &size1);
rb_io_buffer_get_bytes_for_reading(other, &ptr2, &size2);
if (size1 < size2) {
return RB_INT2NUM(-1);
}
if (size1 > size2) {
return RB_INT2NUM(1);
}
return RB_INT2NUM(memcmp(ptr1, ptr2, size1));
}
static void
io_buffer_validate_type(size_t size, size_t offset)
{
if (offset > size) {
rb_raise(rb_eArgError, "Type extends beyond end of buffer! (offset=%"PRIdSIZE" > size=%"PRIdSIZE")", offset, size);
}
}
// Lower case: little endian.
// Upper case: big endian (network endian).
//
// :U8 | unsigned 8-bit integer.
// :S8 | signed 8-bit integer.
//
// :u16, :U16 | unsigned 16-bit integer.
// :s16, :S16 | signed 16-bit integer.
//
// :u32, :U32 | unsigned 32-bit integer.
// :s32, :S32 | signed 32-bit integer.
//
// :u64, :U64 | unsigned 64-bit integer.
// :s64, :S64 | signed 64-bit integer.
//
// :f32, :F32 | 32-bit floating point number.
// :f64, :F64 | 64-bit floating point number.
#define ruby_swap8(value) value
union swapf32 {
uint32_t integral;
float value;
};
static float
ruby_swapf32(float value)
{
union swapf32 swap = {.value = value};
swap.integral = ruby_swap32(swap.integral);
return swap.value;
}
union swapf64 {
uint64_t integral;
double value;
};
static double
ruby_swapf64(double value)
{
union swapf64 swap = {.value = value};
swap.integral = ruby_swap64(swap.integral);
return swap.value;
}
#define IO_BUFFER_DECLARE_TYPE(name, type, endian, wrap, unwrap, swap) \
static ID RB_IO_BUFFER_DATA_TYPE_##name; \
\
static VALUE \
io_buffer_read_##name(const void* base, size_t size, size_t *offset) \
{ \
io_buffer_validate_type(size, *offset + sizeof(type)); \
type value; \
memcpy(&value, (char*)base + *offset, sizeof(type)); \
if (endian != RB_IO_BUFFER_HOST_ENDIAN) value = swap(value); \
*offset += sizeof(type); \
return wrap(value); \
} \
\
static void \
io_buffer_write_##name(const void* base, size_t size, size_t *offset, VALUE _value) \
{ \
io_buffer_validate_type(size, *offset + sizeof(type)); \
type value = unwrap(_value); \
if (endian != RB_IO_BUFFER_HOST_ENDIAN) value = swap(value); \
memcpy((char*)base + *offset, &value, sizeof(type)); \
*offset += sizeof(type); \
} \
\
enum { \
RB_IO_BUFFER_DATA_TYPE_##name##_SIZE = sizeof(type) \
};
IO_BUFFER_DECLARE_TYPE(U8, uint8_t, RB_IO_BUFFER_BIG_ENDIAN, RB_UINT2NUM, RB_NUM2UINT, ruby_swap8)
IO_BUFFER_DECLARE_TYPE(S8, int8_t, RB_IO_BUFFER_BIG_ENDIAN, RB_INT2NUM, RB_NUM2INT, ruby_swap8)
IO_BUFFER_DECLARE_TYPE(u16, uint16_t, RB_IO_BUFFER_LITTLE_ENDIAN, RB_UINT2NUM, RB_NUM2UINT, ruby_swap16)
IO_BUFFER_DECLARE_TYPE(U16, uint16_t, RB_IO_BUFFER_BIG_ENDIAN, RB_UINT2NUM, RB_NUM2UINT, ruby_swap16)
IO_BUFFER_DECLARE_TYPE(s16, int16_t, RB_IO_BUFFER_LITTLE_ENDIAN, RB_INT2NUM, RB_NUM2INT, ruby_swap16)
IO_BUFFER_DECLARE_TYPE(S16, int16_t, RB_IO_BUFFER_BIG_ENDIAN, RB_INT2NUM, RB_NUM2INT, ruby_swap16)
IO_BUFFER_DECLARE_TYPE(u32, uint32_t, RB_IO_BUFFER_LITTLE_ENDIAN, RB_UINT2NUM, RB_NUM2UINT, ruby_swap32)
IO_BUFFER_DECLARE_TYPE(U32, uint32_t, RB_IO_BUFFER_BIG_ENDIAN, RB_UINT2NUM, RB_NUM2UINT, ruby_swap32)
IO_BUFFER_DECLARE_TYPE(s32, int32_t, RB_IO_BUFFER_LITTLE_ENDIAN, RB_INT2NUM, RB_NUM2INT, ruby_swap32)
IO_BUFFER_DECLARE_TYPE(S32, int32_t, RB_IO_BUFFER_BIG_ENDIAN, RB_INT2NUM, RB_NUM2INT, ruby_swap32)
IO_BUFFER_DECLARE_TYPE(u64, uint64_t, RB_IO_BUFFER_LITTLE_ENDIAN, RB_ULL2NUM, RB_NUM2ULL, ruby_swap64)
IO_BUFFER_DECLARE_TYPE(U64, uint64_t, RB_IO_BUFFER_BIG_ENDIAN, RB_ULL2NUM, RB_NUM2ULL, ruby_swap64)
IO_BUFFER_DECLARE_TYPE(s64, int64_t, RB_IO_BUFFER_LITTLE_ENDIAN, RB_LL2NUM, RB_NUM2LL, ruby_swap64)
IO_BUFFER_DECLARE_TYPE(S64, int64_t, RB_IO_BUFFER_BIG_ENDIAN, RB_LL2NUM, RB_NUM2LL, ruby_swap64)
IO_BUFFER_DECLARE_TYPE(f32, float, RB_IO_BUFFER_LITTLE_ENDIAN, DBL2NUM, NUM2DBL, ruby_swapf32)
IO_BUFFER_DECLARE_TYPE(F32, float, RB_IO_BUFFER_BIG_ENDIAN, DBL2NUM, NUM2DBL, ruby_swapf32)
IO_BUFFER_DECLARE_TYPE(f64, double, RB_IO_BUFFER_LITTLE_ENDIAN, DBL2NUM, NUM2DBL, ruby_swapf64)
IO_BUFFER_DECLARE_TYPE(F64, double, RB_IO_BUFFER_BIG_ENDIAN, DBL2NUM, NUM2DBL, ruby_swapf64)
#undef IO_BUFFER_DECLARE_TYPE
static inline size_t
io_buffer_data_type_size(ID data_type)
{
#define IO_BUFFER_DATA_TYPE_SIZE(name) if (data_type == RB_IO_BUFFER_DATA_TYPE_##name) return RB_IO_BUFFER_DATA_TYPE_##name##_SIZE;
IO_BUFFER_DATA_TYPE_SIZE(U8)
IO_BUFFER_DATA_TYPE_SIZE(S8)
IO_BUFFER_DATA_TYPE_SIZE(u16)
IO_BUFFER_DATA_TYPE_SIZE(U16)
IO_BUFFER_DATA_TYPE_SIZE(s16)
IO_BUFFER_DATA_TYPE_SIZE(S16)
IO_BUFFER_DATA_TYPE_SIZE(u32)
IO_BUFFER_DATA_TYPE_SIZE(U32)
IO_BUFFER_DATA_TYPE_SIZE(s32)
IO_BUFFER_DATA_TYPE_SIZE(S32)
IO_BUFFER_DATA_TYPE_SIZE(u64)
IO_BUFFER_DATA_TYPE_SIZE(U64)
IO_BUFFER_DATA_TYPE_SIZE(s64)
IO_BUFFER_DATA_TYPE_SIZE(S64)
IO_BUFFER_DATA_TYPE_SIZE(f32)
IO_BUFFER_DATA_TYPE_SIZE(F32)
IO_BUFFER_DATA_TYPE_SIZE(f64)
IO_BUFFER_DATA_TYPE_SIZE(F64)
#undef IO_BUFFER_DATA_TYPE_SIZE
rb_raise(rb_eArgError, "Invalid type name!");
}
/*
* call-seq:
* size_of(data_type) -> byte size
* size_of(array of data_type) -> byte size
*
* Returns the size of the given data type(s) in bytes.
*
* Example:
*
* IO::Buffer.size_of(:u32) # => 4
* IO::Buffer.size_of([:u32, :u32]) # => 8
*/
static VALUE
io_buffer_size_of(VALUE klass, VALUE data_type)
{
if (RB_TYPE_P(data_type, T_ARRAY)) {
size_t total = 0;
for (long i = 0; i < RARRAY_LEN(data_type); i++) {
total += io_buffer_data_type_size(RB_SYM2ID(RARRAY_AREF(data_type, i)));
}
return SIZET2NUM(total);
}
else {
return SIZET2NUM(io_buffer_data_type_size(RB_SYM2ID(data_type)));
}
}
static inline VALUE
rb_io_buffer_get_value(const void* base, size_t size, ID data_type, size_t *offset)
{
#define IO_BUFFER_GET_VALUE(name) if (data_type == RB_IO_BUFFER_DATA_TYPE_##name) return io_buffer_read_##name(base, size, offset);
IO_BUFFER_GET_VALUE(U8)
IO_BUFFER_GET_VALUE(S8)
IO_BUFFER_GET_VALUE(u16)
IO_BUFFER_GET_VALUE(U16)
IO_BUFFER_GET_VALUE(s16)
IO_BUFFER_GET_VALUE(S16)
IO_BUFFER_GET_VALUE(u32)
IO_BUFFER_GET_VALUE(U32)
IO_BUFFER_GET_VALUE(s32)
IO_BUFFER_GET_VALUE(S32)
IO_BUFFER_GET_VALUE(u64)
IO_BUFFER_GET_VALUE(U64)
IO_BUFFER_GET_VALUE(s64)
IO_BUFFER_GET_VALUE(S64)
IO_BUFFER_GET_VALUE(f32)
IO_BUFFER_GET_VALUE(F32)
IO_BUFFER_GET_VALUE(f64)
IO_BUFFER_GET_VALUE(F64)
#undef IO_BUFFER_GET_VALUE
rb_raise(rb_eArgError, "Invalid type name!");
}
/*
* call-seq: get_value(data_type, offset) -> numeric
*
* Read from buffer a value of +type+ at +offset+. +data_type+ should be one
* of symbols:
*
* * +:U8+: unsigned integer, 1 byte
* * +:S8+: signed integer, 1 byte
* * +:u16+: unsigned integer, 2 bytes, little-endian
* * +:U16+: unsigned integer, 2 bytes, big-endian
* * +:s16+: signed integer, 2 bytes, little-endian
* * +:S16+: signed integer, 2 bytes, big-endian
* * +:u32+: unsigned integer, 4 bytes, little-endian
* * +:U32+: unsigned integer, 4 bytes, big-endian
* * +:s32+: signed integer, 4 bytes, little-endian
* * +:S32+: signed integer, 4 bytes, big-endian
* * +:u64+: unsigned integer, 8 bytes, little-endian
* * +:U64+: unsigned integer, 8 bytes, big-endian
* * +:s64+: signed integer, 8 bytes, little-endian
* * +:S64+: signed integer, 8 bytes, big-endian
* * +:f32+: float, 4 bytes, little-endian
* * +:F32+: float, 4 bytes, big-endian
* * +:f64+: double, 8 bytes, little-endian
* * +:F64+: double, 8 bytes, big-endian
*
* A data type refers specifically to the type of binary data that is stored
* in the buffer. For example, a +:u32+ data type is a 32-bit unsigned
* integer in little-endian format.
*
* Example:
*
* string = [1.5].pack('f')
* # => "\x00\x00\xC0?"
* IO::Buffer.for(string).get_value(:f32, 0)
* # => 1.5
*/
static VALUE
io_buffer_get_value(VALUE self, VALUE type, VALUE _offset)
{
const void *base;
size_t size;
size_t offset = NUM2SIZET(_offset);
rb_io_buffer_get_bytes_for_reading(self, &base, &size);
return rb_io_buffer_get_value(base, size, RB_SYM2ID(type), &offset);
}
/*
* call-seq: get_values(data_types, offset) -> array
*
* Similar to #get_value, except that it can handle multiple data types and
* returns an array of values.
*
* Example:
*
* string = [1.5, 2.5].pack('ff')
* IO::Buffer.for(string).get_values([:f32, :f32], 0)
* # => [1.5, 2.5]
*/
static VALUE
io_buffer_get_values(VALUE self, VALUE data_types, VALUE _offset)
{
size_t offset = NUM2SIZET(_offset);
const void *base;
size_t size;
rb_io_buffer_get_bytes_for_reading(self, &base, &size);
if (!RB_TYPE_P(data_types, T_ARRAY)) {
rb_raise(rb_eArgError, "Argument data_types should be an array!");
}
VALUE array = rb_ary_new_capa(RARRAY_LEN(data_types));
for (long i = 0; i < RARRAY_LEN(data_types); i++) {
VALUE type = rb_ary_entry(data_types, i);
VALUE value = rb_io_buffer_get_value(base, size, RB_SYM2ID(type), &offset);
rb_ary_push(array, value);
}
return array;
}
/*
* call-seq:
* each(data_type, [offset, [count]]) {|offset, value| ...} -> self
* each(data_type, [offset, [count]]) -> enumerator
*
* Iterates over the buffer, yielding each +value+ of +data_type+ starting
* from +offset+.
*
* If +count+ is given, only +count+ values will be yielded.
*
* Example:
*
* IO::Buffer.for("Hello World").each(:U8, 2, 2) do |offset, value|
* puts "#{offset}: #{value}"
* end
* # 2: 108
* # 3: 108
*/
static VALUE
io_buffer_each(int argc, VALUE *argv, VALUE self)
{
RETURN_ENUMERATOR_KW(self, argc, argv, RB_NO_KEYWORDS);
const void *base;
size_t size;
rb_io_buffer_get_bytes_for_reading(self, &base, &size);
ID data_type;
if (argc >= 1) {
data_type = RB_SYM2ID(argv[0]);
}
else {
data_type = RB_IO_BUFFER_DATA_TYPE_U8;
}
size_t offset;
if (argc >= 2) {
offset = NUM2SIZET(argv[1]);
}
else {
offset = 0;
}
size_t count;
if (argc >= 3) {
count = NUM2SIZET(argv[2]);
}
else {
count = (size - offset) / io_buffer_data_type_size(data_type);
}
for (size_t i = 0; i < count; i++) {
size_t current_offset = offset;
VALUE value = rb_io_buffer_get_value(base, size, data_type, &offset);
rb_yield_values(2, SIZET2NUM(current_offset), value);
}
return self;
}
/*
* call-seq: values(data_type, [offset, [count]]) -> array
*
* Returns an array of values of +data_type+ starting from +offset+.
*
* If +count+ is given, only +count+ values will be returned.
*
* Example:
*
* IO::Buffer.for("Hello World").values(:U8, 2, 2)
* # => [108, 108]
*/
static VALUE
io_buffer_values(int argc, VALUE *argv, VALUE self)
{
const void *base;
size_t size;
rb_io_buffer_get_bytes_for_reading(self, &base, &size);
ID data_type;
if (argc >= 1) {
data_type = RB_SYM2ID(argv[0]);
}
else {
data_type = RB_IO_BUFFER_DATA_TYPE_U8;
}
size_t offset;
if (argc >= 2) {
offset = NUM2SIZET(argv[1]);
}
else {
offset = 0;
}
size_t count;
if (argc >= 3) {
count = NUM2SIZET(argv[2]);
}
else {
count = (size - offset) / io_buffer_data_type_size(data_type);
}
VALUE array = rb_ary_new_capa(count);
for (size_t i = 0; i < count; i++) {
VALUE value = rb_io_buffer_get_value(base, size, data_type, &offset);
rb_ary_push(array, value);
}
return array;
}
/*
* call-seq:
* each_byte([offset, [count]]) {|offset, byte| ...} -> self
* each_byte([offset, [count]]) -> enumerator
*
* Iterates over the buffer, yielding each byte starting from +offset+.
*
* If +count+ is given, only +count+ bytes will be yielded.
*
* Example:
*
* IO::Buffer.for("Hello World").each_byte(2, 2) do |offset, byte|
* puts "#{offset}: #{byte}"
* end
* # 2: 108
* # 3: 108
*/
static VALUE
io_buffer_each_byte(int argc, VALUE *argv, VALUE self)
{
RETURN_ENUMERATOR_KW(self, argc, argv, RB_NO_KEYWORDS);
const void *base;
size_t size;
rb_io_buffer_get_bytes_for_reading(self, &base, &size);
size_t offset;
if (argc >= 2) {
offset = NUM2SIZET(argv[1]);
}
else {
offset = 0;
}
size_t count;
if (argc >= 3) {
count = NUM2SIZET(argv[2]);
}
else {
count = (size - offset);
}
for (size_t i = 0; i < count; i++) {
unsigned char *value = (unsigned char *)base + i + offset;
rb_yield(RB_INT2FIX(*value));
}
return self;
}
static inline void
rb_io_buffer_set_value(const void* base, size_t size, ID data_type, size_t *offset, VALUE value)
{
#define IO_BUFFER_SET_VALUE(name) if (data_type == RB_IO_BUFFER_DATA_TYPE_##name) {io_buffer_write_##name(base, size, offset, value); return;}
IO_BUFFER_SET_VALUE(U8);
IO_BUFFER_SET_VALUE(S8);
IO_BUFFER_SET_VALUE(u16);
IO_BUFFER_SET_VALUE(U16);
IO_BUFFER_SET_VALUE(s16);
IO_BUFFER_SET_VALUE(S16);
IO_BUFFER_SET_VALUE(u32);
IO_BUFFER_SET_VALUE(U32);
IO_BUFFER_SET_VALUE(s32);
IO_BUFFER_SET_VALUE(S32);
IO_BUFFER_SET_VALUE(u64);
IO_BUFFER_SET_VALUE(U64);
IO_BUFFER_SET_VALUE(s64);
IO_BUFFER_SET_VALUE(S64);
IO_BUFFER_SET_VALUE(f32);
IO_BUFFER_SET_VALUE(F32);
IO_BUFFER_SET_VALUE(f64);
IO_BUFFER_SET_VALUE(F64);
#undef IO_BUFFER_SET_VALUE
rb_raise(rb_eArgError, "Invalid type name!");
}
/*
* call-seq: set_value(type, offset, value) -> offset
*
* Write to a buffer a +value+ of +type+ at +offset+. +type+ should be one of
* symbols described in #get_value.
*
* buffer = IO::Buffer.new(8)
* # =>
* # #<IO::Buffer 0x0000555f5c9a2d50+8 INTERNAL>
* # 0x00000000 00 00 00 00 00 00 00 00
*
* buffer.set_value(:U8, 1, 111)
* # => 1
*
* buffer
* # =>
* # #<IO::Buffer 0x0000555f5c9a2d50+8 INTERNAL>
* # 0x00000000 00 6f 00 00 00 00 00 00 .o......
*
* Note that if the +type+ is integer and +value+ is Float, the implicit truncation is performed:
*
* buffer = IO::Buffer.new(8)
* buffer.set_value(:U32, 0, 2.5)
*
* buffer
* # =>
* # #<IO::Buffer 0x0000555f5c9a2d50+8 INTERNAL>
* # 0x00000000 00 00 00 02 00 00 00 00
* # ^^ the same as if we'd pass just integer 2
*/
static VALUE
io_buffer_set_value(VALUE self, VALUE type, VALUE _offset, VALUE value)
{
void *base;
size_t size;
size_t offset = NUM2SIZET(_offset);
rb_io_buffer_get_bytes_for_writing(self, &base, &size);
rb_io_buffer_set_value(base, size, RB_SYM2ID(type), &offset, value);
return SIZET2NUM(offset);
}
/*
* call-seq: set_values(data_types, offset, values) -> offset
*
* Write +values+ of +data_types+ at +offset+ to the buffer. +data_types+
* should be an array of symbols as described in #get_value. +values+ should
* be an array of values to write.
*
* Example:
*
* buffer = IO::Buffer.new(8)
* buffer.set_values([:U8, :U16], 0, [1, 2])
* buffer
* # =>
* # #<IO::Buffer 0x696f717561746978+8 INTERNAL>
* # 0x00000000 01 00 02 00 00 00 00 00 ........
*/
static VALUE
io_buffer_set_values(VALUE self, VALUE data_types, VALUE _offset, VALUE values)
{
if (!RB_TYPE_P(data_types, T_ARRAY)) {
rb_raise(rb_eArgError, "Argument data_types should be an array!");
}
if (!RB_TYPE_P(values, T_ARRAY)) {
rb_raise(rb_eArgError, "Argument values should be an array!");
}
if (RARRAY_LEN(data_types) != RARRAY_LEN(values)) {
rb_raise(rb_eArgError, "Argument data_types and values should have the same length!");
}
size_t offset = NUM2SIZET(_offset);
void *base;
size_t size;
rb_io_buffer_get_bytes_for_writing(self, &base, &size);
for (long i = 0; i < RARRAY_LEN(data_types); i++) {
VALUE type = rb_ary_entry(data_types, i);
VALUE value = rb_ary_entry(values, i);
rb_io_buffer_set_value(base, size, RB_SYM2ID(type), &offset, value);
}
return SIZET2NUM(offset);
}
static void
io_buffer_memcpy(struct rb_io_buffer *data, size_t offset, const void *source_base, size_t source_offset, size_t source_size, size_t length)
{
void *base;
size_t size;
io_buffer_get_bytes_for_writing(data, &base, &size);
io_buffer_validate_range(data, offset, length);
if (source_offset + length > source_size) {
rb_raise(rb_eArgError, "The computed source range exceeds the size of the source!");
}
memcpy((unsigned char*)base+offset, (unsigned char*)source_base+source_offset, length);
}
// (offset, length, source_offset) -> length
static VALUE
io_buffer_copy_from(struct rb_io_buffer *data, const void *source_base, size_t source_size, int argc, VALUE *argv)
{
size_t offset;
size_t length;
size_t source_offset;
// The offset we copy into the buffer:
if (argc >= 1) {
offset = NUM2SIZET(argv[0]);
}
else {
offset = 0;
}
// The offset we start from within the string:
if (argc >= 3) {
source_offset = NUM2SIZET(argv[2]);
if (source_offset > source_size) {
rb_raise(rb_eArgError, "The given source offset is bigger than the source itself!");
}
}
else {
source_offset = 0;
}
// The length we are going to copy:
if (argc >= 2 && !RB_NIL_P(argv[1])) {
length = NUM2SIZET(argv[1]);
}
else {
// Default to the source offset -> source size:
length = source_size - source_offset;
}
io_buffer_memcpy(data, offset, source_base, source_offset, source_size, length);
return SIZET2NUM(length);
}
/*
* call-seq:
* dup -> io_buffer
* clone -> io_buffer
*
* Make an internal copy of the source buffer. Updates to the copy will not
* affect the source buffer.
*
* source = IO::Buffer.for("Hello World")
* # =>
* # #<IO::Buffer 0x00007fd598466830+11 EXTERNAL READONLY SLICE>
* # 0x00000000 48 65 6c 6c 6f 20 57 6f 72 6c 64 Hello World
* buffer = source.dup
* # =>
* # #<IO::Buffer 0x0000558cbec03320+11 INTERNAL>
* # 0x00000000 48 65 6c 6c 6f 20 57 6f 72 6c 64 Hello World
*/
static VALUE
rb_io_buffer_initialize_copy(VALUE self, VALUE source)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
const void *source_base;
size_t source_size;
rb_io_buffer_get_bytes_for_reading(source, &source_base, &source_size);
io_buffer_initialize(data, NULL, source_size, io_flags_for_size(source_size), Qnil);
return io_buffer_copy_from(data, source_base, source_size, 0, NULL);
}
/*
* call-seq:
* copy(source, [offset, [length, [source_offset]]]) -> size
*
* Efficiently copy data from a source IO::Buffer into the buffer,
* at +offset+ using +memcpy+. For copying String instances, see #set_string.
*
* buffer = IO::Buffer.new(32)
* # =>
* # #<IO::Buffer 0x0000555f5ca22520+32 INTERNAL>
* # 0x00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
* # 0x00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ *
*
* buffer.copy(IO::Buffer.for("test"), 8)
* # => 4 -- size of data copied
* buffer
* # =>
* # #<IO::Buffer 0x0000555f5cf8fe40+32 INTERNAL>
* # 0x00000000 00 00 00 00 00 00 00 00 74 65 73 74 00 00 00 00 ........test....
* # 0x00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ *
*
* #copy can be used to put data into strings associated with buffer:
*
* string= "data: "
* # => "data: "
* buffer = IO::Buffer.for(string)
* buffer.copy(IO::Buffer.for("test"), 5)
* # => 4
* string
* # => "data:test"
*
* Attempt to copy into a read-only buffer will fail:
*
* File.write('test.txt', 'test')
* buffer = IO::Buffer.map(File.open('test.txt'), nil, 0, IO::Buffer::READONLY)
* buffer.copy(IO::Buffer.for("test"), 8)
* # in `copy': Buffer is not writable! (IO::Buffer::AccessError)
*
* See ::map for details of creation of mutable file mappings, this will
* work:
*
* buffer = IO::Buffer.map(File.open('test.txt', 'r+'))
* buffer.copy(IO::Buffer.for("boom"), 0)
* # => 4
* File.read('test.txt')
* # => "boom"
*
* Attempt to copy the data which will need place outside of buffer's
* bounds will fail:
*
* buffer = IO::Buffer.new(2)
* buffer.copy(IO::Buffer.for('test'), 0)
* # in `copy': Specified offset+length exceeds source size! (ArgumentError)
*/
static VALUE
io_buffer_copy(int argc, VALUE *argv, VALUE self)
{
rb_check_arity(argc, 1, 4);
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
VALUE source = argv[0];
const void *source_base;
size_t source_size;
rb_io_buffer_get_bytes_for_reading(source, &source_base, &source_size);
return io_buffer_copy_from(data, source_base, source_size, argc-1, argv+1);
}
/*
* call-seq: get_string([offset, [length, [encoding]]]) -> string
*
* Read a chunk or all of the buffer into a string, in the specified
* +encoding+. If no encoding is provided +Encoding::BINARY+ is used.
*
* buffer = IO::Buffer.for('test')
* buffer.get_string
* # => "test"
* buffer.get_string(2)
* # => "st"
* buffer.get_string(2, 1)
* # => "s"
*/
static VALUE
io_buffer_get_string(int argc, VALUE *argv, VALUE self)
{
rb_check_arity(argc, 0, 3);
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
const void *base;
size_t size;
io_buffer_get_bytes_for_reading(data, &base, &size);
size_t offset = 0;
size_t length = size;
rb_encoding *encoding = rb_ascii8bit_encoding();
if (argc >= 1) {
offset = NUM2SIZET(argv[0]);
}
if (argc >= 2 && !RB_NIL_P(argv[1])) {
length = NUM2SIZET(argv[1]);
}
else {
length = size - offset;
}
if (argc >= 3) {
encoding = rb_find_encoding(argv[2]);
}
io_buffer_validate_range(data, offset, length);
return rb_enc_str_new((const char*)base + offset, length, encoding);
}
/*
* call-seq: set_string(string, [offset, [length, [source_offset]]]) -> size
*
* Efficiently copy data from a source String into the buffer,
* at +offset+ using +memcpy+.
*
* buf = IO::Buffer.new(8)
* # =>
* # #<IO::Buffer 0x0000557412714a20+8 INTERNAL>
* # 0x00000000 00 00 00 00 00 00 00 00 ........
*
* # set data starting from offset 1, take 2 bytes starting from string's
* # second
* buf.set_string('test', 1, 2, 1)
* # => 2
* buf
* # =>
* # #<IO::Buffer 0x0000557412714a20+8 INTERNAL>
* # 0x00000000 00 65 73 00 00 00 00 00 .es.....
*
* See also #copy for examples of how buffer writing might be used for changing
* associated strings and files.
*/
static VALUE
io_buffer_set_string(int argc, VALUE *argv, VALUE self)
{
rb_check_arity(argc, 1, 4);
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
VALUE string = rb_str_to_str(argv[0]);
const void *source_base = RSTRING_PTR(string);
size_t source_size = RSTRING_LEN(string);
return io_buffer_copy_from(data, source_base, source_size, argc-1, argv+1);
}
void
rb_io_buffer_clear(VALUE self, uint8_t value, size_t offset, size_t length)
{
void *base;
size_t size;
rb_io_buffer_get_bytes_for_writing(self, &base, &size);
if (offset + length > size) {
rb_raise(rb_eArgError, "The given offset + length out of bounds!");
}
memset((char*)base + offset, value, length);
}
/*
* call-seq: clear(value = 0, [offset, [length]]) -> self
*
* Fill buffer with +value+, starting with +offset+ and going for +length+
* bytes.
*
* buffer = IO::Buffer.for('test')
* # =>
* # <IO::Buffer 0x00007fca40087c38+4 SLICE>
* # 0x00000000 74 65 73 74 test
*
* buffer.clear
* # =>
* # <IO::Buffer 0x00007fca40087c38+4 SLICE>
* # 0x00000000 00 00 00 00 ....
*
* buf.clear(1) # fill with 1
* # =>
* # <IO::Buffer 0x00007fca40087c38+4 SLICE>
* # 0x00000000 01 01 01 01 ....
*
* buffer.clear(2, 1, 2) # fill with 2, starting from offset 1, for 2 bytes
* # =>
* # <IO::Buffer 0x00007fca40087c38+4 SLICE>
* # 0x00000000 01 02 02 01 ....
*
* buffer.clear(2, 1) # fill with 2, starting from offset 1
* # =>
* # <IO::Buffer 0x00007fca40087c38+4 SLICE>
* # 0x00000000 01 02 02 02 ....
*/
static VALUE
io_buffer_clear(int argc, VALUE *argv, VALUE self)
{
rb_check_arity(argc, 0, 3);
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
uint8_t value = 0;
if (argc >= 1) {
value = NUM2UINT(argv[0]);
}
size_t offset = 0;
if (argc >= 2) {
offset = NUM2SIZET(argv[1]);
}
size_t length;
if (argc >= 3) {
length = NUM2SIZET(argv[2]);
}
else {
length = data->size - offset;
}
rb_io_buffer_clear(self, value, offset, length);
return self;
}
static size_t
io_buffer_default_size(size_t page_size)
{
// Platform agnostic default size, based on empirical performance observation:
const size_t platform_agnostic_default_size = 64*1024;
// Allow user to specify custom default buffer size:
const char *default_size = getenv("RUBY_IO_BUFFER_DEFAULT_SIZE");
if (default_size) {
// For the purpose of setting a default size, 2^31 is an acceptable maximum:
int value = atoi(default_size);
// assuming sizeof(int) <= sizeof(size_t)
if (value > 0) {
return value;
}
}
if (platform_agnostic_default_size < page_size) {
return page_size;
}
return platform_agnostic_default_size;
}
struct io_buffer_read_internal_argument {
int descriptor;
void *base;
size_t size;
};
static VALUE
io_buffer_read_internal(void *_argument)
{
struct io_buffer_read_internal_argument *argument = _argument;
ssize_t result = read(argument->descriptor, argument->base, argument->size);
return rb_fiber_scheduler_io_result(result, errno);
}
VALUE
rb_io_buffer_read(VALUE self, VALUE io, size_t length, size_t offset)
{
VALUE scheduler = rb_fiber_scheduler_current();
if (scheduler != Qnil) {
VALUE result = rb_fiber_scheduler_io_read(scheduler, io, self, length, offset);
if (!UNDEF_P(result)) {
return result;
}
}
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
io_buffer_validate_range(data, offset, length);
int descriptor = rb_io_descriptor(io);
void * base;
size_t size;
io_buffer_get_bytes_for_writing(data, &base, &size);
base = (unsigned char*)base + offset;
struct io_buffer_read_internal_argument argument = {
.descriptor = descriptor,
.base = base,
.size = length,
};
return rb_thread_io_blocking_region(io_buffer_read_internal, &argument, descriptor);
}
/*
* call-seq: read(io, length, [offset]) -> read length or -errno
*
* Read at most +length+ bytes from +io+ into the buffer, starting at
* +offset+. If an error occurs, return <tt>-errno</tt>.
*
* If +offset+ is not given, read from the beginning of the buffer.
*
* If +length+ is 0, read nothing.
*
* Example:
*
* IO::Buffer.for('test') do |buffer|
* p buffer
* # =>
* # <IO::Buffer 0x00007fca40087c38+4 SLICE>
* # 0x00000000 74 65 73 74 test
* buffer.read(File.open('/dev/urandom', 'rb'), 2)
* p buffer
* # =>
* # <IO::Buffer 0x00007f3bc65f2a58+4 EXTERNAL SLICE>
* # 0x00000000 05 35 73 74 .5st
* end
*/
static VALUE
io_buffer_read(int argc, VALUE *argv, VALUE self)
{
rb_check_arity(argc, 2, 3);
VALUE io = argv[0];
if (rb_int_negative_p(argv[1])) {
rb_raise(rb_eArgError, "Length can't be negative!");
}
size_t length = NUM2SIZET(argv[1]);
size_t offset = 0;
if (argc >= 3) {
if (rb_int_negative_p(argv[2])) {
rb_raise(rb_eArgError, "Offset can't be negative!");
}
offset = NUM2SIZET(argv[2]);
}
return rb_io_buffer_read(self, io, length, offset);
}
struct io_buffer_pread_internal_argument {
int descriptor;
void *base;
size_t size;
off_t offset;
};
static VALUE
io_buffer_pread_internal(void *_argument)
{
struct io_buffer_pread_internal_argument *argument = _argument;
#if defined(HAVE_PREAD)
ssize_t result = pread(argument->descriptor, argument->base, argument->size, argument->offset);
#else
// This emulation is not thread safe.
rb_off_t offset = lseek(argument->descriptor, 0, SEEK_CUR);
if (offset == (rb_off_t)-1)
return rb_fiber_scheduler_io_result(-1, errno);
if (lseek(argument->descriptor, argument->offset, SEEK_SET) == (rb_off_t)-1)
return rb_fiber_scheduler_io_result(-1, errno);
ssize_t result = read(argument->descriptor, argument->base, argument->size);
if (lseek(argument->descriptor, offset, SEEK_SET) == (rb_off_t)-1)
return rb_fiber_scheduler_io_result(-1, errno);
#endif
return rb_fiber_scheduler_io_result(result, errno);
}
VALUE
rb_io_buffer_pread(VALUE self, VALUE io, rb_off_t from, size_t length, size_t offset)
{
VALUE scheduler = rb_fiber_scheduler_current();
if (scheduler != Qnil) {
VALUE result = rb_fiber_scheduler_io_pread(scheduler, io, from, self, length, offset);
if (!UNDEF_P(result)) {
return result;
}
}
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
io_buffer_validate_range(data, offset, length);
int descriptor = rb_io_descriptor(io);
void * base;
size_t size;
io_buffer_get_bytes_for_writing(data, &base, &size);
struct io_buffer_pread_internal_argument argument = {
.descriptor = descriptor,
// Move the base pointer to the offset:
.base = (unsigned char*)base + offset,
// And the size to the length of data we want to read:
.size = length,
// From the offset in the file we want to read from:
.offset = from,
};
return rb_thread_io_blocking_region(io_buffer_pread_internal, &argument, descriptor);
}
/*
* call-seq: pread(io, from, length, [offset]) -> read length or -errno
*
* Read at most +length+ bytes from +io+ into the buffer, starting at
* +from+, and put it in buffer starting from specified +offset+.
* If an error occurs, return <tt>-errno</tt>.
*
* If +offset+ is not given, put it at the beginning of the buffer.
*
* Example:
*
* IO::Buffer.for('test') do |buffer|
* p buffer
* # =>
* # <IO::Buffer 0x00007fca40087c38+4 SLICE>
* # 0x00000000 74 65 73 74 test
*
* # take 2 bytes from the beginning of urandom,
* # put them in buffer starting from position 2
* buffer.pread(File.open('/dev/urandom', 'rb'), 0, 2, 2)
* p buffer
* # =>
* # <IO::Buffer 0x00007f3bc65f2a58+4 EXTERNAL SLICE>
* # 0x00000000 05 35 73 74 te.5
* end
*/
static VALUE
io_buffer_pread(int argc, VALUE *argv, VALUE self)
{
rb_check_arity(argc, 3, 4);
VALUE io = argv[0];
rb_off_t from = NUM2OFFT(argv[1]);
size_t length;
if (rb_int_negative_p(argv[2])) {
rb_raise(rb_eArgError, "Length can't be negative!");
}
length = NUM2SIZET(argv[2]);
size_t offset = 0;
if (argc >= 4) {
if (rb_int_negative_p(argv[3])) {
rb_raise(rb_eArgError, "Offset can't be negative!");
}
offset = NUM2SIZET(argv[3]);
}
return rb_io_buffer_pread(self, io, from, length, offset);
}
struct io_buffer_write_internal_argument {
int descriptor;
const void *base;
size_t size;
};
static VALUE
io_buffer_write_internal(void *_argument)
{
struct io_buffer_write_internal_argument *argument = _argument;
ssize_t result = write(argument->descriptor, argument->base, argument->size);
return rb_fiber_scheduler_io_result(result, errno);
}
VALUE
rb_io_buffer_write(VALUE self, VALUE io, size_t length, size_t offset)
{
VALUE scheduler = rb_fiber_scheduler_current();
if (scheduler != Qnil) {
VALUE result = rb_fiber_scheduler_io_write(scheduler, io, self, length, offset);
if (!UNDEF_P(result)) {
return result;
}
}
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
io_buffer_validate_range(data, offset, length);
int descriptor = rb_io_descriptor(io);
const void * base;
size_t size;
io_buffer_get_bytes_for_reading(data, &base, &size);
base = (unsigned char *)base + offset;
struct io_buffer_write_internal_argument argument = {
.descriptor = descriptor,
.base = base,
.size = length,
};
return rb_thread_io_blocking_region(io_buffer_write_internal, &argument, descriptor);
}
/*
* call-seq: write(io, length, [offset]) -> written length or -errno
*
* Writes +length+ bytes from buffer into +io+, starting at
* +offset+ in the buffer. If an error occurs, return <tt>-errno</tt>.
*
* If +offset+ is not given, the bytes are taken from the beginning
* of the buffer.
*
* out = File.open('output.txt', 'wb')
* IO::Buffer.for('1234567').write(out, 3)
*
* This leads to +123+ being written into <tt>output.txt</tt>
*/
static VALUE
io_buffer_write(int argc, VALUE *argv, VALUE self)
{
rb_check_arity(argc, 2, 3);
VALUE io = argv[0];
if (rb_int_negative_p(argv[1])) {
rb_raise(rb_eArgError, "Length can't be negative!");
}
size_t length = NUM2SIZET(argv[1]);
size_t offset = 0;
if (argc >= 3) {
if (rb_int_negative_p(argv[2])) {
rb_raise(rb_eArgError, "Offset can't be negative!");
}
offset = NUM2SIZET(argv[2]);
}
return rb_io_buffer_write(self, io, length, offset);
}
struct io_buffer_pwrite_internal_argument {
int descriptor;
const void *base;
size_t size;
off_t offset;
};
static VALUE
io_buffer_pwrite_internal(void *_argument)
{
struct io_buffer_pwrite_internal_argument *argument = _argument;
#if defined(HAVE_PWRITE)
ssize_t result = pwrite(argument->descriptor, argument->base, argument->size, argument->offset);
#else
// This emulation is not thread safe.
rb_off_t offset = lseek(argument->descriptor, 0, SEEK_CUR);
if (offset == (rb_off_t)-1)
return rb_fiber_scheduler_io_result(-1, errno);
if (lseek(argument->descriptor, argument->offset, SEEK_SET) == (rb_off_t)-1)
return rb_fiber_scheduler_io_result(-1, errno);
ssize_t result = write(argument->descriptor, argument->base, argument->size);
if (lseek(argument->descriptor, offset, SEEK_SET) == (rb_off_t)-1)
return rb_fiber_scheduler_io_result(-1, errno);
#endif
return rb_fiber_scheduler_io_result(result, errno);
}
VALUE
rb_io_buffer_pwrite(VALUE self, VALUE io, rb_off_t from, size_t length, size_t offset)
{
VALUE scheduler = rb_fiber_scheduler_current();
if (scheduler != Qnil) {
VALUE result = rb_fiber_scheduler_io_pwrite(scheduler, io, from, self, length, offset);
if (!UNDEF_P(result)) {
return result;
}
}
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
io_buffer_validate_range(data, offset, length);
int descriptor = rb_io_descriptor(io);
const void * base;
size_t size;
io_buffer_get_bytes_for_reading(data, &base, &size);
struct io_buffer_pwrite_internal_argument argument = {
.descriptor = descriptor,
// Move the base pointer to the offset:
.base = (unsigned char *)base + offset,
// And the size to the length of data we want to read:
.size = length,
// And the offset in the file we want to write from:
.offset = from,
};
return rb_thread_io_blocking_region(io_buffer_pwrite_internal, &argument, descriptor);
}
/*
* call-seq: pwrite(io, from, length, [offset]) -> written length or -errno
*
* Writes +length+ bytes from buffer into +io+, starting at
* +offset+ in the buffer. If an error occurs, return <tt>-errno</tt>.
*
* If +offset+ is not given, the bytes are taken from the beginning of the
* buffer. If the +offset+ is given and is beyond the end of the file, the
* gap will be filled with null (0 value) bytes.
*
* out = File.open('output.txt', File::RDWR) # open for read/write, no truncation
* IO::Buffer.for('1234567').pwrite(out, 2, 3, 1)
*
* This leads to +234+ (3 bytes, starting from position 1) being written into
* <tt>output.txt</tt>, starting from file position 2.
*/
static VALUE
io_buffer_pwrite(int argc, VALUE *argv, VALUE self)
{
rb_check_arity(argc, 3, 4);
VALUE io = argv[0];
rb_off_t from = NUM2OFFT(argv[1]);
size_t length;
if (rb_int_negative_p(argv[2])) {
rb_raise(rb_eArgError, "Length can't be negative!");
}
length = NUM2SIZET(argv[2]);
size_t offset = 0;
if (argc >= 4) {
if (rb_int_negative_p(argv[3])) {
rb_raise(rb_eArgError, "Offset can't be negative!");
}
offset = NUM2SIZET(argv[3]);
}
return rb_io_buffer_pwrite(self, io, from, length, offset);
}
static inline void
io_buffer_check_mask(const struct rb_io_buffer *buffer)
{
if (buffer->size == 0)
rb_raise(rb_eIOBufferMaskError, "Zero-length mask given!");
}
static void
memory_and(unsigned char * restrict output, unsigned char * restrict base, size_t size, unsigned char * restrict mask, size_t mask_size)
{
for (size_t offset = 0; offset < size; offset += 1) {
output[offset] = base[offset] & mask[offset % mask_size];
}
}
/*
* call-seq:
* source & mask -> io_buffer
*
* Generate a new buffer the same size as the source by applying the binary AND
* operation to the source, using the mask, repeating as necessary.
*
* IO::Buffer.for("1234567890") & IO::Buffer.for("\xFF\x00\x00\xFF")
* # =>
* # #<IO::Buffer 0x00005589b2758480+4 INTERNAL>
* # 0x00000000 31 00 00 34 35 00 00 38 39 00 1..45..89.
*/
static VALUE
io_buffer_and(VALUE self, VALUE mask)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
struct rb_io_buffer *mask_data = NULL;
TypedData_Get_Struct(mask, struct rb_io_buffer, &rb_io_buffer_type, mask_data);
io_buffer_check_mask(mask_data);
VALUE output = rb_io_buffer_new(NULL, data->size, io_flags_for_size(data->size));
struct rb_io_buffer *output_data = NULL;
TypedData_Get_Struct(output, struct rb_io_buffer, &rb_io_buffer_type, output_data);
memory_and(output_data->base, data->base, data->size, mask_data->base, mask_data->size);
return output;
}
static void
memory_or(unsigned char * restrict output, unsigned char * restrict base, size_t size, unsigned char * restrict mask, size_t mask_size)
{
for (size_t offset = 0; offset < size; offset += 1) {
output[offset] = base[offset] | mask[offset % mask_size];
}
}
/*
* call-seq:
* source | mask -> io_buffer
*
* Generate a new buffer the same size as the source by applying the binary OR
* operation to the source, using the mask, repeating as necessary.
*
* IO::Buffer.for("1234567890") | IO::Buffer.for("\xFF\x00\x00\xFF")
* # =>
* # #<IO::Buffer 0x0000561785ae3480+10 INTERNAL>
* # 0x00000000 ff 32 33 ff ff 36 37 ff ff 30 .23..67..0
*/
static VALUE
io_buffer_or(VALUE self, VALUE mask)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
struct rb_io_buffer *mask_data = NULL;
TypedData_Get_Struct(mask, struct rb_io_buffer, &rb_io_buffer_type, mask_data);
io_buffer_check_mask(mask_data);
VALUE output = rb_io_buffer_new(NULL, data->size, io_flags_for_size(data->size));
struct rb_io_buffer *output_data = NULL;
TypedData_Get_Struct(output, struct rb_io_buffer, &rb_io_buffer_type, output_data);
memory_or(output_data->base, data->base, data->size, mask_data->base, mask_data->size);
return output;
}
static void
memory_xor(unsigned char * restrict output, unsigned char * restrict base, size_t size, unsigned char * restrict mask, size_t mask_size)
{
for (size_t offset = 0; offset < size; offset += 1) {
output[offset] = base[offset] ^ mask[offset % mask_size];
}
}
/*
* call-seq:
* source ^ mask -> io_buffer
*
* Generate a new buffer the same size as the source by applying the binary XOR
* operation to the source, using the mask, repeating as necessary.
*
* IO::Buffer.for("1234567890") ^ IO::Buffer.for("\xFF\x00\x00\xFF")
* # =>
* # #<IO::Buffer 0x000055a2d5d10480+10 INTERNAL>
* # 0x00000000 ce 32 33 cb ca 36 37 c7 c6 30 .23..67..0
*/
static VALUE
io_buffer_xor(VALUE self, VALUE mask)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
struct rb_io_buffer *mask_data = NULL;
TypedData_Get_Struct(mask, struct rb_io_buffer, &rb_io_buffer_type, mask_data);
io_buffer_check_mask(mask_data);
VALUE output = rb_io_buffer_new(NULL, data->size, io_flags_for_size(data->size));
struct rb_io_buffer *output_data = NULL;
TypedData_Get_Struct(output, struct rb_io_buffer, &rb_io_buffer_type, output_data);
memory_xor(output_data->base, data->base, data->size, mask_data->base, mask_data->size);
return output;
}
static void
memory_not(unsigned char * restrict output, unsigned char * restrict base, size_t size)
{
for (size_t offset = 0; offset < size; offset += 1) {
output[offset] = ~base[offset];
}
}
/*
* call-seq:
* ~source -> io_buffer
*
* Generate a new buffer the same size as the source by applying the binary NOT
* operation to the source.
*
* ~IO::Buffer.for("1234567890")
* # =>
* # #<IO::Buffer 0x000055a5ac42f120+10 INTERNAL>
* # 0x00000000 ce cd cc cb ca c9 c8 c7 c6 cf ..........
*/
static VALUE
io_buffer_not(VALUE self)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
VALUE output = rb_io_buffer_new(NULL, data->size, io_flags_for_size(data->size));
struct rb_io_buffer *output_data = NULL;
TypedData_Get_Struct(output, struct rb_io_buffer, &rb_io_buffer_type, output_data);
memory_not(output_data->base, data->base, data->size);
return output;
}
static inline int
io_buffer_overlaps(const struct rb_io_buffer *a, const struct rb_io_buffer *b)
{
if (a->base > b->base) {
return io_buffer_overlaps(b, a);
}
return (b->base >= a->base) && (b->base <= (void*)((unsigned char *)a->base + a->size));
}
static inline void
io_buffer_check_overlaps(struct rb_io_buffer *a, struct rb_io_buffer *b)
{
if (io_buffer_overlaps(a, b))
rb_raise(rb_eIOBufferMaskError, "Mask overlaps source data!");
}
static void
memory_and_inplace(unsigned char * restrict base, size_t size, unsigned char * restrict mask, size_t mask_size)
{
for (size_t offset = 0; offset < size; offset += 1) {
base[offset] &= mask[offset % mask_size];
}
}
/*
* call-seq:
* source.and!(mask) -> io_buffer
*
* Modify the source buffer in place by applying the binary AND
* operation to the source, using the mask, repeating as necessary.
*
* source = IO::Buffer.for("1234567890").dup # Make a read/write copy.
* # =>
* # #<IO::Buffer 0x000056307a0d0c20+10 INTERNAL>
* # 0x00000000 31 32 33 34 35 36 37 38 39 30 1234567890
*
* source.and!(IO::Buffer.for("\xFF\x00\x00\xFF"))
* # =>
* # #<IO::Buffer 0x000056307a0d0c20+10 INTERNAL>
* # 0x00000000 31 00 00 34 35 00 00 38 39 00 1..45..89.
*/
static VALUE
io_buffer_and_inplace(VALUE self, VALUE mask)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
struct rb_io_buffer *mask_data = NULL;
TypedData_Get_Struct(mask, struct rb_io_buffer, &rb_io_buffer_type, mask_data);
io_buffer_check_mask(mask_data);
io_buffer_check_overlaps(data, mask_data);
void *base;
size_t size;
io_buffer_get_bytes_for_writing(data, &base, &size);
memory_and_inplace(base, size, mask_data->base, mask_data->size);
return self;
}
static void
memory_or_inplace(unsigned char * restrict base, size_t size, unsigned char * restrict mask, size_t mask_size)
{
for (size_t offset = 0; offset < size; offset += 1) {
base[offset] |= mask[offset % mask_size];
}
}
/*
* call-seq:
* source.or!(mask) -> io_buffer
*
* Modify the source buffer in place by applying the binary OR
* operation to the source, using the mask, repeating as necessary.
*
* source = IO::Buffer.for("1234567890").dup # Make a read/write copy.
* # =>
* # #<IO::Buffer 0x000056307a272350+10 INTERNAL>
* # 0x00000000 31 32 33 34 35 36 37 38 39 30 1234567890
*
* source.or!(IO::Buffer.for("\xFF\x00\x00\xFF"))
* # =>
* # #<IO::Buffer 0x000056307a272350+10 INTERNAL>
* # 0x00000000 ff 32 33 ff ff 36 37 ff ff 30 .23..67..0
*/
static VALUE
io_buffer_or_inplace(VALUE self, VALUE mask)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
struct rb_io_buffer *mask_data = NULL;
TypedData_Get_Struct(mask, struct rb_io_buffer, &rb_io_buffer_type, mask_data);
io_buffer_check_mask(mask_data);
io_buffer_check_overlaps(data, mask_data);
void *base;
size_t size;
io_buffer_get_bytes_for_writing(data, &base, &size);
memory_or_inplace(base, size, mask_data->base, mask_data->size);
return self;
}
static void
memory_xor_inplace(unsigned char * restrict base, size_t size, unsigned char * restrict mask, size_t mask_size)
{
for (size_t offset = 0; offset < size; offset += 1) {
base[offset] ^= mask[offset % mask_size];
}
}
/*
* call-seq:
* source.xor!(mask) -> io_buffer
*
* Modify the source buffer in place by applying the binary XOR
* operation to the source, using the mask, repeating as necessary.
*
* source = IO::Buffer.for("1234567890").dup # Make a read/write copy.
* # =>
* # #<IO::Buffer 0x000056307a25b3e0+10 INTERNAL>
* # 0x00000000 31 32 33 34 35 36 37 38 39 30 1234567890
*
* source.xor!(IO::Buffer.for("\xFF\x00\x00\xFF"))
* # =>
* # #<IO::Buffer 0x000056307a25b3e0+10 INTERNAL>
* # 0x00000000 ce 32 33 cb ca 36 37 c7 c6 30 .23..67..0
*/
static VALUE
io_buffer_xor_inplace(VALUE self, VALUE mask)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
struct rb_io_buffer *mask_data = NULL;
TypedData_Get_Struct(mask, struct rb_io_buffer, &rb_io_buffer_type, mask_data);
io_buffer_check_mask(mask_data);
io_buffer_check_overlaps(data, mask_data);
void *base;
size_t size;
io_buffer_get_bytes_for_writing(data, &base, &size);
memory_xor_inplace(base, size, mask_data->base, mask_data->size);
return self;
}
static void
memory_not_inplace(unsigned char * restrict base, size_t size)
{
for (size_t offset = 0; offset < size; offset += 1) {
base[offset] = ~base[offset];
}
}
/*
* call-seq:
* source.not! -> io_buffer
*
* Modify the source buffer in place by applying the binary NOT
* operation to the source.
*
* source = IO::Buffer.for("1234567890").dup # Make a read/write copy.
* # =>
* # #<IO::Buffer 0x000056307a33a450+10 INTERNAL>
* # 0x00000000 31 32 33 34 35 36 37 38 39 30 1234567890
*
* source.not!
* # =>
* # #<IO::Buffer 0x000056307a33a450+10 INTERNAL>
* # 0x00000000 ce cd cc cb ca c9 c8 c7 c6 cf ..........
*/
static VALUE
io_buffer_not_inplace(VALUE self)
{
struct rb_io_buffer *data = NULL;
TypedData_Get_Struct(self, struct rb_io_buffer, &rb_io_buffer_type, data);
void *base;
size_t size;
io_buffer_get_bytes_for_writing(data, &base, &size);
memory_not_inplace(base, size);
return self;
}
/*
* Document-class: IO::Buffer
*
* IO::Buffer is a low-level efficient buffer for input/output. There are three
* ways of using buffer:
*
* * Create an empty buffer with ::new, fill it with data using #copy or
* #set_value, #set_string, get data with #get_string;
* * Create a buffer mapped to some string with ::for, then it could be used
* both for reading with #get_string or #get_value, and writing (writing will
* change the source string, too);
* * Create a buffer mapped to some file with ::map, then it could be used for
* reading and writing the underlying file.
*
* Interaction with string and file memory is performed by efficient low-level
* C mechanisms like `memcpy`.
*
* The class is meant to be an utility for implementing more high-level mechanisms
* like Fiber::SchedulerInterface#io_read and Fiber::SchedulerInterface#io_write.
*
* <b>Examples of usage:</b>
*
* Empty buffer:
*
* buffer = IO::Buffer.new(8) # create empty 8-byte buffer
* # =>
* # #<IO::Buffer 0x0000555f5d1a5c50+8 INTERNAL>
* # ...
* buffer
* # =>
* # <IO::Buffer 0x0000555f5d156ab0+8 INTERNAL>
* # 0x00000000 00 00 00 00 00 00 00 00
* buffer.set_string('test', 2) # put there bytes of the "test" string, starting from offset 2
* # => 4
* buffer.get_string # get the result
* # => "\x00\x00test\x00\x00"
*
* \Buffer from string:
*
* string = 'data'
* buffer = IO::Buffer.for(string)
* # =>
* # #<IO::Buffer 0x00007f3f02be9b18+4 SLICE>
* # ...
* buffer
* # =>
* # #<IO::Buffer 0x00007f3f02be9b18+4 SLICE>
* # 0x00000000 64 61 74 61 data
*
* buffer.get_string(2) # read content starting from offset 2
* # => "ta"
* buffer.set_string('---', 1) # write content, starting from offset 1
* # => 3
* buffer
* # =>
* # #<IO::Buffer 0x00007f3f02be9b18+4 SLICE>
* # 0x00000000 64 2d 2d 2d d---
* string # original string changed, too
* # => "d---"
*
* \Buffer from file:
*
* File.write('test.txt', 'test data')
* # => 9
* buffer = IO::Buffer.map(File.open('test.txt'))
* # =>
* # #<IO::Buffer 0x00007f3f0768c000+9 MAPPED IMMUTABLE>
* # ...
* buffer.get_string(5, 2) # read 2 bytes, starting from offset 5
* # => "da"
* buffer.set_string('---', 1) # attempt to write
* # in `set_string': Buffer is not writable! (IO::Buffer::AccessError)
*
* # To create writable file-mapped buffer
* # Open file for read-write, pass size, offset, and flags=0
* buffer = IO::Buffer.map(File.open('test.txt', 'r+'), 9, 0, 0)
* buffer.set_string('---', 1)
* # => 3 -- bytes written
* File.read('test.txt')
* # => "t--- data"
*
* <b>The class is experimental and the interface is subject to change.</b>
*/
void
Init_IO_Buffer(void)
{
rb_cIOBuffer = rb_define_class_under(rb_cIO, "Buffer", rb_cObject);
rb_eIOBufferLockedError = rb_define_class_under(rb_cIOBuffer, "LockedError", rb_eRuntimeError);
rb_eIOBufferAllocationError = rb_define_class_under(rb_cIOBuffer, "AllocationError", rb_eRuntimeError);
rb_eIOBufferAccessError = rb_define_class_under(rb_cIOBuffer, "AccessError", rb_eRuntimeError);
rb_eIOBufferInvalidatedError = rb_define_class_under(rb_cIOBuffer, "InvalidatedError", rb_eRuntimeError);
rb_eIOBufferMaskError = rb_define_class_under(rb_cIOBuffer, "MaskError", rb_eArgError);
rb_define_alloc_func(rb_cIOBuffer, rb_io_buffer_type_allocate);
rb_define_singleton_method(rb_cIOBuffer, "for", rb_io_buffer_type_for, 1);
rb_define_singleton_method(rb_cIOBuffer, "string", rb_io_buffer_type_string, 1);
#ifdef _WIN32
SYSTEM_INFO info;
GetSystemInfo(&info);
RUBY_IO_BUFFER_PAGE_SIZE = info.dwPageSize;
#else /* not WIN32 */
RUBY_IO_BUFFER_PAGE_SIZE = sysconf(_SC_PAGESIZE);
#endif
RUBY_IO_BUFFER_DEFAULT_SIZE = io_buffer_default_size(RUBY_IO_BUFFER_PAGE_SIZE);
// Efficient sizing of mapped buffers:
rb_define_const(rb_cIOBuffer, "PAGE_SIZE", SIZET2NUM(RUBY_IO_BUFFER_PAGE_SIZE));
rb_define_const(rb_cIOBuffer, "DEFAULT_SIZE", SIZET2NUM(RUBY_IO_BUFFER_DEFAULT_SIZE));
rb_define_singleton_method(rb_cIOBuffer, "map", io_buffer_map, -1);
// General use:
rb_define_method(rb_cIOBuffer, "initialize", rb_io_buffer_initialize, -1);
rb_define_method(rb_cIOBuffer, "initialize_copy", rb_io_buffer_initialize_copy, 1);
rb_define_method(rb_cIOBuffer, "inspect", rb_io_buffer_inspect, 0);
rb_define_method(rb_cIOBuffer, "hexdump", rb_io_buffer_hexdump, 0);
rb_define_method(rb_cIOBuffer, "to_s", rb_io_buffer_to_s, 0);
rb_define_method(rb_cIOBuffer, "size", rb_io_buffer_size, 0);
rb_define_method(rb_cIOBuffer, "valid?", rb_io_buffer_valid_p, 0);
// Ownership:
rb_define_method(rb_cIOBuffer, "transfer", rb_io_buffer_transfer, 0);
// Flags:
rb_define_const(rb_cIOBuffer, "EXTERNAL", RB_INT2NUM(RB_IO_BUFFER_EXTERNAL));
rb_define_const(rb_cIOBuffer, "INTERNAL", RB_INT2NUM(RB_IO_BUFFER_INTERNAL));
rb_define_const(rb_cIOBuffer, "MAPPED", RB_INT2NUM(RB_IO_BUFFER_MAPPED));
rb_define_const(rb_cIOBuffer, "SHARED", RB_INT2NUM(RB_IO_BUFFER_SHARED));
rb_define_const(rb_cIOBuffer, "LOCKED", RB_INT2NUM(RB_IO_BUFFER_LOCKED));
rb_define_const(rb_cIOBuffer, "PRIVATE", RB_INT2NUM(RB_IO_BUFFER_PRIVATE));
rb_define_const(rb_cIOBuffer, "READONLY", RB_INT2NUM(RB_IO_BUFFER_READONLY));
// Endian:
rb_define_const(rb_cIOBuffer, "LITTLE_ENDIAN", RB_INT2NUM(RB_IO_BUFFER_LITTLE_ENDIAN));
rb_define_const(rb_cIOBuffer, "BIG_ENDIAN", RB_INT2NUM(RB_IO_BUFFER_BIG_ENDIAN));
rb_define_const(rb_cIOBuffer, "HOST_ENDIAN", RB_INT2NUM(RB_IO_BUFFER_HOST_ENDIAN));
rb_define_const(rb_cIOBuffer, "NETWORK_ENDIAN", RB_INT2NUM(RB_IO_BUFFER_NETWORK_ENDIAN));
rb_define_method(rb_cIOBuffer, "null?", rb_io_buffer_null_p, 0);
rb_define_method(rb_cIOBuffer, "empty?", rb_io_buffer_empty_p, 0);
rb_define_method(rb_cIOBuffer, "external?", rb_io_buffer_external_p, 0);
rb_define_method(rb_cIOBuffer, "internal?", rb_io_buffer_internal_p, 0);
rb_define_method(rb_cIOBuffer, "mapped?", rb_io_buffer_mapped_p, 0);
rb_define_method(rb_cIOBuffer, "shared?", rb_io_buffer_shared_p, 0);
rb_define_method(rb_cIOBuffer, "locked?", rb_io_buffer_locked_p, 0);
rb_define_method(rb_cIOBuffer, "readonly?", io_buffer_readonly_p, 0);
// Locking to prevent changes while using pointer:
// rb_define_method(rb_cIOBuffer, "lock", rb_io_buffer_lock, 0);
// rb_define_method(rb_cIOBuffer, "unlock", rb_io_buffer_unlock, 0);
rb_define_method(rb_cIOBuffer, "locked", rb_io_buffer_locked, 0);
// Manipulation:
rb_define_method(rb_cIOBuffer, "slice", io_buffer_slice, -1);
rb_define_method(rb_cIOBuffer, "<=>", rb_io_buffer_compare, 1);
rb_define_method(rb_cIOBuffer, "resize", io_buffer_resize, 1);
rb_define_method(rb_cIOBuffer, "clear", io_buffer_clear, -1);
rb_define_method(rb_cIOBuffer, "free", rb_io_buffer_free, 0);
rb_include_module(rb_cIOBuffer, rb_mComparable);
#define IO_BUFFER_DEFINE_DATA_TYPE(name) RB_IO_BUFFER_DATA_TYPE_##name = rb_intern_const(#name)
IO_BUFFER_DEFINE_DATA_TYPE(U8);
IO_BUFFER_DEFINE_DATA_TYPE(S8);
IO_BUFFER_DEFINE_DATA_TYPE(u16);
IO_BUFFER_DEFINE_DATA_TYPE(U16);
IO_BUFFER_DEFINE_DATA_TYPE(s16);
IO_BUFFER_DEFINE_DATA_TYPE(S16);
IO_BUFFER_DEFINE_DATA_TYPE(u32);
IO_BUFFER_DEFINE_DATA_TYPE(U32);
IO_BUFFER_DEFINE_DATA_TYPE(s32);
IO_BUFFER_DEFINE_DATA_TYPE(S32);
IO_BUFFER_DEFINE_DATA_TYPE(u64);
IO_BUFFER_DEFINE_DATA_TYPE(U64);
IO_BUFFER_DEFINE_DATA_TYPE(s64);
IO_BUFFER_DEFINE_DATA_TYPE(S64);
IO_BUFFER_DEFINE_DATA_TYPE(f32);
IO_BUFFER_DEFINE_DATA_TYPE(F32);
IO_BUFFER_DEFINE_DATA_TYPE(f64);
IO_BUFFER_DEFINE_DATA_TYPE(F64);
#undef IO_BUFFER_DEFINE_DATA_TYPE
rb_define_singleton_method(rb_cIOBuffer, "size_of", io_buffer_size_of, 1);
// Data access:
rb_define_method(rb_cIOBuffer, "get_value", io_buffer_get_value, 2);
rb_define_method(rb_cIOBuffer, "get_values", io_buffer_get_values, 2);
rb_define_method(rb_cIOBuffer, "each", io_buffer_each, -1);
rb_define_method(rb_cIOBuffer, "values", io_buffer_values, -1);
rb_define_method(rb_cIOBuffer, "each_byte", io_buffer_each_byte, -1);
rb_define_method(rb_cIOBuffer, "set_value", io_buffer_set_value, 3);
rb_define_method(rb_cIOBuffer, "set_values", io_buffer_set_values, 3);
rb_define_method(rb_cIOBuffer, "copy", io_buffer_copy, -1);
rb_define_method(rb_cIOBuffer, "get_string", io_buffer_get_string, -1);
rb_define_method(rb_cIOBuffer, "set_string", io_buffer_set_string, -1);
// Binary data manipulations:
rb_define_method(rb_cIOBuffer, "&", io_buffer_and, 1);
rb_define_method(rb_cIOBuffer, "|", io_buffer_or, 1);
rb_define_method(rb_cIOBuffer, "^", io_buffer_xor, 1);
rb_define_method(rb_cIOBuffer, "~", io_buffer_not, 0);
rb_define_method(rb_cIOBuffer, "and!", io_buffer_and_inplace, 1);
rb_define_method(rb_cIOBuffer, "or!", io_buffer_or_inplace, 1);
rb_define_method(rb_cIOBuffer, "xor!", io_buffer_xor_inplace, 1);
rb_define_method(rb_cIOBuffer, "not!", io_buffer_not_inplace, 0);
// IO operations:
rb_define_method(rb_cIOBuffer, "read", io_buffer_read, -1);
rb_define_method(rb_cIOBuffer, "pread", io_buffer_pread, -1);
rb_define_method(rb_cIOBuffer, "write", io_buffer_write, -1);
rb_define_method(rb_cIOBuffer, "pwrite", io_buffer_pwrite, -1);
}
|