File: gvariant_ref.h

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (2066 lines) | stat: -rw-r--r-- 74,145 bytes parent folder | download | duplicates (3)
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
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef REMOTING_HOST_LINUX_GVARIANT_REF_H_
#define REMOTING_HOST_LINUX_GVARIANT_REF_H_

#include <glib-object.h>
#include <glib.h>
#include <glibconfig.h>

#include <algorithm>
#include <array>
#include <compare>
#include <concepts>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <iterator>
#include <map>
#include <optional>
#include <ranges>
#include <string>
#include <string_view>
#include <tuple>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>

#include "base/check.h"
#include "base/check_op.h"
#include "base/compiler_specific.h"
#include "base/location.h"
#include "base/strings/strcat.h"
#include "base/strings/stringprintf.h"
#include "base/types/expected.h"
#include "remoting/host/base/loggable.h"
#include "remoting/host/base/pointer_utils.h"
#include "remoting/host/linux/gvariant_type.h"

// Provides a scoped wrapper, GVariantRef, around a GLib Variant to handle
// reference counting, conversion to and from other C++ types, and additional
// convenience methods when the GVariant's type is statically known.
//
// A good familiarity with the GVariant type system is recommended to use or
// read this code: https://docs.gtk.org/glib/struct.VariantType.html

namespace remoting {
namespace gvariant {

// A GVariantRef is a wrapper around a GLib Variant that handles scoped
// reference counting and convenient, typesafe conversion between GVariants and
// standard types.
//
// GVariants are logically immutable once created, and this class's only data
// member is a reference-counted pointer. Thus, instances can be copied and
// passed around cheaply.
//
// Sample usage:
//
// Creating a GVariantRef:
//
//     // Creates a GVariantRef with a compile-time type of "*" (can hold any
//     // value) and initialize it with a value of type "as" (array of strings)
//     // constructed from the provided span.
//     GVariantRef<> variant =
//         GVariantRef<>::From(base::span{{"Bob", "Sally", "Alice"}});
//
// If a type string is provided as a template argument, the GVariantRef may only
// hold values that match that type string, which may be indefinite. E.g., a
// GVariantRef<"s"> may only strings, while a GVariantRef<"{?*}"> may hold any
// dictionary entry. The type may be narrowed using TryFrom:
//
//     GVariantRef<> variant = ...;
//     // expectedVariant will be a base::expected with either the requested
//     // GVariantRef or an error message suitable for logging.
//     auto expectedVariant = GVariantRef<"as">::TryFrom(variant);
//     if (expectedVariant.has_value()) {
//         // expectedVariant.value() is guaranteed to be an array of strings
//         // and can be iterated through, infalibly converted to a
//         // std::vector<std::string>, passed to functions expected GVariantRef
//         // arrays, et cetera.
//     }
//
// Conversion can combine narrowing and converting from C++ types:
//
//     std::tuple<GVariantRef<>> tuple = ...;
//     auto expectedVariant = GVariantRef<"(s)">::TryFrom(tuple);
//
// Getting values from a GVariantRef:
//
//     GVariantRef<> variant = ...;
//     // Returns a base::expected with the value or an error message.
//     auto value = result.TryInto<std::vector<std::string>>();
//
// If the requested conversion is valid for all values of the GVariantRef's
// static type, you can use Into instead to get the value directly:
//
//     GVariantRef<"s"> variant = ...;
//     std::string value = variant.Into<std::string>();
//
// Like TryFrom, TryInto can also be used to attempt to narrow a GVariantRef's
// static type, and can be combined with conversions to C++ types:
//
//     GVariantRef<> variant = ...;  // Compile-time type string is "*";
//     // Value will be returned if variant's run-time type is a subtype of
//     // "a(s*)". Otherwise, an error string will be returned.
//     auto result2 = variant.TryInto<std::vector<GVariantRef<"(s*)">>>();
//
// If the GVariantRef is known to be a container (that is, it's static type is
// a boxed value, an array, a maybe value, a tuple, or a dictionary entry), it
// can be used with range-based for:
//
//     GVariantRef<"a(iu)"> variant1 = ...;
//     for (auto item : variant1) { /* item is a GVariantRef<"(iu)"> */}
//     GVariantRef<"r"> variant2 = ...;
//     for (auto item : variant1) { /* item is a GVariantRef<"*"> */}
//
// If it is known to be a container of a fixed size (boxed value, fixed-size
// tuple (not "r"), or dictionary entry), it can be used with structured
// binding:
//
//     GVariantRef<"(uba{sv})"> variant = ...;
//     // Yields GVariantRef<"u">, GVariantRef<"b">, and GVariantRef<"a{sv}">
//     auto [first, second, third] = variant;
//
// For convenience, GVariantRefs known to be a dictionary type (the compile-time
// type string is a subtype of "a{?*}") provide a LookUp() method to find the
// first value with a matching key.
//
//     GVariantRef<"a{is}"> variant = ...;
//     std::optional<GVariantRef<"s">> value = variant.LookUp(5);
//
// Finally, values can be extracted from containers using Destructure() and
// TryDestructure(). Destructure requires a known fixed-size container, while
// TryDestructure checks if the GVariantRef holds a matching container at
// runtime.
//
//     GVariantRef<"(ii(ssssv))"> variant = ...;
//     std::uint32_t i1, i2;
//     std::string s1, s2, s3, s4;
//     GVariantRef<> v;
//     // Inner containers can be unpacked by passing (possibly nested) tuples
//     // of lvalue references.
//     variant.Destructure(i1, i2, std::forward_as_tuple(s1, s2, s3, s4,
//                                                       std::tie(v)));
//
//     GVariantRef<"mb"> variant = ...;
//     bool b;
//     // result will contain an error if the maybe value is unexpectedly empty.
//     base::expected<void, Loggable> result = variant.TryDestructure(b);
//
// Access to the underlying GVariant pointer can be obtained via raw() and
// release(). A GVariantRef can be created from a raw GVariant pointer via
// Ref(), RefSink(), and Take().
//
// For convenience, the GVariantRef class is exported to the remoting namespace.
//
// This header provides conversions to and from the following types. Additional
// support for additional types can be added by providing an appropriate
// specialization of gvariant::Mapping<T>.
//
// Basic fixed types:
//
// bool (type code "b")
// std::uint8_t (type code "y")
// std::int16_t (type code "n")
// std::uint16_t (type code "q")
// std::int32_t (type code "i")
// std::uint32_t (type code "u")
// std::int64_t (type code "x")
// std::uint64_t (type code "t")
// double (type code "d")
//
// Strings:
//
// std::string (type code "s")
// const char * ([Try]From() only, type code "s")
// std::string_view ([Try]From() only, type code "s")
//
// Note: Strings must be valid UTF-8. For convenience, both From() and TryFrom()
// are provided. If the string (or all strings in an aggregate type) are
// known to be valid UTF-8, From() may be used. Otherwise TryFrom() should be
// used. Calling From() with a string containing invalid UTF-8 will
// result in a crash.
//
// Containers:
//
// std::optional<T> (type code "mT") - To use with From(), the type string of T
//     must be definite. E.g., it may not contain an unboxed heterogeneous
//     std::variant or unconstrained GVariantRef. Otherwise, TryFrom() must be
//     used. Alternatively, GVariantRef::FilledMaybe can be used for indefinite
//     types that will never actually be absent. Note that maybe values are not
//     currently supported by D-Bus.
// std::vector<T> (type code "aT") - To use with From(), the type string of T
//     must be definite. Otherwise, TryFrom() must be used.
// std::map<K, T> (type code "a{KT}") - To use with From(), the type string of K
//     and T must be definite. Otherwise, TryFrom() must be used.
// std::pair<K, T> (type code "{KT}")
// std::ranges::range<T> ([Try]From() only, type code "aE" where
//     E = std::ranges::range_value_t<T>) - The type string of T must be
//     definite to use with From(). Otherwise, TryFrom() must be used.
// std::tuple<...> (type code "(...)")
// std::variant<...> (type code "S", where S is the narrowest common supertype
//     of all of the variant alternatives) - Despite the name, when used with
//     From(), the type will be the type of the active variant, not "v". If the
//     type should be "v", use a gvariant::Boxed<std::variant<...>>. When used
//     with [Try]Into(), each variant alternative will be
//     tried in turn until one succeeds or all are exhausted. Similarly to
//     From(), if the type in the GVariant is expected to be "v" rather than a
//     concrete type, use with gvariant::Boxed. From() and TryFrom() are
//     provided if all of the alternatives provide the respected method.
//     TryInto() is provided if provided by any of the alternatives. Into() is
//     provided if the GVariantRef at hand can be infallibly converted to any
//     of the variant's alternatives. E.g., the following is valid:
//
//         GVariantRef<"i"> gvariant = ...;
//         auto v = gvariant.Into<std::variant<std::int32, bool>>();
//
// Special types:
//
// GVariantRef<C> (type code "C") - GVariantRef can itself be used with
//     [Try]From() or [Try]Into(). This can be used to widen or narrow the
//     type or to hold inner values as nested GVariants. Like with
//     std::variant, the type of the GVariantRef is used directly. If the
//     expected/desired type is "v", wrap it in a gvariant::Boxed.
// gvariant::Ignored ([Try]Into() only, type code "*") - Discard the value at
//     this position instead of decoding it.
// decltype(std::ignore) - Same as gvariant::Ignored. Allows passing std::ignore
//     to [Try]Destructure().
// gvariant::Boxed<T> (type code "v") - Wrapper for a value that appears boxed
//     inside a nested variant, rather than directly. A Boxed<T> is definite
//     regardless of whether the contained type is. Provides [Try]From() and
//     [Try]Into() if the inner type provides them for GVariantRef<"*">.
// gvariant::FilledMaybe<T> (type code "mT") - Wrapper for a value that
//     appears inside a maybe, but will always be present. Presence of
//     [Try]From() and TryInto() mirror the inner type. Into() is never
//     provided.
// gvariant::EmptyArrayOf<C> (type code "aC") - Represents an empty array of
//     the type C, which should be an instance of GVariantRef::Type. C must be
//     definite to use with [Try]From(). Into() is never provided; TryInto()
//     must be used to check if the array is, in fact, empty.
// gvariant::ObjectPath (type code "o") - Wrapper around a std::string that
//     contains a DBus object path.
// gvariant::ObjectPathCStr ([Try]From() only, type code "o") - An owned object
//     path that can be used as a function parameter (somewhat analogous to a
//     string_view) or to hold a compile-time-verified object path constant.
// gvariant::TypeSignature (type code "g") - Wrapper around a std::string
//     that contains a DBus type signature.
// gvariant::TypeSignatureCStr ([Try]From() only, type code "g") - An owned type
//     signature that can be used as a function parameter (somewhat analogous to
//     a string_view) or to hold a compile-time-verified type signature
//     constant.
//
// Convenience functions:
//
// GVariantFrom(value) - Like GVariantRef<C>::From(), but infers C from value's
//     type.
// gvariant::BoxedRef(value) - Returns a gvariant::Boxed that holds a const
//     reference to value. (Whereas Boxed{value} would hold a copy of value.)
// gvariant::FilledMaybeRef(value) - Returns a gvariant::FilledMaybe that holds
//     a const reference to value. (Whereas FilledMaybe{value} would hold a copy
//     of value.)
template <Type C = Type("*")>
class GVariantRef;

// A struct specialized for each type supporting conversion to or from a
// GVariant.
//
// All specializations must provide a kType field, which should be in the form
// of a static constexpr Type. If the exact type can only be determined at
// runtime, an indefinite type can be used (e.g., "*").
//
//     static constexpr Type kType{"i"};
//
// A given type may support conversion to a GVariant, from a GVariant, or
// both. An example of a type that only supports conversion to a GVariant is
// a C-style string (const char *). An example of a type that only supports
// conversion from a GVariant is GVariantRef::Ignored.
//
// To support conversion to a GVariant, the specialization should provide a
// static From or TryFrom method that takes a value of the type and returns a
// GVariantRef<kType>, e.g.,
//
//     static GVariantRef<kType> From(const T&);
//     static base::expected<GVariantRef<kType>, Loggable> TryFrom(const T&);
//
// Usually a specialization will provide one or the other.
//
// To support conversion from a GVariant, the specialization should provide a
// static Into or TryInto method that takes a GVariantRef<kType> and returns a
// value of the type, e.g.,
//
//     static T Into(const GVariantRef<kType>&);
//     static base::expected<T, Loggable> TryInto(const GVariantRef<kType>&);
//
// Usually a specialization will provide one or the other, with one exception:
// In the event that infallible conversion is possible for only some subtypes of
// kType, Into may be specified only for those subtypes. In that case, TryInto
// must also be specified. E.g., if a conversion can take an int or a string,
// the definition might look like this:
//
//     static constexpr Type kType{"?"};
//     static base::expected<T, Loggable> TryInto(const GVariantRef<kType>&);
//     static T Into(const GVariantRef<"i">&);
//     static T Into(const GVariantRef<"s">&);
//
// In the event a Try* conversion fails, the method should return an error
// string suitable for inclusion in a log message.
template <typename T>
struct Mapping;

// Common members of all GVariantRefs.
class GVariantBase {
 public:
  // Allows creating an owned reference given a reference to GVariantBase.
  explicit operator GVariantRef<>() const;

  // Returns the inner GVariant reference without incrementing the count. It is
  // the caller's responsibility to increment the ref count if it is to be held
  // longer than the containing remoting::GVariant instance. Otherwise, the
  // caller should not call unref on it.
  GVariant* raw() const;

  // Takes owneriship of the inner GVariant, leaving this in a moved-from state.
  // It is the caller's responsibility to call unref when they are done with it.
  [[nodiscard]] GVariant* release() &&;

  // Returns the type of the value currently held in the GVariant. Will always
  // be definite.
  Type<> GetType() const;

  friend bool operator==(const GVariantBase& lhs, const GVariantBase& rhs);

 protected:
  using GVariantPtr = CRefCounted<GVariant,
                                  g_variant_ref,
                                  g_variant_unref,
                                  g_variant_take_ref,
                                  g_variant_ref_sink>;

  GVariantBase();
  explicit GVariantBase(GVariantPtr variant);
  GVariantBase(const GVariantBase& other);
  GVariantBase(GVariantBase&& other);
  GVariantBase& operator=(const GVariantBase& other);
  GVariantBase& operator=(GVariantBase&& other);
  ~GVariantBase();

 private:
  GVariantPtr variant_;
};

bool operator==(const GVariantBase& lhs, const GVariantBase& rhs);

template <Type C>
class GVariantRef : public GVariantBase {
 public:
  static constexpr auto kType = C;

  // Default constructor constructs an empty GVariantRef in the same state as
  // one that has been moved from. No operations are valid until a value has
  // been assigned.
  GVariantRef() = default;

  // Copyable and movable. Copies are cheap, only bumping the reference count.
  // The only valid operations for a moved-from instance are dropping it and
  // assigning a new value.
  GVariantRef(const GVariantRef& other) = default;
  GVariantRef(GVariantRef&& other) = default;
  GVariantRef& operator=(const GVariantRef& other) = default;
  GVariantRef& operator=(GVariantRef&& other) = default;
  ~GVariantRef() = default;

  // Allow implicit conversion from subtype to supertype.
  template <Type D>
  // NOLINTNEXTLINE(google-explicit-constructor)
  GVariantRef(const GVariantRef<D>& other)
    requires(D.IsSubtypeOf(C));

  template <Type D>
  // NOLINTNEXTLINE(google-explicit-constructor)
  GVariantRef(GVariantRef<D>&& other)
    requires(D.IsSubtypeOf(C));

  // Type conversions

  // Constructs a new GVariantRef from the provided value.
  template <typename T>
  static GVariantRef From(const T& value)
    requires(Mapping<T>::kType.IsSubtypeOf(C) &&
             requires { Mapping<T>::From(value); });

  // Constructs a new GVariantRef from the provided value, if possible.
  template <typename T>
  static base::expected<GVariantRef, Loggable> TryFrom(const T& value)
    requires(Mapping<T>::kType.HasCommonTypeWith(C) &&
             (requires { Mapping<T>::TryFrom(value); } ||
              requires { Mapping<T>::From(value); }));

  // Builds a value of the provided type from the contents of the GVariant.
  // Calls will only compile if they are guaranteed to succeed at runtime.
  template <typename T>
  T Into() const
    requires(C.IsSubtypeOf(Mapping<T>::kType) &&
             requires { Mapping<T>::Into(*this); });

  // Builds a value of the provided type from the contents of the GVariant, if
  // possible. Fails to compile if the conversion can statically be determined
  // never to succeed.
  template <typename T>
  base::expected<T, Loggable> TryInto() const
    requires(C.HasCommonTypeWith(Mapping<T>::kType) &&
             (requires(GVariantRef<Mapping<T>::kType> v) {
                Mapping<T>::TryInto(v);
              } ||
              requires(GVariantRef<Mapping<T>::kType> v) {
                Mapping<T>::Into(v);
              }));

  // Unpacks a container GVariant into lvalue references. The GVariant must be a
  // boxed value, a tuple, or a dictionary entry. Each argument must be a lvalue
  // reference or a tuple to unpack a nested container. Each tuple should
  // similarly consist of lvalue references and tuples. std::tie and
  // std::forward_as_tuple can be useful for constructing such tuples. Calls to
  // Destructure will only compile if it can be guaranteed at compile time that
  // the operation will succeed.
  template <typename... Types>
  void Destructure(Types&&... refs) const;

  // As above, but allows conversions that could fail at runtime. The GVariant
  // must be a boxed value, a maybe value, a tuple, an array, or a dictionary
  // entry. If the types or number of values don't match at runtime, an error
  // message will be returned. In this case, the reference lvalues will be in an
  // indeterminate state, as some values may have been read prior to the error
  // occurring.
  template <typename... Types>
  base::expected<void, Loggable> TryDestructure(Types&&... refs) const;

  // Iterate through the values of a container GVariant. The value type will be
  // GVariant<TypeBase::ContainedType(C)>.
  auto begin() const
    requires(C.IsContainer());
  auto end() const
    requires(C.IsContainer());
  std::size_t size() const
    requires(C.IsContainer());

  // Get the Ith element from a fixed-size container GVariant. Specializations
  // of std::tuple_size and std::tuple_element are also provided to make fixed-
  // size container GVariants tuple-like.
  template <std::size_t I>
  auto get() const
    requires(C.IsFixedSizeContainer());

  // Look up the provided key in a dictionary GVariant. The provided argument
  // must be convertible to the key type via TryFrom. Returns a
  // std::optional<GVariantRef<[value type]>> containing the found value, or
  // nullopt if the key was not found. Note that this performs a linear search
  // through the dictionary. If the dictionary is large and many lookups will be
  // performed, it might be more efficient to convert to a std::map or another
  // datastructure first.
  template <typename T>
  auto LookUp(const T& key)
    requires(C.IsSubtypeOf(Type("a{?*}")) && requires {
      decltype((*begin()).template get<0>())::TryFrom(key);
    });

  // Access the contained string without copying. C must be "s", "o", or "g".
  std::string_view string_view() const
    requires(C.IsStringType());

  // Access the contained string without copying. C must be "s", "o", or "g".
  const char* c_string() const
    requires(C.IsStringType());

  // Create from a raw GVariant*. Can only be used with GVariantRef<Type("*")>.
  // To get a narrower GVariantRef, first create one with "*" and then use
  // TryInto (or TryFrom) to convert to the narrower type.

  // Takes ownership of the reference. If it is floating, it will be sunk. May
  // not be null.
  //
  // This is the right method to call with a floating or caller-owned
  // GVariant* when one wants to pass ownership to the new GVariantRef. Most
  // GLib functions returning a GVariant* will return either a floating
  // reference (e.g., `g_variant_new`) or a caller owned reference (e.g.,
  // `get_child_value`), making their return value suitable to be passed to this
  // method (after checking for null, if the function is falible).
  static GVariantRef Take(GVariant* variant)
    requires(C == Type("*"));

  // Takes a new reference unconditionally. If object is floating, it will
  // remain so. May not be null.
  //
  // This is the right method to call with a borrowed GVariant* (such as is
  // returned by `raw()` or might be owned by a different class/struct) or a
  // caller-owned GVariant* of which the caller wants to maintain ownership.
  static GVariantRef Ref(GVariant* variant)
    requires(C == Type("*"));

  // If the reference count is floating, takes ownership and sinks it.
  // Otherwise, takes a new reference. May not be null.
  //
  // This is usually the right method to call with a GVariant* that was passed
  // into the caller as an argument. That gives the caller's caller the
  // flexibility to pass in either a newly-constructed GVariant (in which case
  // the reference will be floating, and GVariantRef will take ownership) or an
  // existing GVariant* (in which case GVariantRef will take its own reference).
  static GVariantRef RefSink(GVariant* variant)
    requires(C == Type("*"));

  // Same as above, but can be used with any GVariantRef type. The caller must
  // ensure the passed pointer is actually of the appropriate type. Passing a
  // pointer that does not match C can result in undefined behavior.
  static GVariantRef TakeUnchecked(GVariant* variant);
  static GVariantRef RefUnchecked(GVariant* variant);
  static GVariantRef RefSinkUnchecked(GVariant* variant);

 private:
  using GVariantBase::GVariantBase;
};

// Constructs a new GVariantRef from the provided value, inferring the type
// string.
template <typename T>
static GVariantRef<Mapping<T>::kType> GVariantFrom(const T& value) {
  return GVariantRef<Mapping<T>::kType>::From(value);
}

// Wrapper types and special types

// Can be used as a nested type in a call to [Try]Into() as a placeholder for a
// value the caller isn't interested in.
struct Ignored {};

// Wrapper for a value to specify that it will appear in the GVariant "boxed".
// That is, as a nested variant (type "v") holding the value, rather than the
// value directly.
template <typename T>
struct Boxed {
  T value;
};

template <typename T, typename U>
bool operator==(const Boxed<T>& lhs, const Boxed<U>& rhs)
  requires requires(T t, U u) { t == u; }
{
  return lhs.value == rhs.value;
}

// Returns a gvariant::Boxed that holds a const reference to value. (Whereas
// Boxed{value} would hold a copy of value.) Useful to avoid making an extra
// copy when constructing a GVariantRef.
template <typename T>
Boxed<const T&> BoxedRef(const T& value LIFETIME_BOUND) {
  return {value};
}

// Wrapper for a value that should appear inside a maybe, but will always be
// present.
template <typename T>
struct FilledMaybe {
  T value;
};

template <typename T, typename U>
bool operator==(const FilledMaybe<T>& lhs, const FilledMaybe<U>& rhs)
  requires requires(T t, U u) { t == u; }
{
  return lhs.value == rhs.value;
}

// Returns a gvariant::FilledMaybe that holds a const reference to value.
// (Whereas FilledMaybe{value} would hold a copy of value.) Useful to avoid
// making an extra copy when constructing a GVariantRef.
template <typename T>
FilledMaybe<const T&> FilledMaybeRef(const T& value LIFETIME_BOUND) {
  return {value};
}

// Represents an empty array of the given type.
template <Type C>
struct EmptyArrayOf {};

class ObjectPath;

// Holds an unowned pointer to a null-terminated string known to be a valid
// D-Bus object path.
class ObjectPathCStr {
 public:
  // Constructs from a compile-time constant. The passed string is checked at
  // compile time to be a valid object path.
  // Allows implicit construction so string constants can easily be passed to
  // ObjectPathCStr parameters.
  // NOLINTNEXTLINE(google-explicit-constructor)
  consteval ObjectPathCStr(const char* path);
  // Constructs from an ObjectPath object. The resulting ObjectPathCStr is only
  // valid as long as the ObjectPath to which it refers.
  // Allows explicit construction so ObjectPaths can easily be passed to
  // ObjectPathCStr parameters.
  // NOLINTNEXTLINE(google-explicit-constructor)
  ObjectPathCStr(const ObjectPath& path LIFETIME_BOUND);

  // Attempts to construct from an existing C string. Returns an error string
  // if |path| is not a valid object path.
  static base::expected<ObjectPathCStr, Loggable> TryFrom(
      const char* path LIFETIME_BOUND);

  // Gets the object path C string.
  constexpr const char* c_str() const LIFETIME_BOUND;

  friend constexpr bool operator==(const ObjectPathCStr& lhs,
                                   const ObjectPathCStr& rhs);

 private:
  struct Checked {};
  // Construct from already-checked path. Extra parameter to avoid conflicting
  // with consteval constructor.
  ObjectPathCStr(const char* path LIFETIME_BOUND, Checked);

  const char* path_;
};

constexpr bool operator==(const ObjectPathCStr& lhs, const ObjectPathCStr& rhs);

// Represents an owned D-Bus object path.
class ObjectPath {
 public:
  // Constructs an instance of the root path "/"
  ObjectPath();

  // Constructs an owned copy of |path|.
  explicit ObjectPath(ObjectPathCStr path);

  // Attempts to construct from an existing std::string. Returns an error string
  // if |path| is not a valid object path.
  static base::expected<ObjectPath, Loggable> TryFrom(std::string path);

  // Gets the object path.
  const std::string& value() const LIFETIME_BOUND;

  // Shorthand for .value().c_str()
  const char* c_str() const LIFETIME_BOUND;

 private:
  // Construct from already-checked path.
  explicit ObjectPath(std::string path);
  std::string path_;
  friend struct Mapping<ObjectPath>;
};

class TypeSignature;

// Holds an unowned pointer to a null-terminated string known to be a valid
// D-Bus type signature.
class TypeSignatureCStr {
 public:
  // Constructs from a compile-time constant. The passed string is checked at
  // compile time to be a valid type signature.
  // Allows implicit construction so string constants can easily be passed to
  // TypeSignatureCStr parameters.
  // NOLINTNEXTLINE(google-explicit-constructor)
  consteval TypeSignatureCStr(const char* signature);

  // Constructs from a TypeSignature object. The resulting TypeSignatureCStr is
  // only valid as long as the TypeSignature to which it refers.
  // Allows implicit construction so TypeSignatures can easily be passed to
  // TypeSignatureCStr parameters.
  // NOLINTNEXTLINE(google-explicit-constructor)
  TypeSignatureCStr(const TypeSignature& signature LIFETIME_BOUND);

  // Attempts to construct from an existing C string. Returns an error if
  // |signature| is not a valid type signature.
  static base::expected<TypeSignatureCStr, Loggable> TryFrom(
      const char* signature LIFETIME_BOUND);

  // Gets the type signature C string.
  constexpr const char* c_str() const LIFETIME_BOUND;

  friend constexpr bool operator==(const TypeSignatureCStr& lhs,
                                   const TypeSignatureCStr& rhs);

 private:
  struct Checked {};
  // Construct from already-checked path. Extra parameter to avoid conflicting
  // with consteval constructor.
  TypeSignatureCStr(const char* signature LIFETIME_BOUND, Checked);

  const char* signature_;
};

constexpr bool operator==(const TypeSignatureCStr& lhs,
                          const TypeSignatureCStr& rhs);

// Represents an owned D-Bus type signature.
class TypeSignature {
 public:
  // Constructs an empty type signature.
  TypeSignature();

  // Constructs an owned copy of |signature|.
  explicit TypeSignature(TypeSignatureCStr signature);

  // Attempts to construct from an existing std::string. Returns an error if
  // |signature| is not a valid type signature.
  static base::expected<TypeSignature, Loggable> TryFrom(std::string signature);

  // Gets the type signature.
  const std::string& value() const LIFETIME_BOUND;

  // Shorthand for .value().c_str()
  const char* c_str() const LIFETIME_BOUND;

 private:
  // Construct from already-checked signature.
  explicit TypeSignature(std::string);
  std::string signature_;
  friend struct Mapping<TypeSignature>;
};

// Iterator type for a container GVariant
template <Type C>
class Iterator;

template <Type C>
Iterator<C> operator+(std::ptrdiff_t n, const Iterator<C>& iter);

template <Type C>
class Iterator {
 public:
  Iterator() = default;
  // Copyable and movable
  Iterator(const Iterator& other) = default;
  Iterator(Iterator&& other) = default;
  Iterator& operator=(const Iterator& other) = default;
  Iterator& operator=(Iterator&& other) = default;

  // Iterator interface

  // LegacyForwardIterator requires reference_type be &value_type or
  // const &value_type, so this implementation is only a LegacyInputIterator.
  using iterator_category = std::input_iterator_tag;

  // The std::forward_iterator and higher concepts impose no such requirement,
  // so this can be a full random-access iterator.
  using iterator_concept = std::random_access_iterator_tag;

  using value_type = GVariantRef<C>;
  using reference_type = GVariantRef<C>;
  using difference_type = std::ptrdiff_t;

  // input iterator
  value_type operator*() const;
  Iterator& operator++();
  Iterator operator++(int);

  // forward iterator
  bool operator==(const Iterator& other) const;

  // bidirectional iterator
  Iterator& operator--();
  Iterator operator--(int);

  // random access iterator
  std::partial_ordering operator<=>(const Iterator& other) const;
  difference_type operator-(const Iterator& other) const;
  Iterator operator+(difference_type n) const;
  friend Iterator operator+ <C>(difference_type n, const Iterator& iter);
  Iterator operator-(difference_type n) const;
  Iterator& operator+=(difference_type n);
  Iterator& operator-=(difference_type n);
  value_type operator[](difference_type i) const;

 private:
  Iterator(GVariantRef<> variant, std::size_t i);
  std::size_t i_ = 0;
  GVariantRef<> variant_;

  template <Type D>
  friend class GVariantRef;
};

// GVariantRef implementation

template <Type C>
template <Type D>
GVariantRef<C>::GVariantRef(const GVariantRef<D>& other)
  requires(D.IsSubtypeOf(C))
    : GVariantBase(other) {}

template <Type C>
template <Type D>
GVariantRef<C>::GVariantRef(GVariantRef<D>&& other)
  requires(D.IsSubtypeOf(C))
    : GVariantBase(std::move(other)) {}

// static
template <Type C>
template <typename T>
GVariantRef<C> GVariantRef<C>::From(const T& value)
  requires(Mapping<T>::kType.IsSubtypeOf(C) &&
           requires { Mapping<T>::From(value); })
{
  return Mapping<T>::From(value);
}

// static
template <Type C>
template <typename T>
base::expected<GVariantRef<C>, Loggable> GVariantRef<C>::TryFrom(
    const T& value)
  requires(Mapping<T>::kType.HasCommonTypeWith(C) &&
           (requires { Mapping<T>::TryFrom(value); } ||
            requires { Mapping<T>::From(value); }))
{
  if constexpr (requires { Mapping<T>::TryFrom(value); }) {
    return Mapping<T>::TryFrom(value).and_then(
        [](auto value) { return value.template TryInto<GVariantRef>(); });
  } else {
    return Mapping<T>::From(value).template TryInto<GVariantRef>();
  }
}

template <Type C>
template <typename T>
T GVariantRef<C>::Into() const
  requires(C.IsSubtypeOf(Mapping<T>::kType) &&
           requires { Mapping<T>::Into(*this); })
{
  return Mapping<T>::Into(*this);
}

template <Type C>
template <typename T>
base::expected<T, Loggable> GVariantRef<C>::TryInto() const
  requires(C.HasCommonTypeWith(Mapping<T>::kType) &&
           (requires(GVariantRef<Mapping<T>::kType> v) {
              Mapping<T>::TryInto(v);
            } ||
            requires(GVariantRef<Mapping<T>::kType> v) {
              Mapping<T>::Into(v);
            }))
{
  if constexpr (!C.IsSubtypeOf(Mapping<T>::kType)) {
    if (GetType().IsSubtypeOf(Mapping<T>::kType)) {
      return GVariantRef<Mapping<T>::kType>::RefUnchecked(raw())
          .template TryInto<T>();
    } else {
      return base::unexpected(Loggable(
          FROM_HERE,
          base::StrCat({"Expected type: ", Mapping<T>::kType.string_view(),
                        " Found: ", GetType().string_view()})));
    }
  } else if constexpr (requires { Mapping<T>::TryInto(*this); }) {
    return Mapping<T>::TryInto(*this);
  } else {
    return base::ok(Mapping<T>::Into(*this));
  }
}

template <Type C>
template <typename... Types>
void GVariantRef<C>::Destructure(Types&&... refs) const {
  static_assert((... && (std::is_lvalue_reference_v<Types> ||
                         requires { std::tuple_size_v<Types>; })));
  constexpr auto contained_types = TypeBase::Unpack<C>();
  static_assert(std::tuple_size_v<decltype(contained_types)> == sizeof...(refs),
                "Incorrect number of elements.");
  [&]<std::size_t... Is>(std::index_sequence<Is...>) {
    (
        [&]() {
          auto inner_variant =
              GVariantRef<std::get<Is>(contained_types)>::TakeUnchecked(
                  g_variant_get_child_value(raw(), Is));
          if constexpr (std::is_lvalue_reference_v<Types>) {
            refs =
                inner_variant.template Into<std::remove_reference_t<Types>>();
          } else {
            std::apply(
                [&]<typename... Ts>(Ts&&... subref) {
                  return inner_variant.Destructure(std::forward<Ts>(subref)...);
                },
                std::forward<Types>(refs));
          }
        }(),
        ...);
  }(std::index_sequence_for<Types...>());
}

template <Type C>
template <typename... Types>
base::expected<void, Loggable> GVariantRef<C>::TryDestructure(
    Types&&... refs) const {
  static_assert((... && (std::is_lvalue_reference_v<Types> ||
                         requires { std::tuple_size_v<Types>; })));

  if (!g_variant_is_container(raw())) {
    return base::unexpected(
        Loggable(FROM_HERE, "Destructured GVariant is not a container."));
  }

  if (std::size_t size = g_variant_n_children(raw()); size != sizeof...(refs)) {
    return base::unexpected(Loggable(
        FROM_HERE, base::StringPrintf(
                       "Incorrect number of elements. Expected: %zd Found: %zd",
                       sizeof...(refs), size)));
  }

  base::expected<void, Loggable> result;

  [&]<std::size_t... Is>(std::index_sequence<Is...>) {
    ([&]() {
      GVariantRef<> inner_variant =
          GVariantRef<>::Take(g_variant_get_child_value(raw(), Is));
      if constexpr (std::is_lvalue_reference_v<Types>) {
        auto value = inner_variant.TryInto<std::remove_reference_t<Types>>();
        if (!value.has_value()) {
          result = std::move(value).error().UnexpectedWithContext(
              FROM_HERE, "While destructuring container");
          return false;
        }
        refs = value.value();
      } else {
        auto nested_result = std::apply(
            [&]<typename... Ts>(Ts&&... subref) {
              return inner_variant.TryDestructure(std::forward<Ts>(subref)...);
            },
            std::forward<Types>(refs));
        if (!nested_result.has_value()) {
          result = std::move(nested_result);
          return false;
        }
      }
      return true;
    }() &&
     ...);
  }(std::index_sequence_for<Types...>());

  return result;
}

template <Type C>
auto GVariantRef<C>::begin() const
  requires(C.IsContainer())
{
  return Iterator<TypeBase::ContainedType<C>()>(*this, 0);
}

template <Type C>
auto GVariantRef<C>::end() const
  requires(C.IsContainer())
{
  return Iterator<TypeBase::ContainedType<C>()>(*this,
                                                g_variant_n_children(raw()));
}

template <Type C>
std::size_t GVariantRef<C>::size() const
  requires(C.IsContainer())
{
  return g_variant_n_children(raw());
}

template <Type C>
template <std::size_t I>
auto GVariantRef<C>::get() const
  requires(C.IsFixedSizeContainer())
{
  return GVariantRef<std::get<I>(TypeBase::Unpack<C>())>::TakeUnchecked(
      g_variant_get_child_value(raw(), I));
}

// Define free version as well for generic code that calls get(tuple_like) using
// argument-dependent lookup.
template <std::size_t I, Type C>
  requires(C.IsFixedSizeContainer())
auto get(const GVariantRef<C>& variant) {
  return variant.template get<I>();
}

template <Type C>
template <typename T>
auto GVariantRef<C>::LookUp(const T& needle)
  requires(C.IsSubtypeOf(Type("a{?*}")) &&
           requires {
             decltype((*begin()).template get<0>())::TryFrom(needle);
           })
{
  using KeyType = decltype((*begin()).template get<0>());
  using ValueType = decltype((*begin()).template get<1>());
  auto needle_variant = KeyType::TryFrom(needle);
  if (!needle_variant.has_value()) {
    // If the value is something that can't be converted to a GVariant (e.g.,
    // a non-UTF-8 string), it's probably safe to say it's not in the
    // dictionary.
    return std::optional<ValueType>();
  }
  for (auto [key, value] : *this) {
    if (key == needle_variant.value()) {
      return std::optional<ValueType>(std::move(value));
    }
  }
  return std::optional<ValueType>();
}

template <Type C>
std::string_view GVariantRef<C>::string_view() const
  requires(C.IsStringType())
{
  gsize length;
  const char* string = g_variant_get_string(raw(), &length);
  return std::string_view(string, length);
}

template <Type C>
const char* GVariantRef<C>::c_string() const
  requires(C.IsStringType())
{
  return g_variant_get_string(raw(), nullptr);
}

// static
template <Type C>
GVariantRef<C> GVariantRef<C>::TakeUnchecked(GVariant* variant) {
  DCHECK(g_variant_is_of_type(variant, C.gvariant_type()));
  return GVariantRef<C>(GVariantPtr::Take(variant));
}

// static
template <Type C>
GVariantRef<C> GVariantRef<C>::RefUnchecked(GVariant* variant) {
  DCHECK(g_variant_is_of_type(variant, C.gvariant_type()));
  return GVariantRef<C>(GVariantPtr::Ref(variant));
}

// static
template <Type C>
GVariantRef<C> GVariantRef<C>::RefSinkUnchecked(GVariant* variant) {
  DCHECK(g_variant_is_of_type(variant, C.gvariant_type()));
  return GVariantRef<C>(GVariantPtr::RefSink(variant));
}

// Wrapper implementation

consteval ObjectPathCStr::ObjectPathCStr(const char* path) {
  // SAFETY: Since this constructor is consteval, it can only execute at compile
  // time. Thus, a read past the end triggered by a missing null terminator will
  // result in a compile-time error, with no risk at runtime.

  // TODO: bug 400761089 - Remove UNSAFE_BUFFERS annotations when Clang no
  // longer flags consteval code.

  // CHECKs cannot actually print messages at compile time, but a failed check
  // will trigger a compiler error pointing to the failed check, allowing the
  // message to be seen in the source code.
  CHECK_EQ(*path, '/') << "Path must start with a '/'";
  const char* prev_char = path;
  const char* current_char = UNSAFE_BUFFERS(path + 1);
  while (*current_char != '\0') {
    CHECK((*current_char >= 'A' && *current_char <= 'Z') ||
          (*current_char >= 'a' && *current_char <= 'z') ||
          (*current_char >= '0' && *current_char <= '9') ||
          *current_char == '_' || *current_char == '/')
        << "Path contains invalid character";
    CHECK(*prev_char != '/' || *current_char != '/')
        << "Two '/' characters may not appear in a row";
    UNSAFE_BUFFERS(++prev_char);
    UNSAFE_BUFFERS(++current_char;)
  }
  CHECK(*prev_char != '/' || prev_char == path)
      << "Path may not end in '/' unless the whole path is only a single '/' "
         "referring to the root path";
  path_ = path;
}

constexpr const char* ObjectPathCStr::c_str() const {
  return path_;
}

constexpr bool operator==(const ObjectPathCStr& lhs,
                          const ObjectPathCStr& rhs) {
  if (std::is_constant_evaluated()) {
    return std::string_view(lhs.c_str()) == std::string_view(rhs.c_str());
  } else {
    return UNSAFE_TODO(std::strcmp(lhs.c_str(), rhs.c_str())) == 0;
  }
}

consteval TypeSignatureCStr::TypeSignatureCStr(const char* signature) {
  // SAFETY: Since this constructor is consteval, it can only execute at compile
  // time. Thus, a read past the end triggered by a missing null terminator will
  // result in a compile-time error, with no risk at runtime.

  // TODO: bug 400761089 - Remove UNSAFE_BUFFERS annotations when Clang no
  // longer flags consteval code.

  // CHECKs cannot actually print messages at compile time, but a failed check
  // will trigger a compiler error pointing to the failed check, allowing the
  // message to be seen in the source code.
  CHECK(Type("(", signature, ")").IsValid()) << "Not a valid signature";
  CHECK(Type("(", signature, ")").IsDefinite()) << "Signature must be definite";
  char prev_char = '\0';
  for (const char* current_char = signature; *current_char != '\0';
       UNSAFE_BUFFERS(++current_char)) {
    CHECK(*current_char != 'm') << "Maybe type not valid in D-Bus signature";
    CHECK(*current_char != '{' || prev_char == 'a')
        << "Dict entry not part of a dictionary.";
    prev_char = *current_char;
  }
  signature_ = signature;
}

constexpr const char* TypeSignatureCStr::c_str() const {
  return signature_;
}

constexpr bool operator==(const TypeSignatureCStr& lhs,
                          const TypeSignatureCStr& rhs) {
  if (std::is_constant_evaluated()) {
    return std::string_view(lhs.c_str()) == std::string_view(rhs.c_str());
  } else {
    return UNSAFE_TODO(std::strcmp(lhs.c_str(), rhs.c_str())) == 0;
  }
}

// Iterator implementation

template <Type C>
GVariantRef<C> Iterator<C>::operator*() const {
  return GVariantRef<C>::TakeUnchecked(
      g_variant_get_child_value(variant_.raw(), i_));
}

template <Type C>
Iterator<C>& Iterator<C>::operator++() {
  ++i_;
  return *this;
}

template <Type C>
Iterator<C> Iterator<C>::operator++(int) {
  return Iterator(variant_, i_++);
}

template <Type C>
bool Iterator<C>::operator==(const Iterator& other) const {
  return variant_.raw() == other.variant_.raw() && i_ == other.i_;
}

template <Type C>
Iterator<C>& Iterator<C>::operator--() {
  --i_;
  return *this;
}

template <Type C>
Iterator<C> Iterator<C>::operator--(int) {
  return Iterator(variant_, i_--);
}

template <Type C>
std::partial_ordering Iterator<C>::operator<=>(const Iterator& other) const {
  if (variant_.raw() != other.variant_.raw()) {
    return std::partial_ordering::unordered;
  }
  return i_ <=> other.i_;
}

template <Type C>
std::ptrdiff_t Iterator<C>::operator-(const Iterator& other) const {
  return static_cast<std::ptrdiff_t>(i_) -
         static_cast<std::ptrdiff_t>(other.i_);
}

template <Type C>
Iterator<C> Iterator<C>::operator+(std::ptrdiff_t n) const {
  return Iterator(variant_, static_cast<std::ptrdiff_t>(i_) + n);
}

template <Type C>
Iterator<C> operator+(std::ptrdiff_t n, const Iterator<C>& iter) {
  return Iterator<C>(iter.variant_, n + static_cast<std::ptrdiff_t>(iter.i_));
}

template <Type C>
Iterator<C> Iterator<C>::operator-(std::ptrdiff_t n) const {
  return Iterator(variant_, static_cast<std::ptrdiff_t>(i_) - n);
}

template <Type C>
Iterator<C>& Iterator<C>::operator+=(std::ptrdiff_t n) {
  i_ = static_cast<std::size_t>(static_cast<std::ptrdiff_t>(i_) + n);
  return *this;
}

template <Type C>
Iterator<C>& Iterator<C>::operator-=(std::ptrdiff_t n) {
  i_ = static_cast<std::size_t>(static_cast<std::ptrdiff_t>(i_) - n);
  return *this;
}

template <Type C>
GVariantRef<C> Iterator<C>::operator[](std::ptrdiff_t i) const {
  return GVariantRef<C>::TakeUnchecked(g_variant_get_child_value(
      variant_.raw(),
      static_cast<std::size_t>(static_cast<std::ptrdiff_t>(i_) + i)));
}

template <Type C>
Iterator<C>::Iterator(GVariantRef<> variant, std::size_t i)
    : i_(i), variant_(variant) {}

// Mapping implementations

// Possibly cv-qualified reference can be used with *From() but not *Into().
template <typename T>
  requires(!std::same_as<T, std::decay_t<T>>)
struct Mapping<T> {
  static constexpr Type kType = Mapping<std::decay_t<const T&>>::kType;

  static auto From(const T& value)
      // Typically one wouldn't want a requires clause that just mirrors the
      // function body. Unfortunately, it is necessary to allow other generic
      // mappings to detect when From is absent, since requires expressions only
      // care about what is valid according to the declaration, not whether the
      // resulting instantiation would actually compile.
    requires(requires {
      GVariantRef<kType>::template From<std::decay_t<const T&>>(value);
    })
  {
    return GVariantRef<kType>::template From<std::decay_t<const T&>>(value);
  }

  static auto TryFrom(const T& value)
    requires(requires {
      GVariantRef<kType>::template TryFrom<std::decay_t<const T&>>(value);
    })
  {
    return GVariantRef<kType>::template TryFrom<std::decay_t<const T&>>(value);
  }
};

// Basic fixed values.

template <>
struct Mapping<bool> {
  static constexpr Type kType{"b"};
  static GVariantRef<kType> From(bool value);
  static bool Into(const GVariantRef<kType>& variant);
};

template <>
struct Mapping<std::uint8_t> {
  static constexpr Type kType{"y"};
  static GVariantRef<kType> From(std::uint8_t value);
  static std::uint8_t Into(const GVariantRef<kType>& variant);
};

template <>
struct Mapping<std::int16_t> {
  static constexpr Type kType{"n"};
  static GVariantRef<kType> From(std::int16_t value);
  static std::int16_t Into(const GVariantRef<kType>& variant);
};

template <>
struct Mapping<std::uint16_t> {
  static constexpr Type kType{"q"};
  static GVariantRef<kType> From(std::uint16_t value);
  static std::uint16_t Into(const GVariantRef<kType>& variant);
};

template <>
struct Mapping<std::int32_t> {
  static constexpr Type kType{"i"};
  static GVariantRef<kType> From(std::int32_t value);
  static std::int32_t Into(const GVariantRef<kType>& variant);
};

template <>
struct Mapping<std::uint32_t> {
  static constexpr Type kType{"u"};
  static GVariantRef<kType> From(std::uint32_t value);
  static std::uint32_t Into(const GVariantRef<kType>& variant);
};

template <>
struct Mapping<std::int64_t> {
  static constexpr Type kType{"x"};
  static GVariantRef<kType> From(std::int64_t value);
  static std::int64_t Into(const GVariantRef<kType>& variant);
};

template <>
struct Mapping<std::uint64_t> {
  static constexpr Type kType{"t"};
  static GVariantRef<kType> From(std::uint64_t value);
  static std::uint64_t Into(const GVariantRef<kType>& variant);
};

template <>
struct Mapping<double> {
  static constexpr Type kType{"d"};
  static GVariantRef<kType> From(double value);
  static double Into(const GVariantRef<kType>& variant);
};

// Strings.

template <>
struct Mapping<std::string> {
  static constexpr Type kType{"s"};
  // Crashes if string is not valid UTF-8.
  static GVariantRef<kType> From(const std::string& value);
  // Fails if string is not valid UTF-8.
  static base::expected<GVariantRef<kType>, Loggable> TryFrom(
      const std::string& value);
  static std::string Into(const GVariantRef<kType>& variant);
};

template <>
struct Mapping<std::string_view> {
  static constexpr Type kType{"s"};
  // Crashes if string is not valid UTF-8.
  static GVariantRef<kType> From(std::string_view value);
  // Fails if string is not valid UTF-8.
  static base::expected<GVariantRef<kType>, Loggable> TryFrom(
      std::string_view value);
};

template <>
struct Mapping<const char*> {
  static constexpr Type kType{"s"};
  // Crashes if string is not valid UTF-8.
  static GVariantRef<kType> From(const char* value);
  // Fails if string is not valid UTF-8.
  static base::expected<GVariantRef<kType>, Loggable> TryFrom(
      const char* value);
};

// Containers

template <typename T>
struct Mapping<std::optional<T>> {
  static constexpr Type kInnerType = Mapping<T>::kType;
  static constexpr Type kType{"m", kInnerType};

  static GVariantRef<kType> From(const std::optional<T>& value)
    requires(kInnerType.IsDefinite() &&
             requires(T v) { GVariantRef<kInnerType>::From(v); })
  {
    std::optional<GVariantRef<kInnerType>> variant;
    GVariant* child = nullptr;
    if (value) {
      variant = GVariantRef<kInnerType>::From(*value);
      child = variant->raw();
    }
    return GVariantRef<kType>::TakeUnchecked(
        g_variant_new_maybe(kInnerType.gvariant_type(), child));
  }

  static base::expected<GVariantRef<kType>, Loggable> TryFrom(
      const std::optional<T>& value)
    requires(requires(T v) { GVariantRef<kInnerType>::TryFrom(v); })
  {
    if (value.has_value()) {
      auto result = GVariantRef<kInnerType>::TryFrom(*value);
      if (!result.has_value()) {
        return base::unexpected(std::move(result).error());
      }
      return base::ok(GVariantRef<kType>::From(FilledMaybe{result.value()}));
    } else if constexpr (kInnerType.IsDefinite()) {
      return base::ok(
          GVariantRef<kType>::From(std::optional<GVariantRef<kInnerType>>()));
    } else {
      return base::unexpected(Loggable(
          FROM_HERE, "Can't convert indefinite optional with no value."));
    }
  }

  static std::optional<T> Into(const GVariantRef<kType>& variant)
    requires(requires(GVariantRef<kInnerType> v) { v.template Into<T>(); })
  {
    GVariant* child = g_variant_get_maybe(variant.raw());
    if (child) {
      return GVariantRef<kInnerType>::TakeUnchecked(child).template Into<T>();
    } else {
      return std::nullopt;
    }
  }

  static base::expected<std::optional<T>, Loggable> TryInto(
      const GVariantRef<kType>& variant)
    requires(requires(GVariantRef<kInnerType> v) { v.template TryInto<T>(); })
  {
    auto optional =
        variant.template Into<std::optional<GVariantRef<kInnerType>>>();

    if (optional.has_value()) {
      return optional->template TryInto<T>();
    } else {
      return base::ok(std::nullopt);
    }
  }
};

namespace internal {
template <Type kType, Type kInnerType, typename R>
GVariantRef<kType> FromRange(const R& value)
  requires(kInnerType.IsDefinite())
{
  GVariantBuilder builder;
  g_variant_builder_init(&builder, kType.gvariant_type());
  for (const auto& item : value) {
    g_variant_builder_add_value(&builder,
                                GVariantRef<kInnerType>::From(item).raw());
  }
  return GVariantRef<kType>::TakeUnchecked(g_variant_builder_end(&builder));
}

template <Type kType, Type kInnerType, typename R>
static base::expected<GVariantRef<kType>, Loggable> TryFromRange(
    const R& value) {
  if (!kInnerType.IsDefinite() && value.empty()) {
    return base::unexpected(
        Loggable(FROM_HERE, "Can't convert empty indefinite array"));
  }

  std::optional<Type<>> inner_type;
  GVariantBuilder builder;
  g_variant_builder_init(&builder, kType.gvariant_type());
  for (const auto& item : value) {
    auto converted = GVariantRef<kInnerType>::TryFrom(item);
    if (!converted.has_value()) {
      g_variant_builder_clear(&builder);
      return base::unexpected(std::move(converted).error());
    }
    if constexpr (!kInnerType.IsDefinite()) {
      if (!inner_type.has_value()) {
        inner_type = converted->GetType();
      } else if (!converted->GetType().IsSubtypeOf(inner_type.value())) {
        g_variant_builder_clear(&builder);
        return base::unexpected(
            Loggable(FROM_HERE, "Mismatched types in array"));
      }
    }
    g_variant_builder_add_value(&builder, converted->raw());
  }
  return base::ok(
      GVariantRef<kType>::TakeUnchecked(g_variant_builder_end(&builder)));
}
}  // namespace internal

// If needed, a further specialization could be added for vectors and
// contiguous ranges of fixed basic types (bools, bytes, ints, and doubles)
// to use g_variant_{new,get}_fixed_array() rather than processing each
// element individually. This would make handling, e.g., large blobs of binary
// data much more efficient.

template <typename T>
struct Mapping<std::vector<T>> {
  static constexpr Type kInnerType = Mapping<T>::kType;
  static constexpr Type kType{"a", kInnerType};

  static GVariantRef<kType> From(const std::vector<T>& value)
    requires(kInnerType.IsDefinite() &&
             requires(T v) { GVariantRef<kInnerType>::From(v); })
  {
    return internal::FromRange<kType, kInnerType>(value);
  }

  static base::expected<GVariantRef<kType>, Loggable> TryFrom(
      const std::vector<T>& value)
    requires(requires(T v) { GVariantRef<kInnerType>::TryFrom(v); })
  {
    return internal::TryFromRange<kType, kInnerType>(value);
  }

  static std::vector<T> Into(const GVariantRef<kType>& variant)
    requires(requires(GVariantRef<kInnerType> v) { v.template Into<T>(); })
  {
    std::vector<T> result;
    GVariantIter iter;
    g_variant_iter_init(&iter, variant.raw());
    result.reserve(g_variant_iter_n_children(&iter));
    while (GVariant* next = g_variant_iter_next_value(&iter)) {
      auto item_gvariant = GVariantRef<kInnerType>::TakeUnchecked(next);
      result.push_back(item_gvariant.template Into<T>());
    }
    return result;
  }

  static base::expected<std::vector<T>, Loggable> TryInto(
      const GVariantRef<kType>& variant)
    requires(requires(GVariantRef<kInnerType> v) { v.template TryInto<T>(); })
  {
    std::vector<T> result;
    GVariantIter iter;
    g_variant_iter_init(&iter, variant.raw());
    result.reserve(g_variant_iter_n_children(&iter));
    while (GVariant* next = g_variant_iter_next_value(&iter)) {
      auto item_gvariant = GVariantRef<>::Take(next);
      auto item_result = item_gvariant.TryInto<T>();
      if (item_result.has_value()) {
        result.push_back(std::move(item_result).value());
      } else {
        return base::unexpected(std::move(item_result).error());
      }
    }
    return result;
  }
};

template <typename K, typename T>
  requires(Mapping<K>::kType.IsBasic())
struct Mapping<std::map<K, T>> {
  static constexpr Type kKeyType = Mapping<K>::kType;
  static constexpr Type kValueType = Mapping<T>::kType;
  static constexpr Type kInnerType{"{", kKeyType, kValueType, "}"};
  static constexpr Type kType{"a", kInnerType};

  static GVariantRef<kType> From(const std::map<K, T>& value)
    requires(kInnerType.IsDefinite() &&
             requires(std::pair<K, T> v) { GVariantRef<kInnerType>::From(v); })
  {
    return internal::FromRange<kType, kInnerType>(value);
  }

  static base::expected<GVariantRef<kType>, Loggable> TryFrom(
      const std::map<K, T>& value)
    requires(requires(std::pair<K, T> v) {
      GVariantRef<kInnerType>::TryFrom(v);
    })
  {
    return internal::TryFromRange<kType, kInnerType>(value);
  }

  static std::map<K, T> Into(const GVariantRef<kType>& variant)
    requires(requires(GVariantRef<kInnerType> v) {
      v.template Into<std::pair<K, T>>();
    })
  {
    std::map<K, T> result;
    GVariantIter iter;
    g_variant_iter_init(&iter, variant.raw());
    while (GVariant* next = g_variant_iter_next_value(&iter)) {
      auto item_gvariant = GVariantRef<kInnerType>::TakeUnchecked(next);
      result.insert(item_gvariant.template Into<std::pair<K, T>>());
    }
    return result;
  }

  static base::expected<std::map<K, T>, Loggable> TryInto(
      const GVariantRef<kType>& variant)
    requires(requires(GVariantRef<kInnerType> v) {
      v.template TryInto<std::pair<K, T>>();
    })
  {
    std::map<K, T> result;
    GVariantIter iter;
    g_variant_iter_init(&iter, variant.raw());
    while (GVariant* next = g_variant_iter_next_value(&iter)) {
      auto item_gvariant = GVariantRef<>::Take(next);
      auto item_result = item_gvariant.TryInto<std::pair<K, T>>();
      if (item_result.has_value()) {
        result.insert(std::move(item_result).value());
      } else {
        return base::unexpected(std::move(item_result).error());
      }
    }
    return result;
  }
};

template <typename K, typename T>
  requires(Mapping<K>::kType.IsBasic())
struct Mapping<std::pair<K, T>> {
  static constexpr Type kKeyType = Mapping<K>::kType;
  static constexpr Type kValueType = Mapping<T>::kType;
  static constexpr Type kType{"{", kKeyType, kValueType, "}"};

  static GVariantRef<kType> From(const std::pair<K, T>& pair)
    requires(requires(K k, T v) {
      GVariantRef<kKeyType>::From(k);
      GVariantRef<kValueType>::From(v);
    })
  {
    auto key = GVariantRef<kKeyType>::From(pair.first);
    auto value = GVariantRef<kValueType>::From(pair.second);
    return GVariantRef<kType>::TakeUnchecked(
        g_variant_new_dict_entry(key.raw(), value.raw()));
  }

  static base::expected<GVariantRef<kType>, Loggable> TryFrom(
      const std::pair<K, T>& pair)
    requires(requires(K k, T v) {
      GVariantRef<kKeyType>::TryFrom(k);
      GVariantRef<kValueType>::TryFrom(v);
    })
  {
    auto key = GVariantRef<kKeyType>::TryFrom(pair.first);
    if (!key.has_value()) {
      return base::unexpected(std::move(key).error());
    }
    auto value = GVariantRef<kValueType>::TryFrom(pair.second);
    if (!value.has_value()) {
      return base::unexpected(std::move(value).error());
    }
    return GVariantRef<kType>::From(std::pair(key.value(), value.value()));
  }

  static std::pair<K, T> Into(const GVariantRef<kType>& variant)
    requires(requires(GVariantRef<kKeyType> k, GVariantRef<kValueType> v) {
      k.template Into<K>();
      v.template Into<T>();
    })
  {
    GVariantIter iter;
    g_variant_iter_init(&iter, variant.raw());
    auto key_gvariant =
        GVariantRef<kKeyType>::TakeUnchecked(g_variant_iter_next_value(&iter));
    auto value_gvariant = GVariantRef<kValueType>::TakeUnchecked(
        g_variant_iter_next_value(&iter));
    return std::pair(key_gvariant.template Into<K>(),
                     value_gvariant.template Into<T>());
  }

  static base::expected<std::pair<K, T>, Loggable> TryInto(
      const GVariantRef<kType>& variant)
    requires(requires(GVariantRef<kKeyType> k, GVariantRef<kValueType> v) {
      k.template TryInto<K>();
      v.template TryInto<T>();
    })
  {
    auto gvariants = variant.template Into<
        std::pair<GVariantRef<kKeyType>, GVariantRef<kValueType>>>();
    auto key_result = gvariants.first.template TryInto<K>();
    if (!key_result.has_value()) {
      return base::unexpected(std::move(key_result).error());
    }
    auto value_result = gvariants.second.template TryInto<T>();
    if (!value_result.has_value()) {
      return base::unexpected(std::move(value_result).error());
    }
    return std::pair(std::move(key_result).value(),
                     std::move(value_result).value());
  }
};

template <typename R>
// If the type can decay, let that happen first to avoid ambiguities.
// E.g., a std::vector<double>& could either be used as a range directly or
// decayed into a std::vector<double>. Resolving in favor of decay is
// desirable so that string constants decay into a const char* and are treated
// as a C string rather than a range of chars.
  requires(std::ranges::range<R> && std::same_as<R, std::decay_t<R>>)
struct Mapping<R> {
  static constexpr Type kInnerType =
      Mapping<std::ranges::range_value_t<R>>::kType;
  static constexpr Type kType{"a", kInnerType};

  static GVariantRef<kType> From(const R& value)
    requires(kInnerType.IsDefinite() &&
             requires(std::ranges::range_value_t<R> v) {
               GVariantRef<kInnerType>::From(v);
             })
  {
    return internal::FromRange<kType, kInnerType>(value);
  }

  static base::expected<GVariantRef<kType>, Loggable> TryFrom(const R& value)
    requires(requires(std::ranges::range_value_t<R> v) {
      GVariantRef<kInnerType>::TryFrom(v);
    })
  {
    return internal::TryFromRange<kType, kInnerType>(value);
  }
};

template <typename... Types>
struct Mapping<std::tuple<Types...>> {
  static constexpr Type kType{"(", Mapping<Types>::kType..., ")"};

  static GVariantRef<kType> From(const std::tuple<Types...>& value)
    requires(requires(Types... v) {
      (GVariantRef<Mapping<Types>::kType>::From(v), ...);
    })
  {
    GVariantBuilder builder;
    g_variant_builder_init(&builder, kType.gvariant_type());

    std::apply(
        [&](const Types&... values) {
          (g_variant_builder_add_value(
               &builder,
               GVariantRef<Mapping<Types>::kType>::From(values).raw()),
           ...);
        },
        value);

    return GVariantRef<kType>::TakeUnchecked(g_variant_builder_end(&builder));
  }

  static base::expected<GVariantRef<kType>, Loggable> TryFrom(
      const std::tuple<Types...>& value)
    requires(requires(Types... v) {
      (GVariantRef<Mapping<Types>::kType>::TryFrom(v), ...);
    })
  {
    auto conversion_result = std::apply(
        [](const Types&... item) { return TupleTryFrom<Types...>(item...); },
        value);
    if (!conversion_result.has_value()) {
      return base::unexpected(std::move(conversion_result).error());
    }
    return GVariantRef<kType>::From(conversion_result.value());
  }

  static std::tuple<Types...> Into(const GVariantRef<kType>& variant)
    requires(requires(GVariantRef<Mapping<Types>::kType>... v) {
      (v.template Into<Types>(), ...);
    })
  {
    GVariantIter iter;
    g_variant_iter_init(&iter, variant.raw());
    // Must use uniform-initialization syntax since (in contrast to
    // function-call syntax) it is specified to evalulate values in order.
    auto gvariant_items =
        std::tuple{GVariantRef<Mapping<Types>::kType>::TakeUnchecked(
            g_variant_iter_next_value(&iter))...};
    return std::apply(
        [](const GVariantRef<Mapping<Types>::kType>&... items) {
          return std::tuple(items.template Into<Types>()...);
        },
        gvariant_items);
  }

  static base::expected<std::tuple<Types...>, Loggable> TryInto(
      const GVariantRef<kType>& variant)
    requires(requires(GVariantRef<Mapping<Types>::kType>... v) {
      (v.template TryInto<Types>(), ...);
    })
  {
    auto gvariant_items =
        variant
            .template Into<std::tuple<GVariantRef<Mapping<Types>::kType>...>>();
    return std::apply(
        [](const GVariantRef<Mapping<Types>::kType>&... items) {
          return TupleTryInto<Types...>(items...);
        },
        gvariant_items);
  }

 private:
  // Attempt to turn a tuple of Ts into a tuple of GVariantRefs
  template <typename T = void>
  static base::expected<std::tuple<>, Loggable> TupleTryFrom() {
    return base::ok(std::tuple());
  }

  template <typename T, typename... Ts>
  static base::expected<std::tuple<GVariantRef<Mapping<T>::kType>,
                                   GVariantRef<Mapping<Ts>::kType>...>,
                        Loggable>
  TupleTryFrom(const T& first, const Ts&... rest) {
    auto first_result = GVariantRef<Mapping<T>::kType>::TryFrom(first);
    if (!first_result.has_value()) {
      return base::unexpected(std::move(first_result).error());
    }
    auto rest_result = TupleTryFrom<Ts...>(rest...);
    if (!rest_result.has_value()) {
      return base::unexpected(std::move(first_result).error());
    }
    return std::tuple_cat(std::tuple(first_result.value()),
                          rest_result.value());
  }

  // Attempt to turn a tuple of GVariantRefs into a tuple of Ts
  template <typename T = void>
  static base::expected<std::tuple<>, Loggable> TupleTryInto() {
    return base::ok(std::tuple());
  }

  template <typename T, typename... Ts>
  static base::expected<std::tuple<T, Ts...>, Loggable> TupleTryInto(
      const GVariantRef<Mapping<T>::kType>& first,
      const GVariantRef<Mapping<Ts>::kType>&... rest) {
    auto first_result = first.template TryInto<T>();
    if (!first_result.has_value()) {
      return base::unexpected(std::move(first_result).error());
    }
    auto rest_result = TupleTryInto<Ts...>(rest...);
    if (!rest_result.has_value()) {
      return base::unexpected(std::move(first_result).error());
    }
    return std::tuple_cat(std::tuple(first_result.value()),
                          rest_result.value());
  }
};

template <typename... Types>
  requires(sizeof...(Types) > 0)
struct Mapping<std::variant<Types...>> {
  static constexpr Type kType =
      TypeBase::CommonSuperTypeOf<Mapping<Types>::kType...>();

  static GVariantRef<kType> From(const std::variant<Types...>& value)
    requires(requires(Types... v) { (GVariantRef<kType>::From(v), ...); })
  {
    return [&]<std::size_t... Is>(std::index_sequence<Is...>) {
      std::optional<GVariantRef<kType>> result;
      ((std::ignore =
            value.index() == Is &&
            (result.emplace(GVariantRef<kType>::From(std::get<Is>(value))),
             false)),
       ...);
      return std::move(*result);
    }(std::index_sequence_for<Types...>());
  }

  static base::expected<GVariantRef<kType>, Loggable> TryFrom(
      const std::variant<Types...>& value)
    requires(requires(Types... v) { (GVariantRef<kType>::TryFrom(v), ...); })
  {
    return [&]<std::size_t... Is>(std::index_sequence<Is...>) {
      std::optional<base::expected<GVariantRef<kType>, Loggable>> result;
      ((std::ignore =
            value.index() == Is &&
            (result.emplace(GVariantRef<kType>::TryFrom(std::get<Is>(value))),
             false)),
       ...);
      return std::move(*result);
    }(std::index_sequence_for<Types...>());
  }

  template <Type C>
  static std::variant<Types...> Into(const GVariantRef<C>& variant)
      // Infallible Into is provided if at least one alternative provides an
      // infallible Into for the provided type.
    requires(... || requires { variant.template Into<Types>(); })
  {
    // Try TryInto() first so where possible Into and TryInto produce the same
    // variant.
    auto result = VariantTryInto<0, Types...>(variant);
    if (result.has_value()) {
      return std::move(result).value();
    }

    // To get here, one of the types must provide both a fallible and infallible
    // conversion, and the fallible version failed. Loop through again and call
    // the infallible version to get a value to return.
    return VariantInto<C, 0, Types...>(variant);
  }

  static base::expected<std::variant<Types...>, Loggable> TryInto(
      const GVariantRef<kType>& variant)
      // TryInto is only provided if it is provided by at least one alternative.
    requires(... || requires { variant.template TryInto<Types>(); })
  {
    return VariantTryInto<0, Types...>(variant);
  }

 private:
  template <std::size_t I>
  static base::expected<std::variant<Types...>, Loggable> VariantTryInto(
      const GVariantRef<kType>& variant) {
    return base::unexpected(
        Loggable(FROM_HERE, "No variant alternative could decode value"));
  }

  template <std::size_t I, typename T, typename... Ts>
  static base::expected<std::variant<Types...>, Loggable> VariantTryInto(
      const GVariantRef<kType>& variant) {
    if constexpr (requires { variant.template TryInto<T>(); }) {
      auto alternative_result = variant.template TryInto<T>();
      if (alternative_result.has_value()) {
        return base::ok(std::variant<Types...>(
            std::in_place_index<I>, std::move(alternative_result).value()));
      }
    }
    return VariantTryInto<I + 1, Ts...>(variant);
  }

  // No base case needed, as at least one type is guaranteed to provide an
  // infallible conversion.
  template <Type C, std::size_t I, typename T, typename... Ts>
  static std::variant<Types...> VariantInto(const GVariantRef<C>& variant) {
    if constexpr (requires { variant.template Into<T>(); }) {
      return std::variant<Types...>(std::in_place_index<I>,
                                    variant.template Into<T>());
    } else {
      return VariantInto<C, I + 1, Ts...>(variant);
    }
  }
};

// Special Types

template <Type C>
struct Mapping<GVariantRef<C>> {
  static constexpr Type kType = C;
  static GVariantRef<kType> From(GVariantRef<kType> value) { return value; }
  static GVariantRef<kType> Into(GVariantRef<kType> value) { return value; }
};

template <>
struct Mapping<Ignored> {
  static constexpr Type kType{"*"};
  static Ignored Into(const GVariantRef<kType>& variant);
};

template <>
struct Mapping<decltype(std::ignore)> {
  static constexpr Type kType{"*"};
  static decltype(std::ignore) Into(const GVariantRef<kType>& variant);
};

template <typename T>
struct Mapping<Boxed<T>> {
  static constexpr Type kType{"v"};

  static GVariantRef<kType> From(const Boxed<T>& value)
    requires(requires(T v) { GVariantRef<>::From(v); })
  {
    return GVariantRef<kType>::TakeUnchecked(
        g_variant_new_variant(GVariantRef<>::From(value.value).raw()));
  }

  static base::expected<GVariantRef<kType>, Loggable> TryFrom(
      const Boxed<T>& value)
    requires(requires(T v) { GVariantRef<>::TryFrom(v); })
  {
    auto result = GVariantRef<>::TryFrom(value.value);
    if (!result.has_value()) {
      return base::unexpected(std::move(result).error());
    }
    return base::ok(GVariantRef<kType>::From(Boxed{result.value()}));
  }

  static Boxed<T> Into(const GVariantRef<kType>& variant)
    requires(requires(GVariantRef<> v) { v.Into<T>(); })
  {
    return Boxed{
        GVariantRef<>::Take(g_variant_get_variant(variant.raw())).Into<T>()};
  }

  static base::expected<Boxed<T>, Loggable> TryInto(
      const GVariantRef<kType>& variant)
    requires(requires(GVariantRef<> v) { v.TryInto<T>(); })
  {
    return variant.Into<Boxed<GVariantRef<>>>().value.TryInto<T>().transform(
        [](auto v) { return Boxed{std::move(v)}; });
  }
};

template <typename T>
struct Mapping<FilledMaybe<T>> {
  static constexpr Type kInnerType = Mapping<T>::kType;
  static constexpr Type kType{"m", kInnerType};

  static GVariantRef<kType> From(const FilledMaybe<T>& value)
    requires(requires(T v) { GVariantRef<kInnerType>::From(v); })
  {
    return GVariantRef<kType>::TakeUnchecked(g_variant_new_maybe(
        nullptr, GVariantRef<kInnerType>::From(value.value).raw()));
  }

  static base::expected<GVariantRef<kType>, Loggable> TryFrom(
      const FilledMaybe<T>& value)
    requires(requires(T v) { GVariantRef<kInnerType>::TryFrom(v); })
  {
    auto result = GVariantRef<kInnerType>::TryFrom(value.value);
    if (!result.has_value()) {
      return base::unexpected(std::move(result).error());
    }
    return base::ok(GVariantRef<kType>::From(FilledMaybe{result.value()}));
  }

  static base::expected<FilledMaybe<T>, Loggable> TryInto(
      const GVariantRef<kType>& variant)
    requires(requires(GVariantRef<kInnerType> v) { v.template TryInto<T>(); })
  {
    GVariant* contents = g_variant_get_maybe(variant.raw());
    if (!contents) {
      return base::unexpected(
          Loggable(FROM_HERE, "Maybe value unexpectedly empty"));
    }

    return GVariantRef<kInnerType>::TakeUnchecked(contents)
        .template TryInto<T>()
        .transform([](auto v) { return FilledMaybe{std::move(v)}; });
  }
};

template <Type C>
struct Mapping<EmptyArrayOf<C>> {
  static constexpr Type kType{"a", C};

  static GVariantRef<kType> From(const EmptyArrayOf<C>& value)
    requires(C.IsDefinite())
  {
    return GVariantRef<kType>::TakeUnchecked(
        g_variant_new_array(C.gvariant_type(), nullptr, 0));
  }

  static base::expected<EmptyArrayOf<C>, Loggable> TryInto(
      const GVariantRef<kType>& variant) {
    if (auto size = g_variant_n_children(variant.raw()); size != 0) {
      return base::unexpected(
          Loggable(FROM_HERE, "Array unexpectedly not empty."));
    }

    return EmptyArrayOf<C>{};
  }
};

template <>
struct Mapping<ObjectPathCStr> {
  static constexpr Type kType{"o"};
  static GVariantRef<kType> From(const ObjectPathCStr& value);
};

template <>
struct Mapping<ObjectPath> {
  static constexpr Type kType{"o"};
  static GVariantRef<kType> From(const ObjectPath& value);
  static ObjectPath Into(const GVariantRef<kType>& variant);
};

template <>
struct Mapping<TypeSignatureCStr> {
  static constexpr Type kType{"g"};
  static GVariantRef<kType> From(const TypeSignatureCStr& value);
};

template <>
struct Mapping<TypeSignature> {
  static constexpr Type kType{"g"};
  static GVariantRef<kType> From(const TypeSignature& value);
  static TypeSignature Into(const GVariantRef<kType>& variant);
};

}  // namespace gvariant

using gvariant::GVariantFrom;
using gvariant::GVariantRef;

}  // namespace remoting

// Make tuple-like
template <remoting::gvariant::Type C>
  requires(C.IsFixedSizeContainer())
struct std::tuple_size<remoting::GVariantRef<C>>
    : public std::tuple_size<
          decltype(remoting::gvariant::TypeBase::Unpack<C>())> {};

template <std::size_t I, remoting::gvariant::Type C>
  requires(C.IsFixedSizeContainer())
struct std::tuple_element<I, remoting::GVariantRef<C>> {
  using type = remoting::GVariantRef<std::get<I>(
      remoting::gvariant::TypeBase::Unpack<C>())>;
};

#endif  // REMOTING_HOST_LINUX_GVARIANT_REF_H_