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
// Take a look at the license at the top of the repository in the LICENSE file.

// rustdoc-stripper-ignore-next
//! Translation between GLib/GLib-based FFI types and their Rust counterparts.
//!
//! This module allows library bindings authors to decouple type translation
//! logic and use unified idioms at FFI boundaries. It also implements
//! translation of GLib core data types.
//!
//! `FromGlib`, `from_glib` and `IntoGlib` translate simple types like `bool`.
//!
//! ```ignore
//!     pub fn set_accept_focus(&self, accept_focus: bool) {
//!         unsafe { gdk::ffi::gdk_window_set_accept_focus(self.pointer, accept_focus.into_glib()) }
//!     }
//!
//!     pub fn get_accept_focus(&self) -> bool {
//!         unsafe { from_glib(gdk::ffi::gdk_window_get_accept_focus(self.pointer)) }
//!     }
//! ```
//!
//! Implementing [`OptionIntoGlib`] on a Rust type `T` allows specifying a sentinel to indicate
//! a `None` value and auto-implementing [`FromGlib`] for `Option<T>`, which would not be
//! possible in dependent crates due to the [orphan rule](https://doc.rust-lang.org/book/ch10-02-traits.html#implementing-a-trait-on-a-type).
//! In the example below, [`IntoGlib`] is auto-implemented for `Option<SpecialU32>`.
//!
//! ```
//! # use glib::translate::*;
//! struct SpecialU32(u32);
//! impl IntoGlib for SpecialU32 {
//!     type GlibType = libc::c_uint;
//!     fn into_glib(self) -> libc::c_uint {
//!         self.0 as libc::c_uint
//!     }
//! }
//! impl OptionIntoGlib for SpecialU32 {
//!     const GLIB_NONE: Self::GlibType = 0xFFFFFF;
//! }
//! ```
//!
//! In order to auto-implement [`FromGlib`] for `Option<SpecialU32>`, proceed as follows:
//!
//! ```
//! # use glib::translate::*;
//! # struct SpecialU32(u32);
//! # impl IntoGlib for SpecialU32 {
//! #     type GlibType = libc::c_uint;
//! #     fn into_glib(self) -> libc::c_uint {
//! #         self.0 as libc::c_uint
//! #     }
//! # }
//! # impl OptionIntoGlib for SpecialU32 {
//! #     const GLIB_NONE: Self::GlibType = 0xFFFFFF;
//! # }
//! impl TryFromGlib<libc::c_uint> for SpecialU32 {
//!     type Error = GlibNoneError;
//!     unsafe fn try_from_glib(val: libc::c_uint) -> Result<Self, GlibNoneError> {
//!         if val == SpecialU32::GLIB_NONE {
//!             return Err(GlibNoneError);
//!         }
//!         Ok(SpecialU32(val as u32))
//!     }
//! }
//! ```
//!
//! The [`TryFromGlib`] trait can also be implemented when the Glib type range is larger than the
//! target Rust type's range. In the example below, the Rust type `U32` can be built from a signed
//! [`libc::c_long`], which means that the negative range is not valid.
//!
//! ```
//! # use std::convert::TryFrom;
//! # use std::num::TryFromIntError;
//! # use glib::translate::*;
//! struct U32(u32);
//! impl TryFromGlib<libc::c_long> for U32 {
//!     type Error = TryFromIntError;
//!     unsafe fn try_from_glib(val: libc::c_long) -> Result<Self, TryFromIntError> {
//!         Ok(U32(u32::try_from(val)?))
//!     }
//! }
//! ```
//!
//! Finally, you can define [`TryFromGlib`] with both `None` and `Invalid` alternatives by setting
//! the associated `type Error = GlibNoneOrInvalidError<I>` (where `I` is the `Error` type
//! when the value is invalid), which results in auto-implementing [`FromGlib`] for
//! `Result<Option<T>, I>`.
//!
//! `ToGlibPtr`, `FromGlibPtrNone`, `FromGlibPtrFull` and `FromGlibPtrBorrow` work on `gpointer`s
//! and ensure correct ownership of values
//! according to [Glib ownership transfer rules](https://gi.readthedocs.io/en/latest/annotations/giannotations.html).
//!
//! `FromGlibPtrNone` and `FromGlibPtrFull`
//! must be called on values obtained from C,
//! according to their `transfer` annotations.
//! They acquire non-gobject types,
//! as well as turning floating references to strong ones,
//! which are the only ones properly handled by the Rust bindings.
//!
//! For more information about floating references, please refer to the "Floating references" section
//! of [the gobject reference](https://docs.gtk.org/gobject/floating-refs.html).
//!
//! ```ignore
//!     fn get_title(&self) -> Option<String> {
//!         unsafe {
//!             let title = gtk::ffi::gtk_window_get_title(self.pointer);
//!             from_glib_none(title)
//!         }
//!     }
//!     fn create_bool(value: gboolean) -> Variant {
//!         unsafe {
//!             let variant = ffi::g_variant_new_boolean(value);
//!             // g_variant_new_boolean has `transfer none`
//!             from_glib_none(variant)
//!         }
//!     }
//! ```
//!
//! Letting the foreign library borrow pointers from the Rust side often
//! requires having a temporary variable of an intermediate type (e.g. `CString`).
//! A `Stash` contains the temporary storage and a pointer into it that
//! is valid for the lifetime of the `Stash`. As the lifetime of the `Stash` returned
//! from `to_glib_none` is at least the enclosing statement, you can avoid explicitly
//! binding the stash in most cases and just take the pointer out of it:
//!
//! ```ignore
//!     pub fn set_icon_name(&self, name: &str) {
//!         unsafe {
//!             gdk::ffi::gdk_window_set_icon_name(self.pointer, name.to_glib_none().0)
//!         }
//!     }
//! ```

#[cfg(not(windows))]
use std::os::unix::prelude::*;
use std::{
    borrow::Cow,
    char,
    cmp::{Eq, Ordering, PartialEq},
    collections::HashMap,
    error::Error,
    ffi::{CStr, CString, OsStr, OsString},
    fmt,
    marker::PhantomData,
    mem,
    path::{Path, PathBuf},
    ptr,
};

use libc::{c_char, size_t};

// rustdoc-stripper-ignore-next
/// A pointer
pub trait Ptr: Copy + 'static {
    fn is_null(&self) -> bool;
    fn from<X>(ptr: *mut X) -> Self;
    fn to<X>(self) -> *mut X;
}

impl<T: 'static> Ptr for *const T {
    #[inline]
    fn is_null(&self) -> bool {
        (*self).is_null()
    }

    #[inline]
    fn from<X>(ptr: *mut X) -> *const T {
        ptr as *const T
    }

    #[inline]
    fn to<X>(self) -> *mut X {
        self as *mut X
    }
}

impl<T: 'static> Ptr for *mut T {
    #[inline]
    fn is_null(&self) -> bool {
        (*self).is_null()
    }

    #[inline]
    fn from<X>(ptr: *mut X) -> *mut T {
        ptr as *mut T
    }

    #[inline]
    fn to<X>(self) -> *mut X {
        self as *mut X
    }
}

// rustdoc-stripper-ignore-next
/// Overrides pointer mutability.
///
/// Use when the C API should be specifying a const pointer but doesn't.
#[inline]
pub fn mut_override<T>(ptr: *const T) -> *mut T {
    ptr as *mut T
}

// rustdoc-stripper-ignore-next
/// Overrides pointer constness.
///
/// Use when the C API need const pointer, but function with `IsA<T>` constraint,
/// that usually don't have const pointer conversion.
#[inline]
pub fn const_override<T>(ptr: *mut T) -> *const T {
    ptr as *const T
}

// rustdoc-stripper-ignore-next
/// A trait for creating an uninitialized value. Handy for receiving outparams.
pub trait Uninitialized {
    // Returns an uninitialized value.
    unsafe fn uninitialized() -> Self;
}

// rustdoc-stripper-ignore-next
/// Returns an uninitialized value.
#[inline]
pub unsafe fn uninitialized<T: Uninitialized>() -> T {
    T::uninitialized()
}

// rustdoc-stripper-ignore-next
/// Helper type that stores temporary values used for translation.
///
/// `P` is the foreign type pointer and the first element of the tuple.
///
/// `T` is the Rust type that is translated.
///
/// The second element of the tuple is the temporary storage defined
/// by the implementation of `ToGlibPtr<P> for T`
///
/// Say you want to pass a `*mut GdkWindowAttr` to a foreign function. The `Stash`
/// will own a `GdkWindowAttr` and a `CString` that `GdkWindowAttr::title` points into.
///
/// ```ignore
/// impl <'a> ToGlibPtr<'a, *mut ffi::GdkWindowAttr> for WindowAttr {
///     type Storage = (Box<ffi::GdkWindowAttr>, Stash<'a, *const c_char, Option<String>>);
///
///     fn to_glib_none(&'a self) -> Stash<*mut ffi::GdkWindowAttr, WindowAttr> {
///         let title = self.title.to_glib_none();
///
///         let mut attrs = Box::new(ffi::GdkWindowAttr {
///             title: title.0,
///             // ....
///         });
///
///         Stash(&mut *attrs, (attrs, title))
///     }
/// }
/// ```
pub struct Stash<'a, P: Copy, T: ?Sized + ToGlibPtr<'a, P>>(
    pub P,
    pub <T as ToGlibPtr<'a, P>>::Storage,
);

pub struct StashMut<'a, P: Copy, T: ?Sized>(pub P, pub <T as ToGlibPtrMut<'a, P>>::Storage)
where
    T: ToGlibPtrMut<'a, P>;

// rustdoc-stripper-ignore-next
/// Wrapper around values representing borrowed C memory.
///
/// This is returned by `from_glib_borrow()` and ensures that the wrapped value
/// is never dropped when going out of scope.
///
/// Borrowed values must never be passed by value or mutable reference to safe Rust code and must
/// not leave the C scope in which they are valid.
#[derive(Debug)]
pub struct Borrowed<T>(mem::ManuallyDrop<T>);

impl<T> Borrowed<T> {
    // rustdoc-stripper-ignore-next
    /// Creates a new borrowed value.
    #[inline]
    pub fn new(val: T) -> Self {
        Self(mem::ManuallyDrop::new(val))
    }

    // rustdoc-stripper-ignore-next
    /// Extracts the contained value.
    ///
    /// # Safety
    ///
    /// The returned value must never be dropped and instead has to be passed to `mem::forget()` or
    /// be directly wrapped in `mem::ManuallyDrop` or another `Borrowed` wrapper.
    #[inline]
    pub unsafe fn into_inner(self) -> T {
        mem::ManuallyDrop::into_inner(self.0)
    }
}

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

impl<T> std::ops::Deref for Borrowed<T> {
    type Target = T;

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

// rustdoc-stripper-ignore-next
/// Unsafe variant of the `From` trait.
pub trait UnsafeFrom<T> {
    // rustdoc-stripper-ignore-next
    /// # Safety
    ///
    /// It is the responsibility of the caller to ensure *all* invariants of
    /// the `T` hold before this is called, and that after conversion
    /// to assume nothing other than the invariants of the output.  Implementors
    /// of this must ensure that the invariants of the output type hold.
    unsafe fn unsafe_from(t: T) -> Self;
}

// rustdoc-stripper-ignore-next
/// Translate a simple type.
pub trait IntoGlib {
    type GlibType: Copy;

    fn into_glib(self) -> Self::GlibType;
}

impl IntoGlib for bool {
    type GlibType = ffi::gboolean;

    #[inline]
    fn into_glib(self) -> ffi::gboolean {
        if self {
            ffi::GTRUE
        } else {
            ffi::GFALSE
        }
    }
}

impl IntoGlib for char {
    type GlibType = u32;

    #[inline]
    fn into_glib(self) -> u32 {
        self as u32
    }
}

unsafe impl TransparentType for char {
    type GlibType = u32;
}

impl IntoGlib for Option<char> {
    type GlibType = u32;

    #[inline]
    fn into_glib(self) -> u32 {
        self.as_ref().map(|&c| c as u32).unwrap_or(0)
    }
}

impl IntoGlib for Ordering {
    type GlibType = i32;

    #[inline]
    fn into_glib(self) -> i32 {
        match self {
            Ordering::Less => -1,
            Ordering::Equal => 0,
            Ordering::Greater => 1,
        }
    }
}

impl<O, E, G> IntoGlib for Result<O, E>
where
    G: Copy,
    O: IntoGlib<GlibType = G> + TryFromGlib<G, Error = E>,
    E: IntoGlib<GlibType = G>,
{
    type GlibType = G;

    #[inline]
    fn into_glib(self) -> Self::GlibType {
        match self {
            Ok(ok) => ok.into_glib(),
            Err(err) => err.into_glib(),
        }
    }
}

// rustdoc-stripper-ignore-next
/// A Rust type `T` for which `Option<T>` translates to the same glib type as T.
pub trait OptionIntoGlib: IntoGlib {
    const GLIB_NONE: Self::GlibType;
}

impl<T: OptionIntoGlib> IntoGlib for Option<T> {
    type GlibType = T::GlibType;

    #[inline]
    fn into_glib(self) -> Self::GlibType {
        match self {
            Some(t) => t.into_glib(),
            None => T::GLIB_NONE,
        }
    }
}

// rustdoc-stripper-ignore-next
/// Provides the default pointer type to be used in some container conversions.
///
/// It's `*mut c_char` for `String`, `*mut GtkButton` for `gtk::Button`, etc.
pub trait GlibPtrDefault {
    type GlibType: Ptr;
}

impl<'a, T: ?Sized + GlibPtrDefault> GlibPtrDefault for &'a T {
    type GlibType = <T as GlibPtrDefault>::GlibType;
}

// rustdoc-stripper-ignore-next
/// Translate to a pointer.
pub trait ToGlibPtr<'a, P: Copy> {
    type Storage;

    // rustdoc-stripper-ignore-next
    /// Transfer: none.
    ///
    /// The pointer in the `Stash` is only valid for the lifetime of the `Stash`.
    fn to_glib_none(&'a self) -> Stash<'a, P, Self>;

    // rustdoc-stripper-ignore-next
    /// Transfer: container.
    ///
    /// We transfer the container ownership to the foreign library retaining
    /// the elements ownership.
    fn to_glib_container(&'a self) -> Stash<'a, P, Self> {
        unimplemented!();
    }

    // rustdoc-stripper-ignore-next
    /// Transfer: full.
    ///
    /// We transfer the ownership to the foreign library.
    fn to_glib_full(&self) -> P {
        unimplemented!();
    }
}

// rustdoc-stripper-ignore-next
/// Translate to a pointer with a mutable borrow.
pub trait ToGlibPtrMut<'a, P: Copy> {
    type Storage;

    // rustdoc-stripper-ignore-next
    /// Transfer: none.
    ///
    /// The pointer in the `Stash` is only valid for the lifetime of the `Stash`.
    #[allow(clippy::wrong_self_convention)]
    fn to_glib_none_mut(&'a mut self) -> StashMut<P, Self>;
}

impl<'a, P: Ptr, T: ToGlibPtr<'a, P>> ToGlibPtr<'a, P> for Option<T> {
    type Storage = Option<<T as ToGlibPtr<'a, P>>::Storage>;

    #[inline]
    fn to_glib_none(&'a self) -> Stash<'a, P, Option<T>> {
        self.as_ref()
            .map_or(Stash(Ptr::from::<()>(ptr::null_mut()), None), |s| {
                let s = s.to_glib_none();
                Stash(s.0, Some(s.1))
            })
    }

    #[inline]
    fn to_glib_full(&self) -> P {
        self.as_ref()
            .map_or(Ptr::from::<()>(ptr::null_mut()), ToGlibPtr::to_glib_full)
    }
}

impl<'a, 'opt: 'a, P: Ptr, T: ToGlibPtrMut<'a, P>> ToGlibPtrMut<'a, P> for Option<&'opt mut T> {
    type Storage = Option<<T as ToGlibPtrMut<'a, P>>::Storage>;

    #[inline]
    fn to_glib_none_mut(&'a mut self) -> StashMut<'a, P, Option<&'opt mut T>> {
        self.as_mut()
            .map_or(StashMut(Ptr::from::<()>(ptr::null_mut()), None), |s| {
                let s = s.to_glib_none_mut();
                StashMut(s.0, Some(s.1))
            })
    }
}

impl<'a, P: Ptr, T: ?Sized + ToGlibPtr<'a, P>> ToGlibPtr<'a, P> for &'a T {
    type Storage = <T as ToGlibPtr<'a, P>>::Storage;

    #[inline]
    fn to_glib_none(&'a self) -> Stash<'a, P, Self> {
        let s = (*self).to_glib_none();
        Stash(s.0, s.1)
    }

    #[inline]
    fn to_glib_full(&self) -> P {
        (*self).to_glib_full()
    }
}

#[doc(hidden)]
#[derive(Debug)]
pub enum CowStash<B, O> {
    Borrowed(B),
    Owned(O),
}

impl<'a, P: Ptr, T> ToGlibPtr<'a, P> for Cow<'a, T>
where
    T: ToOwned + ?Sized + ToGlibPtr<'a, P>,
    T::Owned: ToGlibPtr<'a, P>,
{
    type Storage = CowStash<T::Storage, <T::Owned as ToGlibPtr<'a, P>>::Storage>;

    #[inline]
    fn to_glib_none(&'a self) -> Stash<'a, P, Self> {
        match self {
            Cow::Borrowed(v) => {
                let s = v.to_glib_none();
                Stash(s.0, CowStash::Borrowed(s.1))
            }
            Cow::Owned(v) => {
                let s = v.to_glib_none();
                Stash(s.0, CowStash::Owned(s.1))
            }
        }
    }

    #[inline]
    fn to_glib_full(&self) -> P {
        match self {
            Cow::Borrowed(v) => v.to_glib_full(),
            Cow::Owned(v) => v.to_glib_full(),
        }
    }
}

impl<'a> ToGlibPtr<'a, *const c_char> for str {
    type Storage = Cow<'static, [u8]>;

    fn to_glib_none(&'a self) -> Stash<'a, *const c_char, Self> {
        static EMPTY_STRING: &[u8] = &[0];

        let bytes = if self.is_empty() {
            Cow::Borrowed(EMPTY_STRING)
        } else {
            if cfg!(debug_assertions) {
                crate::GStr::check_interior_nuls(self).unwrap();
            }
            let mut bytes = Vec::with_capacity(self.len() + 1);
            unsafe {
                ptr::copy_nonoverlapping(self.as_ptr(), bytes.as_mut_ptr(), self.len());
                bytes.as_mut_ptr().add(self.len()).write(0);
                bytes.set_len(self.len() + 1);
            }
            Cow::Owned(bytes)
        };
        Stash(bytes.as_ptr() as *const c_char, bytes)
    }

    #[inline]
    fn to_glib_full(&self) -> *const c_char {
        if cfg!(debug_assertions) {
            crate::GStr::check_interior_nuls(self).unwrap();
        }
        unsafe {
            ffi::g_strndup(self.as_ptr() as *const c_char, self.len() as size_t) as *const c_char
        }
    }
}

impl<'a> ToGlibPtr<'a, *mut c_char> for str {
    type Storage = Cow<'static, [u8]>;

    #[inline]
    fn to_glib_none(&'a self) -> Stash<'a, *mut c_char, Self> {
        let s = ToGlibPtr::<*const c_char>::to_glib_none(self);
        Stash(s.0 as *mut _, s.1)
    }

    #[inline]
    fn to_glib_full(&self) -> *mut c_char {
        ToGlibPtr::<*const c_char>::to_glib_full(self) as *mut _
    }
}

impl<'a> ToGlibPtr<'a, *const c_char> for String {
    type Storage = Cow<'static, [u8]>;

    #[inline]
    fn to_glib_none(&self) -> Stash<'a, *const c_char, String> {
        let s = ToGlibPtr::to_glib_none(self.as_str());
        Stash(s.0, s.1)
    }

    #[inline]
    fn to_glib_full(&self) -> *const c_char {
        ToGlibPtr::to_glib_full(self.as_str())
    }
}

impl<'a> ToGlibPtr<'a, *mut c_char> for String {
    type Storage = Cow<'static, [u8]>;

    #[inline]
    fn to_glib_none(&self) -> Stash<'a, *mut c_char, String> {
        let s = ToGlibPtr::to_glib_none(self.as_str());
        Stash(s.0, s.1)
    }

    #[inline]
    fn to_glib_full(&self) -> *mut c_char {
        ToGlibPtr::to_glib_full(self.as_str())
    }
}

impl<'a> ToGlibPtr<'a, *const c_char> for CStr {
    type Storage = PhantomData<&'a Self>;

    #[inline]
    fn to_glib_none(&'a self) -> Stash<'a, *const c_char, Self> {
        Stash(self.as_ptr(), PhantomData)
    }

    #[inline]
    fn to_glib_full(&self) -> *const c_char {
        unsafe {
            ffi::g_strndup(
                self.as_ptr() as *const c_char,
                self.to_bytes().len() as size_t,
            ) as *const c_char
        }
    }
}

impl<'a> ToGlibPtr<'a, *mut c_char> for CStr {
    type Storage = PhantomData<&'a Self>;

    #[inline]
    fn to_glib_none(&'a self) -> Stash<'a, *mut c_char, Self> {
        Stash(self.as_ptr() as *mut c_char, PhantomData)
    }

    #[inline]
    fn to_glib_full(&self) -> *mut c_char {
        unsafe {
            ffi::g_strndup(
                self.as_ptr() as *const c_char,
                self.to_bytes().len() as size_t,
            ) as *mut c_char
        }
    }
}

impl<'a> ToGlibPtr<'a, *const c_char> for CString {
    type Storage = PhantomData<&'a Self>;

    #[inline]
    fn to_glib_none(&'a self) -> Stash<'a, *const c_char, Self> {
        Stash(self.as_ptr(), PhantomData)
    }

    #[inline]
    fn to_glib_full(&self) -> *const c_char {
        unsafe {
            ffi::g_strndup(
                self.as_ptr() as *const c_char,
                self.as_bytes().len() as size_t,
            ) as *const c_char
        }
    }
}

impl<'a> ToGlibPtr<'a, *mut c_char> for CString {
    type Storage = PhantomData<&'a Self>;

    #[inline]
    fn to_glib_none(&'a self) -> Stash<'a, *mut c_char, Self> {
        Stash(self.as_ptr() as *mut c_char, PhantomData)
    }

    #[inline]
    fn to_glib_full(&self) -> *mut c_char {
        unsafe {
            ffi::g_strndup(
                self.as_ptr() as *const c_char,
                self.as_bytes().len() as size_t,
            ) as *mut c_char
        }
    }
}

// rustdoc-stripper-ignore-next
/// Translate to a pointer.
pub trait IntoGlibPtr<P: Ptr> {
    // rustdoc-stripper-ignore-next
    /// Transfer: full.
    #[allow(clippy::wrong_self_convention)]
    unsafe fn into_glib_ptr(self) -> P;
}

impl<P: Ptr, T: IntoGlibPtr<P>> IntoGlibPtr<P> for Option<T> {
    #[inline]
    unsafe fn into_glib_ptr(self) -> P {
        self.map_or(Ptr::from::<()>(ptr::null_mut()), |s| {
            IntoGlibPtr::into_glib_ptr(s)
        })
    }
}

impl GlibPtrDefault for str {
    type GlibType = *mut c_char;
}

impl GlibPtrDefault for String {
    type GlibType = *mut c_char;
}

#[cfg(not(windows))]
pub(crate) fn path_to_c(path: &Path) -> CString {
    // GLib paths on UNIX are always in the local encoding, just like in Rust
    //
    // Paths on UNIX must not contain NUL bytes, in which case the conversion
    // to a CString would fail. The only thing we can do then is to panic, as passing
    // NULL or the empty string to GLib would cause undefined behaviour.
    CString::new(path.as_os_str().as_bytes()).expect("Invalid path with NUL bytes")
}

#[cfg(windows)]
pub(crate) fn path_to_c(path: &Path) -> CString {
    // GLib paths are always UTF-8 strings on Windows, while in Rust they are
    // WTF-8. As such, we need to convert to a UTF-8 string. This conversion can
    // fail, see https://simonsapin.github.io/wtf-8/#converting-wtf-8-utf-8
    //
    // It's not clear what we're supposed to do if it fails: the path is not
    // representable in UTF-8 and thus can't possibly be passed to GLib.
    // Passing NULL or the empty string to GLib can lead to undefined behaviour, so
    // the only safe option seems to be to simply panic here.
    let path_str = path
        .to_str()
        .expect("Path can't be represented as UTF-8")
        .to_owned();

    // On Windows, paths can have \\?\ prepended for long-path support. See
    // MSDN documentation about CreateFile
    //
    // We have to get rid of this and let GLib take care of all these
    // weirdnesses later
    if path_str.starts_with("\\\\?\\") {
        CString::new(path_str[4..].as_bytes())
    } else {
        CString::new(path_str.as_bytes())
    }
    .expect("Invalid path with NUL bytes")
}

#[cfg(not(windows))]
pub(crate) fn os_str_to_c(s: &OsStr) -> CString {
    // GLib OS string (environment strings) on UNIX are always in the local encoding,
    // just like in Rust
    //
    // OS string on UNIX must not contain NUL bytes, in which case the conversion
    // to a CString would fail. The only thing we can do then is to panic, as passing
    // NULL or the empty string to GLib would cause undefined behaviour.
    CString::new(s.as_bytes()).expect("Invalid OS String with NUL bytes")
}

#[cfg(windows)]
pub(crate) fn os_str_to_c(s: &OsStr) -> CString {
    // GLib OS string (environment strings) are always UTF-8 strings on Windows,
    // while in Rust they are WTF-8. As such, we need to convert to a UTF-8 string.
    // This conversion can fail, see https://simonsapin.github.io/wtf-8/#converting-wtf-8-utf-8
    //
    // It's not clear what we're supposed to do if it fails: the OS string is not
    // representable in UTF-8 and thus can't possibly be passed to GLib.
    // Passing NULL or the empty string to GLib can lead to undefined behaviour, so
    // the only safe option seems to be to simply panic here.
    let os_str = s
        .to_str()
        .expect("OS String can't be represented as UTF-8")
        .to_owned();

    CString::new(os_str.as_bytes()).expect("Invalid OS string with NUL bytes")
}

impl<'a> ToGlibPtr<'a, *const c_char> for Path {
    type Storage = CString;

    #[inline]
    fn to_glib_none(&'a self) -> Stash<'a, *const c_char, Self> {
        let tmp = path_to_c(self);
        Stash(tmp.as_ptr(), tmp)
    }
}

impl<'a> ToGlibPtr<'a, *mut c_char> for Path {
    type Storage = CString;

    #[inline]
    fn to_glib_none(&'a self) -> Stash<'a, *mut c_char, Self> {
        let tmp = path_to_c(self);
        Stash(tmp.as_ptr() as *mut c_char, tmp)
    }

    #[inline]
    fn to_glib_full(&self) -> *mut c_char {
        let tmp = path_to_c(self);
        unsafe { ffi::g_strdup(tmp.as_ptr()) }
    }
}

impl<'a> ToGlibPtr<'a, *const c_char> for PathBuf {
    type Storage = CString;

    #[inline]
    fn to_glib_none(&'a self) -> Stash<'a, *const c_char, Self> {
        let tmp = path_to_c(self);
        Stash(tmp.as_ptr(), tmp)
    }
}

impl<'a> ToGlibPtr<'a, *mut c_char> for PathBuf {
    type Storage = CString;

    #[inline]
    fn to_glib_none(&'a self) -> Stash<'a, *mut c_char, Self> {
        let tmp = path_to_c(self);
        Stash(tmp.as_ptr() as *mut c_char, tmp)
    }

    #[inline]
    fn to_glib_full(&self) -> *mut c_char {
        let tmp = path_to_c(self);
        unsafe { ffi::g_strdup(tmp.as_ptr()) }
    }
}

impl GlibPtrDefault for Path {
    type GlibType = *mut c_char;
}

impl GlibPtrDefault for PathBuf {
    type GlibType = *mut c_char;
}

impl<'a> ToGlibPtr<'a, *const c_char> for OsStr {
    type Storage = CString;

    #[inline]
    fn to_glib_none(&'a self) -> Stash<'a, *const c_char, Self> {
        let tmp = os_str_to_c(self);
        Stash(tmp.as_ptr(), tmp)
    }
}

impl<'a> ToGlibPtr<'a, *mut c_char> for OsStr {
    type Storage = CString;

    #[inline]
    fn to_glib_none(&'a self) -> Stash<'a, *mut c_char, Self> {
        let tmp = os_str_to_c(self);
        Stash(tmp.as_ptr() as *mut c_char, tmp)
    }

    #[inline]
    fn to_glib_full(&self) -> *mut c_char {
        let tmp = os_str_to_c(self);
        unsafe { ffi::g_strdup(tmp.as_ptr()) }
    }
}

impl<'a> ToGlibPtr<'a, *const c_char> for OsString {
    type Storage = CString;

    #[inline]
    fn to_glib_none(&'a self) -> Stash<'a, *const c_char, Self> {
        let tmp = os_str_to_c(self);
        Stash(tmp.as_ptr(), tmp)
    }
}

impl<'a> ToGlibPtr<'a, *mut c_char> for OsString {
    type Storage = CString;

    #[inline]
    fn to_glib_none(&'a self) -> Stash<'a, *mut c_char, Self> {
        let tmp = os_str_to_c(self);
        Stash(tmp.as_ptr() as *mut c_char, tmp)
    }

    #[inline]
    fn to_glib_full(&self) -> *mut c_char {
        let tmp = os_str_to_c(self);
        unsafe { ffi::g_strdup(tmp.as_ptr()) }
    }
}

impl GlibPtrDefault for OsStr {
    type GlibType = *mut c_char;
}

impl GlibPtrDefault for OsString {
    type GlibType = *mut c_char;
}

pub trait ToGlibContainerFromSlice<'a, P>
where
    Self: Sized,
{
    type Storage;

    #[allow(clippy::wrong_self_convention)]
    fn to_glib_none_from_slice(t: &'a [Self]) -> (P, Self::Storage);
    #[allow(clippy::wrong_self_convention)]
    fn to_glib_container_from_slice(t: &'a [Self]) -> (P, Self::Storage);
    #[allow(clippy::wrong_self_convention)]
    fn to_glib_full_from_slice(t: &[Self]) -> P;
}

macro_rules! impl_to_glib_container_from_slice_fundamental {
    ($name:ty) => {
        impl<'a> ToGlibContainerFromSlice<'a, *mut $name> for $name {
            type Storage = std::marker::PhantomData<&'a [$name]>;

            #[inline]
            fn to_glib_none_from_slice(t: &'a [$name]) -> (*mut $name, Self::Storage) {
                (t.as_ptr() as *mut $name, std::marker::PhantomData)
            }

            #[inline]
            fn to_glib_container_from_slice(t: &'a [$name]) -> (*mut $name, Self::Storage) {
                (
                    ToGlibContainerFromSlice::to_glib_full_from_slice(t),
                    std::marker::PhantomData,
                )
            }

            #[inline]
            fn to_glib_full_from_slice(t: &[$name]) -> *mut $name {
                if t.len() == 0 {
                    return ptr::null_mut();
                }

                unsafe {
                    let res = ffi::g_malloc(mem::size_of_val(t)) as *mut $name;
                    ptr::copy_nonoverlapping(t.as_ptr(), res, t.len());
                    res
                }
            }
        }
    };
}

impl_to_glib_container_from_slice_fundamental!(u8);
impl_to_glib_container_from_slice_fundamental!(i8);
impl_to_glib_container_from_slice_fundamental!(u16);
impl_to_glib_container_from_slice_fundamental!(i16);
impl_to_glib_container_from_slice_fundamental!(u32);
impl_to_glib_container_from_slice_fundamental!(i32);
impl_to_glib_container_from_slice_fundamental!(u64);
impl_to_glib_container_from_slice_fundamental!(i64);
impl_to_glib_container_from_slice_fundamental!(f32);
impl_to_glib_container_from_slice_fundamental!(f64);

macro_rules! impl_to_glib_container_from_slice_string {
    ($name:ty, $ffi_name:ty) => {
        impl<'a> ToGlibContainerFromSlice<'a, *mut $ffi_name> for $name {
            type Storage = (Vec<Stash<'a, $ffi_name, $name>>, Option<Vec<$ffi_name>>);

            fn to_glib_none_from_slice(t: &'a [$name]) -> (*mut $ffi_name, Self::Storage) {
                let v: Vec<_> = t.iter().map(ToGlibPtr::to_glib_none).collect();
                let mut v_ptr: Vec<_> = v.iter().map(|s| s.0).collect();
                v_ptr.push(ptr::null_mut() as $ffi_name);

                (v_ptr.as_ptr() as *mut $ffi_name, (v, Some(v_ptr)))
            }

            fn to_glib_container_from_slice(t: &'a [$name]) -> (*mut $ffi_name, Self::Storage) {
                let v: Vec<_> = t.iter().map(ToGlibPtr::to_glib_none).collect();

                let v_ptr = unsafe {
                    let v_ptr = ffi::g_malloc(mem::size_of::<$ffi_name>() * (t.len() + 1))
                        as *mut $ffi_name;

                    for (i, s) in v.iter().enumerate() {
                        ptr::write(v_ptr.add(i), s.0);
                    }
                    ptr::write(v_ptr.add(t.len()), ptr::null_mut());

                    v_ptr
                };

                (v_ptr, (v, None))
            }

            fn to_glib_full_from_slice(t: &[$name]) -> *mut $ffi_name {
                unsafe {
                    let v_ptr = ffi::g_malloc(mem::size_of::<$ffi_name>() * (t.len() + 1))
                        as *mut $ffi_name;

                    for (i, s) in t.iter().enumerate() {
                        ptr::write(v_ptr.add(i), s.to_glib_full());
                    }
                    ptr::write(v_ptr.add(t.len()), ptr::null_mut());

                    v_ptr
                }
            }
        }
        impl<'a> ToGlibContainerFromSlice<'a, *const $ffi_name> for $name {
            type Storage = (Vec<Stash<'a, $ffi_name, $name>>, Option<Vec<$ffi_name>>);

            fn to_glib_none_from_slice(t: &'a [$name]) -> (*const $ffi_name, Self::Storage) {
                let v: Vec<_> = t.iter().map(ToGlibPtr::to_glib_none).collect();
                let mut v_ptr: Vec<_> = v.iter().map(|s| s.0).collect();
                v_ptr.push(ptr::null_mut() as $ffi_name);

                (v_ptr.as_ptr() as *const $ffi_name, (v, Some(v_ptr)))
            }

            fn to_glib_container_from_slice(t: &'a [$name]) -> (*const $ffi_name, Self::Storage) {
                let v: Vec<_> = t.iter().map(ToGlibPtr::to_glib_none).collect();

                let v_ptr = unsafe {
                    let v_ptr = ffi::g_malloc(mem::size_of::<$ffi_name>() * (t.len() + 1))
                        as *mut $ffi_name;

                    for (i, s) in v.iter().enumerate() {
                        ptr::write(v_ptr.add(i), s.0);
                    }
                    ptr::write(v_ptr.add(t.len()), ptr::null_mut());

                    v_ptr as *const $ffi_name
                };

                (v_ptr, (v, None))
            }

            fn to_glib_full_from_slice(t: &[$name]) -> *const $ffi_name {
                unsafe {
                    let v_ptr = ffi::g_malloc(mem::size_of::<$ffi_name>() * (t.len() + 1))
                        as *mut $ffi_name;

                    for (i, s) in t.iter().enumerate() {
                        ptr::write(v_ptr.add(i), s.to_glib_full());
                    }
                    ptr::write(v_ptr.add(t.len()), ptr::null_mut());

                    v_ptr as *const $ffi_name
                }
            }
        }
    };
}

impl_to_glib_container_from_slice_string!(&'a str, *mut c_char);
impl_to_glib_container_from_slice_string!(&'a str, *const c_char);
impl_to_glib_container_from_slice_string!(String, *mut c_char);
impl_to_glib_container_from_slice_string!(String, *const c_char);
impl_to_glib_container_from_slice_string!(&'a Path, *mut c_char);
impl_to_glib_container_from_slice_string!(&'a Path, *const c_char);
impl_to_glib_container_from_slice_string!(PathBuf, *mut c_char);
impl_to_glib_container_from_slice_string!(PathBuf, *const c_char);
impl_to_glib_container_from_slice_string!(&'a OsStr, *mut c_char);
impl_to_glib_container_from_slice_string!(&'a OsStr, *const c_char);
impl_to_glib_container_from_slice_string!(OsString, *mut c_char);
impl_to_glib_container_from_slice_string!(OsString, *const c_char);
impl_to_glib_container_from_slice_string!(crate::GString, *mut c_char);
impl_to_glib_container_from_slice_string!(crate::GString, *const c_char);

impl<'a, T> ToGlibContainerFromSlice<'a, *mut ffi::GList> for T
where
    T: GlibPtrDefault + ToGlibPtr<'a, <T as GlibPtrDefault>::GlibType>,
{
    type Storage = (
        Option<List>,
        Vec<Stash<'a, <T as GlibPtrDefault>::GlibType, T>>,
    );

    #[inline]
    fn to_glib_none_from_slice(t: &'a [T]) -> (*mut ffi::GList, Self::Storage) {
        let stash_vec: Vec<_> = t.iter().rev().map(ToGlibPtr::to_glib_none).collect();
        let mut list: *mut ffi::GList = ptr::null_mut();
        unsafe {
            for stash in &stash_vec {
                list = ffi::g_list_prepend(list, Ptr::to(stash.0));
            }
        }
        let stash = (ptr::NonNull::new(list).map(List), stash_vec);
        (list, stash)
    }

    #[inline]
    fn to_glib_container_from_slice(t: &'a [T]) -> (*mut ffi::GList, Self::Storage) {
        let stash_vec: Vec<_> = t.iter().rev().map(ToGlibPtr::to_glib_none).collect();
        let mut list: *mut ffi::GList = ptr::null_mut();
        unsafe {
            for stash in &stash_vec {
                list = ffi::g_list_prepend(list, Ptr::to(stash.0));
            }
        }
        (list, (None, stash_vec))
    }

    #[inline]
    fn to_glib_full_from_slice(t: &[T]) -> *mut ffi::GList {
        let mut list: *mut ffi::GList = ptr::null_mut();
        unsafe {
            for ptr in t.iter().rev().map(ToGlibPtr::to_glib_full) {
                list = ffi::g_list_prepend(list, Ptr::to(ptr));
            }
        }
        list
    }
}

impl<'a, T> ToGlibContainerFromSlice<'a, *const ffi::GList> for T
where
    T: GlibPtrDefault + ToGlibPtr<'a, <T as GlibPtrDefault>::GlibType>,
{
    type Storage = (
        Option<List>,
        Vec<Stash<'a, <T as GlibPtrDefault>::GlibType, T>>,
    );

    #[inline]
    fn to_glib_none_from_slice(t: &'a [T]) -> (*const ffi::GList, Self::Storage) {
        let (list, stash) = ToGlibContainerFromSlice::<*mut ffi::GList>::to_glib_none_from_slice(t);
        (list as *const ffi::GList, stash)
    }

    #[inline]
    fn to_glib_container_from_slice(_t: &'a [T]) -> (*const ffi::GList, Self::Storage) {
        unimplemented!()
    }

    #[inline]
    fn to_glib_full_from_slice(_t: &[T]) -> *const ffi::GList {
        unimplemented!()
    }
}

#[doc(alias = "GList")]
pub struct List(ptr::NonNull<ffi::GList>);

impl Drop for List {
    #[inline]
    fn drop(&mut self) {
        unsafe { ffi::g_list_free(self.0.as_ptr()) }
    }
}

impl<'a, T> ToGlibContainerFromSlice<'a, *mut ffi::GSList> for &'a T
where
    T: GlibPtrDefault + ToGlibPtr<'a, <T as GlibPtrDefault>::GlibType>,
{
    type Storage = (
        Option<SList>,
        Vec<Stash<'a, <T as GlibPtrDefault>::GlibType, &'a T>>,
    );

    #[inline]
    fn to_glib_none_from_slice(t: &'a [&'a T]) -> (*mut ffi::GSList, Self::Storage) {
        let stash_vec: Vec<_> = t.iter().rev().map(ToGlibPtr::to_glib_none).collect();
        let mut list: *mut ffi::GSList = ptr::null_mut();
        unsafe {
            for stash in &stash_vec {
                list = ffi::g_slist_prepend(list, Ptr::to(stash.0));
            }
        }

        let stash = (ptr::NonNull::new(list).map(SList), stash_vec);
        (list, stash)
    }

    #[inline]
    fn to_glib_container_from_slice(t: &'a [&'a T]) -> (*mut ffi::GSList, Self::Storage) {
        let stash_vec: Vec<_> = t.iter().rev().map(ToGlibPtr::to_glib_none).collect();
        let mut list: *mut ffi::GSList = ptr::null_mut();
        unsafe {
            for stash in &stash_vec {
                list = ffi::g_slist_prepend(list, Ptr::to(stash.0));
            }
        }
        (list, (None, stash_vec))
    }

    #[inline]
    fn to_glib_full_from_slice(t: &[&'a T]) -> *mut ffi::GSList {
        let mut list: *mut ffi::GSList = ptr::null_mut();
        unsafe {
            for ptr in t.iter().rev().map(ToGlibPtr::to_glib_full) {
                list = ffi::g_slist_prepend(list, Ptr::to(ptr));
            }
        }
        list
    }
}

impl<'a, T> ToGlibContainerFromSlice<'a, *const ffi::GSList> for &'a T
where
    T: GlibPtrDefault + ToGlibPtr<'a, <T as GlibPtrDefault>::GlibType>,
{
    type Storage = (
        Option<SList>,
        Vec<Stash<'a, <T as GlibPtrDefault>::GlibType, &'a T>>,
    );

    #[inline]
    fn to_glib_none_from_slice(t: &'a [&'a T]) -> (*const ffi::GSList, Self::Storage) {
        let (list, stash) =
            ToGlibContainerFromSlice::<*mut ffi::GSList>::to_glib_none_from_slice(t);
        (list as *const ffi::GSList, stash)
    }

    #[inline]
    fn to_glib_container_from_slice(_t: &'a [&'a T]) -> (*const ffi::GSList, Self::Storage) {
        unimplemented!()
    }

    #[inline]
    fn to_glib_full_from_slice(_t: &[&'a T]) -> *const ffi::GSList {
        unimplemented!()
    }
}

#[doc(alias = "GSList")]
pub struct SList(ptr::NonNull<ffi::GSList>);

impl Drop for SList {
    #[inline]
    fn drop(&mut self) {
        unsafe { ffi::g_slist_free(self.0.as_ptr()) }
    }
}

impl<'a, P: Ptr, T: ToGlibContainerFromSlice<'a, P>> ToGlibPtr<'a, P> for [T] {
    type Storage = T::Storage;

    #[inline]
    fn to_glib_none(&'a self) -> Stash<'a, P, Self> {
        let result = ToGlibContainerFromSlice::to_glib_none_from_slice(self);
        Stash(result.0, result.1)
    }

    #[inline]
    fn to_glib_container(&'a self) -> Stash<'a, P, Self> {
        let result = ToGlibContainerFromSlice::to_glib_container_from_slice(self);
        Stash(result.0, result.1)
    }

    #[inline]
    fn to_glib_full(&self) -> P {
        ToGlibContainerFromSlice::to_glib_full_from_slice(self)
    }
}

#[allow(clippy::implicit_hasher)]
impl<'a> ToGlibPtr<'a, *mut ffi::GHashTable> for HashMap<String, String> {
    type Storage = HashTable;

    #[inline]
    fn to_glib_none(&self) -> Stash<'a, *mut ffi::GHashTable, Self> {
        let ptr = self.to_glib_full();
        Stash(ptr, HashTable(unsafe { ptr::NonNull::new_unchecked(ptr) }))
    }

    #[inline]
    fn to_glib_full(&self) -> *mut ffi::GHashTable {
        unsafe {
            let ptr = ffi::g_hash_table_new_full(
                Some(ffi::g_str_hash),
                Some(ffi::g_str_equal),
                Some(ffi::g_free),
                Some(ffi::g_free),
            );
            for (k, v) in self {
                let k: *mut c_char = k.to_glib_full();
                let v: *mut c_char = v.to_glib_full();
                ffi::g_hash_table_insert(ptr, k as *mut _, v as *mut _);
            }
            ptr
        }
    }
}

#[doc(alias = "GHashTable")]
pub struct HashTable(ptr::NonNull<ffi::GHashTable>);

impl Drop for HashTable {
    #[inline]
    fn drop(&mut self) {
        unsafe { ffi::g_hash_table_unref(self.0.as_ptr()) }
    }
}

#[doc(alias = "GPtrArray")]
pub struct PtrArray(ptr::NonNull<ffi::GPtrArray>);

impl Drop for PtrArray {
    #[inline]
    fn drop(&mut self) {
        unsafe {
            ffi::g_ptr_array_unref(self.0.as_ptr());
        }
    }
}

impl<'a, T> ToGlibContainerFromSlice<'a, *mut ffi::GPtrArray> for T
where
    T: GlibPtrDefault + ToGlibPtr<'a, <T as GlibPtrDefault>::GlibType>,
{
    type Storage = (
        Option<PtrArray>,
        Vec<Stash<'a, <T as GlibPtrDefault>::GlibType, T>>,
    );

    #[inline]
    fn to_glib_none_from_slice(t: &'a [T]) -> (*mut ffi::GPtrArray, Self::Storage) {
        let stash_vec: Vec<_> = t.iter().map(ToGlibPtr::to_glib_none).collect();
        let arr = unsafe { ffi::g_ptr_array_sized_new(t.len() as _) };
        unsafe {
            for stash in &stash_vec {
                ffi::g_ptr_array_add(arr, Ptr::to(stash.0));
            }
        }

        (
            arr,
            (
                Some(PtrArray(unsafe { ptr::NonNull::new_unchecked(arr) })),
                stash_vec,
            ),
        )
    }

    #[inline]
    fn to_glib_container_from_slice(t: &'a [T]) -> (*mut ffi::GPtrArray, Self::Storage) {
        let stash_vec: Vec<_> = t.iter().map(ToGlibPtr::to_glib_none).collect();
        let arr = unsafe { ffi::g_ptr_array_sized_new(t.len() as _) };
        unsafe {
            for stash in &stash_vec {
                ffi::g_ptr_array_add(arr, Ptr::to(stash.0));
            }
        }
        (arr, (None, stash_vec))
    }

    #[inline]
    fn to_glib_full_from_slice(t: &[T]) -> *mut ffi::GPtrArray {
        let arr = unsafe { ffi::g_ptr_array_sized_new(t.len() as _) };
        unsafe {
            for ptr in t.iter().map(ToGlibPtr::to_glib_full) {
                ffi::g_ptr_array_add(arr, Ptr::to(ptr));
            }
        }
        arr
    }
}

impl<'a, T> ToGlibContainerFromSlice<'a, *const ffi::GPtrArray> for T
where
    T: GlibPtrDefault + ToGlibPtr<'a, <T as GlibPtrDefault>::GlibType>,
{
    type Storage = (
        Option<PtrArray>,
        Vec<Stash<'a, <T as GlibPtrDefault>::GlibType, T>>,
    );

    #[inline]
    fn to_glib_none_from_slice(t: &'a [T]) -> (*const ffi::GPtrArray, Self::Storage) {
        let (arr, stash) =
            ToGlibContainerFromSlice::<*mut ffi::GPtrArray>::to_glib_none_from_slice(t);
        (arr as *const ffi::GPtrArray, stash)
    }

    #[inline]
    fn to_glib_container_from_slice(_t: &'a [T]) -> (*const ffi::GPtrArray, Self::Storage) {
        unimplemented!()
    }

    #[inline]
    fn to_glib_full_from_slice(_t: &[T]) -> *const ffi::GPtrArray {
        unimplemented!()
    }
}

// rustdoc-stripper-ignore-next
/// Translate a simple type.
pub trait FromGlib<G: Copy>: Sized {
    unsafe fn from_glib(val: G) -> Self;
}

// rustdoc-stripper-ignore-next
/// Translate a simple type.
#[inline]
pub unsafe fn from_glib<G: Copy, T: FromGlib<G>>(val: G) -> T {
    FromGlib::from_glib(val)
}

impl FromGlib<ffi::gboolean> for bool {
    #[inline]
    unsafe fn from_glib(val: ffi::gboolean) -> Self {
        val != ffi::GFALSE
    }
}

impl FromGlib<i32> for Ordering {
    #[inline]
    unsafe fn from_glib(val: i32) -> Self {
        val.cmp(&0)
    }
}

// rustdoc-stripper-ignore-next
/// Translate from a Glib type which can result in an undefined and/or invalid value.
pub trait TryFromGlib<G: Copy>: Sized {
    type Error;
    unsafe fn try_from_glib(val: G) -> Result<Self, Self::Error>;
}

// rustdoc-stripper-ignore-next
/// Translate from a Glib type which can result in an undefined and/or invalid value.
#[inline]
pub unsafe fn try_from_glib<G: Copy, T: TryFromGlib<G>>(
    val: G,
) -> Result<T, <T as TryFromGlib<G>>::Error> {
    TryFromGlib::try_from_glib(val)
}

// rustdoc-stripper-ignore-next
/// Error type for [`TryFromGlib`] when the Glib value is None.
#[derive(Debug, PartialEq, Eq)]
pub struct GlibNoneError;

impl fmt::Display for GlibNoneError {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(fmt, "glib value is None")
    }
}

impl std::error::Error for GlibNoneError {}

impl<G: Copy, T: TryFromGlib<G, Error = GlibNoneError>> FromGlib<G> for Option<T> {
    #[inline]
    unsafe fn from_glib(val: G) -> Self {
        T::try_from_glib(val).ok()
    }
}

// rustdoc-stripper-ignore-next
/// Error type for [`TryFromGlib`] when the Glib value can be None or invalid.
#[derive(Debug, Eq, PartialEq)]
pub enum GlibNoneOrInvalidError<I: Error> {
    Invalid(I),
    None,
}

impl<I: Error> GlibNoneOrInvalidError<I> {
    // rustdoc-stripper-ignore-next
    /// Builds the `None` variant.
    #[inline]
    pub fn none() -> Self {
        Self::None
    }

    // rustdoc-stripper-ignore-next
    /// Returns `true` if `self` is the `None` variant.
    #[inline]
    pub fn is_none(&self) -> bool {
        matches!(self, Self::None)
    }

    // rustdoc-stripper-ignore-next
    /// Returns `true` if `self` is the `Invalid` variant.
    #[inline]
    pub fn is_invalid(&self) -> bool {
        matches!(self, Self::Invalid(_))
    }
}

impl<I: Error> From<I> for GlibNoneOrInvalidError<I> {
    #[inline]
    fn from(invalid: I) -> Self {
        Self::Invalid(invalid)
    }
}

impl<I: Error> fmt::Display for GlibNoneOrInvalidError<I> {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Invalid(err) => {
                write!(fmt, "glib value is invalid: ")?;
                fmt::Display::fmt(err, fmt)
            }
            Self::None => write!(fmt, "glib value is None"),
        }
    }
}

impl<I: Error> Error for GlibNoneOrInvalidError<I> {}

impl<G: Copy, I: Error, T: TryFromGlib<G, Error = GlibNoneOrInvalidError<I>>> FromGlib<G>
    for Result<Option<T>, I>
{
    #[inline]
    unsafe fn from_glib(val: G) -> Self {
        match T::try_from_glib(val) {
            Ok(value) => Ok(Some(value)),
            Err(GlibNoneOrInvalidError::None) => Ok(None),
            Err(GlibNoneOrInvalidError::Invalid(err)) => Err(err),
        }
    }
}

// rustdoc-stripper-ignore-next
/// Translate from a pointer type which is annotated with `transfer none`.
/// The resulting value is referenced at least once, by the bindings.
///
/// This is suitable for floating references, which become strong references.
/// It is also suitable for acquiring non-gobject values, like `gchar*`.
///
/// <a name="safety_points"></a>
/// # Safety
///
/// The implementation of this trait should acquire a reference to the value
/// in a way appropriate to the type,
/// e.g. by increasing the reference count or copying.
/// Values obtained using this trait must be properly released on `drop()`
/// by the implementing type.
///
/// For more information, refer to module level documentation.
pub trait FromGlibPtrNone<P: Ptr>: Sized {
    // rustdoc-stripper-ignore-next
    /// # Safety
    ///
    /// See trait level [notes on safety](#safety_points)
    unsafe fn from_glib_none(ptr: P) -> Self;
}

// rustdoc-stripper-ignore-next
/// Translate from a pointer type which is annotated with `transfer full`.
/// This transfers the ownership of the value to the Rust side.
///
/// Because ownership can only be transferred if something is already referenced,
/// this is unsuitable for floating references.
///
/// <a name="safety_points"></a>
/// # Safety
///
/// The implementation of this trait should not alter the reference count
/// or make copies of the underlying value.
/// Values obtained using this trait must be properly released on `drop()`
/// by the implementing type.
///
/// For more information, refer to module level documentation.
pub trait FromGlibPtrFull<P: Ptr>: Sized {
    // rustdoc-stripper-ignore-next
    /// # Safety
    ///
    /// See trait level [notes on safety](#safety_points)
    unsafe fn from_glib_full(ptr: P) -> Self;
}

// rustdoc-stripper-ignore-next
/// Translate from a pointer type by borrowing, without affecting the refcount.
///
/// The purpose of this trait is to access values inside callbacks
/// without changing their reference status.
/// The obtained borrow must not be accessed outside of the scope of the callback,
/// and called procedures must not store any references to the underlying data.
/// Safe Rust code must never obtain a mutable Rust reference.
///
/// <a name="safety_points"></a>
/// # Safety
///
/// The implementation of this trait as well as the returned type
/// must satisfy the same constraints together.
/// They must not take ownership of the underlying value, copy it,
/// and should not change its reference count.
/// If it does, it must properly release obtained references.
///
/// The returned value, when dropped,
/// must leave the underlying value in the same state
/// as before from_glib_borrow was called:
/// - it must not be dropped,
/// - it must be the same type of reference, e.g. still floating.
///
/// For more information, refer to module level documentation.
pub trait FromGlibPtrBorrow<P: Ptr>: Sized {
    // rustdoc-stripper-ignore-next
    /// # Safety
    ///
    /// See trait level [notes on safety](#safety_points)
    unsafe fn from_glib_borrow(_ptr: P) -> Borrowed<Self> {
        unimplemented!();
    }
}

// rustdoc-stripper-ignore-next
/// Translate from a pointer type, transfer: none.
///
/// See [`FromGlibPtrNone`](trait.FromGlibPtrNone.html).
#[inline]
pub unsafe fn from_glib_none<P: Ptr, T: FromGlibPtrNone<P>>(ptr: P) -> T {
    FromGlibPtrNone::from_glib_none(ptr)
}

// rustdoc-stripper-ignore-next
/// Translate from a pointer type, transfer: full (assume ownership).
///
/// See [`FromGlibPtrFull`](trait.FromGlibPtrFull.html).
#[inline]
pub unsafe fn from_glib_full<P: Ptr, T: FromGlibPtrFull<P>>(ptr: P) -> T {
    FromGlibPtrFull::from_glib_full(ptr)
}

// rustdoc-stripper-ignore-next
/// Translate from a pointer type, borrowing the pointer.
///
/// See [`FromGlibPtrBorrow`](trait.FromGlibPtrBorrow.html).
#[inline]
pub unsafe fn from_glib_borrow<P: Ptr, T: FromGlibPtrBorrow<P>>(ptr: P) -> Borrowed<T> {
    FromGlibPtrBorrow::from_glib_borrow(ptr)
}

impl<P: Ptr, T: FromGlibPtrNone<P>> FromGlibPtrNone<P> for Option<T> {
    #[inline]
    unsafe fn from_glib_none(ptr: P) -> Option<T> {
        if ptr.is_null() {
            None
        } else {
            Some(from_glib_none(ptr))
        }
    }
}

impl<P: Ptr, T: FromGlibPtrBorrow<P>> FromGlibPtrBorrow<P> for Option<T> {
    #[inline]
    unsafe fn from_glib_borrow(ptr: P) -> Borrowed<Option<T>> {
        if ptr.is_null() {
            Borrowed::new(None)
        } else {
            let val = T::from_glib_borrow(ptr);
            Borrowed::new(Some(val.into_inner()))
        }
    }
}

impl<P: Ptr, T: FromGlibPtrFull<P>> FromGlibPtrFull<P> for Option<T> {
    #[inline]
    unsafe fn from_glib_full(ptr: P) -> Option<T> {
        if ptr.is_null() {
            None
        } else {
            Some(from_glib_full(ptr))
        }
    }
}

impl FromGlibPtrNone<*const c_char> for String {
    #[inline]
    unsafe fn from_glib_none(ptr: *const c_char) -> Self {
        debug_assert!(!ptr.is_null());
        Self::from_utf8_lossy(CStr::from_ptr(ptr).to_bytes()).into_owned()
    }
}

// TODO: Deprecate this
impl FromGlibPtrFull<*const c_char> for String {
    #[inline]
    unsafe fn from_glib_full(ptr: *const c_char) -> Self {
        let res = from_glib_none(ptr);
        ffi::g_free(ptr as *mut _);
        res
    }
}

// TODO: Deprecate this
impl FromGlibPtrNone<*mut c_char> for String {
    #[inline]
    unsafe fn from_glib_none(ptr: *mut c_char) -> Self {
        debug_assert!(!ptr.is_null());
        Self::from_utf8_lossy(CStr::from_ptr(ptr).to_bytes()).into_owned()
    }
}

// TODO: Deprecate this
impl FromGlibPtrFull<*mut c_char> for String {
    #[inline]
    unsafe fn from_glib_full(ptr: *mut c_char) -> Self {
        let res = from_glib_none(ptr);
        ffi::g_free(ptr as *mut _);
        res
    }
}

#[cfg(not(windows))]
pub(crate) unsafe fn c_to_path_buf(ptr: *const c_char) -> PathBuf {
    debug_assert!(!ptr.is_null());

    // GLib paths on UNIX are always in the local encoding, which can be
    // UTF-8 or anything else really, but is always a NUL-terminated string
    // and must not contain any other NUL bytes
    OsString::from_vec(CStr::from_ptr(ptr).to_bytes().to_vec()).into()
}

#[cfg(windows)]
pub(crate) unsafe fn c_to_path_buf(ptr: *const c_char) -> PathBuf {
    debug_assert!(!ptr.is_null());

    // GLib paths on Windows are always UTF-8, as such we can convert to a String
    // first and then go to a PathBuf from there. Unless there is a bug
    // in the C library, the conversion from UTF-8 can never fail so we can
    // safely panic here if that ever happens
    String::from_utf8(CStr::from_ptr(ptr).to_bytes().into())
        .expect("Invalid, non-UTF8 path")
        .into()
}

#[cfg(not(windows))]
pub(crate) unsafe fn c_to_os_string(ptr: *const c_char) -> OsString {
    debug_assert!(!ptr.is_null());

    // GLib OS string (environment strings) on UNIX are always in the local encoding,
    // which can be UTF-8 or anything else really, but is always a NUL-terminated string
    // and must not contain any other NUL bytes
    OsString::from_vec(CStr::from_ptr(ptr).to_bytes().to_vec())
}

#[cfg(windows)]
pub(crate) unsafe fn c_to_os_string(ptr: *const c_char) -> OsString {
    debug_assert!(!ptr.is_null());

    // GLib OS string (environment strings) on Windows are always UTF-8,
    // as such we can convert to a String
    // first and then go to a OsString from there. Unless there is a bug
    // in the C library, the conversion from UTF-8 can never fail so we can
    // safely panic here if that ever happens
    String::from_utf8(CStr::from_ptr(ptr).to_bytes().into())
        .expect("Invalid, non-UTF8 path")
        .into()
}

impl FromGlibPtrNone<*const c_char> for PathBuf {
    #[inline]
    unsafe fn from_glib_none(ptr: *const c_char) -> Self {
        debug_assert!(!ptr.is_null());
        c_to_path_buf(ptr)
    }
}

impl FromGlibPtrFull<*const c_char> for PathBuf {
    #[inline]
    unsafe fn from_glib_full(ptr: *const c_char) -> Self {
        let res = from_glib_none(ptr);
        ffi::g_free(ptr as *mut _);
        res
    }
}

impl FromGlibPtrNone<*mut c_char> for PathBuf {
    #[inline]
    unsafe fn from_glib_none(ptr: *mut c_char) -> Self {
        debug_assert!(!ptr.is_null());
        c_to_path_buf(ptr)
    }
}

impl FromGlibPtrFull<*mut c_char> for PathBuf {
    #[inline]
    unsafe fn from_glib_full(ptr: *mut c_char) -> Self {
        let res = from_glib_none(ptr);
        ffi::g_free(ptr as *mut _);
        res
    }
}

#[cfg(not(windows))]
pub(crate) unsafe fn c_to_path_buf_num(ptr: *const c_char, num: usize) -> PathBuf {
    debug_assert!(!ptr.is_null());
    let slice = std::slice::from_raw_parts(ptr as *const u8, num);
    OsString::from_vec(slice.to_vec()).into()
}

#[cfg(windows)]
pub(crate) unsafe fn c_to_path_buf_num(ptr: *const c_char, num: usize) -> PathBuf {
    debug_assert!(!ptr.is_null());
    let slice = std::slice::from_raw_parts(ptr as *const u8, num);
    String::from_utf8(slice.into())
        .expect("Invalid, non-UTF8 path")
        .into()
}

#[doc(hidden)]
impl FromGlibContainer<*const c_char, *const i8> for PathBuf {
    unsafe fn from_glib_none_num(ptr: *const i8, num: usize) -> Self {
        c_to_path_buf_num(ptr as *const _, num)
    }

    unsafe fn from_glib_container_num(ptr: *const i8, num: usize) -> Self {
        c_to_path_buf_num(ptr as *const _, num)
    }

    unsafe fn from_glib_full_num(ptr: *const i8, num: usize) -> Self {
        let res = c_to_path_buf_num(ptr as *const _, num);
        ffi::g_free(ptr as *mut _);
        res
    }
}

#[doc(hidden)]
impl FromGlibContainer<*const c_char, *mut i8> for PathBuf {
    unsafe fn from_glib_none_num(ptr: *mut i8, num: usize) -> Self {
        FromGlibContainer::from_glib_none_num(ptr as *const i8, num)
    }

    unsafe fn from_glib_container_num(ptr: *mut i8, num: usize) -> Self {
        FromGlibContainer::from_glib_container_num(ptr as *const i8, num)
    }

    unsafe fn from_glib_full_num(ptr: *mut i8, num: usize) -> Self {
        FromGlibContainer::from_glib_full_num(ptr as *const i8, num)
    }
}

#[doc(hidden)]
impl FromGlibContainer<*const c_char, *const u8> for PathBuf {
    unsafe fn from_glib_none_num(ptr: *const u8, num: usize) -> Self {
        FromGlibContainer::from_glib_none_num(ptr as *const i8, num)
    }

    unsafe fn from_glib_container_num(ptr: *const u8, num: usize) -> Self {
        FromGlibContainer::from_glib_container_num(ptr as *const i8, num)
    }

    unsafe fn from_glib_full_num(ptr: *const u8, num: usize) -> Self {
        FromGlibContainer::from_glib_full_num(ptr as *const i8, num)
    }
}

#[doc(hidden)]
impl FromGlibContainer<*const c_char, *mut u8> for PathBuf {
    unsafe fn from_glib_none_num(ptr: *mut u8, num: usize) -> Self {
        FromGlibContainer::from_glib_none_num(ptr as *const i8, num)
    }

    unsafe fn from_glib_container_num(ptr: *mut u8, num: usize) -> Self {
        FromGlibContainer::from_glib_container_num(ptr as *const i8, num)
    }

    unsafe fn from_glib_full_num(ptr: *mut u8, num: usize) -> Self {
        FromGlibContainer::from_glib_full_num(ptr as *const i8, num)
    }
}

impl FromGlibPtrNone<*const c_char> for OsString {
    #[inline]
    unsafe fn from_glib_none(ptr: *const c_char) -> Self {
        debug_assert!(!ptr.is_null());
        c_to_os_string(ptr)
    }
}

impl FromGlibPtrFull<*const c_char> for OsString {
    #[inline]
    unsafe fn from_glib_full(ptr: *const c_char) -> Self {
        let res = from_glib_none(ptr);
        ffi::g_free(ptr as *mut _);
        res
    }
}

impl FromGlibPtrNone<*mut c_char> for OsString {
    #[inline]
    unsafe fn from_glib_none(ptr: *mut c_char) -> Self {
        debug_assert!(!ptr.is_null());
        c_to_os_string(ptr)
    }
}

impl FromGlibPtrFull<*mut c_char> for OsString {
    #[inline]
    unsafe fn from_glib_full(ptr: *mut c_char) -> Self {
        let res = from_glib_none(ptr);
        ffi::g_free(ptr as *mut _);
        res
    }
}

/// Translate from a container.
pub trait FromGlibContainer<T, P: Ptr>: Sized {
    /// Transfer: none.
    ///
    /// `num` is the advised number of elements.
    unsafe fn from_glib_none_num(ptr: P, num: usize) -> Self;

    /// Transfer: container.
    ///
    /// `num` is the advised number of elements.
    unsafe fn from_glib_container_num(ptr: P, num: usize) -> Self;

    /// Transfer: full.
    ///
    /// `num` is the advised number of elements.
    unsafe fn from_glib_full_num(ptr: P, num: usize) -> Self;
}

/// Translate from a container of pointers.
pub trait FromGlibPtrContainer<P: Ptr, PP: Ptr>: FromGlibContainer<P, PP> + Sized {
    /// Transfer: none.
    unsafe fn from_glib_none(ptr: PP) -> Self;

    /// Transfer: container.
    unsafe fn from_glib_container(ptr: PP) -> Self;

    /// Transfer: full.
    unsafe fn from_glib_full(ptr: PP) -> Self;
}

pub unsafe fn c_ptr_array_len<P: Ptr>(mut ptr: *const P) -> usize {
    let mut len = 0;

    if !ptr.is_null() {
        while !(*ptr).is_null() {
            len += 1;
            ptr = ptr.offset(1);
        }
    }
    len
}

pub trait FromGlibContainerAsVec<T, P: Ptr>
where
    Self: Sized,
{
    unsafe fn from_glib_none_num_as_vec(ptr: P, num: usize) -> Vec<Self>;
    unsafe fn from_glib_container_num_as_vec(ptr: P, num: usize) -> Vec<Self>;
    unsafe fn from_glib_full_num_as_vec(ptr: P, num: usize) -> Vec<Self>;
}

pub trait FromGlibPtrArrayContainerAsVec<P: Ptr, PP: Ptr>: FromGlibContainerAsVec<P, PP>
where
    Self: Sized,
{
    unsafe fn from_glib_none_as_vec(ptr: PP) -> Vec<Self>;
    unsafe fn from_glib_container_as_vec(ptr: PP) -> Vec<Self>;
    unsafe fn from_glib_full_as_vec(ptr: PP) -> Vec<Self>;
}

impl FromGlibContainerAsVec<bool, *const ffi::gboolean> for bool {
    unsafe fn from_glib_none_num_as_vec(ptr: *const ffi::gboolean, num: usize) -> Vec<Self> {
        if num == 0 || ptr.is_null() {
            return Vec::new();
        }

        let mut res = Vec::<Self>::with_capacity(num);
        let res_ptr = res.as_mut_ptr();
        for i in 0..num {
            *res_ptr.add(i) = from_glib(ptr::read(ptr.add(i)));
        }
        res.set_len(num);
        res
    }

    unsafe fn from_glib_container_num_as_vec(_: *const ffi::gboolean, _: usize) -> Vec<Self> {
        // Can't really free a *const
        unimplemented!();
    }

    unsafe fn from_glib_full_num_as_vec(_: *const ffi::gboolean, _: usize) -> Vec<Self> {
        // Can't really free a *const
        unimplemented!();
    }
}

impl FromGlibContainerAsVec<bool, *mut ffi::gboolean> for bool {
    unsafe fn from_glib_none_num_as_vec(ptr: *mut ffi::gboolean, num: usize) -> Vec<Self> {
        FromGlibContainerAsVec::from_glib_none_num_as_vec(ptr as *const _, num)
    }

    unsafe fn from_glib_container_num_as_vec(ptr: *mut ffi::gboolean, num: usize) -> Vec<Self> {
        let res = FromGlibContainerAsVec::from_glib_none_num_as_vec(ptr, num);
        ffi::g_free(ptr as *mut _);
        res
    }

    unsafe fn from_glib_full_num_as_vec(ptr: *mut ffi::gboolean, num: usize) -> Vec<Self> {
        FromGlibContainerAsVec::from_glib_container_num_as_vec(ptr, num)
    }
}

macro_rules! impl_from_glib_container_as_vec_fundamental {
    ($name:ty) => {
        unsafe impl TransparentType for $name {
            type GlibType = $name;
        }

        impl FromGlibContainerAsVec<$name, *const $name> for $name {
            unsafe fn from_glib_none_num_as_vec(ptr: *const $name, num: usize) -> Vec<Self> {
                if num == 0 || ptr.is_null() {
                    return Vec::new();
                }

                let mut res = Vec::with_capacity(num);
                let res_ptr = res.as_mut_ptr();
                std::ptr::copy_nonoverlapping(ptr, res_ptr, num);
                res.set_len(num);
                res
            }

            unsafe fn from_glib_container_num_as_vec(_: *const $name, _: usize) -> Vec<Self> {
                // Can't really free a *const
                unimplemented!();
            }

            unsafe fn from_glib_full_num_as_vec(_: *const $name, _: usize) -> Vec<Self> {
                // Can't really free a *const
                unimplemented!();
            }
        }

        impl FromGlibContainerAsVec<$name, *mut $name> for $name {
            unsafe fn from_glib_none_num_as_vec(ptr: *mut $name, num: usize) -> Vec<Self> {
                FromGlibContainerAsVec::from_glib_none_num_as_vec(ptr as *const _, num)
            }

            unsafe fn from_glib_container_num_as_vec(ptr: *mut $name, num: usize) -> Vec<Self> {
                let res = FromGlibContainerAsVec::from_glib_none_num_as_vec(ptr, num);
                ffi::g_free(ptr as *mut _);
                res
            }

            unsafe fn from_glib_full_num_as_vec(ptr: *mut $name, num: usize) -> Vec<Self> {
                FromGlibContainerAsVec::from_glib_container_num_as_vec(ptr, num)
            }
        }
    };
}

impl_from_glib_container_as_vec_fundamental!(u8);
impl_from_glib_container_as_vec_fundamental!(i8);
impl_from_glib_container_as_vec_fundamental!(u16);
impl_from_glib_container_as_vec_fundamental!(i16);
impl_from_glib_container_as_vec_fundamental!(u32);
impl_from_glib_container_as_vec_fundamental!(i32);
impl_from_glib_container_as_vec_fundamental!(u64);
impl_from_glib_container_as_vec_fundamental!(i64);
impl_from_glib_container_as_vec_fundamental!(f32);
impl_from_glib_container_as_vec_fundamental!(f64);

macro_rules! impl_from_glib_container_as_vec_string {
    ($name:ty, $ffi_name:ty) => {
        impl FromGlibContainerAsVec<$ffi_name, *const $ffi_name> for $name {
            unsafe fn from_glib_none_num_as_vec(ptr: *const $ffi_name, num: usize) -> Vec<Self> {
                if num == 0 || ptr.is_null() {
                    return Vec::new();
                }

                let mut res = Vec::<Self>::with_capacity(num);
                let res_ptr = res.as_mut_ptr();
                for i in 0..num {
                    std::ptr::write(
                        res_ptr.add(i),
                        from_glib_none(ptr::read(ptr.add(i)) as $ffi_name),
                    );
                }
                res.set_len(num);
                res
            }

            unsafe fn from_glib_container_num_as_vec(_: *const $ffi_name, _: usize) -> Vec<Self> {
                // Can't really free a *const
                unimplemented!();
            }

            unsafe fn from_glib_full_num_as_vec(_: *const $ffi_name, _: usize) -> Vec<Self> {
                // Can't really free a *const
                unimplemented!();
            }
        }

        impl FromGlibContainerAsVec<$ffi_name, *mut $ffi_name> for $name {
            unsafe fn from_glib_none_num_as_vec(ptr: *mut $ffi_name, num: usize) -> Vec<Self> {
                FromGlibContainerAsVec::from_glib_none_num_as_vec(ptr as *const _, num)
            }

            unsafe fn from_glib_container_num_as_vec(ptr: *mut $ffi_name, num: usize) -> Vec<Self> {
                let res = FromGlibContainerAsVec::from_glib_none_num_as_vec(ptr, num);
                ffi::g_free(ptr as *mut _);
                res
            }

            unsafe fn from_glib_full_num_as_vec(ptr: *mut $ffi_name, num: usize) -> Vec<Self> {
                if num == 0 || ptr.is_null() {
                    ffi::g_free(ptr as *mut _);
                    return Vec::new();
                }

                let mut res = Vec::<Self>::with_capacity(num);
                let res_ptr = res.as_mut_ptr();
                for i in 0..num {
                    std::ptr::write(
                        res_ptr.add(i),
                        from_glib_full(ptr::read(ptr.add(i)) as $ffi_name),
                    );
                }
                res.set_len(num);
                ffi::g_free(ptr as *mut _);
                res
            }
        }

        impl FromGlibPtrArrayContainerAsVec<$ffi_name, *mut $ffi_name> for $name {
            unsafe fn from_glib_none_as_vec(ptr: *mut $ffi_name) -> Vec<Self> {
                FromGlibContainerAsVec::from_glib_none_num_as_vec(ptr, c_ptr_array_len(ptr))
            }

            unsafe fn from_glib_container_as_vec(ptr: *mut $ffi_name) -> Vec<Self> {
                FromGlibContainerAsVec::from_glib_container_num_as_vec(ptr, c_ptr_array_len(ptr))
            }

            unsafe fn from_glib_full_as_vec(ptr: *mut $ffi_name) -> Vec<Self> {
                FromGlibContainerAsVec::from_glib_full_num_as_vec(ptr, c_ptr_array_len(ptr))
            }
        }

        impl FromGlibPtrArrayContainerAsVec<$ffi_name, *const $ffi_name> for $name {
            unsafe fn from_glib_none_as_vec(ptr: *const $ffi_name) -> Vec<Self> {
                FromGlibContainerAsVec::from_glib_none_num_as_vec(ptr, c_ptr_array_len(ptr))
            }

            unsafe fn from_glib_container_as_vec(ptr: *const $ffi_name) -> Vec<Self> {
                FromGlibContainerAsVec::from_glib_container_num_as_vec(ptr, c_ptr_array_len(ptr))
            }

            unsafe fn from_glib_full_as_vec(ptr: *const $ffi_name) -> Vec<Self> {
                FromGlibContainerAsVec::from_glib_full_num_as_vec(ptr, c_ptr_array_len(ptr))
            }
        }
    };
}

// TODO: Deprecate this
impl_from_glib_container_as_vec_string!(String, *const c_char);
impl_from_glib_container_as_vec_string!(String, *mut c_char);

impl_from_glib_container_as_vec_string!(PathBuf, *const c_char);
impl_from_glib_container_as_vec_string!(PathBuf, *mut c_char);
impl_from_glib_container_as_vec_string!(OsString, *const c_char);
impl_from_glib_container_as_vec_string!(OsString, *mut c_char);

impl<P, PP: Ptr, T: FromGlibContainerAsVec<P, PP>> FromGlibContainer<P, PP> for Vec<T> {
    unsafe fn from_glib_none_num(ptr: PP, num: usize) -> Vec<T> {
        FromGlibContainerAsVec::from_glib_none_num_as_vec(ptr, num)
    }

    unsafe fn from_glib_container_num(ptr: PP, num: usize) -> Vec<T> {
        FromGlibContainerAsVec::from_glib_container_num_as_vec(ptr, num)
    }

    unsafe fn from_glib_full_num(ptr: PP, num: usize) -> Vec<T> {
        FromGlibContainerAsVec::from_glib_full_num_as_vec(ptr, num)
    }
}

impl<P: Ptr, PP: Ptr, T: FromGlibPtrArrayContainerAsVec<P, PP>> FromGlibPtrContainer<P, PP>
    for Vec<T>
{
    unsafe fn from_glib_none(ptr: PP) -> Vec<T> {
        FromGlibPtrArrayContainerAsVec::from_glib_none_as_vec(ptr)
    }

    unsafe fn from_glib_container(ptr: PP) -> Vec<T> {
        FromGlibPtrArrayContainerAsVec::from_glib_container_as_vec(ptr)
    }

    unsafe fn from_glib_full(ptr: PP) -> Vec<T> {
        FromGlibPtrArrayContainerAsVec::from_glib_full_as_vec(ptr)
    }
}

impl<T> FromGlibContainerAsVec<<T as GlibPtrDefault>::GlibType, *mut ffi::GSList> for T
where
    T: GlibPtrDefault
        + FromGlibPtrNone<<T as GlibPtrDefault>::GlibType>
        + FromGlibPtrFull<<T as GlibPtrDefault>::GlibType>,
{
    unsafe fn from_glib_none_num_as_vec(mut ptr: *mut ffi::GSList, num: usize) -> Vec<T> {
        if num == 0 || ptr.is_null() {
            return Vec::new();
        }
        let mut res = Vec::with_capacity(num);
        for _ in 0..num {
            if ptr.is_null() {
                break;
            }

            let item_ptr: <T as GlibPtrDefault>::GlibType = Ptr::from((*ptr).data);
            if !item_ptr.is_null() {
                res.push(from_glib_none(item_ptr));
            }
            ptr = (*ptr).next;
        }
        res
    }

    unsafe fn from_glib_container_num_as_vec(ptr: *mut ffi::GSList, num: usize) -> Vec<T> {
        let res = FromGlibContainerAsVec::from_glib_none_num_as_vec(ptr, num);
        ffi::g_slist_free(ptr);
        res
    }

    unsafe fn from_glib_full_num_as_vec(mut ptr: *mut ffi::GSList, num: usize) -> Vec<T> {
        if num == 0 || ptr.is_null() {
            return Vec::new();
        }
        let orig_ptr = ptr;
        let mut res = Vec::with_capacity(num);
        for _ in 0..num {
            if ptr.is_null() {
                break;
            }

            let item_ptr: <T as GlibPtrDefault>::GlibType = Ptr::from((*ptr).data);
            if !item_ptr.is_null() {
                res.push(from_glib_full(item_ptr));
            }
            ptr = (*ptr).next;
        }
        ffi::g_slist_free(orig_ptr);
        res
    }
}

impl<T> FromGlibPtrArrayContainerAsVec<<T as GlibPtrDefault>::GlibType, *mut ffi::GSList> for T
where
    T: GlibPtrDefault
        + FromGlibPtrNone<<T as GlibPtrDefault>::GlibType>
        + FromGlibPtrFull<<T as GlibPtrDefault>::GlibType>,
{
    unsafe fn from_glib_none_as_vec(mut ptr: *mut ffi::GSList) -> Vec<T> {
        let mut res = Vec::new();
        while !ptr.is_null() {
            let item_ptr: <T as GlibPtrDefault>::GlibType = Ptr::from((*ptr).data);
            if !item_ptr.is_null() {
                res.push(from_glib_none(item_ptr));
            }
            ptr = (*ptr).next;
        }
        res
    }

    unsafe fn from_glib_container_as_vec(ptr: *mut ffi::GSList) -> Vec<T> {
        let res = FromGlibPtrArrayContainerAsVec::from_glib_none_as_vec(ptr);
        ffi::g_slist_free(ptr);
        res
    }

    unsafe fn from_glib_full_as_vec(mut ptr: *mut ffi::GSList) -> Vec<T> {
        let orig_ptr = ptr;
        let mut res = Vec::new();
        while !ptr.is_null() {
            let item_ptr: <T as GlibPtrDefault>::GlibType = Ptr::from((*ptr).data);
            if !item_ptr.is_null() {
                res.push(from_glib_full(item_ptr));
            }
            ptr = (*ptr).next;
        }
        ffi::g_slist_free(orig_ptr);
        res
    }
}

impl<T> FromGlibContainerAsVec<<T as GlibPtrDefault>::GlibType, *mut ffi::GList> for T
where
    T: GlibPtrDefault
        + FromGlibPtrNone<<T as GlibPtrDefault>::GlibType>
        + FromGlibPtrFull<<T as GlibPtrDefault>::GlibType>,
{
    unsafe fn from_glib_none_num_as_vec(mut ptr: *mut ffi::GList, num: usize) -> Vec<T> {
        if num == 0 || ptr.is_null() {
            return Vec::new();
        }
        let mut res = Vec::with_capacity(num);
        for _ in 0..num {
            if ptr.is_null() {
                break;
            }

            let item_ptr: <T as GlibPtrDefault>::GlibType = Ptr::from((*ptr).data);
            if !item_ptr.is_null() {
                res.push(from_glib_none(item_ptr));
            }
            ptr = (*ptr).next;
        }
        res
    }

    unsafe fn from_glib_container_num_as_vec(ptr: *mut ffi::GList, num: usize) -> Vec<T> {
        let res = FromGlibContainerAsVec::from_glib_none_num_as_vec(ptr, num);
        ffi::g_list_free(ptr);
        res
    }

    unsafe fn from_glib_full_num_as_vec(mut ptr: *mut ffi::GList, num: usize) -> Vec<T> {
        if num == 0 || ptr.is_null() {
            return Vec::new();
        }
        let orig_ptr = ptr;
        let mut res = Vec::with_capacity(num);
        for _ in 0..num {
            if ptr.is_null() {
                break;
            }

            let item_ptr: <T as GlibPtrDefault>::GlibType = Ptr::from((*ptr).data);
            if !item_ptr.is_null() {
                res.push(from_glib_full(item_ptr));
            }
            ptr = (*ptr).next;
        }
        ffi::g_list_free(orig_ptr);
        res
    }
}

impl<T> FromGlibPtrArrayContainerAsVec<<T as GlibPtrDefault>::GlibType, *mut ffi::GList> for T
where
    T: GlibPtrDefault
        + FromGlibPtrNone<<T as GlibPtrDefault>::GlibType>
        + FromGlibPtrFull<<T as GlibPtrDefault>::GlibType>,
{
    unsafe fn from_glib_none_as_vec(mut ptr: *mut ffi::GList) -> Vec<T> {
        let mut res = Vec::new();
        while !ptr.is_null() {
            let item_ptr: <T as GlibPtrDefault>::GlibType = Ptr::from((*ptr).data);
            if !item_ptr.is_null() {
                res.push(from_glib_none(item_ptr));
            }
            ptr = (*ptr).next;
        }
        res
    }

    unsafe fn from_glib_container_as_vec(ptr: *mut ffi::GList) -> Vec<T> {
        let res = FromGlibPtrArrayContainerAsVec::from_glib_none_as_vec(ptr);
        ffi::g_list_free(ptr);
        res
    }

    unsafe fn from_glib_full_as_vec(mut ptr: *mut ffi::GList) -> Vec<T> {
        let orig_ptr = ptr;
        let mut res = Vec::new();
        while !ptr.is_null() {
            let item_ptr: <T as GlibPtrDefault>::GlibType = Ptr::from((*ptr).data);
            if !item_ptr.is_null() {
                res.push(from_glib_full(item_ptr));
            }
            ptr = (*ptr).next;
        }
        ffi::g_list_free(orig_ptr);
        res
    }
}

impl<T> FromGlibContainerAsVec<<T as GlibPtrDefault>::GlibType, *const ffi::GList> for T
where
    T: GlibPtrDefault
        + FromGlibPtrNone<<T as GlibPtrDefault>::GlibType>
        + FromGlibPtrFull<<T as GlibPtrDefault>::GlibType>,
{
    unsafe fn from_glib_none_num_as_vec(ptr: *const ffi::GList, num: usize) -> Vec<T> {
        FromGlibContainerAsVec::from_glib_none_num_as_vec(mut_override(ptr), num)
    }

    unsafe fn from_glib_container_num_as_vec(_: *const ffi::GList, _: usize) -> Vec<T> {
        // Can't really free a *const
        unimplemented!()
    }

    unsafe fn from_glib_full_num_as_vec(_: *const ffi::GList, _: usize) -> Vec<T> {
        // Can't really free a *const
        unimplemented!()
    }
}

impl<T> FromGlibPtrArrayContainerAsVec<<T as GlibPtrDefault>::GlibType, *const ffi::GList> for T
where
    T: GlibPtrDefault
        + FromGlibPtrNone<<T as GlibPtrDefault>::GlibType>
        + FromGlibPtrFull<<T as GlibPtrDefault>::GlibType>,
{
    unsafe fn from_glib_none_as_vec(ptr: *const ffi::GList) -> Vec<T> {
        FromGlibPtrArrayContainerAsVec::from_glib_none_as_vec(mut_override(ptr))
    }

    unsafe fn from_glib_container_as_vec(_: *const ffi::GList) -> Vec<T> {
        // Can't really free a *const
        unimplemented!()
    }

    unsafe fn from_glib_full_as_vec(_: *const ffi::GList) -> Vec<T> {
        // Can't really free a *const
        unimplemented!()
    }
}

impl<T> FromGlibContainerAsVec<<T as GlibPtrDefault>::GlibType, *const ffi::GSList> for T
where
    T: GlibPtrDefault
        + FromGlibPtrNone<<T as GlibPtrDefault>::GlibType>
        + FromGlibPtrFull<<T as GlibPtrDefault>::GlibType>,
{
    unsafe fn from_glib_none_num_as_vec(ptr: *const ffi::GSList, num: usize) -> Vec<T> {
        FromGlibContainerAsVec::from_glib_none_num_as_vec(mut_override(ptr), num)
    }

    unsafe fn from_glib_container_num_as_vec(_: *const ffi::GSList, _: usize) -> Vec<T> {
        // Can't really free a *const
        unimplemented!()
    }

    unsafe fn from_glib_full_num_as_vec(_: *const ffi::GSList, _: usize) -> Vec<T> {
        // Can't really free a *const
        unimplemented!()
    }
}

impl<T> FromGlibPtrArrayContainerAsVec<<T as GlibPtrDefault>::GlibType, *const ffi::GSList> for T
where
    T: GlibPtrDefault
        + FromGlibPtrNone<<T as GlibPtrDefault>::GlibType>
        + FromGlibPtrFull<<T as GlibPtrDefault>::GlibType>,
{
    unsafe fn from_glib_none_as_vec(ptr: *const ffi::GSList) -> Vec<T> {
        FromGlibPtrArrayContainerAsVec::from_glib_none_as_vec(mut_override(ptr))
    }

    unsafe fn from_glib_container_as_vec(_: *const ffi::GSList) -> Vec<T> {
        // Can't really free a *const
        unimplemented!()
    }

    unsafe fn from_glib_full_as_vec(_: *const ffi::GSList) -> Vec<T> {
        // Can't really free a *const
        unimplemented!()
    }
}

#[allow(clippy::implicit_hasher)]
impl FromGlibContainer<*const c_char, *mut ffi::GHashTable> for HashMap<String, String> {
    unsafe fn from_glib_none_num(ptr: *mut ffi::GHashTable, _: usize) -> Self {
        FromGlibPtrContainer::from_glib_none(ptr)
    }

    unsafe fn from_glib_container_num(ptr: *mut ffi::GHashTable, _: usize) -> Self {
        FromGlibPtrContainer::from_glib_full(ptr)
    }

    unsafe fn from_glib_full_num(ptr: *mut ffi::GHashTable, _: usize) -> Self {
        FromGlibPtrContainer::from_glib_full(ptr)
    }
}

#[allow(clippy::implicit_hasher)]
impl FromGlibPtrContainer<*const c_char, *mut ffi::GHashTable> for HashMap<String, String> {
    unsafe fn from_glib_none(ptr: *mut ffi::GHashTable) -> Self {
        unsafe extern "C" fn read_string_hash_table(
            key: ffi::gpointer,
            value: ffi::gpointer,
            hash_map: ffi::gpointer,
        ) {
            let key: String = from_glib_none(key as *const c_char);
            let value: String = from_glib_none(value as *const c_char);
            let hash_map: &mut HashMap<String, String> =
                &mut *(hash_map as *mut HashMap<String, String>);
            hash_map.insert(key, value);
        }
        let mut map = HashMap::with_capacity(ffi::g_hash_table_size(ptr) as usize);
        ffi::g_hash_table_foreach(
            ptr,
            Some(read_string_hash_table),
            &mut map as *mut HashMap<String, String> as *mut _,
        );
        map
    }

    unsafe fn from_glib_container(ptr: *mut ffi::GHashTable) -> Self {
        FromGlibPtrContainer::from_glib_full(ptr)
    }

    unsafe fn from_glib_full(ptr: *mut ffi::GHashTable) -> Self {
        let map = FromGlibPtrContainer::from_glib_none(ptr);
        ffi::g_hash_table_unref(ptr);
        map
    }
}

impl<T> FromGlibContainerAsVec<<T as GlibPtrDefault>::GlibType, *mut ffi::GPtrArray> for T
where
    T: GlibPtrDefault
        + FromGlibPtrNone<<T as GlibPtrDefault>::GlibType>
        + FromGlibPtrFull<<T as GlibPtrDefault>::GlibType>,
{
    unsafe fn from_glib_none_num_as_vec(ptr: *mut ffi::GPtrArray, num: usize) -> Vec<T> {
        if num == 0 || ptr.is_null() {
            return Vec::new();
        }
        let pdata = (*ptr).pdata;
        debug_assert!((*ptr).len as usize >= num);
        let mut res = Vec::with_capacity(num);
        for i in 0..num {
            let item_ptr: <T as GlibPtrDefault>::GlibType = Ptr::from(ptr::read(pdata.add(i)));
            if !item_ptr.is_null() {
                res.push(from_glib_none(item_ptr));
            }
        }
        res
    }

    unsafe fn from_glib_container_num_as_vec(ptr: *mut ffi::GPtrArray, num: usize) -> Vec<T> {
        let res = FromGlibContainer::from_glib_none_num(ptr, num);
        if !ptr.is_null() {
            ffi::g_ptr_array_unref(ptr);
        }
        res
    }

    unsafe fn from_glib_full_num_as_vec(ptr: *mut ffi::GPtrArray, num: usize) -> Vec<T> {
        if ptr.is_null() {
            return Vec::new();
        }
        if num == 0 {
            ffi::g_ptr_array_unref(ptr);
            return Vec::new();
        }
        let pdata = (*ptr).pdata;
        debug_assert!((*ptr).len as usize >= num);
        let mut res = Vec::with_capacity(num);
        for i in 0..num {
            let item_ptr: <T as GlibPtrDefault>::GlibType = Ptr::from(ptr::read(pdata.add(i)));
            if !item_ptr.is_null() {
                res.push(from_glib_none(item_ptr));
            }
        }
        ffi::g_ptr_array_unref(ptr);
        res
    }
}

impl<T> FromGlibPtrArrayContainerAsVec<<T as GlibPtrDefault>::GlibType, *mut ffi::GPtrArray> for T
where
    T: GlibPtrDefault
        + FromGlibPtrNone<<T as GlibPtrDefault>::GlibType>
        + FromGlibPtrFull<<T as GlibPtrDefault>::GlibType>,
{
    unsafe fn from_glib_none_as_vec(ptr: *mut ffi::GPtrArray) -> Vec<T> {
        let num = (*ptr).len as usize;
        FromGlibContainer::from_glib_none_num(ptr, num)
    }

    unsafe fn from_glib_container_as_vec(ptr: *mut ffi::GPtrArray) -> Vec<T> {
        let num = (*ptr).len as usize;
        FromGlibContainer::from_glib_container_num(ptr, num)
    }

    unsafe fn from_glib_full_as_vec(ptr: *mut ffi::GPtrArray) -> Vec<T> {
        let num = (*ptr).len as usize;
        FromGlibContainer::from_glib_full_num(ptr, num)
    }
}

impl<T> FromGlibContainerAsVec<<T as GlibPtrDefault>::GlibType, *const ffi::GPtrArray> for T
where
    T: GlibPtrDefault
        + FromGlibPtrNone<<T as GlibPtrDefault>::GlibType>
        + FromGlibPtrFull<<T as GlibPtrDefault>::GlibType>,
{
    unsafe fn from_glib_none_num_as_vec(ptr: *const ffi::GPtrArray, num: usize) -> Vec<T> {
        FromGlibContainerAsVec::from_glib_none_num_as_vec(mut_override(ptr), num)
    }

    unsafe fn from_glib_container_num_as_vec(_: *const ffi::GPtrArray, _: usize) -> Vec<T> {
        // Can't really free a *const
        unimplemented!()
    }

    unsafe fn from_glib_full_num_as_vec(_: *const ffi::GPtrArray, _: usize) -> Vec<T> {
        // Can't really free a *const
        unimplemented!()
    }
}

impl<T> FromGlibPtrArrayContainerAsVec<<T as GlibPtrDefault>::GlibType, *const ffi::GPtrArray> for T
where
    T: GlibPtrDefault
        + FromGlibPtrNone<<T as GlibPtrDefault>::GlibType>
        + FromGlibPtrFull<<T as GlibPtrDefault>::GlibType>,
{
    unsafe fn from_glib_none_as_vec(ptr: *const ffi::GPtrArray) -> Vec<T> {
        FromGlibPtrArrayContainerAsVec::from_glib_none_as_vec(mut_override(ptr))
    }

    unsafe fn from_glib_container_as_vec(_: *const ffi::GPtrArray) -> Vec<T> {
        // Can't really free a *const
        unimplemented!()
    }

    unsafe fn from_glib_full_as_vec(_: *const ffi::GPtrArray) -> Vec<T> {
        // Can't really free a *const
        unimplemented!()
    }
}

/// Trait for types that have the same memory representation as a pointer to their FFI type.
///
/// Values of types implementing this trait can be transmuted to pointers of the FFI type,
/// references to pointers of pointers to the FFI type.
pub unsafe trait TransparentPtrType: Clone + Sized + GlibPtrDefault {}

/// Trait for types that have the same memory representation as their FFI type.
///
/// Values of types implementing this trait can be transmuted directly to the FFI type, references
/// to pointers to the FFI type.
pub unsafe trait TransparentType: Clone + Sized {
    type GlibType;
}

unsafe impl<T: TransparentPtrType> TransparentType for T {
    type GlibType = <T as GlibPtrDefault>::GlibType;
}

#[cfg(test)]
mod tests {
    use std::{collections::HashMap, fs};

    use tempfile::tempdir;

    use super::*;
    use crate::{FileTest, GString};

    #[test]
    fn boolean() {
        assert_eq!(true.into_glib(), ffi::GTRUE);
        assert_eq!(false.into_glib(), ffi::GFALSE);
        assert!(unsafe { bool::from_glib(ffi::GTRUE) });
        assert!(!unsafe { bool::from_glib(ffi::GFALSE) });
        assert!(unsafe { bool::from_glib(42) });
    }

    #[test]
    fn ordering() {
        assert_eq!(Ordering::Less.into_glib(), -1);
        assert_eq!(Ordering::Equal.into_glib(), 0);
        assert_eq!(Ordering::Greater.into_glib(), 1);
        assert_eq!(Ordering::Less, unsafe { Ordering::from_glib(-42) });
        assert_eq!(Ordering::Less, unsafe { Ordering::from_glib(-1) });
        assert_eq!(Ordering::Equal, unsafe { Ordering::from_glib(0) });
        assert_eq!(Ordering::Greater, unsafe { Ordering::from_glib(1) });
        assert_eq!(Ordering::Greater, unsafe { Ordering::from_glib(42) });
    }

    #[test]
    fn string() {
        let s = "ABC";
        let owned = "ABC".to_string();
        let cstring = CString::new("ABC").unwrap();

        let stash = s.to_glib_none();
        assert_eq!(unsafe { CStr::from_ptr(stash.0) }, cstring.as_c_str());

        let stash = owned.to_glib_none();
        assert_eq!(unsafe { CStr::from_ptr(stash.0) }, cstring.as_c_str());

        let ptr: *mut c_char = s.to_glib_full();
        assert_eq!(unsafe { CStr::from_ptr(ptr) }, cstring.as_c_str());

        unsafe {
            ffi::g_free(ptr as *mut _);
        }

        let ptr: *mut c_char = owned.to_glib_full();
        assert_eq!(unsafe { CStr::from_ptr(ptr) }, cstring.as_c_str());

        assert_eq!(s, unsafe { String::from_glib_none(ptr) });
        assert_eq!(owned, unsafe { String::from_glib_full(ptr) });
    }

    #[test]
    fn string_hash_map() {
        let mut map = HashMap::new();
        map.insert("A".into(), "1".into());
        map.insert("B".into(), "2".into());
        map.insert("C".into(), "3".into());
        let ptr: *mut ffi::GHashTable = map.to_glib_full();
        let map = unsafe { HashMap::from_glib_full(ptr) };
        assert_eq!(map.get("A"), Some(&"1".into()));
        assert_eq!(map.get("B"), Some(&"2".into()));
        assert_eq!(map.get("C"), Some(&"3".into()));
    }

    #[test]
    fn string_array() {
        let v = vec!["A".to_string(), "B".to_string(), "C".to_string()];
        let stash = v.to_glib_none();
        let ptr: *mut *mut c_char = stash.0;
        let ptr_copy = unsafe { ffi::g_strdupv(ptr) };

        let actual: Vec<String> = unsafe { FromGlibPtrContainer::from_glib_full(ptr_copy) };
        assert_eq!(v, actual);
    }

    #[test]
    fn gstring_array() {
        let v = vec!["A".to_string(), "B".to_string(), "C".to_string()];
        let stash = v.to_glib_none();
        let ptr: *mut *mut c_char = stash.0;
        let ptr_copy = unsafe { ffi::g_strdupv(ptr) };

        let actual: Vec<GString> = unsafe { FromGlibPtrContainer::from_glib_full(ptr_copy) };
        assert_eq!(v, actual);
    }

    #[test]
    fn ptr_array() {
        let strings = &["A", "B", "C"];
        let (ptr, _stash) =
            ToGlibContainerFromSlice::<*mut ffi::GPtrArray>::to_glib_none_from_slice(strings);
        let v: Vec<GString> = unsafe { FromGlibPtrArrayContainerAsVec::from_glib_none_as_vec(ptr) };
        assert_eq!(&v, strings);
    }

    #[test]
    #[cfg(not(target_os = "macos"))]
    fn test_paths() {
        let tmp_dir = tempdir().unwrap();

        // Test if passing paths to GLib and getting them back
        // gives us useful results
        let dir_1 = tmp_dir.path().join("abcd");
        fs::create_dir(&dir_1).unwrap();
        assert_eq!(crate::path_get_basename(&dir_1), Path::new("abcd"));
        assert_eq!(
            crate::path_get_basename(dir_1.canonicalize().unwrap()),
            Path::new("abcd")
        );
        // This currently fails on Windows because C:\\Users\\runneradmin
        // gets shortened to C:\\Users\\RUNNER~1
        #[cfg(not(windows))]
        assert_eq!(
            crate::path_get_dirname(dir_1.canonicalize().unwrap()),
            tmp_dir.path()
        );
        assert!(crate::file_test(
            &dir_1,
            FileTest::EXISTS | FileTest::IS_DIR
        ));
        assert!(crate::file_test(
            dir_1.canonicalize().unwrap(),
            FileTest::EXISTS | FileTest::IS_DIR
        ));

        // And test with some non-ASCII characters
        let dir_2 = tmp_dir.as_ref().join("øäöü");
        fs::create_dir(&dir_2).unwrap();
        assert_eq!(crate::path_get_basename(&dir_2), Path::new("øäöü"));
        assert_eq!(
            crate::path_get_basename(dir_2.canonicalize().unwrap()),
            Path::new("øäöü")
        );
        // This currently fails on Windows because C:\\Users\\runneradmin
        // gets shortened to C:\\Users\\RUNNER~1
        #[cfg(not(windows))]
        assert_eq!(
            crate::path_get_dirname(dir_2.canonicalize().unwrap()),
            tmp_dir.path()
        );
        assert!(crate::file_test(
            &dir_2,
            FileTest::EXISTS | FileTest::IS_DIR
        ));
        assert!(crate::file_test(
            dir_2.canonicalize().unwrap(),
            FileTest::EXISTS | FileTest::IS_DIR
        ));
    }

    #[test]
    #[cfg(target_os = "macos")]
    fn test_paths() {
        let t_dir = tempdir().unwrap();
        let tmp_dir = t_dir.path().canonicalize().unwrap();

        // Test if passing paths to GLib and getting them back
        // gives us useful results
        let dir_1 = tmp_dir.join("abcd");
        fs::create_dir(&dir_1).unwrap();
        assert_eq!(crate::path_get_basename(&dir_1), Path::new("abcd"));
        assert_eq!(
            crate::path_get_basename(dir_1.canonicalize().unwrap()),
            Path::new("abcd")
        );
        assert_eq!(
            crate::path_get_dirname(dir_1.canonicalize().unwrap()),
            tmp_dir
        );
        assert!(crate::file_test(
            &dir_1,
            FileTest::EXISTS | FileTest::IS_DIR
        ));
        assert!(crate::file_test(
            &dir_1.canonicalize().unwrap(),
            FileTest::EXISTS | FileTest::IS_DIR
        ));
    }

    #[test]
    fn none_value() {
        const CLONG_NONE: libc::c_long = -1;

        #[derive(Debug, PartialEq, Eq)]
        struct SpecialU32(u32);
        impl IntoGlib for SpecialU32 {
            type GlibType = libc::c_uint;
            fn into_glib(self) -> libc::c_uint {
                self.0 as libc::c_uint
            }
        }
        impl OptionIntoGlib for SpecialU32 {
            const GLIB_NONE: Self::GlibType = CLONG_NONE as libc::c_uint;
        }

        assert_eq!(SpecialU32(0).into_glib(), 0);
        assert_eq!(SpecialU32(42).into_glib(), 42);
        assert_eq!(Some(SpecialU32(0)).into_glib(), 0);
        assert_eq!(Some(SpecialU32(42)).into_glib(), 42);
        assert_eq!(
            Option::None::<SpecialU32>.into_glib(),
            SpecialU32::GLIB_NONE
        );

        impl TryFromGlib<libc::c_uint> for SpecialU32 {
            type Error = GlibNoneError;
            #[allow(clippy::unnecessary_cast)]
            unsafe fn try_from_glib(val: libc::c_uint) -> Result<Self, GlibNoneError> {
                if val == SpecialU32::GLIB_NONE {
                    return Err(GlibNoneError);
                }

                Ok(SpecialU32(val as u32))
            }
        }

        assert_eq!(unsafe { SpecialU32::try_from_glib(0) }, Ok(SpecialU32(0)));
        assert_eq!(unsafe { SpecialU32::try_from_glib(42) }, Ok(SpecialU32(42)));
        assert_eq!(
            unsafe { SpecialU32::try_from_glib(SpecialU32::GLIB_NONE) },
            Err(GlibNoneError)
        );

        assert_eq!(
            unsafe { Option::<SpecialU32>::from_glib(0) },
            Some(SpecialU32(0))
        );
        assert_eq!(
            unsafe { Option::<SpecialU32>::from_glib(42) },
            Some(SpecialU32(42))
        );
        assert!(unsafe { Option::<SpecialU32>::from_glib(SpecialU32::GLIB_NONE) }.is_none());
    }

    #[test]
    fn invalid_value() {
        use std::{convert::TryFrom, num::TryFromIntError};

        #[derive(Debug, PartialEq, Eq)]
        struct U32(u32);

        impl TryFromGlib<libc::c_long> for U32 {
            type Error = TryFromIntError;
            unsafe fn try_from_glib(val: libc::c_long) -> Result<Self, TryFromIntError> {
                Ok(U32(u32::try_from(val)?))
            }
        }

        assert_eq!(unsafe { U32::try_from_glib(0) }, Ok(U32(0)));
        assert_eq!(unsafe { U32::try_from_glib(42) }, Ok(U32(42)));
        assert!(unsafe { U32::try_from_glib(-1) }.is_err());
        assert!(unsafe { U32::try_from_glib(-42) }.is_err());
    }

    #[test]
    fn none_or_invalid_value() {
        use std::{convert::TryFrom, num::TryFromIntError};

        #[derive(Debug, PartialEq, Eq)]
        struct SpecialU32(u32);
        impl IntoGlib for SpecialU32 {
            type GlibType = libc::c_long;
            fn into_glib(self) -> libc::c_long {
                self.0 as libc::c_long
            }
        }
        impl OptionIntoGlib for SpecialU32 {
            const GLIB_NONE: Self::GlibType = -1;
        }

        assert_eq!(SpecialU32(0).into_glib(), 0);
        assert_eq!(SpecialU32(42).into_glib(), 42);
        assert_eq!(Some(SpecialU32(42)).into_glib(), 42);
        assert_eq!(
            Option::None::<SpecialU32>.into_glib(),
            SpecialU32::GLIB_NONE
        );

        impl TryFromGlib<libc::c_long> for SpecialU32 {
            type Error = GlibNoneOrInvalidError<TryFromIntError>;
            unsafe fn try_from_glib(
                val: libc::c_long,
            ) -> Result<Self, GlibNoneOrInvalidError<TryFromIntError>> {
                if val == SpecialU32::GLIB_NONE {
                    return Err(GlibNoneOrInvalidError::None);
                }

                Ok(SpecialU32(u32::try_from(val)?))
            }
        }

        assert_eq!(unsafe { SpecialU32::try_from_glib(0) }, Ok(SpecialU32(0)));
        assert_eq!(unsafe { SpecialU32::try_from_glib(42) }, Ok(SpecialU32(42)));
        assert!(unsafe { SpecialU32::try_from_glib(SpecialU32::GLIB_NONE) }
            .unwrap_err()
            .is_none());
        assert!(unsafe { SpecialU32::try_from_glib(-42) }
            .unwrap_err()
            .is_invalid());

        assert_eq!(
            unsafe { Result::<Option<SpecialU32>, _>::from_glib(0) },
            Ok(Some(SpecialU32(0)))
        );
        assert_eq!(
            unsafe { Result::<Option<SpecialU32>, _>::from_glib(42) },
            Ok(Some(SpecialU32(42)))
        );
        assert_eq!(
            unsafe { Result::<Option<SpecialU32>, _>::from_glib(SpecialU32::GLIB_NONE) },
            Ok(None)
        );
        assert!(unsafe { Result::<Option<SpecialU32>, _>::from_glib(-42) }.is_err());
    }
}