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

// rustdoc-stripper-ignore-next
//! `Variant` binding and helper traits.
//!
//! [`Variant`](struct.Variant.html) is an immutable dynamically-typed generic
//! container. Its type and value are defined at construction and never change.
//!
//! `Variant` types are described by [`VariantType`](../struct.VariantType.html)
//! "type strings".
//!
//! `GVariant` supports arbitrarily complex types built from primitives like integers, floating point
//! numbers, strings, arrays, tuples and dictionaries. See [`ToVariant#foreign-impls`] for
//! a full list of supported types. You may also implement [`ToVariant`] and [`FromVariant`]
//! manually, or derive them using the [`Variant`](derive@crate::Variant) derive macro.
//!
//! # Examples
//!
//! ```
//! use glib::prelude::*; // or `use gtk::prelude::*;`
//! use glib::{Variant, FromVariant, ToVariant};
//! use std::collections::HashMap;
//!
//! // Using the `ToVariant` trait.
//! let num = 10.to_variant();
//!
//! // `is` tests the type of the value.
//! assert!(num.is::<i32>());
//!
//! // `get` tries to extract the value.
//! assert_eq!(num.get::<i32>(), Some(10));
//! assert_eq!(num.get::<u32>(), None);
//!
//! // `get_str` tries to borrow a string slice.
//! let hello = "Hello!".to_variant();
//! assert_eq!(hello.str(), Some("Hello!"));
//! assert_eq!(num.str(), None);
//!
//! // `fixed_array` tries to borrow a fixed size array (u8, bool, i16, etc.),
//! // rather than creating a deep copy which would be expensive for
//! // nontrivially sized arrays of fixed size elements.
//! // The test data here is the zstd compression header, which
//! // stands in for arbitrary binary data (e.g. not UTF-8).
//! let bufdata = b"\xFD\x2F\xB5\x28";
//! let bufv = glib::Variant::array_from_fixed_array(&bufdata[..]);
//! assert_eq!(bufv.fixed_array::<u8>().unwrap(), bufdata);
//! assert!(num.fixed_array::<u8>().is_err());
//!
//! // Variant carrying a Variant
//! let variant = Variant::from_variant(&hello);
//! let variant = variant.as_variant().unwrap();
//! assert_eq!(variant.str(), Some("Hello!"));
//!
//! // Variant carrying an array
//! let array = ["Hello", "there!"];
//! let variant = array.into_iter().collect::<Variant>();
//! assert_eq!(variant.n_children(), 2);
//! assert_eq!(variant.child_value(0).str(), Some("Hello"));
//! assert_eq!(variant.child_value(1).str(), Some("there!"));
//!
//! // You can also convert from and to a Vec
//! let variant = vec!["Hello", "there!"].to_variant();
//! assert_eq!(variant.n_children(), 2);
//! let vec = <Vec<String>>::from_variant(&variant).unwrap();
//! assert_eq!(vec[0], "Hello");
//!
//! // Conversion to and from HashMap and BTreeMap is also possible
//! let mut map: HashMap<u16, &str> = HashMap::new();
//! map.insert(1, "hi");
//! map.insert(2, "there");
//! let variant = map.to_variant();
//! assert_eq!(variant.n_children(), 2);
//! let map: HashMap<u16, String> = HashMap::from_variant(&variant).unwrap();
//! assert_eq!(map[&1], "hi");
//! assert_eq!(map[&2], "there");
//!
//! // And conversion to and from tuples.
//! let variant = ("hello", 42u16, vec![ "there", "you" ],).to_variant();
//! assert_eq!(variant.n_children(), 3);
//! assert_eq!(variant.type_().as_str(), "(sqas)");
//! let tuple = <(String, u16, Vec<String>)>::from_variant(&variant).unwrap();
//! assert_eq!(tuple.0, "hello");
//! assert_eq!(tuple.1, 42);
//! assert_eq!(tuple.2, &[ "there", "you"]);
//!
//! // `Option` is supported as well, through maybe types
//! let variant = Some("hello").to_variant();
//! assert_eq!(variant.n_children(), 1);
//! let mut s = <Option<String>>::from_variant(&variant).unwrap();
//! assert_eq!(s.unwrap(), "hello");
//! s = None;
//! let variant = s.to_variant();
//! assert_eq!(variant.n_children(), 0);
//! let s = <Option<String>>::from_variant(&variant).unwrap();
//! assert!(s.is_none());
//!
//! // Paths may be converted, too. Please note the portability warning above!
//! use std::path::{Path, PathBuf};
//! let path = Path::new("foo/bar");
//! let path_variant = path.to_variant();
//! assert_eq!(PathBuf::from_variant(&path_variant).as_deref(), Some(path));
//! ```

use crate::bytes::Bytes;
use crate::translate::*;
use crate::StaticType;
use crate::Type;
use crate::VariantTy;
use crate::VariantType;
use crate::{VariantIter, VariantStrIter};
use std::borrow::Cow;
use std::cmp::{Eq, Ordering, PartialEq, PartialOrd};
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::fmt;
use std::hash::{BuildHasher, Hash, Hasher};
use std::mem;
use std::ptr;
use std::slice;
use std::str;

wrapper! {
    // rustdoc-stripper-ignore-next
    /// A generic immutable value capable of carrying various types.
    ///
    /// See the [module documentation](index.html) for more details.
    // rustdoc-stripper-ignore-next-stop
    /// [`Variant`][struct@crate::Variant] is a variant datatype; it can contain one or more values
    /// along with information about the type of the values.
    ///
    /// A [`Variant`][struct@crate::Variant] may contain simple types, like an integer, or a boolean value;
    /// or complex types, like an array of two strings, or a dictionary of key
    /// value pairs. A [`Variant`][struct@crate::Variant] is also immutable: once it's been created neither
    /// its type nor its content can be modified further.
    ///
    /// GVariant is useful whenever data needs to be serialized, for example when
    /// sending method parameters in D-Bus, or when saving settings using GSettings.
    ///
    /// When creating a new [`Variant`][struct@crate::Variant], you pass the data you want to store in it
    /// along with a string representing the type of data you wish to pass to it.
    ///
    /// For instance, if you want to create a [`Variant`][struct@crate::Variant] holding an integer value you
    /// can use:
    ///
    ///
    ///
    /// **⚠️ The following code is in C ⚠️**
    ///
    /// ```C
    ///   GVariant *v = g_variant_new ("u", 40);
    /// ```
    ///
    /// The string "u" in the first argument tells [`Variant`][struct@crate::Variant] that the data passed to
    /// the constructor (40) is going to be an unsigned integer.
    ///
    /// More advanced examples of [`Variant`][struct@crate::Variant] in use can be found in documentation for
    /// [GVariant format strings][gvariant-format-strings-pointers].
    ///
    /// The range of possible values is determined by the type.
    ///
    /// The type system used by [`Variant`][struct@crate::Variant] is [`VariantType`][crate::VariantType].
    ///
    /// [`Variant`][struct@crate::Variant] instances always have a type and a value (which are given
    /// at construction time). The type and value of a [`Variant`][struct@crate::Variant] instance
    /// can never change other than by the [`Variant`][struct@crate::Variant] itself being
    /// destroyed. A [`Variant`][struct@crate::Variant] cannot contain a pointer.
    ///
    /// [`Variant`][struct@crate::Variant] is reference counted using `g_variant_ref()` and
    /// `g_variant_unref()`. [`Variant`][struct@crate::Variant] also has floating reference counts --
    /// see [`ref_sink()`][Self::ref_sink()].
    ///
    /// [`Variant`][struct@crate::Variant] is completely threadsafe. A [`Variant`][struct@crate::Variant] instance can be
    /// concurrently accessed in any way from any number of threads without
    /// problems.
    ///
    /// [`Variant`][struct@crate::Variant] is heavily optimised for dealing with data in serialized
    /// form. It works particularly well with data located in memory-mapped
    /// files. It can perform nearly all deserialization operations in a
    /// small constant time, usually touching only a single memory page.
    /// Serialized [`Variant`][struct@crate::Variant] data can also be sent over the network.
    ///
    /// [`Variant`][struct@crate::Variant] is largely compatible with D-Bus. Almost all types of
    /// [`Variant`][struct@crate::Variant] instances can be sent over D-Bus. See [`VariantType`][crate::VariantType] for
    /// exceptions. (However, [`Variant`][struct@crate::Variant]'s serialization format is not the same
    /// as the serialization format of a D-Bus message body: use `GDBusMessage`,
    /// in the gio library, for those.)
    ///
    /// For space-efficiency, the [`Variant`][struct@crate::Variant] serialization format does not
    /// automatically include the variant's length, type or endianness,
    /// which must either be implied from context (such as knowledge that a
    /// particular file format always contains a little-endian
    /// `G_VARIANT_TYPE_VARIANT` which occupies the whole length of the file)
    /// or supplied out-of-band (for instance, a length, type and/or endianness
    /// indicator could be placed at the beginning of a file, network message
    /// or network stream).
    ///
    /// A [`Variant`][struct@crate::Variant]'s size is limited mainly by any lower level operating
    /// system constraints, such as the number of bits in `gsize`. For
    /// example, it is reasonable to have a 2GB file mapped into memory
    /// with `GMappedFile`, and call [`from_data()`][Self::from_data()] on it.
    ///
    /// For convenience to C programmers, [`Variant`][struct@crate::Variant] features powerful
    /// varargs-based value construction and destruction. This feature is
    /// designed to be embedded in other libraries.
    ///
    /// There is a Python-inspired text language for describing [`Variant`][struct@crate::Variant]
    /// values. [`Variant`][struct@crate::Variant] includes a printer for this language and a parser
    /// with type inferencing.
    ///
    /// ## Memory Use
    ///
    /// [`Variant`][struct@crate::Variant] tries to be quite efficient with respect to memory use.
    /// This section gives a rough idea of how much memory is used by the
    /// current implementation. The information here is subject to change
    /// in the future.
    ///
    /// The memory allocated by [`Variant`][struct@crate::Variant] can be grouped into 4 broad
    /// purposes: memory for serialized data, memory for the type
    /// information cache, buffer management memory and memory for the
    /// [`Variant`][struct@crate::Variant] structure itself.
    ///
    /// ## Serialized Data Memory
    ///
    /// This is the memory that is used for storing GVariant data in
    /// serialized form. This is what would be sent over the network or
    /// what would end up on disk, not counting any indicator of the
    /// endianness, or of the length or type of the top-level variant.
    ///
    /// The amount of memory required to store a boolean is 1 byte. 16,
    /// 32 and 64 bit integers and double precision floating point numbers
    /// use their "natural" size. Strings (including object path and
    /// signature strings) are stored with a nul terminator, and as such
    /// use the length of the string plus 1 byte.
    ///
    /// Maybe types use no space at all to represent the null value and
    /// use the same amount of space (sometimes plus one byte) as the
    /// equivalent non-maybe-typed value to represent the non-null case.
    ///
    /// Arrays use the amount of space required to store each of their
    /// members, concatenated. Additionally, if the items stored in an
    /// array are not of a fixed-size (ie: strings, other arrays, etc)
    /// then an additional framing offset is stored for each item. The
    /// size of this offset is either 1, 2 or 4 bytes depending on the
    /// overall size of the container. Additionally, extra padding bytes
    /// are added as required for alignment of child values.
    ///
    /// Tuples (including dictionary entries) use the amount of space
    /// required to store each of their members, concatenated, plus one
    /// framing offset (as per arrays) for each non-fixed-sized item in
    /// the tuple, except for the last one. Additionally, extra padding
    /// bytes are added as required for alignment of child values.
    ///
    /// Variants use the same amount of space as the item inside of the
    /// variant, plus 1 byte, plus the length of the type string for the
    /// item inside the variant.
    ///
    /// As an example, consider a dictionary mapping strings to variants.
    /// In the case that the dictionary is empty, 0 bytes are required for
    /// the serialization.
    ///
    /// If we add an item "width" that maps to the int32 value of 500 then
    /// we will use 4 byte to store the int32 (so 6 for the variant
    /// containing it) and 6 bytes for the string. The variant must be
    /// aligned to 8 after the 6 bytes of the string, so that's 2 extra
    /// bytes. 6 (string) + 2 (padding) + 6 (variant) is 14 bytes used
    /// for the dictionary entry. An additional 1 byte is added to the
    /// array as a framing offset making a total of 15 bytes.
    ///
    /// If we add another entry, "title" that maps to a nullable string
    /// that happens to have a value of null, then we use 0 bytes for the
    /// null value (and 3 bytes for the variant to contain it along with
    /// its type string) plus 6 bytes for the string. Again, we need 2
    /// padding bytes. That makes a total of 6 + 2 + 3 = 11 bytes.
    ///
    /// We now require extra padding between the two items in the array.
    /// After the 14 bytes of the first item, that's 2 bytes required.
    /// We now require 2 framing offsets for an extra two
    /// bytes. 14 + 2 + 11 + 2 = 29 bytes to encode the entire two-item
    /// dictionary.
    ///
    /// ## Type Information Cache
    ///
    /// For each GVariant type that currently exists in the program a type
    /// information structure is kept in the type information cache. The
    /// type information structure is required for rapid deserialization.
    ///
    /// Continuing with the above example, if a [`Variant`][struct@crate::Variant] exists with the
    /// type "a{sv}" then a type information struct will exist for
    /// "a{sv}", "{sv}", "s", and "v". Multiple uses of the same type
    /// will share the same type information. Additionally, all
    /// single-digit types are stored in read-only static memory and do
    /// not contribute to the writable memory footprint of a program using
    /// [`Variant`][struct@crate::Variant].
    ///
    /// Aside from the type information structures stored in read-only
    /// memory, there are two forms of type information. One is used for
    /// container types where there is a single element type: arrays and
    /// maybe types. The other is used for container types where there
    /// are multiple element types: tuples and dictionary entries.
    ///
    /// Array type info structures are 6 * sizeof (void *), plus the
    /// memory required to store the type string itself. This means that
    /// on 32-bit systems, the cache entry for "a{sv}" would require 30
    /// bytes of memory (plus malloc overhead).
    ///
    /// Tuple type info structures are 6 * sizeof (void *), plus 4 *
    /// sizeof (void *) for each item in the tuple, plus the memory
    /// required to store the type string itself. A 2-item tuple, for
    /// example, would have a type information structure that consumed
    /// writable memory in the size of 14 * sizeof (void *) (plus type
    /// string) This means that on 32-bit systems, the cache entry for
    /// "{sv}" would require 61 bytes of memory (plus malloc overhead).
    ///
    /// This means that in total, for our "a{sv}" example, 91 bytes of
    /// type information would be allocated.
    ///
    /// The type information cache, additionally, uses a `GHashTable` to
    /// store and look up the cached items and stores a pointer to this
    /// hash table in static storage. The hash table is freed when there
    /// are zero items in the type cache.
    ///
    /// Although these sizes may seem large it is important to remember
    /// that a program will probably only have a very small number of
    /// different types of values in it and that only one type information
    /// structure is required for many different values of the same type.
    ///
    /// ## Buffer Management Memory
    ///
    /// [`Variant`][struct@crate::Variant] uses an internal buffer management structure to deal
    /// with the various different possible sources of serialized data
    /// that it uses. The buffer is responsible for ensuring that the
    /// correct call is made when the data is no longer in use by
    /// [`Variant`][struct@crate::Variant]. This may involve a `g_free()` or a `g_slice_free()` or
    /// even `g_mapped_file_unref()`.
    ///
    /// One buffer management structure is used for each chunk of
    /// serialized data. The size of the buffer management structure
    /// is 4 * (void *). On 32-bit systems, that's 16 bytes.
    ///
    /// ## GVariant structure
    ///
    /// The size of a [`Variant`][struct@crate::Variant] structure is 6 * (void *). On 32-bit
    /// systems, that's 24 bytes.
    ///
    /// [`Variant`][struct@crate::Variant] structures only exist if they are explicitly created
    /// with API calls. For example, if a [`Variant`][struct@crate::Variant] is constructed out of
    /// serialized data for the example given above (with the dictionary)
    /// then although there are 9 individual values that comprise the
    /// entire dictionary (two keys, two values, two variants containing
    /// the values, two dictionary entries, plus the dictionary itself),
    /// only 1 [`Variant`][struct@crate::Variant] instance exists -- the one referring to the
    /// dictionary.
    ///
    /// If calls are made to start accessing the other values then
    /// [`Variant`][struct@crate::Variant] instances will exist for those values only for as long
    /// as they are in use (ie: until you call `g_variant_unref()`). The
    /// type information is shared. The serialized data and the buffer
    /// management structure for that serialized data is shared by the
    /// child.
    ///
    /// ## Summary
    ///
    /// To put the entire example together, for our dictionary mapping
    /// strings to variants (with two entries, as given above), we are
    /// using 91 bytes of memory for type information, 29 bytes of memory
    /// for the serialized data, 16 bytes for buffer management and 24
    /// bytes for the [`Variant`][struct@crate::Variant] instance, or a total of 160 bytes, plus
    /// malloc overhead. If we were to use [`child_value()`][Self::child_value()] to
    /// access the two dictionary entries, we would use an additional 48
    /// bytes. If we were to have other dictionaries of the same type, we
    /// would use more memory for the serialized data and buffer
    /// management for those dictionaries, but the type information would
    /// be shared.
    #[doc(alias = "GVariant")]
    pub struct Variant(Shared<ffi::GVariant>);

    match fn {
        ref => |ptr| ffi::g_variant_ref_sink(ptr),
        unref => |ptr| ffi::g_variant_unref(ptr),
    }
}

impl StaticType for Variant {
    fn static_type() -> Type {
        Type::VARIANT
    }
}

#[doc(hidden)]
impl crate::value::ValueType for Variant {
    type Type = Variant;
}

#[doc(hidden)]
impl crate::value::ValueTypeOptional for Variant {}

#[doc(hidden)]
unsafe impl<'a> crate::value::FromValue<'a> for Variant {
    type Checker = crate::value::GenericValueTypeOrNoneChecker<Self>;

    unsafe fn from_value(value: &'a crate::Value) -> Self {
        let ptr = gobject_ffi::g_value_dup_variant(value.to_glib_none().0);
        assert!(!ptr.is_null());
        from_glib_full(ptr)
    }
}

#[doc(hidden)]
impl crate::value::ToValue for Variant {
    fn to_value(&self) -> crate::Value {
        unsafe {
            let mut value = crate::Value::from_type(Variant::static_type());
            gobject_ffi::g_value_take_variant(
                value.to_glib_none_mut().0,
                self.to_glib_full() as *mut _,
            );
            value
        }
    }

    fn value_type(&self) -> crate::Type {
        Variant::static_type()
    }
}

#[doc(hidden)]
impl crate::value::ToValueOptional for Variant {
    fn to_value_optional(s: Option<&Self>) -> crate::Value {
        let mut value = crate::Value::for_value_type::<Self>();
        unsafe {
            gobject_ffi::g_value_take_variant(
                value.to_glib_none_mut().0,
                s.to_glib_full() as *mut _,
            );
        }

        value
    }
}

// rustdoc-stripper-ignore-next
/// An error returned from the [`try_get`](struct.Variant.html#method.try_get) function
/// on a [`Variant`](struct.Variant.html) when the expected type does not match the actual type.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct VariantTypeMismatchError {
    pub actual: VariantType,
    pub expected: VariantType,
}

impl VariantTypeMismatchError {
    pub fn new(actual: VariantType, expected: VariantType) -> Self {
        Self { actual, expected }
    }
}

impl fmt::Display for VariantTypeMismatchError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Type mismatch: Expected '{}' got '{}'",
            self.expected, self.actual
        )
    }
}

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

impl Variant {
    // rustdoc-stripper-ignore-next
    /// Returns the type of the value.
    // rustdoc-stripper-ignore-next-stop
    /// Determines the type of `self`.
    ///
    /// The return value is valid for the lifetime of `self` and must not
    /// be freed.
    ///
    /// # Returns
    ///
    /// a [`VariantType`][crate::VariantType]
    #[doc(alias = "g_variant_get_type")]
    pub fn type_(&self) -> &VariantTy {
        unsafe { VariantTy::from_ptr(ffi::g_variant_get_type(self.to_glib_none().0)) }
    }

    // rustdoc-stripper-ignore-next
    /// Returns `true` if the type of the value corresponds to `T`.
    #[inline]
    #[doc(alias = "g_variant_is_of_type")]
    pub fn is<T: StaticVariantType>(&self) -> bool {
        self.is_type(&T::static_variant_type())
    }

    // rustdoc-stripper-ignore-next
    /// Returns `true` if the type of the value corresponds to `type_`.
    ///
    /// This is equivalent to [`self.type_().is_subtype_of(type_)`](VariantTy::is_subtype_of).
    #[inline]
    #[doc(alias = "g_variant_is_of_type")]
    pub fn is_type(&self, type_: &VariantTy) -> bool {
        unsafe {
            from_glib(ffi::g_variant_is_of_type(
                self.to_glib_none().0,
                type_.to_glib_none().0,
            ))
        }
    }

    // rustdoc-stripper-ignore-next
    /// Returns the classification of the variant.
    // rustdoc-stripper-ignore-next-stop
    /// Classifies `self` according to its top-level type.
    ///
    /// # Returns
    ///
    /// the [`VariantClass`][crate::VariantClass] of `self`
    #[doc(alias = "g_variant_classify")]
    pub fn classify(&self) -> crate::VariantClass {
        unsafe { from_glib(ffi::g_variant_classify(self.to_glib_none().0)) }
    }

    // rustdoc-stripper-ignore-next
    /// Tries to extract a value of type `T`.
    ///
    /// Returns `Some` if `T` matches the variant's type.
    // rustdoc-stripper-ignore-next-stop
    /// Deconstructs a [`Variant`][struct@crate::Variant] instance.
    ///
    /// Think of this function as an analogue to `scanf()`.
    ///
    /// The arguments that are expected by this function are entirely
    /// determined by `format_string`. `format_string` also restricts the
    /// permissible types of `self`. It is an error to give a value with
    /// an incompatible type. See the section on
    /// [GVariant format strings][gvariant-format-strings].
    /// Please note that the syntax of the format string is very likely to be
    /// extended in the future.
    ///
    /// `format_string` determines the C types that are used for unpacking
    /// the values and also determines if the values are copied or borrowed,
    /// see the section on
    /// [GVariant format strings][gvariant-format-strings-pointers].
    /// ## `format_string`
    /// a [`Variant`][struct@crate::Variant] format string
    #[inline]
    pub fn get<T: FromVariant>(&self) -> Option<T> {
        T::from_variant(self)
    }

    // rustdoc-stripper-ignore-next
    /// Tries to extract a value of type `T`.
    pub fn try_get<T: FromVariant>(&self) -> Result<T, VariantTypeMismatchError> {
        self.get().ok_or_else(|| {
            VariantTypeMismatchError::new(
                self.type_().to_owned(),
                T::static_variant_type().into_owned(),
            )
        })
    }

    // rustdoc-stripper-ignore-next
    /// Boxes value.
    #[inline]
    pub fn from_variant(value: &Variant) -> Self {
        unsafe { from_glib_none(ffi::g_variant_new_variant(value.to_glib_none().0)) }
    }

    // rustdoc-stripper-ignore-next
    /// Unboxes self.
    ///
    /// Returns `Some` if self contains a `Variant`.
    #[inline]
    #[doc(alias = "get_variant")]
    pub fn as_variant(&self) -> Option<Variant> {
        unsafe { from_glib_full(ffi::g_variant_get_variant(self.to_glib_none().0)) }
    }

    // rustdoc-stripper-ignore-next
    /// Reads a child item out of a container `Variant` instance.
    ///
    /// # Panics
    ///
    /// * if `self` is not a container type.
    /// * if given `index` is larger than number of children.
    // rustdoc-stripper-ignore-next-stop
    /// Reads a child item out of a container [`Variant`][struct@crate::Variant] instance. This
    /// includes variants, maybes, arrays, tuples and dictionary
    /// entries. It is an error to call this function on any other type of
    /// [`Variant`][struct@crate::Variant].
    ///
    /// It is an error if `index_` is greater than the number of child items
    /// in the container. See [`n_children()`][Self::n_children()].
    ///
    /// The returned value is never floating. You should free it with
    /// `g_variant_unref()` when you're done with it.
    ///
    /// Note that values borrowed from the returned child are not guaranteed to
    /// still be valid after the child is freed even if you still hold a reference
    /// to `self`, if `self` has not been serialized at the time this function is
    /// called. To avoid this, you can serialize `self` by calling
    /// [`data()`][Self::data()] and optionally ignoring the return value.
    ///
    /// There may be implementation specific restrictions on deeply nested values,
    /// which would result in the unit tuple being returned as the child value,
    /// instead of further nested children. [`Variant`][struct@crate::Variant] is guaranteed to handle
    /// nesting up to at least 64 levels.
    ///
    /// This function is O(1).
    /// ## `index_`
    /// the index of the child to fetch
    ///
    /// # Returns
    ///
    /// the child at the specified index
    #[doc(alias = "get_child_value")]
    #[doc(alias = "g_variant_get_child_value")]
    #[must_use]
    pub fn child_value(&self, index: usize) -> Variant {
        assert!(self.is_container());
        assert!(index < self.n_children());

        unsafe { from_glib_full(ffi::g_variant_get_child_value(self.to_glib_none().0, index)) }
    }

    // rustdoc-stripper-ignore-next
    /// Try to read a child item out of a container `Variant` instance.
    ///
    /// It returns `None` if `self` is not a container type or if the given
    /// `index` is larger than number of children.
    pub fn try_child_value(&self, index: usize) -> Option<Variant> {
        if !(self.is_container() && index < self.n_children()) {
            return None;
        }

        let v =
            unsafe { from_glib_full(ffi::g_variant_get_child_value(self.to_glib_none().0, index)) };
        Some(v)
    }

    // rustdoc-stripper-ignore-next
    /// Try to read a child item out of a container `Variant` instance.
    ///
    /// It returns `Ok(None)` if `self` is not a container type or if the given
    /// `index` is larger than number of children.  An error is thrown if the
    /// type does not match.
    pub fn try_child_get<T: StaticVariantType + FromVariant>(
        &self,
        index: usize,
    ) -> Result<Option<T>, VariantTypeMismatchError> {
        // TODO: In the future optimize this by using g_variant_get_child()
        // directly to avoid allocating a GVariant.
        self.try_child_value(index).map(|v| v.try_get()).transpose()
    }

    // rustdoc-stripper-ignore-next
    /// Read a child item out of a container `Variant` instance.
    ///
    /// # Panics
    ///
    /// * if `self` is not a container type.
    /// * if given `index` is larger than number of children.
    /// * if the expected variant type does not match
    pub fn child_get<T: StaticVariantType + FromVariant>(&self, index: usize) -> T {
        // TODO: In the future optimize this by using g_variant_get_child()
        // directly to avoid allocating a GVariant.
        self.child_value(index).get().unwrap()
    }

    // rustdoc-stripper-ignore-next
    /// Tries to extract a `&str`.
    ///
    /// Returns `Some` if the variant has a string type (`s`, `o` or `g` type
    /// strings).
    #[doc(alias = "get_str")]
    #[doc(alias = "g_variant_get_string")]
    pub fn str(&self) -> Option<&str> {
        unsafe {
            match self.type_().as_str() {
                "s" | "o" | "g" => {
                    let mut len = 0;
                    let ptr = ffi::g_variant_get_string(self.to_glib_none().0, &mut len);
                    if len == 0 {
                        Some("")
                    } else {
                        let ret = str::from_utf8_unchecked(slice::from_raw_parts(
                            ptr as *const u8,
                            len as usize,
                        ));
                        Some(ret)
                    }
                }
                _ => None,
            }
        }
    }

    // rustdoc-stripper-ignore-next
    /// Tries to extract a `&[T]` from a variant of array type with a suitable element type.
    ///
    /// Returns an error if the type is wrong.
    // rustdoc-stripper-ignore-next-stop
    /// Provides access to the serialized data for an array of fixed-sized
    /// items.
    ///
    /// `self` must be an array with fixed-sized elements. Numeric types are
    /// fixed-size, as are tuples containing only other fixed-sized types.
    ///
    /// `element_size` must be the size of a single element in the array,
    /// as given by the section on
    /// [serialized data memory][gvariant-serialized-data-memory].
    ///
    /// In particular, arrays of these fixed-sized types can be interpreted
    /// as an array of the given C type, with `element_size` set to the size
    /// the appropriate type:
    /// - `G_VARIANT_TYPE_INT16` (etc.): `gint16` (etc.)
    /// - `G_VARIANT_TYPE_BOOLEAN`: `guchar` (not `gboolean`!)
    /// - `G_VARIANT_TYPE_BYTE`: `guint8`
    /// - `G_VARIANT_TYPE_HANDLE`: `guint32`
    /// - `G_VARIANT_TYPE_DOUBLE`: `gdouble`
    ///
    /// For example, if calling this function for an array of 32-bit integers,
    /// you might say `sizeof(gint32)`. This value isn't used except for the purpose
    /// of a double-check that the form of the serialized data matches the caller's
    /// expectation.
    ///
    /// `n_elements`, which must be non-[`None`], is set equal to the number of
    /// items in the array.
    /// ## `element_size`
    /// the size of each element
    ///
    /// # Returns
    ///
    /// a pointer to
    ///  the fixed array
    #[doc(alias = "g_variant_get_fixed_array")]
    pub fn fixed_array<T: FixedSizeVariantType>(&self) -> Result<&[T], VariantTypeMismatchError> {
        unsafe {
            let expected_ty = T::static_variant_type().as_array();
            if self.type_() != expected_ty {
                return Err(VariantTypeMismatchError {
                    actual: self.type_().to_owned(),
                    expected: expected_ty.into_owned(),
                });
            }

            let mut n_elements = mem::MaybeUninit::uninit();
            let ptr = ffi::g_variant_get_fixed_array(
                self.to_glib_none().0,
                n_elements.as_mut_ptr(),
                mem::size_of::<T>(),
            );
            assert!(!ptr.is_null());

            let n_elements = n_elements.assume_init();
            if n_elements == 0 {
                Ok(&[])
            } else {
                Ok(slice::from_raw_parts(ptr as *const T, n_elements))
            }
        }
    }

    // rustdoc-stripper-ignore-next
    /// Creates a new Variant array from children.
    ///
    /// # Panics
    ///
    /// This function panics if not all variants are of type `T`.
    #[doc(alias = "g_variant_new_array")]
    pub fn array_from_iter<T: StaticVariantType, I: IntoIterator<Item = Variant>>(
        children: I,
    ) -> Self {
        Self::array_from_iter_with_type(&T::static_variant_type(), children)
    }

    // rustdoc-stripper-ignore-next
    /// Creates a new Variant array from children with the specified type.
    ///
    /// # Panics
    ///
    /// This function panics if not all variants are of type `type_`.
    #[doc(alias = "g_variant_new_array")]
    pub fn array_from_iter_with_type<T: AsRef<Variant>, I: IntoIterator<Item = T>>(
        type_: &VariantTy,
        children: I,
    ) -> Self {
        unsafe {
            let mut builder = mem::MaybeUninit::uninit();
            ffi::g_variant_builder_init(builder.as_mut_ptr(), type_.as_array().to_glib_none().0);
            let mut builder = builder.assume_init();
            for value in children.into_iter() {
                let value = value.as_ref();
                if ffi::g_variant_is_of_type(value.to_glib_none().0, type_.to_glib_none().0)
                    == ffi::GFALSE
                {
                    ffi::g_variant_builder_clear(&mut builder);
                    assert!(value.is_type(type_));
                }

                ffi::g_variant_builder_add_value(&mut builder, value.to_glib_none().0);
            }
            from_glib_none(ffi::g_variant_builder_end(&mut builder))
        }
    }

    // rustdoc-stripper-ignore-next
    /// Creates a new Variant array from a fixed array.
    #[doc(alias = "g_variant_new_fixed_array")]
    pub fn array_from_fixed_array<T: FixedSizeVariantType>(array: &[T]) -> Self {
        let type_ = T::static_variant_type();

        unsafe {
            from_glib_none(ffi::g_variant_new_fixed_array(
                type_.as_ptr(),
                array.as_ptr() as ffi::gconstpointer,
                array.len(),
                mem::size_of::<T>(),
            ))
        }
    }

    // rustdoc-stripper-ignore-next
    /// Creates a new Variant tuple from children.
    #[doc(alias = "g_variant_new_tuple")]
    pub fn tuple_from_iter(children: impl IntoIterator<Item = impl AsRef<Variant>>) -> Self {
        unsafe {
            let mut builder = mem::MaybeUninit::uninit();
            ffi::g_variant_builder_init(builder.as_mut_ptr(), VariantTy::TUPLE.to_glib_none().0);
            let mut builder = builder.assume_init();
            for value in children.into_iter() {
                ffi::g_variant_builder_add_value(&mut builder, value.as_ref().to_glib_none().0);
            }
            from_glib_none(ffi::g_variant_builder_end(&mut builder))
        }
    }

    // rustdoc-stripper-ignore-next
    /// Creates a new dictionary entry Variant.
    ///
    /// [DictEntry] should be preferred over this when the types are known statically.
    #[doc(alias = "g_variant_new_dict_entry")]
    pub fn from_dict_entry(key: &Variant, value: &Variant) -> Self {
        unsafe {
            from_glib_none(ffi::g_variant_new_dict_entry(
                key.to_glib_none().0,
                value.to_glib_none().0,
            ))
        }
    }

    // rustdoc-stripper-ignore-next
    /// Creates a new maybe Variant.
    #[doc(alias = "g_variant_new_maybe")]
    pub fn from_maybe<T: StaticVariantType>(child: Option<&Variant>) -> Self {
        let type_ = T::static_variant_type();
        match child {
            Some(child) => {
                assert_eq!(type_, child.type_());

                Self::from_some(child)
            }
            None => Self::from_none(&type_),
        }
    }

    // rustdoc-stripper-ignore-next
    /// Creates a new maybe Variant from a child.
    #[doc(alias = "g_variant_new_maybe")]
    pub fn from_some(child: &Variant) -> Self {
        unsafe {
            from_glib_none(ffi::g_variant_new_maybe(
                ptr::null(),
                child.to_glib_none().0,
            ))
        }
    }

    // rustdoc-stripper-ignore-next
    /// Creates a new maybe Variant with Nothing.
    #[doc(alias = "g_variant_new_maybe")]
    pub fn from_none(type_: &VariantTy) -> Self {
        unsafe {
            from_glib_none(ffi::g_variant_new_maybe(
                type_.to_glib_none().0,
                ptr::null_mut(),
            ))
        }
    }

    // rustdoc-stripper-ignore-next
    /// Extract the value of a maybe Variant.
    ///
    /// Returns the child value, or `None` if the value is Nothing.
    ///
    /// # Panics
    ///
    /// Panics if compiled with `debug_assertions` and the variant is not maybe-typed.
    #[inline]
    pub fn as_maybe(&self) -> Option<Variant> {
        debug_assert!(self.type_().is_maybe());

        unsafe { from_glib_full(ffi::g_variant_get_maybe(self.to_glib_none().0)) }
    }

    // rustdoc-stripper-ignore-next
    /// Pretty-print the contents of this variant in a human-readable form.
    ///
    /// A variant can be recreated from this output via [`Variant::parse`].
    // rustdoc-stripper-ignore-next-stop
    /// Pretty-prints `self` in the format understood by `g_variant_parse()`.
    ///
    /// The format is described [here][gvariant-text].
    ///
    /// If `type_annotate` is [`true`], then type information is included in
    /// the output.
    /// ## `type_annotate`
    /// [`true`] if type information should be included in
    ///  the output
    ///
    /// # Returns
    ///
    /// a newly-allocated string holding the result.
    #[doc(alias = "g_variant_print")]
    pub fn print(&self, type_annotate: bool) -> crate::GString {
        unsafe {
            from_glib_full(ffi::g_variant_print(
                self.to_glib_none().0,
                type_annotate.into_glib(),
            ))
        }
    }

    // rustdoc-stripper-ignore-next
    /// Parses a GVariant from the text representation produced by [`print()`](Self::print).
    #[doc(alias = "g_variant_parse")]
    pub fn parse(type_: Option<&VariantTy>, text: &str) -> Result<Self, crate::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let text = text.as_bytes().as_ptr_range();
            let variant = ffi::g_variant_parse(
                type_.to_glib_none().0,
                text.start as *const _,
                text.end as *const _,
                ptr::null_mut(),
                &mut error,
            );
            if variant.is_null() {
                assert!(!error.is_null());
                Err(from_glib_full(error))
            } else {
                Ok(from_glib_full(variant))
            }
        }
    }

    // rustdoc-stripper-ignore-next
    /// Constructs a new serialized-mode GVariant instance.
    // rustdoc-stripper-ignore-next-stop
    /// Constructs a new serialized-mode [`Variant`][struct@crate::Variant] instance. This is the
    /// inner interface for creation of new serialized values that gets
    /// called from various functions in gvariant.c.
    ///
    /// A reference is taken on `bytes`.
    ///
    /// The data in `bytes` must be aligned appropriately for the `type_` being loaded.
    /// Otherwise this function will internally create a copy of the memory (since
    /// GLib 2.60) or (in older versions) fail and exit the process.
    /// ## `type_`
    /// a [`VariantType`][crate::VariantType]
    /// ## `bytes`
    /// a [`Bytes`][crate::Bytes]
    /// ## `trusted`
    /// if the contents of `bytes` are trusted
    ///
    /// # Returns
    ///
    /// a new [`Variant`][struct@crate::Variant] with a floating reference
    #[doc(alias = "g_variant_new_from_bytes")]
    pub fn from_bytes<T: StaticVariantType>(bytes: &Bytes) -> Self {
        Variant::from_bytes_with_type(bytes, &T::static_variant_type())
    }

    // rustdoc-stripper-ignore-next
    /// Constructs a new serialized-mode GVariant instance.
    ///
    /// This is the same as `from_bytes`, except that checks on the passed
    /// data are skipped.
    ///
    /// You should not use this function on data from external sources.
    ///
    /// # Safety
    ///
    /// Since the data is not validated, this is potentially dangerous if called
    /// on bytes which are not guaranteed to have come from serialising another
    /// Variant.  The caller is responsible for ensuring bad data is not passed in.
    pub unsafe fn from_bytes_trusted<T: StaticVariantType>(bytes: &Bytes) -> Self {
        Variant::from_bytes_with_type_trusted(bytes, &T::static_variant_type())
    }

    // rustdoc-stripper-ignore-next
    /// Constructs a new serialized-mode GVariant instance.
    // rustdoc-stripper-ignore-next-stop
    /// Creates a new [`Variant`][struct@crate::Variant] instance from serialized data.
    ///
    /// `type_` is the type of [`Variant`][struct@crate::Variant] instance that will be constructed.
    /// The interpretation of `data` depends on knowing the type.
    ///
    /// `data` is not modified by this function and must remain valid with an
    /// unchanging value until such a time as `notify` is called with
    /// `user_data`. If the contents of `data` change before that time then
    /// the result is undefined.
    ///
    /// If `data` is trusted to be serialized data in normal form then
    /// `trusted` should be [`true`]. This applies to serialized data created
    /// within this process or read from a trusted location on the disk (such
    /// as a file installed in /usr/lib alongside your application). You
    /// should set trusted to [`false`] if `data` is read from the network, a
    /// file in the user's home directory, etc.
    ///
    /// If `data` was not stored in this machine's native endianness, any multi-byte
    /// numeric values in the returned variant will also be in non-native
    /// endianness. [`byteswap()`][Self::byteswap()] can be used to recover the original values.
    ///
    /// `notify` will be called with `user_data` when `data` is no longer
    /// needed. The exact time of this call is unspecified and might even be
    /// before this function returns.
    ///
    /// Note: `data` must be backed by memory that is aligned appropriately for the
    /// `type_` being loaded. Otherwise this function will internally create a copy of
    /// the memory (since GLib 2.60) or (in older versions) fail and exit the
    /// process.
    /// ## `type_`
    /// a definite [`VariantType`][crate::VariantType]
    /// ## `data`
    /// the serialized data
    /// ## `trusted`
    /// [`true`] if `data` is definitely in normal form
    /// ## `notify`
    /// function to call when `data` is no longer needed
    ///
    /// # Returns
    ///
    /// a new floating [`Variant`][struct@crate::Variant] of type `type_`
    #[doc(alias = "g_variant_new_from_data")]
    pub fn from_data<T: StaticVariantType, A: AsRef<[u8]>>(data: A) -> Self {
        Variant::from_data_with_type(data, &T::static_variant_type())
    }

    // rustdoc-stripper-ignore-next
    /// Constructs a new serialized-mode GVariant instance.
    ///
    /// This is the same as `from_data`, except that checks on the passed
    /// data are skipped.
    ///
    /// You should not use this function on data from external sources.
    ///
    /// # Safety
    ///
    /// Since the data is not validated, this is potentially dangerous if called
    /// on bytes which are not guaranteed to have come from serialising another
    /// Variant.  The caller is responsible for ensuring bad data is not passed in.
    pub unsafe fn from_data_trusted<T: StaticVariantType, A: AsRef<[u8]>>(data: A) -> Self {
        Variant::from_data_with_type_trusted(data, &T::static_variant_type())
    }

    // rustdoc-stripper-ignore-next
    /// Constructs a new serialized-mode GVariant instance with a given type.
    #[doc(alias = "g_variant_new_from_bytes")]
    pub fn from_bytes_with_type(bytes: &Bytes, type_: &VariantTy) -> Self {
        unsafe {
            from_glib_none(ffi::g_variant_new_from_bytes(
                type_.as_ptr() as *const _,
                bytes.to_glib_none().0,
                false.into_glib(),
            ))
        }
    }

    // rustdoc-stripper-ignore-next
    /// Constructs a new serialized-mode GVariant instance with a given type.
    ///
    /// This is the same as `from_bytes`, except that checks on the passed
    /// data are skipped.
    ///
    /// You should not use this function on data from external sources.
    ///
    /// # Safety
    ///
    /// Since the data is not validated, this is potentially dangerous if called
    /// on bytes which are not guaranteed to have come from serialising another
    /// Variant.  The caller is responsible for ensuring bad data is not passed in.
    pub unsafe fn from_bytes_with_type_trusted(bytes: &Bytes, type_: &VariantTy) -> Self {
        from_glib_none(ffi::g_variant_new_from_bytes(
            type_.as_ptr() as *const _,
            bytes.to_glib_none().0,
            true.into_glib(),
        ))
    }

    // rustdoc-stripper-ignore-next
    /// Constructs a new serialized-mode GVariant instance with a given type.
    #[doc(alias = "g_variant_new_from_data")]
    pub fn from_data_with_type<A: AsRef<[u8]>>(data: A, type_: &VariantTy) -> Self {
        unsafe {
            let data = Box::new(data);
            let (data_ptr, len) = {
                let data = (*data).as_ref();
                (data.as_ptr(), data.len())
            };

            unsafe extern "C" fn free_data<A: AsRef<[u8]>>(ptr: ffi::gpointer) {
                let _ = Box::from_raw(ptr as *mut A);
            }

            from_glib_none(ffi::g_variant_new_from_data(
                type_.as_ptr() as *const _,
                data_ptr as ffi::gconstpointer,
                len,
                false.into_glib(),
                Some(free_data::<A>),
                Box::into_raw(data) as ffi::gpointer,
            ))
        }
    }

    // rustdoc-stripper-ignore-next
    /// Constructs a new serialized-mode GVariant instance with a given type.
    ///
    /// This is the same as `from_data`, except that checks on the passed
    /// data are skipped.
    ///
    /// You should not use this function on data from external sources.
    ///
    /// # Safety
    ///
    /// Since the data is not validated, this is potentially dangerous if called
    /// on bytes which are not guaranteed to have come from serialising another
    /// Variant.  The caller is responsible for ensuring bad data is not passed in.
    pub unsafe fn from_data_with_type_trusted<A: AsRef<[u8]>>(data: A, type_: &VariantTy) -> Self {
        let data = Box::new(data);
        let (data_ptr, len) = {
            let data = (*data).as_ref();
            (data.as_ptr(), data.len())
        };

        unsafe extern "C" fn free_data<A: AsRef<[u8]>>(ptr: ffi::gpointer) {
            let _ = Box::from_raw(ptr as *mut A);
        }

        from_glib_none(ffi::g_variant_new_from_data(
            type_.as_ptr() as *const _,
            data_ptr as ffi::gconstpointer,
            len,
            true.into_glib(),
            Some(free_data::<A>),
            Box::into_raw(data) as ffi::gpointer,
        ))
    }

    // rustdoc-stripper-ignore-next
    /// Returns the serialized form of a GVariant instance.
    // rustdoc-stripper-ignore-next-stop
    /// Returns a pointer to the serialized form of a [`Variant`][struct@crate::Variant] instance.
    /// The semantics of this function are exactly the same as
    /// [`data()`][Self::data()], except that the returned [`Bytes`][crate::Bytes] holds
    /// a reference to the variant data.
    ///
    /// # Returns
    ///
    /// A new [`Bytes`][crate::Bytes] representing the variant data
    #[doc(alias = "get_data_as_bytes")]
    #[doc(alias = "g_variant_get_data_as_bytes")]
    pub fn data_as_bytes(&self) -> Bytes {
        unsafe { from_glib_full(ffi::g_variant_get_data_as_bytes(self.to_glib_none().0)) }
    }

    // rustdoc-stripper-ignore-next
    /// Returns the serialized form of a GVariant instance.
    // rustdoc-stripper-ignore-next-stop
    /// Returns a pointer to the serialized form of a [`Variant`][struct@crate::Variant] instance.
    /// The returned data may not be in fully-normalised form if read from an
    /// untrusted source. The returned data must not be freed; it remains
    /// valid for as long as `self` exists.
    ///
    /// If `self` is a fixed-sized value that was deserialized from a
    /// corrupted serialized container then [`None`] may be returned. In this
    /// case, the proper thing to do is typically to use the appropriate
    /// number of nul bytes in place of `self`. If `self` is not fixed-sized
    /// then [`None`] is never returned.
    ///
    /// In the case that `self` is already in serialized form, this function
    /// is O(1). If the value is not already in serialized form,
    /// serialization occurs implicitly and is approximately O(n) in the size
    /// of the result.
    ///
    /// To deserialize the data returned by this function, in addition to the
    /// serialized data, you must know the type of the [`Variant`][struct@crate::Variant], and (if the
    /// machine might be different) the endianness of the machine that stored
    /// it. As a result, file formats or network messages that incorporate
    /// serialized `GVariants` must include this information either
    /// implicitly (for instance "the file always contains a
    /// `G_VARIANT_TYPE_VARIANT` and it is always in little-endian order") or
    /// explicitly (by storing the type and/or endianness in addition to the
    /// serialized data).
    ///
    /// # Returns
    ///
    /// the serialized form of `self`, or [`None`]
    #[doc(alias = "g_variant_get_data")]
    pub fn data(&self) -> &[u8] {
        unsafe {
            let selfv = self.to_glib_none();
            let len = ffi::g_variant_get_size(selfv.0);
            if len == 0 {
                return &[];
            }
            let ptr = ffi::g_variant_get_data(selfv.0);
            slice::from_raw_parts(ptr as *const u8, len as usize)
        }
    }

    // rustdoc-stripper-ignore-next
    /// Returns the size of serialized form of a GVariant instance.
    // rustdoc-stripper-ignore-next-stop
    /// Determines the number of bytes that would be required to store `self`
    /// with [`store()`][Self::store()].
    ///
    /// If `self` has a fixed-sized type then this function always returned
    /// that fixed size.
    ///
    /// In the case that `self` is already in serialized form or the size has
    /// already been calculated (ie: this function has been called before)
    /// then this function is O(1). Otherwise, the size is calculated, an
    /// operation which is approximately O(n) in the number of values
    /// involved.
    ///
    /// # Returns
    ///
    /// the serialized size of `self`
    #[doc(alias = "g_variant_get_size")]
    pub fn size(&self) -> usize {
        unsafe { ffi::g_variant_get_size(self.to_glib_none().0) }
    }

    // rustdoc-stripper-ignore-next
    /// Stores the serialized form of a GVariant instance into the given slice.
    ///
    /// The slice needs to be big enough.
    // rustdoc-stripper-ignore-next-stop
    /// Stores the serialized form of `self` at `data`. `data` should be
    /// large enough. See [`size()`][Self::size()].
    ///
    /// The stored data is in machine native byte order but may not be in
    /// fully-normalised form if read from an untrusted source. See
    /// [`normal_form()`][Self::normal_form()] for a solution.
    ///
    /// As with [`data()`][Self::data()], to be able to deserialize the
    /// serialized variant successfully, its type and (if the destination
    /// machine might be different) its endianness must also be available.
    ///
    /// This function is approximately O(n) in the size of `data`.
    #[doc(alias = "g_variant_store")]
    pub fn store(&self, data: &mut [u8]) -> Result<usize, crate::BoolError> {
        unsafe {
            let size = ffi::g_variant_get_size(self.to_glib_none().0);
            if data.len() < size {
                return Err(bool_error!("Provided slice is too small"));
            }

            ffi::g_variant_store(self.to_glib_none().0, data.as_mut_ptr() as ffi::gpointer);

            Ok(size)
        }
    }

    // rustdoc-stripper-ignore-next
    /// Returns a copy of the variant in normal form.
    // rustdoc-stripper-ignore-next-stop
    /// Gets a [`Variant`][struct@crate::Variant] instance that has the same value as `self` and is
    /// trusted to be in normal form.
    ///
    /// If `self` is already trusted to be in normal form then a new
    /// reference to `self` is returned.
    ///
    /// If `self` is not already trusted, then it is scanned to check if it
    /// is in normal form. If it is found to be in normal form then it is
    /// marked as trusted and a new reference to it is returned.
    ///
    /// If `self` is found not to be in normal form then a new trusted
    /// [`Variant`][struct@crate::Variant] is created with the same value as `self`.
    ///
    /// It makes sense to call this function if you've received [`Variant`][struct@crate::Variant]
    /// data from untrusted sources and you want to ensure your serialized
    /// output is definitely in normal form.
    ///
    /// If `self` is already in normal form, a new reference will be returned
    /// (which will be floating if `self` is floating). If it is not in normal form,
    /// the newly created [`Variant`][struct@crate::Variant] will be returned with a single non-floating
    /// reference. Typically, `g_variant_take_ref()` should be called on the return
    /// value from this function to guarantee ownership of a single non-floating
    /// reference to it.
    ///
    /// # Returns
    ///
    /// a trusted [`Variant`][struct@crate::Variant]
    #[doc(alias = "g_variant_get_normal_form")]
    #[must_use]
    pub fn normal_form(&self) -> Self {
        unsafe { from_glib_full(ffi::g_variant_get_normal_form(self.to_glib_none().0)) }
    }

    // rustdoc-stripper-ignore-next
    /// Returns a copy of the variant in the opposite endianness.
    // rustdoc-stripper-ignore-next-stop
    /// Performs a byteswapping operation on the contents of `self`. The
    /// result is that all multi-byte numeric data contained in `self` is
    /// byteswapped. That includes 16, 32, and 64bit signed and unsigned
    /// integers as well as file handles and double precision floating point
    /// values.
    ///
    /// This function is an identity mapping on any value that does not
    /// contain multi-byte numeric data. That include strings, booleans,
    /// bytes and containers containing only these things (recursively).
    ///
    /// The returned value is always in normal form and is marked as trusted.
    ///
    /// # Returns
    ///
    /// the byteswapped form of `self`
    #[doc(alias = "g_variant_byteswap")]
    #[must_use]
    pub fn byteswap(&self) -> Self {
        unsafe { from_glib_full(ffi::g_variant_byteswap(self.to_glib_none().0)) }
    }

    // rustdoc-stripper-ignore-next
    /// Determines the number of children in a container GVariant instance.
    // rustdoc-stripper-ignore-next-stop
    /// Determines the number of children in a container [`Variant`][struct@crate::Variant] instance.
    /// This includes variants, maybes, arrays, tuples and dictionary
    /// entries. It is an error to call this function on any other type of
    /// [`Variant`][struct@crate::Variant].
    ///
    /// For variants, the return value is always 1. For values with maybe
    /// types, it is always zero or one. For arrays, it is the length of the
    /// array. For tuples it is the number of tuple items (which depends
    /// only on the type). For dictionary entries, it is always 2
    ///
    /// This function is O(1).
    ///
    /// # Returns
    ///
    /// the number of children in the container
    #[doc(alias = "g_variant_n_children")]
    pub fn n_children(&self) -> usize {
        assert!(self.is_container());

        unsafe { ffi::g_variant_n_children(self.to_glib_none().0) }
    }

    // rustdoc-stripper-ignore-next
    /// Create an iterator over items in the variant.
    ///
    /// Note that this heap allocates a variant for each element,
    /// which can be particularly expensive for large arrays.
    pub fn iter(&self) -> VariantIter {
        assert!(self.is_container());

        VariantIter::new(self.clone())
    }

    // rustdoc-stripper-ignore-next
    /// Create an iterator over borrowed strings from a GVariant of type `as` (array of string).
    ///
    /// This will fail if the variant is not an array of with
    /// the expected child type.
    ///
    /// A benefit of this API over [`Self::iter()`] is that it
    /// minimizes allocation, and provides strongly typed access.
    ///
    /// ```
    /// # use glib::prelude::*;
    /// let strs = &["foo", "bar"];
    /// let strs_variant: glib::Variant = strs.to_variant();
    /// for s in strs_variant.array_iter_str()? {
    ///     println!("{}", s);
    /// }
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn array_iter_str(&self) -> Result<VariantStrIter, VariantTypeMismatchError> {
        let child_ty = String::static_variant_type();
        let actual_ty = self.type_();
        let expected_ty = child_ty.as_array();
        if actual_ty != expected_ty {
            return Err(VariantTypeMismatchError {
                actual: actual_ty.to_owned(),
                expected: expected_ty.into_owned(),
            });
        }

        Ok(VariantStrIter::new(self))
    }

    // rustdoc-stripper-ignore-next
    /// Return whether this Variant is a container type.
    // rustdoc-stripper-ignore-next-stop
    /// Checks if `self` is a container.
    ///
    /// # Returns
    ///
    /// [`true`] if `self` is a container
    #[doc(alias = "g_variant_is_container")]
    pub fn is_container(&self) -> bool {
        unsafe { from_glib(ffi::g_variant_is_container(self.to_glib_none().0)) }
    }

    // rustdoc-stripper-ignore-next
    /// Return whether this Variant is in normal form.
    // rustdoc-stripper-ignore-next-stop
    /// Checks if `self` is in normal form.
    ///
    /// The main reason to do this is to detect if a given chunk of
    /// serialized data is in normal form: load the data into a [`Variant`][struct@crate::Variant]
    /// using [`from_data()`][Self::from_data()] and then use this function to
    /// check.
    ///
    /// If `self` is found to be in normal form then it will be marked as
    /// being trusted. If the value was already marked as being trusted then
    /// this function will immediately return [`true`].
    ///
    /// There may be implementation specific restrictions on deeply nested values.
    /// GVariant is guaranteed to handle nesting up to at least 64 levels.
    ///
    /// # Returns
    ///
    /// [`true`] if `self` is in normal form
    #[doc(alias = "g_variant_is_normal_form")]
    pub fn is_normal_form(&self) -> bool {
        unsafe { from_glib(ffi::g_variant_is_normal_form(self.to_glib_none().0)) }
    }

    // rustdoc-stripper-ignore-next
    /// Return whether input string is a valid `VariantClass::ObjectPath`.
    // rustdoc-stripper-ignore-next-stop
    /// Determines if a given string is a valid D-Bus object path. You
    /// should ensure that a string is a valid D-Bus object path before
    /// passing it to [`new_object_path()`][Self::new_object_path()].
    ///
    /// A valid object path starts with `/` followed by zero or more
    /// sequences of characters separated by `/` characters. Each sequence
    /// must contain only the characters `[A-Z][a-z][0-9]_`. No sequence
    /// (including the one following the final `/` character) may be empty.
    /// ## `string`
    /// a normal C nul-terminated string
    ///
    /// # Returns
    ///
    /// [`true`] if `string` is a D-Bus object path
    #[doc(alias = "g_variant_is_object_path")]
    pub fn is_object_path(string: &str) -> bool {
        unsafe { from_glib(ffi::g_variant_is_object_path(string.to_glib_none().0)) }
    }

    // rustdoc-stripper-ignore-next
    /// Return whether input string is a valid `VariantClass::Signature`.
    // rustdoc-stripper-ignore-next-stop
    /// Determines if a given string is a valid D-Bus type signature. You
    /// should ensure that a string is a valid D-Bus type signature before
    /// passing it to [`new_signature()`][Self::new_signature()].
    ///
    /// D-Bus type signatures consist of zero or more definite [`VariantType`][crate::VariantType]
    /// strings in sequence.
    /// ## `string`
    /// a normal C nul-terminated string
    ///
    /// # Returns
    ///
    /// [`true`] if `string` is a D-Bus type signature
    #[doc(alias = "g_variant_is_signature")]
    pub fn is_signature(string: &str) -> bool {
        unsafe { from_glib(ffi::g_variant_is_signature(string.to_glib_none().0)) }
    }
}

unsafe impl Send for Variant {}
unsafe impl Sync for Variant {}

impl fmt::Debug for Variant {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Variant")
            .field("ptr", &self.to_glib_none().0)
            .field("type", &self.type_())
            .field("value", &self.to_string())
            .finish()
    }
}

impl fmt::Display for Variant {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(&self.print(true))
    }
}

impl str::FromStr for Variant {
    type Err = crate::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(None, s)
    }
}

impl PartialEq for Variant {
    #[doc(alias = "g_variant_equal")]
    fn eq(&self, other: &Self) -> bool {
        unsafe {
            from_glib(ffi::g_variant_equal(
                self.to_glib_none().0 as *const _,
                other.to_glib_none().0 as *const _,
            ))
        }
    }
}

impl Eq for Variant {}

impl PartialOrd for Variant {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        unsafe {
            if ffi::g_variant_classify(self.to_glib_none().0)
                != ffi::g_variant_classify(other.to_glib_none().0)
            {
                return None;
            }

            if self.is_container() {
                return None;
            }

            let res = ffi::g_variant_compare(
                self.to_glib_none().0 as *const _,
                other.to_glib_none().0 as *const _,
            );

            Some(res.cmp(&0))
        }
    }
}

impl Hash for Variant {
    #[doc(alias = "g_variant_hash")]
    fn hash<H: Hasher>(&self, state: &mut H) {
        unsafe { state.write_u32(ffi::g_variant_hash(self.to_glib_none().0 as *const _)) }
    }
}

impl AsRef<Variant> for Variant {
    fn as_ref(&self) -> &Self {
        self
    }
}

// rustdoc-stripper-ignore-next
/// Converts to `Variant`.
pub trait ToVariant {
    // rustdoc-stripper-ignore-next
    /// Returns a `Variant` clone of `self`.
    fn to_variant(&self) -> Variant;
}

// rustdoc-stripper-ignore-next
/// Extracts a value.
pub trait FromVariant: Sized + StaticVariantType {
    // rustdoc-stripper-ignore-next
    /// Tries to extract a value.
    ///
    /// Returns `Some` if the variant's type matches `Self`.
    fn from_variant(variant: &Variant) -> Option<Self>;
}

// rustdoc-stripper-ignore-next
/// Returns `VariantType` of `Self`.
pub trait StaticVariantType {
    // rustdoc-stripper-ignore-next
    /// Returns the `VariantType` corresponding to `Self`.
    fn static_variant_type() -> Cow<'static, VariantTy>;
}

impl StaticVariantType for Variant {
    fn static_variant_type() -> Cow<'static, VariantTy> {
        Cow::Borrowed(VariantTy::VARIANT)
    }
}

impl<'a, T: ?Sized + ToVariant> ToVariant for &'a T {
    fn to_variant(&self) -> Variant {
        <T as ToVariant>::to_variant(self)
    }
}

impl<'a, T: ?Sized + StaticVariantType> StaticVariantType for &'a T {
    fn static_variant_type() -> Cow<'static, VariantTy> {
        <T as StaticVariantType>::static_variant_type()
    }
}

macro_rules! impl_numeric {
    ($name:ty, $typ:expr, $new_fn:ident, $get_fn:ident) => {
        impl StaticVariantType for $name {
            fn static_variant_type() -> Cow<'static, VariantTy> {
                Cow::Borrowed($typ)
            }
        }

        impl ToVariant for $name {
            fn to_variant(&self) -> Variant {
                unsafe { from_glib_none(ffi::$new_fn(*self)) }
            }
        }

        impl FromVariant for $name {
            fn from_variant(variant: &Variant) -> Option<Self> {
                unsafe {
                    if variant.is::<Self>() {
                        Some(ffi::$get_fn(variant.to_glib_none().0))
                    } else {
                        None
                    }
                }
            }
        }
    };
}

impl_numeric!(u8, VariantTy::BYTE, g_variant_new_byte, g_variant_get_byte);
impl_numeric!(
    i16,
    VariantTy::INT16,
    g_variant_new_int16,
    g_variant_get_int16
);
impl_numeric!(
    u16,
    VariantTy::UINT16,
    g_variant_new_uint16,
    g_variant_get_uint16
);
impl_numeric!(
    i32,
    VariantTy::INT32,
    g_variant_new_int32,
    g_variant_get_int32
);
impl_numeric!(
    u32,
    VariantTy::UINT32,
    g_variant_new_uint32,
    g_variant_get_uint32
);
impl_numeric!(
    i64,
    VariantTy::INT64,
    g_variant_new_int64,
    g_variant_get_int64
);
impl_numeric!(
    u64,
    VariantTy::UINT64,
    g_variant_new_uint64,
    g_variant_get_uint64
);
impl_numeric!(
    f64,
    VariantTy::DOUBLE,
    g_variant_new_double,
    g_variant_get_double
);

impl StaticVariantType for () {
    fn static_variant_type() -> Cow<'static, VariantTy> {
        Cow::Borrowed(VariantTy::UNIT)
    }
}

impl ToVariant for () {
    fn to_variant(&self) -> Variant {
        unsafe { from_glib_none(ffi::g_variant_new_tuple(ptr::null(), 0)) }
    }
}

impl FromVariant for () {
    fn from_variant(variant: &Variant) -> Option<Self> {
        if variant.is::<Self>() {
            Some(())
        } else {
            None
        }
    }
}

impl StaticVariantType for bool {
    fn static_variant_type() -> Cow<'static, VariantTy> {
        Cow::Borrowed(VariantTy::BOOLEAN)
    }
}

impl ToVariant for bool {
    fn to_variant(&self) -> Variant {
        unsafe { from_glib_none(ffi::g_variant_new_boolean(self.into_glib())) }
    }
}

impl FromVariant for bool {
    fn from_variant(variant: &Variant) -> Option<Self> {
        unsafe {
            if variant.is::<Self>() {
                Some(from_glib(ffi::g_variant_get_boolean(
                    variant.to_glib_none().0,
                )))
            } else {
                None
            }
        }
    }
}

impl StaticVariantType for String {
    fn static_variant_type() -> Cow<'static, VariantTy> {
        Cow::Borrowed(VariantTy::STRING)
    }
}

impl ToVariant for String {
    fn to_variant(&self) -> Variant {
        self[..].to_variant()
    }
}

impl FromVariant for String {
    fn from_variant(variant: &Variant) -> Option<Self> {
        variant.str().map(String::from)
    }
}

impl StaticVariantType for str {
    fn static_variant_type() -> Cow<'static, VariantTy> {
        String::static_variant_type()
    }
}

impl ToVariant for str {
    fn to_variant(&self) -> Variant {
        unsafe { from_glib_none(ffi::g_variant_new_take_string(self.to_glib_full())) }
    }
}

impl StaticVariantType for std::path::PathBuf {
    fn static_variant_type() -> Cow<'static, VariantTy> {
        std::path::Path::static_variant_type()
    }
}

impl ToVariant for std::path::PathBuf {
    fn to_variant(&self) -> Variant {
        self.as_path().to_variant()
    }
}

impl FromVariant for std::path::PathBuf {
    fn from_variant(variant: &Variant) -> Option<Self> {
        unsafe {
            let ptr = ffi::g_variant_get_bytestring(variant.to_glib_none().0);
            Some(crate::translate::c_to_path_buf(ptr as *const _))
        }
    }
}

impl StaticVariantType for std::path::Path {
    fn static_variant_type() -> Cow<'static, VariantTy> {
        <&[u8]>::static_variant_type()
    }
}

impl ToVariant for std::path::Path {
    fn to_variant(&self) -> Variant {
        let tmp = crate::translate::path_to_c(self);
        unsafe { from_glib_none(ffi::g_variant_new_bytestring(tmp.as_ptr() as *const u8)) }
    }
}

impl StaticVariantType for std::ffi::OsString {
    fn static_variant_type() -> Cow<'static, VariantTy> {
        std::ffi::OsStr::static_variant_type()
    }
}

impl ToVariant for std::ffi::OsString {
    fn to_variant(&self) -> Variant {
        self.as_os_str().to_variant()
    }
}

impl FromVariant for std::ffi::OsString {
    fn from_variant(variant: &Variant) -> Option<Self> {
        unsafe {
            let ptr = ffi::g_variant_get_bytestring(variant.to_glib_none().0);
            Some(crate::translate::c_to_os_string(ptr as *const _))
        }
    }
}

impl StaticVariantType for std::ffi::OsStr {
    fn static_variant_type() -> Cow<'static, VariantTy> {
        <&[u8]>::static_variant_type()
    }
}

impl ToVariant for std::ffi::OsStr {
    fn to_variant(&self) -> Variant {
        let tmp = crate::translate::os_str_to_c(self);
        unsafe { from_glib_none(ffi::g_variant_new_bytestring(tmp.as_ptr() as *const u8)) }
    }
}

impl<T: StaticVariantType> StaticVariantType for Option<T> {
    fn static_variant_type() -> Cow<'static, VariantTy> {
        Cow::Owned(VariantType::new_maybe(&T::static_variant_type()))
    }
}

impl<T: StaticVariantType + ToVariant> ToVariant for Option<T> {
    fn to_variant(&self) -> Variant {
        Variant::from_maybe::<T>(self.as_ref().map(|m| m.to_variant()).as_ref())
    }
}

impl<T: StaticVariantType + FromVariant> FromVariant for Option<T> {
    fn from_variant(variant: &Variant) -> Option<Self> {
        unsafe {
            if variant.is::<Self>() {
                let c_child = ffi::g_variant_get_maybe(variant.to_glib_none().0);
                if !c_child.is_null() {
                    let child: Variant = from_glib_full(c_child);

                    Some(T::from_variant(&child))
                } else {
                    Some(None)
                }
            } else {
                None
            }
        }
    }
}

impl<T: StaticVariantType> StaticVariantType for [T] {
    fn static_variant_type() -> Cow<'static, VariantTy> {
        T::static_variant_type().as_array()
    }
}

impl<T: StaticVariantType + ToVariant> ToVariant for [T] {
    fn to_variant(&self) -> Variant {
        unsafe {
            if self.is_empty() {
                return from_glib_none(ffi::g_variant_new_array(
                    T::static_variant_type().to_glib_none().0,
                    ptr::null(),
                    0,
                ));
            }

            let mut builder = mem::MaybeUninit::uninit();
            ffi::g_variant_builder_init(builder.as_mut_ptr(), VariantTy::ARRAY.to_glib_none().0);
            let mut builder = builder.assume_init();
            for value in self {
                let value = value.to_variant();
                ffi::g_variant_builder_add_value(&mut builder, value.to_glib_none().0);
            }
            from_glib_none(ffi::g_variant_builder_end(&mut builder))
        }
    }
}

impl<T: FromVariant> FromVariant for Vec<T> {
    fn from_variant(variant: &Variant) -> Option<Self> {
        if !variant.is_container() {
            return None;
        }

        let mut vec = Vec::with_capacity(variant.n_children());

        for i in 0..variant.n_children() {
            match variant.child_value(i).get() {
                Some(child) => vec.push(child),
                None => return None,
            }
        }

        Some(vec)
    }
}

impl<T: StaticVariantType + ToVariant> ToVariant for Vec<T> {
    fn to_variant(&self) -> Variant {
        self.as_slice().to_variant()
    }
}

impl<T: StaticVariantType> StaticVariantType for Vec<T> {
    fn static_variant_type() -> Cow<'static, VariantTy> {
        <[T]>::static_variant_type()
    }
}

#[test]
fn test_regression_from_variant_panics() {
    let variant = "text".to_variant();
    let hashmap: Option<HashMap<u64, u64>> = FromVariant::from_variant(&variant);
    assert!(hashmap.is_none());

    let variant = HashMap::<u64, u64>::new().to_variant();
    let hashmap: Option<HashMap<u64, u64>> = FromVariant::from_variant(&variant);
    assert!(hashmap.is_some());
}

impl<K, V, H> FromVariant for HashMap<K, V, H>
where
    K: FromVariant + Eq + Hash,
    V: FromVariant,
    H: BuildHasher + Default,
{
    fn from_variant(variant: &Variant) -> Option<Self> {
        if !variant.is_container() {
            return None;
        }

        let mut map = HashMap::default();

        for i in 0..variant.n_children() {
            let entry = variant.child_value(i);
            let key = match entry.child_value(0).get() {
                Some(key) => key,
                None => return None,
            };
            let val = match entry.child_value(1).get() {
                Some(val) => val,
                None => return None,
            };

            map.insert(key, val);
        }

        Some(map)
    }
}

impl<K, V> FromVariant for BTreeMap<K, V>
where
    K: FromVariant + Eq + Ord,
    V: FromVariant,
{
    fn from_variant(variant: &Variant) -> Option<Self> {
        if !variant.is_container() {
            return None;
        }

        let mut map = BTreeMap::default();

        for i in 0..variant.n_children() {
            let entry = variant.child_value(i);
            let key = match entry.child_value(0).get() {
                Some(key) => key,
                None => return None,
            };
            let val = match entry.child_value(1).get() {
                Some(val) => val,
                None => return None,
            };

            map.insert(key, val);
        }

        Some(map)
    }
}

impl<K, V> ToVariant for HashMap<K, V>
where
    K: StaticVariantType + ToVariant + Eq + Hash,
    V: StaticVariantType + ToVariant,
{
    fn to_variant(&self) -> Variant {
        unsafe {
            if self.is_empty() {
                return from_glib_none(ffi::g_variant_new_array(
                    DictEntry::<K, V>::static_variant_type().to_glib_none().0,
                    ptr::null(),
                    0,
                ));
            }

            let mut builder = mem::MaybeUninit::uninit();
            ffi::g_variant_builder_init(builder.as_mut_ptr(), VariantTy::ARRAY.to_glib_none().0);
            let mut builder = builder.assume_init();
            for (key, value) in self {
                let entry = DictEntry::new(key, value).to_variant();
                ffi::g_variant_builder_add_value(&mut builder, entry.to_glib_none().0);
            }
            from_glib_none(ffi::g_variant_builder_end(&mut builder))
        }
    }
}

impl<K, V> ToVariant for BTreeMap<K, V>
where
    K: StaticVariantType + ToVariant + Eq + Hash,
    V: StaticVariantType + ToVariant,
{
    fn to_variant(&self) -> Variant {
        unsafe {
            if self.is_empty() {
                return from_glib_none(ffi::g_variant_new_array(
                    DictEntry::<K, V>::static_variant_type().to_glib_none().0,
                    ptr::null(),
                    0,
                ));
            }

            let mut builder = mem::MaybeUninit::uninit();
            ffi::g_variant_builder_init(builder.as_mut_ptr(), VariantTy::ARRAY.to_glib_none().0);
            let mut builder = builder.assume_init();
            for (key, value) in self {
                let entry = DictEntry::new(key, value).to_variant();
                ffi::g_variant_builder_add_value(&mut builder, entry.to_glib_none().0);
            }
            from_glib_none(ffi::g_variant_builder_end(&mut builder))
        }
    }
}

/// A Dictionary entry.
///
/// While GVariant format allows a dictionary entry to be an independent type, typically you'll need
/// to use this in a dictionary, which is simply an array of dictionary entries. The following code
/// creates a dictionary:
///
/// ```
///# use glib::prelude::*; // or `use gtk::prelude::*;`
/// use glib::{Variant, FromVariant, ToVariant};
/// use glib::variant::DictEntry;
///
/// let entries = [
///     DictEntry::new("uuid", 1000u32),
///     DictEntry::new("guid", 1001u32),
/// ];
/// let dict = entries.into_iter().collect::<Variant>();
/// assert_eq!(dict.n_children(), 2);
/// assert_eq!(dict.type_().as_str(), "a{su}");
/// ```
pub struct DictEntry<K, V> {
    key: K,
    value: V,
}

impl<K, V> DictEntry<K, V>
where
    K: StaticVariantType + ToVariant,
    V: StaticVariantType + ToVariant,
{
    pub fn new(key: K, value: V) -> Self {
        Self { key, value }
    }

    pub fn key(&self) -> &K {
        &self.key
    }

    pub fn value(&self) -> &V {
        &self.value
    }
}

impl<K, V> FromVariant for DictEntry<K, V>
where
    K: FromVariant,
    V: FromVariant,
{
    fn from_variant(variant: &Variant) -> Option<Self> {
        if !variant.type_().is_subtype_of(VariantTy::DICT_ENTRY) {
            return None;
        }

        let key = match variant.child_value(0).get() {
            Some(key) => key,
            None => return None,
        };
        let value = match variant.child_value(1).get() {
            Some(value) => value,
            None => return None,
        };

        Some(Self { key, value })
    }
}

impl<K, V> ToVariant for DictEntry<K, V>
where
    K: StaticVariantType + ToVariant,
    V: StaticVariantType + ToVariant,
{
    fn to_variant(&self) -> Variant {
        Variant::from_dict_entry(&self.key.to_variant(), &self.value.to_variant())
    }
}

impl ToVariant for Variant {
    fn to_variant(&self) -> Variant {
        Variant::from_variant(self)
    }
}

impl FromVariant for Variant {
    fn from_variant(variant: &Variant) -> Option<Self> {
        variant.as_variant()
    }
}

impl<K: StaticVariantType, V: StaticVariantType> StaticVariantType for DictEntry<K, V> {
    fn static_variant_type() -> Cow<'static, VariantTy> {
        Cow::Owned(VariantType::new_dict_entry(
            &K::static_variant_type(),
            &V::static_variant_type(),
        ))
    }
}

fn static_variant_mapping<K, V>() -> Cow<'static, VariantTy>
where
    K: StaticVariantType,
    V: StaticVariantType,
{
    use std::fmt::Write;

    let key_type = K::static_variant_type();
    let value_type = V::static_variant_type();

    if key_type == VariantTy::STRING && value_type == VariantTy::VARIANT {
        return Cow::Borrowed(VariantTy::VARDICT);
    }

    let mut builder = crate::GStringBuilder::default();
    write!(builder, "a{{{}{}}}", key_type.as_str(), value_type.as_str()).unwrap();

    Cow::Owned(VariantType::from_string(builder.into_string()).unwrap())
}

impl<K, V, H> StaticVariantType for HashMap<K, V, H>
where
    K: StaticVariantType,
    V: StaticVariantType,
    H: BuildHasher + Default,
{
    fn static_variant_type() -> Cow<'static, VariantTy> {
        static_variant_mapping::<K, V>()
    }
}

impl<K, V> StaticVariantType for BTreeMap<K, V>
where
    K: StaticVariantType,
    V: StaticVariantType,
{
    fn static_variant_type() -> Cow<'static, VariantTy> {
        static_variant_mapping::<K, V>()
    }
}

macro_rules! tuple_impls {
    ($($len:expr => ($($n:tt $name:ident)+))+) => {
        $(
            impl<$($name),+> StaticVariantType for ($($name,)+)
            where
                $($name: StaticVariantType,)+
            {
                fn static_variant_type() -> Cow<'static, VariantTy> {
                    Cow::Owned(VariantType::new_tuple(&[
                        $(
                            $name::static_variant_type(),
                        )+
                    ]))
                }
            }

            impl<$($name),+> FromVariant for ($($name,)+)
            where
                $($name: FromVariant,)+
            {
                fn from_variant(variant: &Variant) -> Option<Self> {
                    if !variant.type_().is_subtype_of(VariantTy::TUPLE) {
                        return None;
                    }

                    Some((
                        $(
                            match variant.try_child_get::<$name>($n) {
                                Ok(Some(field)) => field,
                                _ => return None,
                            },
                        )+
                    ))
                }
            }

            impl<$($name),+> ToVariant for ($($name,)+)
            where
                $($name: ToVariant,)+
            {
                fn to_variant(&self) -> Variant {
                    unsafe {
                        let mut builder = mem::MaybeUninit::uninit();
                        ffi::g_variant_builder_init(builder.as_mut_ptr(), VariantTy::TUPLE.to_glib_none().0);
                        let mut builder = builder.assume_init();

                        $(
                            let field = self.$n.to_variant();
                            ffi::g_variant_builder_add_value(&mut builder, field.to_glib_none().0);
                        )+

                        from_glib_none(ffi::g_variant_builder_end(&mut builder))
                    }
                }
            }
        )+
    }
}

tuple_impls! {
    1 => (0 T0)
    2 => (0 T0 1 T1)
    3 => (0 T0 1 T1 2 T2)
    4 => (0 T0 1 T1 2 T2 3 T3)
    5 => (0 T0 1 T1 2 T2 3 T3 4 T4)
    6 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5)
    7 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6)
    8 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7)
    9 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8)
    10 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9)
    11 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10)
    12 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11)
    13 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12)
    14 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13)
    15 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14)
    16 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14 15 T15)
}

impl<T: ToVariant + StaticVariantType> FromIterator<T> for Variant {
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        Variant::array_from_iter::<T, _>(iter.into_iter().map(|v| v.to_variant()))
    }
}

/// Trait for fixed size variant types.
pub unsafe trait FixedSizeVariantType: StaticVariantType + Sized + Copy {}
unsafe impl FixedSizeVariantType for u8 {}
unsafe impl FixedSizeVariantType for i16 {}
unsafe impl FixedSizeVariantType for u16 {}
unsafe impl FixedSizeVariantType for i32 {}
unsafe impl FixedSizeVariantType for u32 {}
unsafe impl FixedSizeVariantType for i64 {}
unsafe impl FixedSizeVariantType for u64 {}
unsafe impl FixedSizeVariantType for f64 {}
unsafe impl FixedSizeVariantType for bool {}

/// Wrapper type for fixed size type arrays.
///
/// Converting this from/to a `Variant` is generally more efficient than working on the type
/// directly. This is especially important when deriving `Variant` trait implementations on custom
/// types.
///
/// This wrapper type can hold for example `Vec<u8>`, `Box<[u8]>` and similar types.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FixedSizeVariantArray<A, T>(A, std::marker::PhantomData<T>)
where
    A: AsRef<[T]>,
    T: FixedSizeVariantType;

impl<A: AsRef<[T]>, T: FixedSizeVariantType> From<A> for FixedSizeVariantArray<A, T> {
    fn from(array: A) -> Self {
        FixedSizeVariantArray(array, std::marker::PhantomData)
    }
}

impl<A: AsRef<[T]>, T: FixedSizeVariantType> FixedSizeVariantArray<A, T> {
    pub fn into_inner(self) -> A {
        self.0
    }
}

impl<A: AsRef<[T]>, T: FixedSizeVariantType> std::ops::Deref for FixedSizeVariantArray<A, T> {
    type Target = A;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<A: AsRef<[T]>, T: FixedSizeVariantType> std::ops::DerefMut for FixedSizeVariantArray<A, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<A: AsRef<[T]>, T: FixedSizeVariantType> AsRef<A> for FixedSizeVariantArray<A, T> {
    fn as_ref(&self) -> &A {
        &self.0
    }
}

impl<A: AsRef<[T]>, T: FixedSizeVariantType> AsMut<A> for FixedSizeVariantArray<A, T> {
    fn as_mut(&mut self) -> &mut A {
        &mut self.0
    }
}

impl<A: AsRef<[T]>, T: FixedSizeVariantType> AsRef<[T]> for FixedSizeVariantArray<A, T> {
    fn as_ref(&self) -> &[T] {
        self.0.as_ref()
    }
}

impl<A: AsRef<[T]> + AsMut<[T]>, T: FixedSizeVariantType> AsMut<[T]>
    for FixedSizeVariantArray<A, T>
{
    fn as_mut(&mut self) -> &mut [T] {
        self.0.as_mut()
    }
}

impl<A: AsRef<[T]>, T: FixedSizeVariantType> StaticVariantType for FixedSizeVariantArray<A, T> {
    fn static_variant_type() -> Cow<'static, VariantTy> {
        <[T]>::static_variant_type()
    }
}

impl<A: AsRef<[T]> + for<'a> From<&'a [T]>, T: FixedSizeVariantType> FromVariant
    for FixedSizeVariantArray<A, T>
{
    fn from_variant(variant: &Variant) -> Option<Self> {
        Some(FixedSizeVariantArray(
            A::from(variant.fixed_array::<T>().ok()?),
            std::marker::PhantomData,
        ))
    }
}

impl<A: AsRef<[T]>, T: FixedSizeVariantType> ToVariant for FixedSizeVariantArray<A, T> {
    fn to_variant(&self) -> Variant {
        Variant::array_from_fixed_array(self.0.as_ref())
    }
}

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

    macro_rules! unsigned {
        ($name:ident, $ty:ident) => {
            #[test]
            fn $name() {
                let mut n = $ty::max_value();
                while n > 0 {
                    let v = n.to_variant();
                    assert_eq!(v.get(), Some(n));
                    n /= 2;
                }
            }
        };
    }

    macro_rules! signed {
        ($name:ident, $ty:ident) => {
            #[test]
            fn $name() {
                let mut n = $ty::max_value();
                while n > 0 {
                    let v = n.to_variant();
                    assert_eq!(v.get(), Some(n));
                    let v = (-n).to_variant();
                    assert_eq!(v.get(), Some(-n));
                    n /= 2;
                }
            }
        };
    }

    unsigned!(test_u8, u8);
    unsigned!(test_u16, u16);
    unsigned!(test_u32, u32);
    unsigned!(test_u64, u64);
    signed!(test_i16, i16);
    signed!(test_i32, i32);
    signed!(test_i64, i64);

    #[test]
    fn test_str() {
        let s = "this is a test";
        let v = s.to_variant();
        assert_eq!(v.str(), Some(s));
        assert_eq!(42u32.to_variant().str(), None);
    }

    #[test]
    fn test_fixed_array() {
        let b = b"this is a test";
        let v = Variant::array_from_fixed_array(&b[..]);
        assert_eq!(v.type_().as_str(), "ay");
        assert_eq!(v.fixed_array::<u8>().unwrap(), b);
        assert!(42u32.to_variant().fixed_array::<u8>().is_err());

        let b = [1u32, 10u32, 100u32];
        let v = Variant::array_from_fixed_array(&b);
        assert_eq!(v.type_().as_str(), "au");
        assert_eq!(v.fixed_array::<u32>().unwrap(), b);
        assert!(v.fixed_array::<u8>().is_err());

        let b = [true, false, true];
        let v = Variant::array_from_fixed_array(&b);
        assert_eq!(v.type_().as_str(), "ab");
        assert_eq!(v.fixed_array::<bool>().unwrap(), b);
        assert!(v.fixed_array::<u8>().is_err());

        let b = [1.0f64, 2.0f64, 3.0f64];
        let v = Variant::array_from_fixed_array(&b);
        assert_eq!(v.type_().as_str(), "ad");
        #[allow(clippy::float_cmp)]
        {
            assert_eq!(v.fixed_array::<f64>().unwrap(), b);
        }
        assert!(v.fixed_array::<u64>().is_err());
    }

    #[test]
    fn test_fixed_variant_array() {
        let b = FixedSizeVariantArray::from(&b"this is a test"[..]);
        let v = b.to_variant();
        assert_eq!(v.type_().as_str(), "ay");
        assert_eq!(
            &*v.get::<FixedSizeVariantArray<Vec<u8>, u8>>().unwrap(),
            &*b
        );

        let b = FixedSizeVariantArray::from(vec![1i32, 2, 3]);
        let v = b.to_variant();
        assert_eq!(v.type_().as_str(), "ai");
        assert_eq!(v.get::<FixedSizeVariantArray<Vec<i32>, i32>>().unwrap(), b);
    }

    #[test]
    fn test_string() {
        let s = String::from("this is a test");
        let v = s.to_variant();
        assert_eq!(v.get(), Some(s));
        assert_eq!(v.normal_form(), v);
    }

    #[test]
    fn test_eq() {
        let v1 = "this is a test".to_variant();
        let v2 = "this is a test".to_variant();
        let v3 = "test".to_variant();
        assert_eq!(v1, v2);
        assert_ne!(v1, v3);
    }

    #[test]
    fn test_hash() {
        let v1 = "this is a test".to_variant();
        let v2 = "this is a test".to_variant();
        let v3 = "test".to_variant();
        let mut set = HashSet::new();
        set.insert(v1);
        assert!(set.contains(&v2));
        assert!(!set.contains(&v3));

        assert_eq!(
            <HashMap<&str, (&str, u8, u32)>>::static_variant_type().as_str(),
            "a{s(syu)}"
        );
    }

    #[test]
    fn test_array() {
        assert_eq!(<Vec<&str>>::static_variant_type().as_str(), "as");
        assert_eq!(
            <Vec<(&str, u8, u32)>>::static_variant_type().as_str(),
            "a(syu)"
        );
        let a = ["foo", "bar", "baz"].to_variant();
        assert_eq!(a.normal_form(), a);
        assert_eq!(a.array_iter_str().unwrap().len(), 3);
        let o = 0u32.to_variant();
        assert!(o.array_iter_str().is_err());
    }

    #[test]
    fn test_array_from_iter() {
        let a = Variant::array_from_iter::<String, _>(
            ["foo", "bar", "baz"].into_iter().map(|s| s.to_variant()),
        );
        assert_eq!(a.type_().as_str(), "as");
        assert_eq!(a.n_children(), 3);

        assert_eq!(a.try_child_get::<String>(0), Ok(Some(String::from("foo"))));
        assert_eq!(a.try_child_get::<String>(1), Ok(Some(String::from("bar"))));
        assert_eq!(a.try_child_get::<String>(2), Ok(Some(String::from("baz"))));
    }

    #[test]
    fn test_array_collect() {
        let a = ["foo", "bar", "baz"].into_iter().collect::<Variant>();
        assert_eq!(a.type_().as_str(), "as");
        assert_eq!(a.n_children(), 3);

        assert_eq!(a.try_child_get::<String>(0), Ok(Some(String::from("foo"))));
        assert_eq!(a.try_child_get::<String>(1), Ok(Some(String::from("bar"))));
        assert_eq!(a.try_child_get::<String>(2), Ok(Some(String::from("baz"))));
    }

    #[test]
    fn test_tuple() {
        assert_eq!(<(&str, u32)>::static_variant_type().as_str(), "(su)");
        assert_eq!(<(&str, u8, u32)>::static_variant_type().as_str(), "(syu)");
        let a = ("test", 1u8, 2u32).to_variant();
        assert_eq!(a.normal_form(), a);
        assert_eq!(a.try_child_get::<String>(0), Ok(Some(String::from("test"))));
        assert_eq!(a.try_child_get::<u8>(1), Ok(Some(1u8)));
        assert_eq!(a.try_child_get::<u32>(2), Ok(Some(2u32)));
        assert_eq!(
            a.try_get::<(String, u8, u32)>(),
            Ok((String::from("test"), 1u8, 2u32))
        );
    }

    #[test]
    fn test_tuple_from_iter() {
        let a = Variant::tuple_from_iter(["foo".to_variant(), 1u8.to_variant(), 2i32.to_variant()]);
        assert_eq!(a.type_().as_str(), "(syi)");
        assert_eq!(a.n_children(), 3);

        assert_eq!(a.try_child_get::<String>(0), Ok(Some(String::from("foo"))));
        assert_eq!(a.try_child_get::<u8>(1), Ok(Some(1u8)));
        assert_eq!(a.try_child_get::<i32>(2), Ok(Some(2i32)));
    }

    #[test]
    fn test_empty() {
        assert_eq!(<()>::static_variant_type().as_str(), "()");
        let a = ().to_variant();
        assert_eq!(a.type_().as_str(), "()");
        assert_eq!(a.get::<()>(), Some(()));
    }

    #[test]
    fn test_maybe() {
        assert!(<Option<()>>::static_variant_type().is_maybe());
        let m1 = Some(()).to_variant();
        assert_eq!(m1.type_().as_str(), "m()");

        assert_eq!(m1.get::<Option<()>>(), Some(Some(())));
        assert!(m1.as_maybe().is_some());

        let m2 = None::<()>.to_variant();
        assert!(m2.as_maybe().is_none());
    }

    #[test]
    fn test_btreemap() {
        assert_eq!(
            <BTreeMap<String, u32>>::static_variant_type().as_str(),
            "a{su}"
        );
        // Validate that BTreeMap adds entries to dict in sorted order
        let mut m = BTreeMap::new();
        let total = 20;
        for n in 0..total {
            let k = format!("v{:04}", n);
            m.insert(k, n as u32);
        }
        let v = m.to_variant();
        let n = v.n_children();
        assert_eq!(total, n);
        for n in 0..total {
            let child = v
                .try_child_get::<DictEntry<String, u32>>(n)
                .unwrap()
                .unwrap();
            assert_eq!(*child.value(), n as u32);
        }

        assert_eq!(BTreeMap::from_variant(&v).unwrap(), m);
    }

    #[test]
    fn test_get() -> Result<(), Box<dyn std::error::Error>> {
        let u = 42u32.to_variant();
        assert!(u.get::<i32>().is_none());
        assert_eq!(u.get::<u32>().unwrap(), 42);
        assert!(u.try_get::<i32>().is_err());
        // Test ? conversion
        assert_eq!(u.try_get::<u32>()?, 42);
        Ok(())
    }

    #[test]
    fn test_byteswap() {
        let u = 42u32.to_variant();
        assert_eq!(u.byteswap().get::<u32>().unwrap(), 704643072u32);
        assert_eq!(u.byteswap().byteswap().get::<u32>().unwrap(), 42u32);
    }

    #[test]
    fn test_try_child() {
        let a = ["foo"].to_variant();
        assert!(a.try_child_value(0).is_some());
        assert_eq!(a.try_child_get::<String>(0).unwrap().unwrap(), "foo");
        assert_eq!(a.child_get::<String>(0), "foo");
        assert!(a.try_child_get::<u32>(0).is_err());
        assert!(a.try_child_value(1).is_none());
        assert!(a.try_child_get::<String>(1).unwrap().is_none());
        let u = 42u32.to_variant();
        assert!(u.try_child_value(0).is_none());
        assert!(u.try_child_get::<String>(0).unwrap().is_none());
    }

    #[test]
    fn test_serialize() {
        let a = ("test", 1u8, 2u32).to_variant();

        let bytes = a.data_as_bytes();
        let data = a.data();
        let len = a.size();
        assert_eq!(bytes.len(), len);
        assert_eq!(data.len(), len);

        let mut store_data = vec![0u8; len];
        assert_eq!(a.store(&mut store_data).unwrap(), len);

        assert_eq!(&bytes, data);
        assert_eq!(&store_data, data);

        let b = Variant::from_data::<(String, u8, u32), _>(store_data);
        assert_eq!(a, b);

        let c = Variant::from_bytes::<(String, u8, u32)>(&bytes);
        assert_eq!(a, c);
    }

    #[test]
    fn test_print_parse() {
        let a = ("test", 1u8, 2u32).to_variant();

        let a2 = Variant::parse(Some(a.type_()), &a.print(false)).unwrap();
        assert_eq!(a, a2);

        let a3: Variant = a.to_string().parse().unwrap();
        assert_eq!(a, a3);
    }

    #[cfg(any(unix, windows))]
    #[test]
    fn test_paths() {
        use std::path::PathBuf;

        let path = PathBuf::from("foo");
        let v = path.to_variant();
        assert_eq!(PathBuf::from_variant(&v), Some(path));
    }
}