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

#[cfg(ruby_use_flonum)]
mod flonum;

#[cfg(not(feature = "deprecated-send-sync-value"))]
use std::marker::PhantomData;
use std::{
    borrow::{Borrow, Cow},
    cell::UnsafeCell,
    ffi::CStr,
    fmt,
    hash::{Hash, Hasher},
    mem::transmute,
    num::NonZeroUsize,
    ops::{Deref, DerefMut},
    os::raw::{c_char, c_int, c_long, c_ulong},
    ptr,
    sync::Once,
};

#[cfg(ruby_use_flonum)]
pub use flonum::Flonum;
use rb_sys::{
    rb_any_to_s, rb_block_call_kw, rb_check_funcall_kw, rb_check_id, rb_check_id_cstr,
    rb_check_symbol_cstr, rb_enumeratorize_with_size_kw, rb_eql, rb_equal,
    rb_funcall_with_block_kw, rb_funcallv_kw, rb_funcallv_public_kw, rb_gc_register_address,
    rb_gc_unregister_address, rb_hash, rb_id2name, rb_id2sym, rb_inspect, rb_intern3, rb_ll2inum,
    rb_obj_as_string, rb_obj_classname, rb_obj_freeze, rb_obj_is_kind_of, rb_obj_respond_to,
    rb_sym2id, rb_ull2inum, ruby_fl_type, ruby_special_consts, ruby_value_type, RBasic, ID, VALUE,
};

// These don't seem to appear consistently in bindgen output, not sure if they
// aren't consistently defined in the headers or what. Lets just do it
// ourselves.
const RUBY_FIXNUM_MAX: c_ulong = (c_long::MAX / 2) as c_ulong;
const RUBY_FIXNUM_MIN: c_long = c_long::MIN / 2;

use crate::{
    block::Proc,
    class::RClass,
    encoding::EncodingCapable,
    enumerator::Enumerator,
    error::{protect, Error},
    gc,
    integer::{Integer, IntegerType},
    into_value::{kw_splat, ArgList, IntoValue, IntoValueFromNative},
    method::{Block, BlockReturn},
    module::Module,
    numeric::Numeric,
    r_bignum::RBignum,
    r_string::RString,
    symbol::{IntoSymbol, Symbol},
    try_convert::{TryConvert, TryConvertOwned},
    Ruby,
};

/// Ruby's `VALUE` type, which can represent any Ruby object.
///
/// Methods for `Value` are implemented on the [`ReprValue`] trait, which is
/// also implemented for all Ruby types.
#[cfg(feature = "deprecated-send-sync-value")]
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct Value(VALUE);

/// Ruby's `VALUE` type, which can represent any Ruby object.
///
/// Methods for `Value` are implemented on the [`ReprValue`] trait, which is
/// also implemented for all Ruby types.
#[cfg(not(feature = "deprecated-send-sync-value"))]
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct Value(VALUE, PhantomData<*mut RBasic>);

impl Value {
    #[cfg(feature = "deprecated-send-sync-value")]
    #[inline]
    pub(crate) const fn new(val: VALUE) -> Self {
        Self(val)
    }

    #[cfg(not(feature = "deprecated-send-sync-value"))]
    #[inline]
    pub(crate) const fn new(val: VALUE) -> Self {
        Self(val, PhantomData)
    }

    #[inline]
    pub(crate) const fn as_rb_value(self) -> VALUE {
        self.0
    }

    #[doc(hidden)]
    #[deprecated(
        since = "0.6.0",
        note = "please use `TryConvert::try_convert` or `T::try_convert` instead"
    )]
    pub fn try_convert<T>(self) -> Result<T, Error>
    where
        T: TryConvert,
    {
        T::try_convert(self.as_value())
    }
}

impl fmt::Display for Value {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", unsafe { self.to_s_infallible() })
    }
}

impl fmt::Debug for Value {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.inspect())
    }
}

impl IntoValue for Value {
    #[inline]
    fn into_value_with(self, _: &Ruby) -> Value {
        self
    }
}

impl IntoValue for i8 {
    #[inline]
    fn into_value_with(self, handle: &Ruby) -> Value {
        handle.integer_from_i64(self as i64).into_value_with(handle)
    }
}

unsafe impl IntoValueFromNative for i8 {}

impl IntoValue for i16 {
    #[inline]
    fn into_value_with(self, handle: &Ruby) -> Value {
        handle.integer_from_i64(self as i64).into_value_with(handle)
    }
}

unsafe impl IntoValueFromNative for i16 {}

impl IntoValue for i32 {
    #[inline]
    fn into_value_with(self, handle: &Ruby) -> Value {
        handle.integer_from_i64(self as i64).into_value_with(handle)
    }
}

unsafe impl IntoValueFromNative for i32 {}

impl IntoValue for i64 {
    #[inline]
    fn into_value_with(self, handle: &Ruby) -> Value {
        handle.integer_from_i64(self).into_value_with(handle)
    }
}

unsafe impl IntoValueFromNative for i64 {}

impl IntoValue for isize {
    #[inline]
    fn into_value_with(self, handle: &Ruby) -> Value {
        handle.integer_from_i64(self as i64).into_value_with(handle)
    }
}

unsafe impl IntoValueFromNative for isize {}

impl IntoValue for u8 {
    #[inline]
    fn into_value_with(self, handle: &Ruby) -> Value {
        handle.integer_from_u64(self as u64).into_value_with(handle)
    }
}

unsafe impl IntoValueFromNative for u8 {}

impl IntoValue for u16 {
    #[inline]
    fn into_value_with(self, handle: &Ruby) -> Value {
        handle.integer_from_u64(self as u64).into_value_with(handle)
    }
}

unsafe impl IntoValueFromNative for u16 {}

impl IntoValue for u32 {
    #[inline]
    fn into_value_with(self, handle: &Ruby) -> Value {
        handle.integer_from_u64(self as u64).into_value_with(handle)
    }
}

unsafe impl IntoValueFromNative for u32 {}

impl IntoValue for u64 {
    #[inline]
    fn into_value_with(self, handle: &Ruby) -> Value {
        handle.integer_from_u64(self).into_value_with(handle)
    }
}

unsafe impl IntoValueFromNative for u64 {}

impl IntoValue for usize {
    #[inline]
    fn into_value_with(self, handle: &Ruby) -> Value {
        handle.integer_from_u64(self as u64).into_value_with(handle)
    }
}

unsafe impl IntoValueFromNative for usize {}

impl IntoValue for f32 {
    #[inline]
    fn into_value_with(self, handle: &Ruby) -> Value {
        handle.float_from_f64(self as f64).into_value_with(handle)
    }
}

unsafe impl IntoValueFromNative for f32 {}

impl IntoValue for f64 {
    #[inline]
    fn into_value_with(self, handle: &Ruby) -> Value {
        handle.float_from_f64(self).into_value_with(handle)
    }
}

unsafe impl IntoValueFromNative for f64 {}

impl TryConvert for Value {
    #[inline]
    fn try_convert(val: Value) -> Result<Self, Error> {
        Ok(val)
    }
}

/// A wrapper to make a Ruby type [`Send`] + [`Sync`].
///
/// Ruby types are not [`Send`] or [`Sync`] as they provide a way to call
/// Ruby's APIs, which it is not safe to do from a non-Ruby thread.
///
/// Ruby types are safe to send between Ruby threads, but Rust's trait system
/// currently can not model this detail.
///
/// To resolve this, the `Opaque` type makes a Ruby type [`Send`] + [`Sync`]
/// by removing the ability to do anything with it, making it impossible to
/// call Ruby's API on non-Ruby threads.
///
/// An `Opaque<T>` can be unwrapped to `T` with [`Ruby::get_inner`],
/// as it is only possible to instantiate a [`Ruby`] on a Ruby thread.
///
/// # Examples
///
/// ```
/// use magnus::{rb_assert, value::Opaque, Ruby};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// let ruby = Ruby::get().unwrap();
/// let opaque_str = Opaque::from(ruby.str_new("example"));
///
/// // send to another Ruby thread
///
/// let ruby = Ruby::get().unwrap(); // errors on non-Ruby thread
/// let str = ruby.get_inner(opaque_str);
/// rb_assert!(ruby, r#"str == "example""#, str);
/// ```
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct Opaque<T>(T);

// implementation detail for opaque_attr_accessor proc macro attribute
#[doc(hidden)]
pub trait OpaqueVal {
    type Val: ReprValue;
}

impl<T> OpaqueVal for Opaque<T>
where
    T: ReprValue,
{
    type Val = T;
}

impl<T> From<T> for Opaque<T>
where
    T: ReprValue,
{
    #[inline]
    fn from(val: T) -> Self {
        Self(val)
    }
}

impl<T> IntoValue for Opaque<T>
where
    T: IntoValue,
{
    #[inline]
    fn into_value_with(self, handle: &Ruby) -> Value {
        self.0.into_value_with(handle)
    }
}

/// Helper trait for [`Ruby::get_inner`].
///
/// This trait allows for [`Ruby::get_inner`] to get the inner value of both
/// [`Opaque`] and [`Lazy`].
pub trait InnerValue {
    /// The specific Ruby value type.
    type Value: ReprValue;

    /// Get the inner value from `self`.
    ///
    /// `ruby` acts as a token proving this is called from a Ruby thread and
    /// thus it is safe to return the inner value.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{
    ///     rb_assert,
    ///     value::{InnerValue, Opaque},
    ///     Ruby,
    /// };
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let ruby = Ruby::get().unwrap();
    /// let opaque_str = Opaque::from(ruby.str_new("example"));
    ///
    /// // send to another Ruby thread
    ///
    /// let ruby = Ruby::get().unwrap(); // errors on non-Ruby thread
    /// let str = opaque_str.get_inner_with(&ruby);
    /// rb_assert!(ruby, r#"str == "example""#, str);
    /// ```
    ///
    /// ```
    /// use magnus::{
    ///     rb_assert,
    ///     value::{InnerValue, Lazy},
    ///     RString, Ruby,
    /// };
    ///
    /// static STATIC_STR: Lazy<RString> = Lazy::new(|ruby| ruby.str_new("example"));
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let ruby = Ruby::get().unwrap(); // errors if Ruby not initialised
    /// let str = STATIC_STR.get_inner_with(&ruby);
    /// rb_assert!(ruby, r#"str == "example""#, str);
    /// ```
    fn get_inner_with(self, ruby: &Ruby) -> Self::Value;
}

impl<T> InnerValue for Opaque<T>
where
    T: ReprValue,
{
    type Value = T;

    #[inline]
    fn get_inner_with(self, _: &Ruby) -> Self::Value {
        self.0
    }
}

/// Helper trait for [`Ruby::get_inner_ref`].
///
/// This trait allows for [`Ruby::get_inner_ref`] to get a reference to the
/// inner value of both [`Opaque`] and [`Lazy`].
pub trait InnerRef {
    /// The specific Ruby value type.
    type Value: ReprValue;

    /// Get a reference to the inner value from `self`.
    ///
    /// `ruby` acts as a token proving this is called from a Ruby thread and
    /// thus it is safe to access the inner value.
    fn get_inner_ref_with<'a>(&'a self, ruby: &Ruby) -> &'a Self::Value;
}

impl<T> InnerRef for Opaque<T>
where
    T: ReprValue,
{
    type Value = T;

    #[inline]
    fn get_inner_ref_with<'a>(&'a self, _: &Ruby) -> &'a Self::Value {
        &self.0
    }
}

/// # Extracting values from `Opaque`/`Lazy`
///
/// Magnus has a number of container types where it is only safe to access the
/// inner Ruby value when you can provide a `Ruby` handle. The functions here
/// provide a unified api to access those container types.
///
/// See also the [`Opaque`] and [`Lazy`] types.
impl Ruby {
    /// Get the inner value from `wrapper`.
    ///
    /// `self` acts as a token proving this is called from a Ruby thread and
    /// thus it is safe to return the inner value. See [`Opaque`] and [`Lazy`].
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{rb_assert, value::Opaque, Ruby};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let ruby = Ruby::get().unwrap();
    /// let opaque_str = Opaque::from(ruby.str_new("example"));
    ///
    /// // send to another Ruby thread
    ///
    /// let ruby = Ruby::get().unwrap(); // errors on non-Ruby thread
    /// let str = ruby.get_inner(opaque_str);
    /// rb_assert!(ruby, r#"str == "example""#, str);
    /// ```
    ///
    /// ```
    /// use magnus::{rb_assert, value::Lazy, RString, Ruby};
    ///
    /// static STATIC_STR: Lazy<RString> = Lazy::new(|ruby| ruby.str_new("example"));
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let ruby = Ruby::get().unwrap(); // errors if Ruby not initialised
    /// let str = ruby.get_inner(&STATIC_STR);
    /// rb_assert!(ruby, r#"str == "example""#, str);
    /// ```
    #[inline]
    pub fn get_inner<T>(&self, wrapper: impl InnerValue<Value = T>) -> T
    where
        T: ReprValue,
    {
        wrapper.get_inner_with(self)
    }

    /// Get a reference to the inner value of `wrapper`.
    ///
    /// `self` acts as a token proving this is called from a Ruby thread and
    /// thus it is safe to access the inner value. See [`Opaque`] and [`Lazy`].
    #[inline]
    pub fn get_inner_ref<'a, T>(&self, wrapper: &'a impl InnerRef<Value = T>) -> &'a T
    where
        T: ReprValue,
    {
        wrapper.get_inner_ref_with(self)
    }
}

unsafe impl<T: ReprValue> Send for Opaque<T> {}
unsafe impl<T: ReprValue> Sync for Opaque<T> {}

/// Lazily initialise a Ruby value so it can be assigned to a `static`.
///
/// Ruby types require the Ruby VM to be started before they can be initialise,
/// so can't be assigned to `static`s. They also can't safely be used from
/// non-Ruby threads, which a `static` Ruby value would allow.
///
/// Lazy allows assigning a Ruby value to a static by lazily initialising it
/// on first use, and by requiring a value of [`Ruby`] to access the inner
/// value, which it is only possible to obtain once the Ruby VM has started and
/// on  on a Ruby thread.
///
/// # Examples
///
/// ```
/// use magnus::{rb_assert, value::Lazy, RString, Ruby};
///
/// static STATIC_STR: Lazy<RString> = Lazy::new(|ruby| ruby.str_new("example"));
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// let ruby = Ruby::get().unwrap(); // errors if Ruby not initialised
/// let str = ruby.get_inner(&STATIC_STR);
/// rb_assert!(ruby, r#"str == "example""#, str);
/// ```
pub struct Lazy<T: ReprValue> {
    init: Once,
    mark: bool,
    func: fn(&Ruby) -> T,
    value: UnsafeCell<Value>,
}

impl<T> Lazy<T>
where
    T: ReprValue,
{
    /// Create a new `Lazy<T>`.
    ///
    /// This function can be called in a `const` context. `func` is evaluated
    /// when the `Lazy<T>` is first accessed (see [`Ruby::get_inner`]). If
    /// multiple threads attempt first access at the same time `func` may be
    /// called more than once, but all threads will recieve the same value.
    ///
    /// This function assumes the `Lazy<T>` will be assinged to a `static`, so
    /// marks the inner Ruby value with Ruby's garbage collector to never be
    /// garbage collected. See [`Lazy::new_without_mark`] if this is not wanted.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{rb_assert, value::Lazy, RString, Ruby};
    ///
    /// static STATIC_STR: Lazy<RString> = Lazy::new(|ruby| ruby.str_new("example"));
    ///
    /// # let _cleanup = unsafe { magnus::embed::init() };
    /// let ruby = Ruby::get().unwrap();
    /// let str = ruby.get_inner(&STATIC_STR);
    /// rb_assert!(ruby, r#"str == "example""#, str);
    /// ```
    pub const fn new(func: fn(&Ruby) -> T) -> Self {
        Self {
            init: Once::new(),
            mark: true,
            func,
            #[allow(deprecated)]
            value: UnsafeCell::new(QNIL.0.get()),
        }
    }

    /// Create a new `Lazy<T>` without protecting the inner value from Ruby's
    /// garbage collector.
    ///
    /// # Safety
    ///
    /// The `Lazy<T>` returned from this function must be kept on the stack, or
    /// the inner value otherwise protected from Ruby's garbage collector.
    pub const unsafe fn new_without_mark(func: fn(&Ruby) -> T) -> Self {
        Self {
            init: Once::new(),
            mark: false,
            func,
            #[allow(deprecated)]
            value: UnsafeCell::new(QNIL.0.get()),
        }
    }

    /// Force evaluation of a `Lazy<T>`.
    ///
    /// This can be used in, for example, your [`init`](macro@crate::init)
    /// function to force initialisation of the `Lazy<T>`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{value::Lazy, RString, Ruby};
    ///
    /// static STATIC_STR: Lazy<RString> = Lazy::new(|ruby| ruby.str_new("example"));
    ///
    /// #[magnus::init]
    /// fn init(ruby: &Ruby) {
    ///     Lazy::force(&STATIC_STR, ruby);
    ///
    ///     assert!(Lazy::try_get_inner(&STATIC_STR).is_some());
    /// }
    /// # let ruby = unsafe { magnus::embed::init() };
    /// # init(&ruby);
    /// ```
    #[inline]
    pub fn force(this: &Self, handle: &Ruby) {
        handle.get_inner(this);
    }

    /// Get the inner value as an [`Opaque<T>`](Opaque) from a `Lazy<T>`, if
    /// it has already been initialised.
    ///
    /// This function will not call Ruby and will not initialise the inner
    /// value. If the `Lazy<T>` has not yet been initialised, returns `None`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{rb_assert, value::Lazy, RString, Ruby};
    ///
    /// static STATIC_STR: Lazy<RString> = Lazy::new(|ruby| ruby.str_new("example"));
    ///
    /// # let _cleanup = unsafe { magnus::embed::init() };
    /// assert!(Lazy::try_get_inner(&STATIC_STR).is_none());
    ///
    /// let ruby = Ruby::get().unwrap();
    /// let str = ruby.get_inner(&STATIC_STR);
    /// rb_assert!(ruby, r#"str == "example""#, str);
    ///
    /// assert!(Lazy::try_get_inner(&STATIC_STR).is_some());
    /// ```
    pub fn try_get_inner(this: &Self) -> Option<Opaque<T>> {
        unsafe {
            this.init
                .is_completed()
                .then(|| T::from_value_unchecked(*this.value.get()).into())
        }
    }
}

unsafe impl<T: ReprValue> Sync for Lazy<T> {}

impl<T> InnerValue for &Lazy<T>
where
    T: ReprValue,
{
    type Value = T;

    #[inline]
    fn get_inner_with(self, ruby: &Ruby) -> Self::Value {
        *self.get_inner_ref_with(ruby)
    }
}

impl<T> InnerRef for Lazy<T>
where
    T: ReprValue,
{
    type Value = T;

    fn get_inner_ref_with<'a>(&'a self, ruby: &Ruby) -> &'a Self::Value {
        unsafe {
            if !self.init.is_completed() {
                let value = (self.func)(ruby);
                self.init.call_once(|| {
                    if self.mark {
                        gc::register_mark_object(value);
                    }
                    *self.value.get() = value.as_value();
                });
            }
            T::ref_from_ref_value_unchecked(&*self.value.get())
        }
    }
}

pub(crate) mod private {
    use super::*;
    use crate::value::ReprValue as _;

    /// Marker trait for types that have the same representation as [`Value`].
    ///
    /// Types that are `ReprValue` can be safely transmuted to Value.
    ///
    /// # Safety
    ///
    /// This trait should only be implemented for types that a guaranteed to
    /// have the same layout as [`Value`] and have come from the Ruby VM.
    pub unsafe trait ReprValue: Copy {
        /// Convert `val` to a `Self`.
        ///
        /// # Safety
        ///
        /// This should only be used when `val` is known to uphold all the
        // invariants of `Self`. It is recommended not to use this method.
        #[inline]
        unsafe fn from_value_unchecked(val: Value) -> Self {
            *(&val as *const Value as *const Self)
        }

        #[inline]
        unsafe fn ref_from_ref_value_unchecked(val: &Value) -> &Self {
            &*(val as *const Value as *const Self)
        }

        #[inline]
        fn copy_as_value(self) -> Value {
            // This trait is only ever implemented for things with the same
            // representation as Value
            unsafe { *(&self as *const Self as *const Value) }
        }

        #[inline]
        fn as_value_ref(&self) -> &Value {
            // This trait is only ever implemented for things with the same
            // representation as Value
            unsafe { &*(self as *const Self as *const Value) }
        }

        #[inline]
        fn as_rb_value(self) -> VALUE {
            self.copy_as_value().0
        }

        #[inline]
        unsafe fn r_basic_unchecked(self) -> ptr::NonNull<RBasic> {
            #[cfg(debug_assertions)]
            if self.is_immediate() {
                panic!("attempting to access immediate value as pointer");
            }
            ptr::NonNull::new_unchecked(self.copy_as_value().0 as *mut RBasic)
        }

        /// Returns whether `self` is an 'immediate' value.
        ///
        /// 'immediate' values are encoded directly into the `Value` and
        /// require no additional lookup. They will never be garbage
        /// collected.
        ///
        /// non-immediate values are pointers to other memory holding the data
        /// for the object.
        #[inline]
        fn is_immediate(self) -> bool {
            let value_p = self.as_rb_value();
            let immediate_p = value_p & ruby_special_consts::RUBY_IMMEDIATE_MASK as VALUE != 0;
            let test = value_p & !(ruby_special_consts::RUBY_Qnil as VALUE) != 0;
            immediate_p || !test // special_const_p
        }

        #[inline]
        fn r_basic(self) -> Option<ptr::NonNull<RBasic>> {
            unsafe { (!self.is_immediate()).then(|| self.r_basic_unchecked()) }
        }

        #[inline]
        fn is_false(self) -> bool {
            self.as_rb_value() == ruby_special_consts::RUBY_Qfalse as VALUE
        }

        #[inline]
        fn is_true(self) -> bool {
            self.as_rb_value() == ruby_special_consts::RUBY_Qtrue as VALUE
        }

        #[inline]
        fn is_undef(self) -> bool {
            self.as_rb_value() == ruby_special_consts::RUBY_Qundef as VALUE
        }

        #[inline]
        fn is_fixnum(self) -> bool {
            self.as_rb_value() & ruby_special_consts::RUBY_FIXNUM_FLAG as VALUE != 0
        }

        #[inline]
        fn is_static_symbol(self) -> bool {
            const MASK: usize = !(usize::MAX << ruby_special_consts::RUBY_SPECIAL_SHIFT as usize);
            self.as_rb_value() as usize & MASK == ruby_special_consts::RUBY_SYMBOL_FLAG as usize
        }

        #[inline]
        fn is_flonum(self) -> bool {
            self.as_rb_value() & ruby_special_consts::RUBY_FLONUM_MASK as VALUE
                == ruby_special_consts::RUBY_FLONUM_FLAG as VALUE
        }

        // derefs a raw pointer that under GC compaction may be outside the
        // process's memory space if the Value has been allowed to get GC'd
        #[inline]
        fn rb_type(self) -> ruby_value_type {
            match self.r_basic() {
                Some(r_basic) => {
                    unsafe {
                        let ret = r_basic.as_ref().flags & (ruby_value_type::RUBY_T_MASK as VALUE);
                        // this bit is safe, ruby_value_type is #[repr(u32)], the flags
                        // value set by Ruby, and Ruby promises that flags masked like
                        // this will always be a valid entry in this enum
                        std::mem::transmute(ret as u32)
                    }
                }
                None => {
                    if self.is_false() {
                        ruby_value_type::RUBY_T_FALSE
                    } else if self.copy_as_value().is_nil() {
                        ruby_value_type::RUBY_T_NIL
                    } else if self.is_true() {
                        ruby_value_type::RUBY_T_TRUE
                    } else if self.is_undef() {
                        ruby_value_type::RUBY_T_UNDEF
                    } else if self.is_fixnum() {
                        ruby_value_type::RUBY_T_FIXNUM
                    } else if self.is_static_symbol() {
                        ruby_value_type::RUBY_T_SYMBOL
                    } else if self.is_flonum() {
                        ruby_value_type::RUBY_T_FLOAT
                    } else {
                        unreachable!()
                    }
                }
            }
        }

        /// Convert `self` to a string. If an error is encountered returns a
        /// generic string (usually the object's class name).
        ///
        /// # Safety
        ///
        /// This may return a direct view of memory owned and managed by Ruby.
        /// Ruby may modify or free the memory backing the returned
        /// str, the caller must ensure this does not happen.
        #[allow(clippy::wrong_self_convention)]
        unsafe fn to_s_infallible(&self) -> Cow<str> {
            match self.as_value_ref().to_s() {
                Ok(v) => v,
                Err(_) => Cow::Owned(
                    RString::from_rb_value_unchecked(rb_any_to_s(self.as_rb_value()))
                        .to_string_lossy()
                        .into_owned(),
                ),
            }
        }
    }
}

use private::ReprValue as _;

/// Marker trait for types that have the same representation as [`Value`].
///
/// Types that are `ReprValue` can be safely transmuted to Value.
pub trait ReprValue: private::ReprValue {
    /// Return `self` as a [`Value`].
    #[inline]
    fn as_value(self) -> Value {
        // This trait is only ever implemented for things with the same
        // representation as Value
        unsafe { *(&self as *const Self as *const Value) }
    }

    /// Returns whether `self` is Ruby's `nil` value.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, prelude::*, Value};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// assert!(eval::<Value>("nil").unwrap().is_nil());
    /// assert!(!eval::<Value>("Object.new").unwrap().is_nil());
    /// assert!(!eval::<Value>("0").unwrap().is_nil());
    /// assert!(!eval::<Value>("[]").unwrap().is_nil());
    /// ```
    #[inline]
    fn is_nil(self) -> bool {
        self.as_rb_value() == ruby_special_consts::RUBY_Qnil as VALUE
    }

    /// Checks for equality, delegating to the Ruby method `#==`.
    ///
    /// Ruby optimises this check if `self` and `other` are the same object
    /// or some built-in types, then calling the `#==` method will be skipped.
    ///
    /// Returns `Err` if `#==` raises.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{prelude::*, Integer, RArray};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let a = RArray::from_vec(vec![1, 2, 3]);
    /// let b = RArray::from_vec(vec![1, 2, 3]);
    /// let c = RArray::from_vec(vec![4, 5, 6]);
    /// let d = Integer::from_i64(1);
    /// assert!(a.equal(a).unwrap());
    /// assert!(a.equal(b).unwrap());
    /// assert!(!a.equal(c).unwrap());
    /// assert!(!a.equal(d).unwrap());
    /// ```
    ///
    /// ```
    /// use magnus::{eval, prelude::*, Value};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let (a, b): (Value, Value) = eval!(
    ///     "
    ///     class Example
    ///       def ==(other)
    ///         raise
    ///       end
    ///     end
    ///     [Example.new, Example.new]
    /// "
    /// )
    /// .unwrap();
    ///
    /// assert!(a.equal(b).is_err());
    /// ```
    fn equal<T>(self, other: T) -> Result<bool, Error>
    where
        T: ReprValue,
    {
        unsafe {
            protect(|| Value::new(rb_equal(self.as_rb_value(), other.as_rb_value())))
                .map(Value::to_bool)
        }
    }

    /// Checks for equality, delegating to the Ruby method `#eql?`.
    ///
    /// See [`Value::equal`] for the equivalent of the `#==` method.
    ///
    /// Ruby optimises this check if `self` and `other` are the same object
    /// for some built-in types, then calling the `#==` method will be skipped.
    ///
    /// Returns `Err` if `#eql?` raises.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{prelude::*, Integer, RArray};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let a = RArray::from_vec(vec![1, 2, 3]);
    /// let b = RArray::from_vec(vec![1, 2, 3]);
    /// let c = RArray::from_vec(vec![4, 5, 6]);
    /// let d = Integer::from_i64(1);
    /// assert!(a.eql(a).unwrap());
    /// assert!(a.eql(b).unwrap());
    /// assert!(!a.eql(c).unwrap());
    /// assert!(!a.eql(d).unwrap());
    /// ```
    ///
    /// ```
    /// use magnus::{eval, prelude::*, Value};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let (a, b): (Value, Value) = eval!(
    ///     "
    ///       class Example
    ///         def eql?(other)
    ///           raise
    ///         end
    ///       end
    ///       [Example.new, Example.new]
    ///     "
    /// )
    /// .unwrap();
    ///
    /// assert!(a.eql(b).is_err());
    /// ```
    fn eql<T>(self, other: T) -> Result<bool, Error>
    where
        T: ReprValue,
    {
        unsafe {
            protect(|| Value::new(rb_eql(self.as_rb_value(), other.as_rb_value()) as VALUE))
                .map(Value::to_bool)
        }
    }

    /// Returns an integer non-uniquely identifying `self`.
    ///
    /// The return value is not stable between different Ruby processes.
    ///
    /// Ruby guarantees the return value will be in the range of a C `long`,
    /// this is usually equivalent to a `i64`, though will be `i32` on Windows.
    ///
    /// Ruby built-in classes will not error, but it is possible for badly
    /// behaving 3rd party classes (or collections such as `Array` containing
    /// them) to error in this function.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{prelude::*, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// assert!(RString::new("test")
    ///     .hash()
    ///     .unwrap()
    ///     .equal(RString::new("test").hash().unwrap())
    ///     .unwrap());
    /// ```
    fn hash(self) -> Result<Integer, Error> {
        unsafe { protect(|| Integer::from_rb_value_unchecked(rb_hash(self.as_rb_value()))) }
    }

    /// Returns the class that `self` is an instance of.
    ///
    /// # Panics
    ///
    /// panics if self is `Qundef`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, prelude::*, Value};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// assert_eq!(
    ///     eval::<Value>("true").unwrap().class().inspect(),
    ///     "TrueClass"
    /// );
    /// assert_eq!(eval::<Value>("[1,2,3]").unwrap().class().inspect(), "Array");
    /// ```
    fn class(self) -> RClass {
        let handle = Ruby::get_with(self);
        unsafe {
            match self.r_basic() {
                Some(r_basic) => RClass::from_rb_value_unchecked(r_basic.as_ref().klass),
                None => {
                    if self.is_false() {
                        handle.class_false_class()
                    } else if self.is_nil() {
                        handle.class_nil_class()
                    } else if self.is_true() {
                        handle.class_true_class()
                    } else if self.is_undef() {
                        panic!("undef does not have a class")
                    } else if self.is_fixnum() {
                        handle.class_integer()
                    } else if self.is_static_symbol() {
                        handle.class_symbol()
                    } else if self.is_flonum() {
                        handle.class_float()
                    } else {
                        unreachable!()
                    }
                }
            }
        }
    }

    /// Returns whether `self` is 'frozen'.
    ///
    /// Ruby prevents modifying frozen objects.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, prelude::*, Value};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// assert!(eval::<Value>(":foo").unwrap().is_frozen());
    /// assert!(eval::<Value>("42").unwrap().is_frozen());
    /// assert!(!eval::<Value>("[]").unwrap().is_frozen());
    /// ```
    fn is_frozen(self) -> bool {
        match self.r_basic() {
            None => true,
            Some(r_basic) => unsafe {
                r_basic.as_ref().flags & ruby_fl_type::RUBY_FL_FREEZE as VALUE != 0
            },
        }
    }

    /// Returns an error if `self` is 'frozen'.
    ///
    /// Useful for checking if an object is frozen in a function that would
    /// modify it.
    ///
    /// # Examples
    /// ```
    /// use magnus::{eval, prelude::*, Error, Value};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// fn mutate(val: Value) -> Result<(), Error> {
    ///     val.check_frozen()?;
    ///
    ///     // ...
    ///     Ok(())
    /// }
    ///
    /// assert!(mutate(eval("Object.new").unwrap()).is_ok());
    /// assert!(mutate(eval(":foo").unwrap()).is_err());
    /// ```
    fn check_frozen(self) -> Result<(), Error> {
        if self.is_frozen() {
            Err(Error::new(
                Ruby::get_with(self).exception_frozen_error(),
                format!("can't modify frozen {}", unsafe { self.classname() }),
            ))
        } else {
            Ok(())
        }
    }

    /// Mark `self` as frozen.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{prelude::*, RArray};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let ary = RArray::new();
    /// assert!(!ary.is_frozen());
    /// ary.freeze();
    /// assert!(ary.is_frozen());
    /// ```
    fn freeze(self) {
        unsafe { rb_obj_freeze(self.as_rb_value()) };
    }

    /// Convert `self` to a `bool`, following Ruby's rules of `false` and `nil`
    /// as boolean `false` and everything else boolean `true`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, prelude::*, Value};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// assert!(!eval::<Value>("false").unwrap().to_bool());
    /// assert!(!eval::<Value>("nil").unwrap().to_bool());
    ///
    /// assert!(eval::<Value>("true").unwrap().to_bool());
    /// assert!(eval::<Value>("0").unwrap().to_bool());
    /// assert!(eval::<Value>("[]").unwrap().to_bool());
    /// assert!(eval::<Value>(":foo").unwrap().to_bool());
    /// assert!(eval::<Value>("Object.new").unwrap().to_bool());
    /// ```
    #[inline]
    fn to_bool(self) -> bool {
        self.as_rb_value() & !(ruby_special_consts::RUBY_Qnil as VALUE) != 0
    }

    /// Call the method named `method` on `self` with `args`.
    ///
    /// Returns `Ok(T)` if the method returns without error and the return
    /// value converts to a `T`, or returns `Err` if the method raises or the
    /// conversion fails.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, prelude::*, RArray};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let values = eval::<RArray>(r#"["foo", 1, :bar]"#).unwrap();
    /// let result: String = values.funcall("join", (" & ",)).unwrap();
    /// assert_eq!(result, "foo & 1 & bar");
    /// ```
    ///
    /// ```
    /// use magnus::{eval, kwargs, prelude::*, RObject};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let object: RObject = eval!(
    ///     r#"
    ///     class Adder
    ///       def add(a, b, c:)
    ///         a + b + c
    ///       end
    ///     end
    ///
    ///     Adder.new
    /// "#
    /// )
    /// .unwrap();
    ///
    /// let result: i32 = object.funcall("add", (1, 2, kwargs!("c" => 3))).unwrap();
    /// assert_eq!(result, 6);
    /// ```
    fn funcall<M, A, T>(self, method: M, args: A) -> Result<T, Error>
    where
        M: IntoId,
        A: ArgList,
        T: TryConvert,
    {
        let handle = Ruby::get_with(self);
        let id = method.into_id_with(&handle);
        let kw_splat = kw_splat(&args);
        let args = args.into_arg_list_with(&handle);
        let slice = args.as_ref();
        unsafe {
            protect(|| {
                Value::new(rb_funcallv_kw(
                    self.as_rb_value(),
                    id.as_rb_id(),
                    slice.len() as c_int,
                    slice.as_ptr() as *const VALUE,
                    kw_splat as c_int,
                ))
            })
            .and_then(TryConvert::try_convert)
        }
    }

    /// Call the public method named `method` on `self` with `args`.
    ///
    /// Returns `Ok(T)` if the method returns without error and the return
    /// value converts to a `T`, or returns `Err` if the method raises or the
    /// conversion fails.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, prelude::*, Error, RObject, Symbol};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let object: RObject = eval!(
    ///     r#"
    ///     class Foo
    ///       def bar
    ///         :bar
    ///       end
    ///
    ///       private
    ///
    ///       def baz
    ///         :baz
    ///       end
    ///     end
    ///
    ///     Foo.new
    /// "#
    /// )
    /// .unwrap();
    ///
    /// let result: Symbol = object.funcall_public("bar", ()).unwrap();
    /// assert_eq!(result.name().unwrap(), "bar");
    ///
    /// let result: Result<Symbol, Error> = object.funcall_public("baz", ());
    /// assert!(result.is_err());
    /// ```
    fn funcall_public<M, A, T>(self, method: M, args: A) -> Result<T, Error>
    where
        M: IntoId,
        A: ArgList,
        T: TryConvert,
    {
        let handle = Ruby::get_with(self);
        let id = method.into_id_with(&handle);
        let kw_splat = kw_splat(&args);
        let args = args.into_arg_list_with(&handle);
        let slice = args.as_ref();
        unsafe {
            protect(|| {
                Value::new(rb_funcallv_public_kw(
                    self.as_rb_value(),
                    id.as_rb_id(),
                    slice.len() as c_int,
                    slice.as_ptr() as *const VALUE,
                    kw_splat as c_int,
                ))
            })
            .and_then(TryConvert::try_convert)
        }
    }

    /// If `self` responds to the method named `method`, call it with `args`.
    ///
    /// Returns `Some(Ok(T))` if the method exists and returns without error,
    /// `None` if it does not exist, or `Some(Err)` if an exception was raised.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{prelude::*, Float, Integer, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let val = Float::from_f64(1.23);
    /// let res: Integer = val.check_funcall("to_int", ()).unwrap().unwrap();
    /// assert_eq!(res.to_i64().unwrap(), 1);
    ///
    /// let val = RString::new("1.23");
    /// let res: Option<Result<Integer, _>> = val.check_funcall("to_int", ());
    /// assert!(res.is_none());
    /// ```
    fn check_funcall<M, A, T>(self, method: M, args: A) -> Option<Result<T, Error>>
    where
        M: IntoId,
        A: ArgList,
        T: TryConvert,
    {
        let handle = Ruby::get_with(self);
        let id = method.into_id_with(&handle);
        let kw_splat = kw_splat(&args);
        let args = args.into_arg_list_with(&handle);
        let slice = args.as_ref();
        unsafe {
            let result = protect(|| {
                Value::new(rb_check_funcall_kw(
                    self.as_rb_value(),
                    id.as_rb_id(),
                    slice.len() as c_int,
                    slice.as_ptr() as *const VALUE,
                    kw_splat as c_int,
                ))
            });
            match result {
                Ok(v) if v.is_undef() => None,
                Ok(v) => Some(T::try_convert(v)),
                Err(e) => Some(Err(e)),
            }
        }
    }

    /// Call the method named `method` on `self` with `args` and `block`.
    ///
    /// Similar to [`funcall`](Value::funcall), but passes `block` as a Ruby
    /// block to the method.
    ///
    /// See also [`block_call`](Value::block_call).
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{block::Proc, eval, prelude::*, RArray, Value};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let values = eval::<RArray>(r#"["foo", 1, :bar]"#).unwrap();
    /// let block = Proc::new(|args, _block| args.first().unwrap().to_r_string());
    /// let _: Value = values.funcall_with_block("map!", (), block).unwrap();
    /// assert_eq!(values.to_vec::<String>().unwrap(), vec!["foo", "1", "bar"]);
    /// ```
    fn funcall_with_block<M, A, T>(self, method: M, args: A, block: Proc) -> Result<T, Error>
    where
        M: IntoId,
        A: ArgList,
        T: TryConvert,
    {
        let handle = Ruby::get_with(self);
        let id = method.into_id_with(&handle);
        let kw_splat = kw_splat(&args);
        let args = args.into_arg_list_with(&handle);
        let slice = args.as_ref();
        unsafe {
            protect(|| {
                Value::new(rb_funcall_with_block_kw(
                    self.as_rb_value(),
                    id.as_rb_id(),
                    slice.len() as c_int,
                    slice.as_ptr() as *const VALUE,
                    block.as_rb_value(),
                    kw_splat as c_int,
                ))
            })
            .and_then(TryConvert::try_convert)
        }
    }

    /// Call the method named `method` on `self` with `args` and `block`.
    ///
    /// Similar to [`funcall`](Value::funcall), but passes `block` as a Ruby
    /// block to the method.
    ///
    /// As `block` is a function pointer, only functions and closures that do
    /// not capture any variables are permitted. For more flexibility (at the
    /// cost of allocating) see [`Proc::from_fn`] and
    /// [`funcall_with_block`](Value::funcall_with_block).
    ///
    /// The function passed as `block` will receive values yielded to the block
    /// as a slice of [`Value`]s, plus `Some(Proc)` if the block itself was
    /// called with a block, or `None` otherwise.
    ///
    /// The `block` function may return any `R` or `Result<R, Error>` where `R`
    /// implements [`IntoValue`]. Returning `Err(Error)` will raise the error
    /// as a Ruby exception.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, prelude::*, RArray, Value};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let values = eval::<RArray>(r#"["foo", 1, :bar]"#).unwrap();
    /// let _: Value = values
    ///     .block_call("map!", (), |args, _block| {
    ///         args.first().unwrap().to_r_string()
    ///     })
    ///     .unwrap();
    /// assert_eq!(values.to_vec::<String>().unwrap(), vec!["foo", "1", "bar"]);
    /// ```
    fn block_call<M, A, R, T>(
        self,
        method: M,
        args: A,
        block: fn(&[Value], Option<Proc>) -> R,
    ) -> Result<T, Error>
    where
        M: IntoId,
        A: ArgList,
        R: BlockReturn,
        T: TryConvert,
    {
        unsafe extern "C" fn call<R>(
            _yielded_arg: VALUE,
            callback_arg: VALUE,
            argc: c_int,
            argv: *const VALUE,
            blockarg: VALUE,
        ) -> VALUE
        where
            R: BlockReturn,
        {
            let func = std::mem::transmute::<VALUE, fn(&[Value], Option<Proc>) -> R>(callback_arg);
            func.call_handle_error(argc, argv as *const Value, Value::new(blockarg))
                .as_rb_value()
        }

        let handle = Ruby::get_with(self);
        let id = method.into_id_with(&handle);
        let kw_splat = kw_splat(&args);
        let args = args.into_arg_list_with(&handle);
        let slice = args.as_ref();
        let call_func =
            call::<R> as unsafe extern "C" fn(VALUE, VALUE, c_int, *const VALUE, VALUE) -> VALUE;
        #[cfg(ruby_lt_2_7)]
        let call_func: unsafe extern "C" fn() -> VALUE = unsafe { std::mem::transmute(call_func) };

        protect(|| unsafe {
            #[allow(clippy::fn_to_numeric_cast)]
            Value::new(rb_block_call_kw(
                self.as_rb_value(),
                id.as_rb_id(),
                slice.len() as c_int,
                slice.as_ptr() as *const VALUE,
                Some(call_func),
                block as VALUE,
                kw_splat as c_int,
            ))
        })
        .and_then(TryConvert::try_convert)
    }

    /// Check if `self` responds to the given Ruby method.
    ///
    /// The `include_private` agument controls whether `self`'s private methods
    /// are checked. If `false` they are not, if `true` they are.
    ///
    /// See also [`Value::check_funcall`].
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{prelude::*, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s = RString::new("example");
    /// assert!(s.respond_to("to_str", false).unwrap());
    /// assert!(!s.respond_to("puts", false).unwrap());
    /// assert!(s.respond_to("puts", true).unwrap());
    /// assert!(!s.respond_to("non_existant", false).unwrap());
    /// assert!(!s.respond_to("non_existant", true).unwrap());
    /// ```
    fn respond_to<M>(self, method: M, include_private: bool) -> Result<bool, Error>
    where
        M: IntoId,
    {
        let handle = Ruby::get_with(self);
        let id = method.into_id_with(&handle);
        let mut res = false;
        protect(|| {
            unsafe {
                res = rb_obj_respond_to(self.as_rb_value(), id.as_rb_id(), include_private as c_int)
                    != 0
            };
            handle.qnil()
        })?;
        Ok(res)
    }

    /// Convert `self` to a Ruby `String`.
    ///
    /// If `self` is already a `String` is it wrapped as a `RString`, otherwise
    /// the Ruby `to_s` method is called.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{class, eval, prelude::*, Value};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let value = eval::<Value>("[]").unwrap();
    /// assert!(value.to_r_string().unwrap().is_kind_of(class::string()));
    /// ```
    fn to_r_string(self) -> Result<RString, Error> {
        match RString::from_value(self.as_value()) {
            Some(v) => Ok(v),
            None => protect(|| unsafe {
                RString::from_rb_value_unchecked(rb_obj_as_string(self.as_rb_value()))
            }),
        }
    }

    /// Convert `self` to a Rust string.
    ///
    /// # Safety
    ///
    /// This may return a direct view of memory owned and managed by Ruby. Ruby
    /// may modify or free the memory backing the returned str, the caller must
    /// ensure this does not happen.
    ///
    /// This can be used safely by immediately calling
    /// [`into_owned`](Cow::into_owned) on the return value.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{prelude::*, IntoValue};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let value = true.into_value();
    /// // safe as we never give Ruby a chance to free the string.
    /// let s = unsafe { value.to_s() }.unwrap().into_owned();
    /// assert_eq!(s, "true");
    /// ```
    #[allow(clippy::wrong_self_convention)]
    unsafe fn to_s(&self) -> Result<Cow<str>, Error> {
        if let Some(s) = RString::ref_from_value(self.as_value_ref()) {
            if s.is_utf8_compatible_encoding() {
                return s.as_str().map(Cow::Borrowed);
            } else {
                return (*s).to_string().map(Cow::Owned);
            }
        }
        self.to_r_string()
            .and_then(|s| s.to_string().map(Cow::Owned))
    }

    /// Convert `self` to its Ruby debug representation.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{prelude::*, IntoValue, Symbol};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// assert_eq!(().into_value().inspect(), "nil");
    /// assert_eq!(Symbol::new("foo").inspect(), ":foo");
    /// ```
    fn inspect(self) -> String {
        let handle = Ruby::get_with(self);
        unsafe {
            let s = protect(|| RString::from_rb_value_unchecked(rb_inspect(self.as_rb_value())))
                .unwrap_or_else(|_| {
                    RString::from_rb_value_unchecked(rb_any_to_s(self.as_rb_value()))
                });
            s.conv_enc(handle.utf8_encoding())
                .unwrap_or(s)
                .to_string_lossy()
                .into_owned()
        }
    }

    /// Return the name of `self`'s class.
    ///
    /// # Safety
    ///
    /// Ruby may modify or free the memory backing the returned str, the caller
    /// must ensure this does not happen.
    ///
    /// This can be used safely by immediately calling
    /// [`into_owned`](Cow::into_owned) on the return value.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{prelude::*, RHash};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let value = RHash::new();
    /// // safe as we never give Ruby a chance to free the string.
    /// let s = unsafe { value.classname() }.into_owned();
    /// assert_eq!(s, "Hash");
    /// ```
    unsafe fn classname(&self) -> Cow<str> {
        let ptr = rb_obj_classname(self.as_rb_value());
        let cstr = CStr::from_ptr(ptr);
        cstr.to_string_lossy()
    }

    /// Returns whether or not `self` is an instance of `class`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{class, eval, prelude::*, Value};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let value = eval::<Value>("[]").unwrap();
    /// assert!(value.is_kind_of(class::array()));
    /// ```
    fn is_kind_of<T>(self, class: T) -> bool
    where
        T: ReprValue + Module,
    {
        unsafe { Value::new(rb_obj_is_kind_of(self.as_rb_value(), class.as_rb_value())).to_bool() }
    }

    /// Generate an [`Enumerator`] from `method` on `self`, passing `args` to
    /// `method`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{class, prelude::*, r_string};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s = r_string!("foo\\bar\\baz");
    /// let mut i = 0;
    /// for line in s.enumeratorize("each_line", ("\\",)) {
    ///     assert!(line.unwrap().is_kind_of(class::string()));
    ///     i += 1;
    /// }
    /// assert_eq!(i, 3);
    /// ```
    fn enumeratorize<M, A>(self, method: M, args: A) -> Enumerator
    where
        M: IntoSymbol,
        A: ArgList,
    {
        let handle = Ruby::get_with(self);
        let kw_splat = kw_splat(&args);
        let args = args.into_arg_list_with(&handle);
        let slice = args.as_ref();
        unsafe {
            Enumerator::from_rb_value_unchecked(rb_enumeratorize_with_size_kw(
                self.as_rb_value(),
                method.into_symbol_with(&handle).as_rb_value(),
                slice.len() as c_int,
                slice.as_ptr() as *const VALUE,
                None,
                kw_splat as c_int,
            ))
        }
    }
}

unsafe impl private::ReprValue for Value {}

impl ReprValue for Value {}

#[cfg(feature = "deprecated-send-sync-value")]
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
#[repr(transparent)]
pub(crate) struct NonZeroValue(NonZeroUsize);

#[cfg(not(feature = "deprecated-send-sync-value"))]
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
#[repr(transparent)]
pub(crate) struct NonZeroValue(NonZeroUsize, PhantomData<ptr::NonNull<RBasic>>);

impl NonZeroValue {
    #[cfg(feature = "deprecated-send-sync-value")]
    #[inline]
    pub(crate) const unsafe fn new_unchecked(val: Value) -> Self {
        Self(NonZeroUsize::new_unchecked(val.as_rb_value() as usize))
    }

    #[cfg(not(feature = "deprecated-send-sync-value"))]
    #[inline]
    pub(crate) const unsafe fn new_unchecked(val: Value) -> Self {
        Self(
            NonZeroUsize::new_unchecked(val.as_rb_value() as usize),
            PhantomData,
        )
    }

    #[inline]
    pub(crate) const fn get(self) -> Value {
        Value::new(self.0.get() as VALUE)
    }
}

/// Protects a Ruby Value from the garbage collector.
///
/// See also [`gc::register_mark_object`](crate::gc::register_mark_object) for
/// a value that should be permanently excluded from garbage collection.
pub struct BoxValue<T>(Box<T>);

impl<T> BoxValue<T>
where
    T: ReprValue,
{
    /// Create a new `BoxValue`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, gc, value::BoxValue, RString, Value};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// # #[inline(never)]
    /// fn box_value() -> BoxValue<RString> {
    ///     BoxValue::new(RString::new("foo"))
    /// }
    ///
    /// # // get the Value in a different stack frame and copy it to a BoxValue
    /// # // test is invalid if this is done in this function.
    /// let boxed = box_value();
    ///
    /// # // make some garbage
    /// # eval::<Value>(r#"1024.times.map {|i| "test#{i}"}"#).unwrap();
    /// // run garbage collector
    /// gc::start();
    ///
    /// # // try and use value
    /// // boxed is still useable
    /// let result: String = eval!(r#"foo + "bar""#, foo = boxed).unwrap();
    ///
    /// assert_eq!(result, "foobar");
    ///
    /// # // didn't segfault? we passed!
    /// ```
    pub fn new(val: T) -> Self {
        let mut boxed = Box::new(val);
        unsafe { rb_gc_register_address(boxed.as_mut() as *mut _ as *mut VALUE) };
        Self(boxed)
    }
}

impl<T> Drop for BoxValue<T> {
    fn drop(&mut self) {
        unsafe {
            rb_gc_unregister_address(self.0.as_mut() as *mut _ as *mut VALUE);
        }
    }
}

impl<T> AsRef<T> for BoxValue<T> {
    #[inline]
    fn as_ref(&self) -> &T {
        &self.0
    }
}

impl<T> AsMut<T> for BoxValue<T> {
    #[inline]
    fn as_mut(&mut self) -> &mut T {
        &mut self.0
    }
}

impl<T> Deref for BoxValue<T> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> DerefMut for BoxValue<T> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<T> fmt::Display for BoxValue<T>
where
    T: ReprValue,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", unsafe { self.as_value().to_s_infallible() })
    }
}

impl<T> fmt::Debug for BoxValue<T>
where
    T: ReprValue,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_value().inspect())
    }
}

impl<T> IntoValue for BoxValue<T>
where
    T: ReprValue,
{
    #[inline]
    fn into_value_with(self, _: &Ruby) -> Value {
        self.as_value()
    }
}

unsafe impl<T> IntoValueFromNative for BoxValue<T> where T: ReprValue {}

/// # `false`
///
/// Get Ruby's `false` value.
///
/// See also the [`Qfalse`] type.
impl Ruby {
    /// Returns Ruby's `false` value.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{rb_assert, Error, Ruby};
    ///
    /// fn example(ruby: &Ruby) -> Result<(), Error> {
    ///     rb_assert!(ruby, "val == false", val = ruby.qfalse());
    ///
    ///     Ok(())
    /// }
    /// # Ruby::init(example).unwrap()
    /// ```
    #[inline]
    pub fn qfalse(&self) -> Qfalse {
        #[allow(deprecated)]
        QFALSE
    }
}

/// Ruby's `false` value.
///
/// See [`Ruby::qfalse`]/[`qfalse`] to obtain a value of this type.
///
/// See the [`ReprValue`] trait for additional methods available on this type.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct Qfalse(Value);

/// Ruby's `false` value.
#[deprecated(
    since = "0.6.0",
    note = "please use `value::qfalse`/`Ruby::qfalse` instead"
)]
pub const QFALSE: Qfalse = Qfalse::new();

/// Returns Ruby's `false` value.
///
/// This should optimise to a constant reference.
///
/// # Panics
///
/// Panics if called from a non-Ruby thread. See [`Ruby::qfalse`] for the
/// non-panicking version.
///
/// # Examples
///
/// ```
/// use magnus::{rb_assert, value::qfalse};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// rb_assert!("val == false", val = qfalse());
/// ```
#[cfg_attr(
    not(feature = "friendly-api"),
    deprecated(note = "please use `Ruby::qfalse` instead")
)]
#[inline]
pub fn qfalse() -> Qfalse {
    get_ruby!().qfalse()
}

impl Qfalse {
    /// Create a new `Qfalse`.
    #[inline]
    const fn new() -> Self {
        Qfalse(Value::new(ruby_special_consts::RUBY_Qfalse as VALUE))
    }

    /// Return `Some(Qfalse)` if `val` is a `Qfalse`, `None` otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, value::Qfalse};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// assert!(Qfalse::from_value(eval("false").unwrap()).is_some());
    /// assert!(Qfalse::from_value(eval("0").unwrap()).is_none());
    /// ```
    #[inline]
    pub fn from_value(val: Value) -> Option<Self> {
        val.is_false().then(Self::new)
    }
}

impl fmt::Display for Qfalse {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", unsafe { self.to_s_infallible() })
    }
}

impl fmt::Debug for Qfalse {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.inspect())
    }
}

impl IntoValue for Qfalse {
    #[inline]
    fn into_value_with(self, _: &Ruby) -> Value {
        self.0
    }
}

unsafe impl private::ReprValue for Qfalse {}

impl ReprValue for Qfalse {}

impl TryConvert for Qfalse {
    fn try_convert(val: Value) -> Result<Self, Error> {
        Self::from_value(val).ok_or_else(|| {
            Error::new(
                Ruby::get_with(val).exception_type_error(),
                format!("no implicit conversion of {} into FalseClass", unsafe {
                    val.classname()
                },),
            )
        })
    }
}
unsafe impl TryConvertOwned for Qfalse {}

/// # `nil`
///
/// Get Ruby's `nil` value.
///
/// See also the [`Qnil`] type.
impl Ruby {
    /// Returns Ruby's `nil` value.
    ///
    /// This should optimise to a constant reference.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{rb_assert, Error, Ruby};
    ///
    /// fn example(ruby: &Ruby) -> Result<(), Error> {
    ///     rb_assert!(ruby, "val == nil", val = ruby.qnil());
    ///
    ///     Ok(())
    /// }
    /// # Ruby::init(example).unwrap()
    /// ```
    #[inline]
    pub fn qnil(&self) -> Qnil {
        #[allow(deprecated)]
        QNIL
    }
}

/// Ruby's `nil` value.
///
/// See [`Ruby::qnil`]/[`qnil`] to obtain a value of this type.
///
/// See the [`ReprValue`] trait for additional methods available on this type.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct Qnil(NonZeroValue);

/// Ruby's `nil` value.
#[deprecated(
    since = "0.6.0",
    note = "please use `value::qnil`/`Ruby::qnil` instead"
)]
pub const QNIL: Qnil = Qnil::new();

/// Returns Ruby's `nil` value.
///
/// This should optimise to a constant reference.
///
/// # Panics
///
/// Panics if called from a non-Ruby thread. See [`Ruby::qnil`] for the
/// non-panicking version.
///
/// # Examples
///
/// ```
/// use magnus::{rb_assert, value::qnil};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// rb_assert!("val == nil", val = qnil());
/// ```
#[cfg_attr(
    not(feature = "friendly-api"),
    deprecated(note = "please use `Ruby::qnil` instead")
)]
#[inline]
pub fn qnil() -> Qnil {
    get_ruby!().qnil()
}

impl Qnil {
    /// Create a new `Qnil`.
    #[inline]
    const fn new() -> Self {
        unsafe {
            Self(NonZeroValue::new_unchecked(Value::new(
                ruby_special_consts::RUBY_Qnil as VALUE,
            )))
        }
    }

    /// Return `Some(Qnil)` if `val` is a `Qnil`, `None` otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, value::Qnil};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// assert!(Qnil::from_value(eval("nil").unwrap()).is_some());
    /// assert!(Qnil::from_value(eval("0").unwrap()).is_none());
    /// ```
    #[inline]
    pub fn from_value(val: Value) -> Option<Self> {
        val.is_nil().then(Self::new)
    }
}

impl fmt::Display for Qnil {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", unsafe { self.to_s_infallible() })
    }
}

impl fmt::Debug for Qnil {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.inspect())
    }
}

impl IntoValue for Qnil {
    #[inline]
    fn into_value_with(self, _: &Ruby) -> Value {
        self.0.get()
    }
}

impl IntoValue for () {
    #[inline]
    fn into_value_with(self, handle: &Ruby) -> Value {
        handle.qnil().as_value()
    }
}

unsafe impl IntoValueFromNative for () {}

impl<T> IntoValue for Option<T>
where
    T: IntoValue,
{
    #[inline]
    fn into_value_with(self, handle: &Ruby) -> Value {
        match self {
            Some(t) => handle.into_value(t),
            None => handle.qnil().as_value(),
        }
    }
}

unsafe impl<T> IntoValueFromNative for Option<T> where T: IntoValueFromNative {}

unsafe impl private::ReprValue for Qnil {}

impl ReprValue for Qnil {}

impl TryConvert for Qnil {
    fn try_convert(val: Value) -> Result<Self, Error> {
        Self::from_value(val).ok_or_else(|| {
            Error::new(
                Ruby::get_with(val).exception_type_error(),
                format!("no implicit conversion of {} into NilClass", unsafe {
                    val.classname()
                },),
            )
        })
    }
}
unsafe impl TryConvertOwned for Qnil {}

/// # `true`
///
/// Get Ruby's `true` value.
///
/// See also the [`Qtrue`] type.
impl Ruby {
    /// Returns Ruby's `true` value.
    ///
    /// This should optimise to a constant reference.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{rb_assert, Error, Ruby};
    ///
    /// fn example(ruby: &Ruby) -> Result<(), Error> {
    ///     rb_assert!(ruby, "val == true", val = ruby.qtrue());
    ///
    ///     Ok(())
    /// }
    /// # Ruby::init(example).unwrap()
    /// ```
    #[inline]
    pub fn qtrue(&self) -> Qtrue {
        #[allow(deprecated)]
        QTRUE
    }
}

/// Ruby's `true` value.
///
/// See [`Ruby::qtrue`]/[`qtrue`] to obtain a value of this type.
///
/// See the [`ReprValue`] trait for additional methods available on this type.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct Qtrue(NonZeroValue);

/// Ruby's `true` value.
#[deprecated(
    since = "0.6.0",
    note = "please use `value::qtrue`/`Ruby::qtrue` instead"
)]
pub const QTRUE: Qtrue = Qtrue::new();

/// Returns Ruby's `true` value.
///
/// This should optimise to a constant reference.
///
/// # Panics
///
/// Panics if called from a non-Ruby thread. See [`Ruby::qtrue`] for the
/// non-panicking version.
///
/// # Examples
///
/// ```
/// use magnus::{rb_assert, value::qtrue};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// rb_assert!("val == true", val = qtrue());
/// ```
#[cfg_attr(
    not(feature = "friendly-api"),
    deprecated(note = "please use `Ruby::qtrue` instead")
)]
#[inline]
pub fn qtrue() -> Qtrue {
    get_ruby!().qtrue()
}

impl Qtrue {
    /// Create a new `Qtrue`.
    #[inline]
    const fn new() -> Self {
        unsafe {
            Self(NonZeroValue::new_unchecked(Value::new(
                ruby_special_consts::RUBY_Qtrue as VALUE,
            )))
        }
    }

    /// Return `Some(Qtrue)` if `val` is a `Qtrue`, `None` otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, value::Qtrue};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// assert!(Qtrue::from_value(eval("true").unwrap()).is_some());
    /// assert!(Qtrue::from_value(eval("1").unwrap()).is_none());
    /// ```
    #[inline]
    pub fn from_value(val: Value) -> Option<Self> {
        val.is_true().then(Self::new)
    }
}

impl fmt::Display for Qtrue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", unsafe { self.to_s_infallible() })
    }
}

impl fmt::Debug for Qtrue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.inspect())
    }
}

impl IntoValue for Qtrue {
    #[inline]
    fn into_value_with(self, _: &Ruby) -> Value {
        self.0.get()
    }
}

impl IntoValue for bool {
    #[inline]
    fn into_value_with(self, handle: &Ruby) -> Value {
        if self {
            handle.qtrue().as_value()
        } else {
            handle.qfalse().as_value()
        }
    }
}

unsafe impl IntoValueFromNative for bool {}

unsafe impl private::ReprValue for Qtrue {}

impl ReprValue for Qtrue {}

impl TryConvert for Qtrue {
    fn try_convert(val: Value) -> Result<Self, Error> {
        Self::from_value(val).ok_or_else(|| {
            Error::new(
                Ruby::get_with(val).exception_type_error(),
                format!("no implicit conversion of {} into TrueClass", unsafe {
                    val.classname()
                },),
            )
        })
    }
}
unsafe impl TryConvertOwned for Qtrue {}

/// A placeholder value that represents an undefined value. Not exposed to
/// Ruby level code.
///
/// See [`QUNDEF`] to obtain a value of this type.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct Qundef(NonZeroValue);

/// A placeholder value that represents an undefined value. Not exposed to
/// Ruby level code.
pub const QUNDEF: Qundef = Qundef::new();

impl Qundef {
    /// Create a new `Qundef`.
    #[inline]
    const fn new() -> Self {
        unsafe {
            Self(NonZeroValue::new_unchecked(Value::new(
                ruby_special_consts::RUBY_Qundef as VALUE,
            )))
        }
    }

    /// Return `Some(Qundef)` if `val` is a `Qundef`, `None` otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, value::Qundef};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// // nil is not undef
    /// assert!(Qundef::from_value(eval("nil").unwrap()).is_none());
    /// ```
    #[inline]
    pub fn from_value(val: Value) -> Option<Self> {
        val.is_undef().then(Self::new)
    }

    /// Return `self` as a [`Value`].
    ///
    /// # Safety
    ///
    /// It is not a good idea to return this to Ruby code, bad things will
    /// happen. There are only a handful of places in Ruby's API where it is
    /// appropriate to pass a [`Value`] created from `Qundef` (hence this
    /// method, rather than implementing [`IntoValue`]).
    #[inline]
    pub unsafe fn as_value(self) -> Value {
        self.0.get()
    }

    #[doc(hidden)]
    #[deprecated(since = "0.6.0", note = "please use `as_value` instead")]
    pub unsafe fn to_value(self) -> Value {
        self.as_value()
    }
}

/// # `Fixnum`
///
/// Functions that can be used to create instances of Ruby's small/fast integer
/// representation.
///
/// See also the [`Fixnum`] type.
impl Ruby {
    /// Create a new `Fixnum` from an `i64.`
    ///
    /// Returns `Ok(Fixnum)` if `n` is in range for `Fixnum`, otherwise returns
    /// `Err(RBignum)`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{Error, Ruby};
    ///
    /// fn example(ruby: &Ruby) -> Result<(), Error> {
    ///     assert!(ruby.fixnum_from_i64(0).is_ok());
    ///     // too big
    ///     assert!(ruby.fixnum_from_i64(4611686018427387904).is_err());
    ///     assert!(ruby.fixnum_from_i64(-4611686018427387905).is_err());
    ///
    ///     Ok(())
    /// }
    /// # Ruby::init(example).unwrap()
    /// ```
    #[inline]
    pub fn fixnum_from_i64(&self, n: i64) -> Result<Fixnum, RBignum> {
        Fixnum::from_i64_impl(n)
            .ok_or_else(|| unsafe { RBignum::from_rb_value_unchecked(rb_ll2inum(n)) })
    }

    /// Create a new `Fixnum` from a `u64.`
    ///
    /// Returns `Ok(Fixnum)` if `n` is in range for `Fixnum`, otherwise returns
    /// `Err(RBignum)`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{Error, Ruby};
    ///
    /// fn example(ruby: &Ruby) -> Result<(), Error> {
    ///     assert!(ruby.fixnum_from_u64(0).is_ok());
    ///     // too big
    ///     assert!(ruby.fixnum_from_u64(4611686018427387904).is_err());
    ///
    ///     Ok(())
    /// }
    /// # Ruby::init(example).unwrap()
    /// ```
    #[inline]
    pub fn fixnum_from_u64(&self, n: u64) -> Result<Fixnum, RBignum> {
        Fixnum::from_i64_impl(i64::try_from(n).unwrap_or(i64::MAX))
            .ok_or_else(|| unsafe { RBignum::from_rb_value_unchecked(rb_ull2inum(n)) })
    }
}

/// A Value known to be a fixnum, Ruby's internal representation of small
/// integers.
///
/// See also [`Integer`].
///
/// See the [`ReprValue`] trait for additional methods available on this type.
/// See [`Ruby`](Ruby#fixnum) for methods to create a `Fixnum`.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct Fixnum(NonZeroValue);

impl Fixnum {
    /// Return `Some(Fixnum)` if `val` is a `Fixnum`, `None` otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, Fixnum};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// assert!(Fixnum::from_value(eval("0").unwrap()).is_some());
    /// // too big
    /// assert!(Fixnum::from_value(eval("9223372036854775807").unwrap()).is_none());
    /// // not an int
    /// assert!(Fixnum::from_value(eval("1.23").unwrap()).is_none());
    /// ```
    #[inline]
    pub fn from_value(val: Value) -> Option<Self> {
        unsafe {
            val.is_fixnum()
                .then(|| Self(NonZeroValue::new_unchecked(val)))
        }
    }

    #[inline]
    pub(crate) unsafe fn from_rb_value_unchecked(val: VALUE) -> Self {
        Self(NonZeroValue::new_unchecked(Value::new(val)))
    }

    #[inline]
    pub(crate) fn from_i64_impl(n: i64) -> Option<Self> {
        #[allow(clippy::useless_conversion)] // not useless when c_long != i64
        (c_ulong::try_from(n)
            .map(|n| n < RUBY_FIXNUM_MAX + 1)
            .unwrap_or(false)
            && c_long::try_from(n)
                .map(|n| n >= RUBY_FIXNUM_MIN)
                .unwrap_or(false))
        .then(|| unsafe {
            let x = transmute::<_, usize>(n as isize);
            Self::from_rb_value_unchecked(x.wrapping_add(x.wrapping_add(1)) as VALUE)
        })
    }

    /// Create a new `Fixnum` from an `i64.`
    ///
    /// Returns `Ok(Fixnum)` if `n` is in range for `Fixnum`, otherwise returns
    /// `Err(RBignum)`.
    ///
    /// # Panics
    ///
    /// Panics if called from a non-Ruby thread. See [`Ruby::fixnum_from_i64`]
    /// for the non-panicking version.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::Fixnum;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// assert!(Fixnum::from_i64(0).is_ok());
    /// // too big
    /// assert!(Fixnum::from_i64(4611686018427387904).is_err());
    /// assert!(Fixnum::from_i64(-4611686018427387905).is_err());
    /// ```
    #[cfg_attr(
        not(feature = "friendly-api"),
        deprecated(note = "please use `Ruby::fixnum_from_i64` instead")
    )]
    #[inline]
    pub fn from_i64(n: i64) -> Result<Self, RBignum> {
        get_ruby!().fixnum_from_i64(n)
    }

    /// Create a new `Fixnum` from a `u64.`
    ///
    /// Returns `Ok(Fixnum)` if `n` is in range for `Fixnum`, otherwise returns
    /// `Err(RBignum)`.
    ///
    /// # Panics
    ///
    /// Panics if called from a non-Ruby thread. See [`Ruby::fixnum_from_u64`]
    /// for the non-panicking version.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::Fixnum;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// assert!(Fixnum::from_u64(0).is_ok());
    /// // too big
    /// assert!(Fixnum::from_u64(4611686018427387904).is_err());
    /// ```
    #[cfg_attr(
        not(feature = "friendly-api"),
        deprecated(note = "please use `Ruby::fixnum_from_u64` instead")
    )]
    #[inline]
    pub fn from_u64(n: u64) -> Result<Self, RBignum> {
        get_ruby!().fixnum_from_u64(n)
    }

    fn is_negative(self) -> bool {
        unsafe { transmute::<_, isize>(self.0) < 0 }
    }

    /// Convert `self` to an `i8`. Returns `Err` if `self` is out of range for
    /// `i8`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, Fixnum};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// assert_eq!(eval::<Fixnum>("127").unwrap().to_i8().unwrap(), 127);
    /// assert!(eval::<Fixnum>("128").unwrap().to_i8().is_err());
    /// assert_eq!(eval::<Fixnum>("-128").unwrap().to_i8().unwrap(), -128);
    /// assert!(eval::<Fixnum>("-129").unwrap().to_i8().is_err());
    /// ```
    #[inline]
    pub fn to_i8(self) -> Result<i8, Error> {
        let res = self.to_isize();
        if res > i8::MAX as isize || res < i8::MIN as isize {
            return Err(Error::new(
                Ruby::get_with(self).exception_range_error(),
                "fixnum too big to convert into `i8`",
            ));
        }
        Ok(res as i8)
    }

    /// Convert `self` to an `i16`. Returns `Err` if `self` is out of range for
    /// `i16`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, Fixnum};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// assert_eq!(eval::<Fixnum>("32767").unwrap().to_i16().unwrap(), 32767);
    /// assert!(eval::<Fixnum>("32768").unwrap().to_i16().is_err());
    /// assert_eq!(eval::<Fixnum>("-32768").unwrap().to_i16().unwrap(), -32768);
    /// assert!(eval::<Fixnum>("-32769").unwrap().to_i16().is_err());
    /// ```
    #[inline]
    pub fn to_i16(self) -> Result<i16, Error> {
        let res = self.to_isize();
        if res > i16::MAX as isize || res < i16::MIN as isize {
            return Err(Error::new(
                Ruby::get_with(self).exception_range_error(),
                "fixnum too big to convert into `i16`",
            ));
        }
        Ok(res as i16)
    }

    /// Convert `self` to an `i32`. Returns `Err` if `self` is out of range for
    /// `i32`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, Fixnum};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// # #[cfg(not(windows))]
    /// # {
    /// assert_eq!(
    ///     eval::<Fixnum>("2147483647").unwrap().to_i32().unwrap(),
    ///     2147483647
    /// );
    /// assert!(eval::<Fixnum>("2147483648").unwrap().to_i32().is_err());
    /// assert_eq!(
    ///     eval::<Fixnum>("-2147483648").unwrap().to_i32().unwrap(),
    ///     -2147483648
    /// );
    /// assert!(eval::<Fixnum>("-2147483649").unwrap().to_i32().is_err());
    /// # }
    /// ```
    #[inline]
    pub fn to_i32(self) -> Result<i32, Error> {
        let res = self.to_isize();
        if res > i32::MAX as isize || res < i32::MIN as isize {
            return Err(Error::new(
                Ruby::get_with(self).exception_range_error(),
                "fixnum too big to convert into `i32`",
            ));
        }
        Ok(res as i32)
    }

    /// Convert `self` to an `i64`. This is infallible as `i64` can represent a
    /// larger range than `Fixnum`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, Fixnum};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// # #[cfg(not(windows))]
    /// assert_eq!(
    ///     eval::<Fixnum>("4611686018427387903").unwrap().to_i64(),
    ///     4611686018427387903
    /// );
    /// # #[cfg(not(windows))]
    /// assert_eq!(
    ///     eval::<Fixnum>("-4611686018427387904").unwrap().to_i64(),
    ///     -4611686018427387904
    /// );
    /// ```
    #[inline]
    pub fn to_i64(self) -> i64 {
        self.to_isize() as i64
    }

    /// Convert `self` to an `isize`. Returns `Err` if `self` is out of range
    /// for `isize`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, Fixnum};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// # #[cfg(not(windows))]
    /// assert_eq!(
    ///     eval::<Fixnum>("4611686018427387903").unwrap().to_isize(),
    ///     4611686018427387903
    /// );
    /// # #[cfg(not(windows))]
    /// assert_eq!(
    ///     eval::<Fixnum>("-4611686018427387904").unwrap().to_isize(),
    ///     -4611686018427387904
    /// );
    /// ```
    #[inline]
    pub fn to_isize(self) -> isize {
        unsafe { transmute::<_, isize>(self) >> 1 }
    }

    /// Convert `self` to a `u8`. Returns `Err` if `self` is negative or out of
    /// range for `u8`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, Fixnum};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// assert_eq!(eval::<Fixnum>("255").unwrap().to_u8().unwrap(), 255);
    /// assert!(eval::<Fixnum>("256").unwrap().to_u8().is_err());
    /// assert!(eval::<Fixnum>("-1").unwrap().to_u8().is_err());
    /// ```
    #[inline]
    pub fn to_u8(self) -> Result<u8, Error> {
        let handle = Ruby::get_with(self);
        if self.is_negative() {
            return Err(Error::new(
                handle.exception_range_error(),
                "can't convert negative integer to unsigned",
            ));
        }
        let res = self.to_isize();
        if res > u8::MAX as isize {
            return Err(Error::new(
                handle.exception_range_error(),
                "fixnum too big to convert into `u8`",
            ));
        }
        Ok(res as u8)
    }

    /// Convert `self` to a `u16`. Returns `Err` if `self` is negative or out
    /// of range for `u16`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, Fixnum};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// assert_eq!(eval::<Fixnum>("65535").unwrap().to_u16().unwrap(), 65535);
    /// assert!(eval::<Fixnum>("65536").unwrap().to_u16().is_err());
    /// assert!(eval::<Fixnum>("-1").unwrap().to_u16().is_err());
    /// ```
    #[inline]
    pub fn to_u16(self) -> Result<u16, Error> {
        let handle = Ruby::get_with(self);
        if self.is_negative() {
            return Err(Error::new(
                handle.exception_range_error(),
                "can't convert negative integer to unsigned",
            ));
        }
        let res = self.to_isize();
        if res > u16::MAX as isize {
            return Err(Error::new(
                handle.exception_range_error(),
                "fixnum too big to convert into `u16`",
            ));
        }
        Ok(res as u16)
    }

    /// Convert `self` to a `u32`. Returns `Err` if `self` is negative or out
    /// of range for `u32`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, Fixnum};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// # #[cfg(not(windows))]
    /// # {
    /// assert_eq!(
    ///     eval::<Fixnum>("4294967295").unwrap().to_u32().unwrap(),
    ///     4294967295
    /// );
    /// assert!(eval::<Fixnum>("4294967296").unwrap().to_u32().is_err());
    /// # }
    /// assert!(eval::<Fixnum>("-1").unwrap().to_u32().is_err());
    /// ```
    #[inline]
    pub fn to_u32(self) -> Result<u32, Error> {
        let handle = Ruby::get_with(self);
        if self.is_negative() {
            return Err(Error::new(
                handle.exception_range_error(),
                "can't convert negative integer to unsigned",
            ));
        }
        let res = self.to_isize();
        if res > u32::MAX as isize {
            return Err(Error::new(
                handle.exception_range_error(),
                "fixnum too big to convert into `u32`",
            ));
        }
        Ok(res as u32)
    }

    /// Convert `self` to a `u64`. Returns `Err` if `self` is negative.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, Fixnum};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// # #[cfg(not(windows))]
    /// assert_eq!(
    ///     eval::<Fixnum>("4611686018427387903")
    ///         .unwrap()
    ///         .to_u64()
    ///         .unwrap(),
    ///     4611686018427387903
    /// );
    /// assert!(eval::<Fixnum>("-1").unwrap().to_u64().is_err());
    /// ```
    #[inline]
    pub fn to_u64(self) -> Result<u64, Error> {
        if self.is_negative() {
            return Err(Error::new(
                Ruby::get_with(self).exception_range_error(),
                "can't convert negative integer to unsigned",
            ));
        }
        Ok(self.to_isize() as u64)
    }

    /// Convert `self` to a `usize`. Returns `Err` if `self` is negative or out
    /// of range for `usize`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, Fixnum};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// # #[cfg(not(windows))]
    /// assert_eq!(
    ///     eval::<Fixnum>("4611686018427387903")
    ///         .unwrap()
    ///         .to_usize()
    ///         .unwrap(),
    ///     4611686018427387903
    /// );
    /// assert!(eval::<Fixnum>("-1").unwrap().to_usize().is_err());
    /// ```
    #[inline]
    pub fn to_usize(self) -> Result<usize, Error> {
        if self.is_negative() {
            return Err(Error::new(
                Ruby::get_with(self).exception_range_error(),
                "can't convert negative integer to unsigned",
            ));
        }
        Ok(self.to_isize() as usize)
    }
}

impl fmt::Display for Fixnum {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", unsafe { self.to_s_infallible() })
    }
}

impl fmt::Debug for Fixnum {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.inspect())
    }
}

impl IntoValue for Fixnum {
    #[inline]
    fn into_value_with(self, _: &Ruby) -> Value {
        self.0.get()
    }
}

unsafe impl private::ReprValue for Fixnum {}

impl Numeric for Fixnum {}

impl ReprValue for Fixnum {}

impl TryConvert for Fixnum {
    fn try_convert(val: Value) -> Result<Self, Error> {
        match Integer::try_convert(val)?.integer_type() {
            IntegerType::Fixnum(fix) => Ok(fix),
            IntegerType::Bignum(_) => Err(Error::new(
                Ruby::get_with(val).exception_range_error(),
                "integer too big for fixnum",
            )),
        }
    }
}
unsafe impl TryConvertOwned for Fixnum {}

/// # `StaticSymbol`
///
/// Functions to create Ruby `Symbol`s that will never be garbage collected.
///
/// See also the [`StaticSymbol`] type.
impl Ruby {
    /// Create a new StaticSymbol.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{rb_assert, Error, Ruby};
    ///
    /// fn example(ruby: &Ruby) -> Result<(), Error> {
    ///     let sym = ruby.sym_new("example");
    ///     rb_assert!(ruby, ":example == sym", sym);
    ///
    ///     Ok(())
    /// }
    /// # Ruby::init(example).unwrap()
    /// ```
    #[inline]
    pub fn sym_new<T>(&self, name: T) -> StaticSymbol
    where
        T: IntoId,
    {
        name.into_id_with(self).into()
    }

    /// Return the `StaticSymbol` for `name`, if one exists.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{Error, Ruby, StaticSymbol};
    ///
    /// fn example(ruby: &Ruby) -> Result<(), Error> {
    ///     assert!(ruby.check_symbol("example").is_none());
    ///     let _: StaticSymbol = ruby.eval(":example")?;
    ///     assert!(ruby.check_symbol("example").is_some());
    ///
    ///     Ok(())
    /// }
    /// # Ruby::init(example).unwrap()
    /// ```
    pub fn check_symbol(&self, name: &str) -> Option<StaticSymbol> {
        unsafe {
            let res = Value::new(rb_check_symbol_cstr(
                name.as_ptr() as *mut c_char,
                name.len() as c_long,
                self.utf8_encoding().as_ptr(),
            ));
            (!res.is_nil()).then(|| StaticSymbol::from_rb_value_unchecked(res.as_rb_value()))
        }
    }
}

/// A static Ruby symbol that will live for the life of the program and never
/// be garbage collected.
///
/// See also [`Symbol`].
///
/// See the [`ReprValue`] trait for additional methods available on this type.
/// See [`Ruby`](Ruby#staticsymbol) for methods to create a `StaticSymbol`.
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
#[repr(transparent)]
pub struct StaticSymbol(NonZeroValue);

impl StaticSymbol {
    /// Return `Some(StaticSymbol)` if `val` is a `StaticSymbol`, `None`
    /// otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, StaticSymbol};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// assert!(StaticSymbol::from_value(eval(":foo").unwrap()).is_some());
    /// assert!(StaticSymbol::from_value(eval(r#""bar""#).unwrap()).is_none());
    /// assert!(StaticSymbol::from_value(eval(r#""baz".to_sym"#).unwrap()).is_none());
    /// ```
    #[inline]
    pub fn from_value(val: Value) -> Option<Self> {
        fn is_static_or_permanent_symbol(val: Value) -> bool {
            if val.is_static_symbol() {
                return true;
            }
            debug_assert_value!(val);
            if val.rb_type() != ruby_value_type::RUBY_T_SYMBOL {
                return false;
            }
            let mut p = val.as_rb_value();
            unsafe { rb_check_id(&mut p as *mut _) != 0 }
        }
        unsafe {
            is_static_or_permanent_symbol(val).then(|| Self(NonZeroValue::new_unchecked(val)))
        }
    }

    #[inline]
    pub(crate) unsafe fn from_rb_value_unchecked(val: VALUE) -> Self {
        Self(NonZeroValue::new_unchecked(Value::new(val)))
    }

    /// Create a new StaticSymbol.
    ///
    /// # Panics
    ///
    /// Panics if called from a non-Ruby thread. See [`Ruby::sym_new`] for the
    /// non-panicking version.
    ///
    /// # Examples
    /// ```
    /// use magnus::{rb_assert, StaticSymbol};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let sym = StaticSymbol::new("example");
    /// rb_assert!(":example == sym", sym);
    /// ```
    #[cfg_attr(
        not(feature = "friendly-api"),
        deprecated(note = "please use `Ruby::sym_new` instead")
    )]
    #[inline]
    pub fn new<T>(name: T) -> Self
    where
        T: IntoId,
    {
        get_ruby!().sym_new(name)
    }

    /// Return the `StaticSymbol` for `name`, if one exists.
    ///
    /// # Panics
    ///
    /// Panics if called from a non-Ruby thread. See [`Ruby::check_symbol`] for
    /// the non-panicking version.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, StaticSymbol};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// assert!(StaticSymbol::check("example").is_none());
    /// let _: StaticSymbol = eval(":example").unwrap();
    /// assert!(StaticSymbol::check("example").is_some());
    /// ```
    #[cfg_attr(
        not(feature = "friendly-api"),
        deprecated(note = "please use `Ruby::check_symbol` instead")
    )]
    #[inline]
    pub fn check(name: &str) -> Option<Self> {
        get_ruby!().check_symbol(name)
    }

    /// Return the symbol as a static string reference.
    ///
    /// May error if the name is not valid utf-8.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::StaticSymbol;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let sym = StaticSymbol::new("example");
    /// assert_eq!(sym.name().unwrap(), "example");
    /// ```
    #[inline]
    pub fn name(self) -> Result<&'static str, Error> {
        Id::from(self).name()
    }
}

impl Borrow<Symbol> for StaticSymbol {
    fn borrow(&self) -> &Symbol {
        unsafe { &*(self as *const Self as *const Symbol) }
    }
}

impl fmt::Display for StaticSymbol {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", unsafe { self.to_s_infallible() })
    }
}

impl fmt::Debug for StaticSymbol {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.inspect())
    }
}

impl EncodingCapable for StaticSymbol {}

impl From<Id> for StaticSymbol {
    fn from(id: Id) -> Self {
        unsafe { Self::from_rb_value_unchecked(rb_id2sym(id.as_rb_id())) }
    }
}

impl IntoValue for StaticSymbol {
    #[inline]
    fn into_value_with(self, _: &Ruby) -> Value {
        self.0.get()
    }
}

impl PartialEq<Id> for StaticSymbol {
    #[inline]
    fn eq(&self, other: &Id) -> bool {
        self.into_id_with(&Ruby::get_with(*self)) == *other
    }
}

impl PartialEq<OpaqueId> for StaticSymbol {
    #[inline]
    fn eq(&self, other: &OpaqueId) -> bool {
        self.into_id_with(&Ruby::get_with(*self)).0 == other.0
    }
}

impl PartialEq<LazyId> for StaticSymbol {
    /// # Panics
    ///
    /// Panics if the first call is from a non-Ruby thread. The `LazyId` will
    /// then be *poisoned* and all future use of it will panic.
    #[inline]
    fn eq(&self, other: &LazyId) -> bool {
        self.into_id_with(&Ruby::get_with(*self)).0 == other.0
    }
}

impl PartialEq<Symbol> for StaticSymbol {
    #[inline]
    fn eq(&self, other: &Symbol) -> bool {
        other.as_static().map(|o| *self == o).unwrap_or(false)
    }
}

unsafe impl private::ReprValue for StaticSymbol {}

impl ReprValue for StaticSymbol {}

impl TryConvert for StaticSymbol {
    fn try_convert(val: Value) -> Result<Self, Error> {
        Symbol::try_convert(val).map(|s| s.to_static())
    }
}
unsafe impl TryConvertOwned for StaticSymbol {}

/// # `Id`
///
/// Functions to create Ruby's low-level `Symbol` representation.
///
/// See also the [`Id`] type.
impl Ruby {
    /// Create a new `Id` for `name`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{Error, Ruby};
    ///
    /// fn example(ruby: &Ruby) -> Result<(), Error> {
    ///     let id = ruby.intern("example");
    ///     assert_eq!(id.name()?, "example");
    ///
    ///     Ok(())
    /// }
    /// # Ruby::init(example).unwrap()
    /// ```
    pub fn intern(&self, name: &str) -> Id {
        Id::from_rb_id(unsafe {
            rb_intern3(
                name.as_ptr() as *const c_char,
                name.len() as c_long,
                self.utf8_encoding().as_ptr(),
            )
        })
    }

    /// Return the `Id` for `name`, if one exists.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{Error, Ruby};
    ///
    /// fn example(ruby: &Ruby) -> Result<(), Error> {
    ///     assert!(ruby.check_id("example").is_none());
    ///     ruby.intern("example");
    ///     assert!(ruby.check_id("example").is_some());
    ///
    ///     Ok(())
    /// }
    /// # Ruby::init(example).unwrap()
    /// ```
    pub fn check_id(&self, name: &str) -> Option<Id> {
        let res = unsafe {
            rb_check_id_cstr(
                name.as_ptr() as *mut c_char,
                name.len() as c_long,
                self.utf8_encoding().as_ptr(),
            )
        };
        (res != 0).then(|| Id::from_rb_id(res))
    }
}

/// The internal value of a Ruby symbol.
#[cfg(feature = "deprecated-send-sync-value")]
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[repr(transparent)]
pub struct Id(ID);

/// The internal value of a Ruby symbol.
///
/// See [`Ruby`](Ruby#id) for methods to create an `Id`.
#[cfg(not(feature = "deprecated-send-sync-value"))]
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[repr(transparent)]
pub struct Id(ID, PhantomData<*mut u8>);

impl Id {
    /// Create a new `Id` for `name`.
    ///
    /// # Panics
    ///
    /// Panics if called from a non-Ruby thread. See [`Ruby::intern`] for the
    /// non-panicking version.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::value::Id;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let id = Id::new("example");
    /// assert_eq!(id.name().unwrap(), "example");
    /// ```
    #[cfg_attr(
        not(feature = "friendly-api"),
        deprecated(note = "please use `Ruby::intern` instead")
    )]
    pub fn new<T>(name: T) -> Self
    where
        T: AsRef<str>,
    {
        get_ruby!().intern(name.as_ref())
    }

    #[cfg(feature = "deprecated-send-sync-value")]
    pub(crate) fn from_rb_id(id: ID) -> Self {
        Self(id)
    }

    #[cfg(not(feature = "deprecated-send-sync-value"))]
    #[inline]
    pub(crate) fn from_rb_id(id: ID) -> Self {
        Self(id, PhantomData)
    }

    #[inline]
    pub(crate) fn as_rb_id(self) -> ID {
        self.0
    }

    /// Return the `Id` for `name`, if one exists.
    ///
    /// # Panics
    ///
    /// Panics if called from a non-Ruby thread. See [`Ruby::check_id`] for the
    /// non-panicking version.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{value::Id, StaticSymbol};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// assert!(Id::check("example").is_none());
    /// StaticSymbol::new("example");
    /// assert!(Id::check("example").is_some());
    /// ```
    #[cfg_attr(
        not(feature = "friendly-api"),
        deprecated(note = "please use `Ruby::check_id` instead")
    )]
    #[inline]
    pub fn check(name: &str) -> Option<Self> {
        get_ruby!().check_id(name)
    }

    /// Return the symbol name associated with this Id as a static string
    /// reference.
    ///
    /// May error if the name is not valid utf-8.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::value::Id;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let id = Id::new("example");
    /// assert_eq!(id.name().unwrap(), "example");
    /// ```
    pub fn name(self) -> Result<&'static str, Error> {
        unsafe {
            let ptr = rb_id2name(self.as_rb_id());
            let cstr = CStr::from_ptr(ptr);
            cstr.to_str().map_err(|e| {
                Error::new(
                    Ruby::get_unchecked().exception_encoding_error(),
                    e.to_string(),
                )
            })
        }
    }
}

impl Borrow<OpaqueId> for Id {
    fn borrow(&self) -> &OpaqueId {
        unsafe { &*(self as *const Self as *const OpaqueId) }
    }
}

/// Conversions from Rust types into [`Id`].
pub trait IntoId: Sized {
    /// Convert `self` into [`Id`].
    ///
    /// # Panics
    ///
    /// Panics if called from a non-Ruby thread. See [`IntoId::into_id_with`]
    /// for the non-panicking version.
    #[cfg_attr(
        not(feature = "friendly-api"),
        deprecated(note = "please use `IntoId::into_id_with` instead")
    )]
    #[inline]
    fn into_id(self) -> Id {
        self.into_id_with(&get_ruby!())
    }

    /// Convert `self` into [`Id`].
    ///
    /// # Safety
    ///
    /// This method should only be called from a Ruby thread.
    #[inline]
    unsafe fn into_id_unchecked(self) -> Id {
        self.into_id_with(&Ruby::get_unchecked())
    }

    /// Convert `self` into [`Id`].
    fn into_id_with(self, handle: &Ruby) -> Id;
}

impl IntoId for Id {
    #[inline]
    fn into_id_with(self, _: &Ruby) -> Id {
        self
    }
}

impl IntoId for &str {
    #[inline]
    fn into_id_with(self, handle: &Ruby) -> Id {
        handle.intern(self)
    }
}

impl IntoId for String {
    #[inline]
    fn into_id_with(self, handle: &Ruby) -> Id {
        self.as_str().into_id_with(handle)
    }
}

impl IntoId for StaticSymbol {
    #[inline]
    fn into_id_with(self, handle: &Ruby) -> Id {
        self.into_symbol_with(handle).into_id_with(handle)
    }
}

impl From<StaticSymbol> for Id {
    #[inline]
    fn from(sym: StaticSymbol) -> Self {
        sym.into_id_with(&Ruby::get_with(sym))
    }
}

impl IntoId for Symbol {
    #[inline]
    fn into_id_with(self, _: &Ruby) -> Id {
        if self.is_static_symbol() {
            Id::from_rb_id(self.as_rb_value() >> ruby_special_consts::RUBY_SPECIAL_SHIFT as VALUE)
        } else {
            Id::from_rb_id(unsafe { rb_sym2id(self.as_rb_value()) })
        }
    }
}

impl IntoValue for Id {
    #[inline]
    fn into_value_with(self, handle: &Ruby) -> Value {
        StaticSymbol::from(self).into_value_with(handle)
    }
}

impl From<Symbol> for Id {
    #[inline]
    fn from(sym: Symbol) -> Self {
        sym.into_id_with(&Ruby::get_with(sym))
    }
}

impl PartialEq<OpaqueId> for Id {
    #[inline]
    fn eq(&self, other: &OpaqueId) -> bool {
        self.0 == other.0
    }
}

impl PartialEq<LazyId> for Id {
    #[inline]
    fn eq(&self, other: &LazyId) -> bool {
        self.0 == other.0
    }
}

impl PartialEq<StaticSymbol> for Id {
    #[inline]
    fn eq(&self, other: &StaticSymbol) -> bool {
        *self == other.into_id_with(&Ruby::get_with(*other))
    }
}

impl PartialEq<Symbol> for Id {
    #[inline]
    fn eq(&self, other: &Symbol) -> bool {
        other.as_static().map(|o| *self == o).unwrap_or(false)
    }
}

/// A wrapper to make a Ruby [`Id`] [`Send`] + [`Sync`].
///
/// [`Id`] is not [`Send`] or [`Sync`] as it provides a way to call some of
/// Ruby's APIs, which are not safe to call from a non-Ruby thread.
///
/// [`Id`] is safe to send between Ruby threads, but Rust's trait system
/// currently can not model this detail.
///
/// To resolve this, the `OpaqueId` type makes an [`Id`] [`Send`] + [`Sync`]
/// by removing the ability use it with any Ruby APIs.
///
/// [`IntoId`] and [`IntoSymbol`] can be used to convert an `OpaqueId` back
/// into a type that can be used with Ruby's APIs. These traits can only be
/// used from a Ruby thread.
///
/// `OpaqueId` implements [`Eq`]/[`PartialEq`] and [`Hash`], so can be used as
/// a key or id on non-Ruby threads, or in data structures that must be
/// [`Send`] or [`Sync`].
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[repr(transparent)]
pub struct OpaqueId(ID);

impl From<Id> for OpaqueId {
    #[inline]
    fn from(id: Id) -> Self {
        Self(id.0)
    }
}

impl From<StaticSymbol> for OpaqueId {
    #[inline]
    fn from(sym: StaticSymbol) -> Self {
        sym.into_id_with(&Ruby::get_with(sym)).into()
    }
}

impl From<Symbol> for OpaqueId {
    #[inline]
    fn from(sym: Symbol) -> Self {
        sym.into_id_with(&Ruby::get_with(sym)).into()
    }
}

impl IntoId for OpaqueId {
    #[inline]
    fn into_id_with(self, _: &Ruby) -> Id {
        Id::from_rb_id(self.0)
    }
}

impl IntoSymbol for OpaqueId {
    #[inline]
    fn into_symbol_with(self, handle: &Ruby) -> Symbol {
        self.into_id_with(handle).into_symbol_with(handle)
    }
}

impl IntoValue for OpaqueId {
    #[inline]
    fn into_value_with(self, handle: &Ruby) -> Value {
        self.into_symbol_with(handle).into_value_with(handle)
    }
}

impl PartialEq<Id> for OpaqueId {
    #[inline]
    fn eq(&self, other: &Id) -> bool {
        self.0 == other.0
    }
}

impl PartialEq<LazyId> for OpaqueId {
    #[inline]
    fn eq(&self, other: &LazyId) -> bool {
        *self == **other
    }
}

impl PartialEq<StaticSymbol> for OpaqueId {
    #[inline]
    fn eq(&self, other: &StaticSymbol) -> bool {
        *self == other.into_id_with(&Ruby::get_with(*other))
    }
}

impl PartialEq<Symbol> for OpaqueId {
    #[inline]
    fn eq(&self, other: &Symbol) -> bool {
        other.as_static().map(|o| *self == o).unwrap_or(false)
    }
}

/// An [`Id`] that can be assigned to a `static` and [`Deref`]s to [`OpaqueId`].
///
/// The underlying Ruby Symbol will be lazily initialised when the `LazyId` is
/// first used. This initialisation must happen on a Ruby thread. If the first
/// use is from a non-Ruby thread the `LazyId` will panic and then become
/// *poisoned* and all future use of it will panic.
pub struct LazyId {
    init: Once,
    inner: UnsafeCell<LazyIdInner>,
}

union LazyIdInner {
    name: &'static str,
    value: OpaqueId,
}

impl LazyId {
    /// Create a new `LazyId`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{rb_assert, value::LazyId};
    ///
    /// static EXAMPLE: LazyId = LazyId::new("example");
    ///
    /// # let _cleanup = unsafe { magnus::embed::init() };
    /// rb_assert!("val == :example", val = *EXAMPLE);
    /// ```
    pub const fn new(name: &'static str) -> Self {
        Self {
            init: Once::new(),
            inner: UnsafeCell::new(LazyIdInner { name }),
        }
    }

    /// Force evaluation of a `LazyId`.
    ///
    /// This can be used in, for example, your [`init`](macro@crate::init)
    /// function to force initialisation of the `LazyId`, to ensure that use
    /// of the `LazyId` can't possibly panic.
    ///
    /// # Panics
    ///
    /// Panics if the `LazyId` is *poisoned*. See [`LazyId`].
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{value::LazyId, Ruby};
    ///
    /// static EXAMPLE: LazyId = LazyId::new("example");
    ///
    /// #[magnus::init]
    /// fn init(ruby: &Ruby) {
    ///     LazyId::force(&EXAMPLE, ruby);
    ///
    ///     assert!(LazyId::try_get_inner(&EXAMPLE).is_some());
    /// }
    /// # let ruby = unsafe { magnus::embed::init() };
    /// # init(&ruby);
    /// ```
    #[inline]
    pub fn force(this: &Self, handle: &Ruby) {
        Self::get_inner_with(this, handle);
    }

    /// Get a [`Id`] from a `LazyId`.
    ///
    /// # Panics
    ///
    /// Panics if the `LazyId` is *poisoned*. See [`LazyId`].
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{
    ///     value::{Id, LazyId},
    ///     Ruby,
    /// };
    ///
    /// static EXAMPLE: LazyId = LazyId::new("example");
    ///
    /// # let _cleanup = unsafe { magnus::embed::init() };
    /// let ruby = Ruby::get().unwrap();
    /// assert!(Id::new("example") == LazyId::get_inner_with(&EXAMPLE, &ruby));
    /// ```
    #[inline]
    pub fn get_inner_with(this: &Self, handle: &Ruby) -> Id {
        unsafe {
            this.init.call_once(|| {
                let inner = this.inner.get();
                (*inner).value = handle.intern((*inner).name).into();
            });
            (*this.inner.get()).value.into_id_with(handle)
        }
    }

    /// Get an [`OpaqueId`] from a `LazyId`, if it has already been evaluated.
    ///
    /// This function will not call Ruby and will not initialise the inner
    /// `OpaqueId`. If the `LazyId` has not yet been initialised, returns
    /// `None`.
    ///
    /// This function will not panic, if the `LazyId` is *poisoned* it will
    /// return `None`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{rb_assert, value::LazyId};
    ///
    /// static EXAMPLE: LazyId = LazyId::new("example");
    ///
    /// # let _cleanup = unsafe { magnus::embed::init() };
    /// assert!(LazyId::try_get_inner(&EXAMPLE).is_none());
    ///
    /// rb_assert!("val == :example", val = *EXAMPLE);
    ///
    /// assert!(LazyId::try_get_inner(&EXAMPLE).is_some());
    /// ```
    pub fn try_get_inner(this: &Self) -> Option<OpaqueId> {
        unsafe { this.init.is_completed().then(|| (*this.inner.get()).value) }
    }
}

unsafe impl Send for LazyId {}
unsafe impl Sync for LazyId {}

impl fmt::Debug for LazyId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        #[allow(non_camel_case_types)]
        #[derive(Debug)]
        struct uninit();

        f.debug_tuple("LazyId")
            .field(
                Self::try_get_inner(self)
                    .as_ref()
                    .map(|v| v as &dyn fmt::Debug)
                    .unwrap_or(&uninit()),
            )
            .finish()
    }
}

impl Deref for LazyId {
    type Target = OpaqueId;

    /// # Panics
    ///
    /// Panics if the first call is from a non-Ruby thread. This `LazyId` will
    /// then be *poisoned* and all future use of it will panic.
    fn deref(&self) -> &Self::Target {
        unsafe {
            self.init.call_once(|| {
                let inner = self.inner.get();
                (*inner).value = Ruby::get().unwrap().intern((*inner).name).into();
            });
            &(*self.inner.get()).value
        }
    }
}

impl Hash for LazyId {
    /// # Panics
    ///
    /// Panics if the first call is from a non-Ruby thread. This `LazyId` will
    /// then be *poisoned* and all future use of it will panic.
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.deref().hash(state);
    }
}

impl PartialEq for LazyId {
    /// # Panics
    ///
    /// Panics if the first call is from a non-Ruby thread. This `LazyId` will
    /// then be *poisoned* and all future use of it will panic.
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.deref() == other.deref()
    }
}
impl Eq for LazyId {}

impl PartialEq<Id> for LazyId {
    /// # Panics
    ///
    /// Panics if the first call is from a non-Ruby thread. This `LazyId` will
    /// then be *poisoned* and all future use of it will panic.
    #[inline]
    fn eq(&self, other: &Id) -> bool {
        *self.deref() == *other
    }
}

impl PartialEq<StaticSymbol> for LazyId {
    /// # Panics
    ///
    /// Panics if the first call is from a non-Ruby thread. This `LazyId` will
    /// then be *poisoned* and all future use of it will panic.
    #[inline]
    fn eq(&self, other: &StaticSymbol) -> bool {
        *self == other.into_id_with(&Ruby::get_with(*other))
    }
}

impl PartialEq<Symbol> for LazyId {
    /// # Panics
    ///
    /// Panics if the first call is from a non-Ruby thread. This `LazyId` will
    /// then be *poisoned* and all future use of it will panic.
    #[inline]
    fn eq(&self, other: &Symbol) -> bool {
        other.as_static().map(|o| *self == o).unwrap_or(false)
    }
}