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

//! FIDL encoding and decoding.

// TODO(https://fxbug.dev/42069912): This file is too big. Split it into smaller files.

pub use static_assertions::const_assert_eq;

use crate::endpoints::ProtocolMarker;
use crate::handle::{
    Handle, HandleBased, HandleDisposition, HandleInfo, HandleOp, ObjectType, Rights, Status,
};
use crate::time::{Instant, Ticks, Timeline};
use crate::{Error, MethodType, Result};
use bitflags::bitflags;
use std::cell::RefCell;
use std::marker::PhantomData;
use std::{mem, ptr, str};

////////////////////////////////////////////////////////////////////////////////
// Traits
////////////////////////////////////////////////////////////////////////////////

/// Trait for a "Box" that wraps a handle when it's inside a client. Useful when
/// we need some infrastructure to make our underlying channels work the way the
/// client code expects.
pub trait ProxyChannelBox<D: ResourceDialect>: std::fmt::Debug + Send + Sync {
    /// Receives a message on the channel and registers this `Channel` as
    /// needing a read on receiving a `io::std::ErrorKind::WouldBlock`.
    #[allow(clippy::type_complexity)]
    fn recv_etc_from(
        &self,
        ctx: &mut std::task::Context<'_>,
        buf: &mut D::MessageBufEtc,
    ) -> std::task::Poll<Result<(), Option<<D::ProxyChannel as ProxyChannelFor<D>>::Error>>>;

    #[cfg(not(target_os = "fuchsia"))]
    /// Closed reason for proxies.
    fn closed_reason(&self) -> Option<String> {
        None
    }

    /// Get a reference to the boxed channel.
    fn as_channel(&self) -> &D::ProxyChannel;

    /// Write data to a Proxy channel
    fn write_etc(
        &self,
        bytes: &[u8],
        handles: &mut [<D::ProxyChannel as ProxyChannelFor<D>>::HandleDisposition],
    ) -> Result<(), Option<<D::ProxyChannel as ProxyChannelFor<D>>::Error>>;

    /// Return whether a `ProxyChannel` is closed.
    fn is_closed(&self) -> bool;

    /// Unbox this channel
    fn unbox(self) -> D::ProxyChannel;
}

/// Message buffer used to hold a message in a particular dialect.
pub trait MessageBufFor<D: ResourceDialect>: std::fmt::Debug + Send + Sync {
    /// Create a new message buffer.
    fn new() -> Self;

    /// Discard any allocated-but-unused space in the byte portion of this buffer.
    fn shrink_bytes_to_fit(&mut self) {}

    /// Access the contents of this buffer as two vectors.
    fn split_mut(&mut self) -> (&mut Vec<u8>, &mut Vec<<D::Handle as HandleFor<D>>::HandleInfo>);
}

/// Channel used for proxies in a particular dialect.
pub trait ProxyChannelFor<D: ResourceDialect>:
    std::fmt::Debug + crate::epitaph::ChannelLike
{
    /// Box we put around a `ProxyChannel` when using it within a client.
    type Boxed: ProxyChannelBox<D>;

    /// Type of the errors we get from this proxy channel.
    type Error: Into<crate::TransportError>;

    /// Handle disposition used in this dialect.
    ///
    /// This is for sending handles, and includes the intended type/rights.
    type HandleDisposition: HandleDispositionFor<D>;

    /// Construct a new box around a proxy channel.
    fn boxed(self) -> Self::Boxed;

    /// Write data to a Proxy channel
    fn write_etc(
        &self,
        bytes: &[u8],
        handles: &mut [Self::HandleDisposition],
    ) -> Result<(), Option<Self::Error>>;
}

/// Handle disposition struct used for a particular dialect.
pub trait HandleDispositionFor<D: ResourceDialect>: std::fmt::Debug {
    /// Wrap a handle in a handle disposition.
    fn from_handle(
        handle: D::Handle,
        object_type: crate::ObjectType,
        rights: crate::Rights,
    ) -> Self;
}

/// Handle type used for a particular dialect.
pub trait HandleFor<D: ResourceDialect> {
    /// Handle info used in this dialect.
    ///
    /// This is used for receiving handles, and includes type/rights from the
    /// kernel.
    type HandleInfo: HandleInfoFor<D>;

    /// Produce an invalid version of `Handle` used as a place filler when
    /// we remove handles from an array.
    fn invalid() -> Self;

    /// Check whether a handle is invalid.
    fn is_invalid(&self) -> bool;
}

/// Handle info struct used for a particular dialect.
pub trait HandleInfoFor<D: ResourceDialect>: std::fmt::Debug {
    /// Verifies a `HandleInfo` has the type and rights we expect and
    /// extracts the `D::Handle` from it.
    fn consume(
        &mut self,
        expected_object_type: crate::ObjectType,
        expected_rights: crate::Rights,
    ) -> Result<D::Handle>;

    /// Destroy the given handle info, leaving it invalid.
    fn drop_in_place(&mut self);
}

/// Describes how a given transport encodes resources like handles.
pub trait ResourceDialect: 'static + Sized + Default + std::fmt::Debug + Copy + Clone {
    /// Handle type used in this dialect.
    type Handle: HandleFor<Self>;

    /// Message buffer type used in this dialect.
    type MessageBufEtc: MessageBufFor<Self>;

    /// Channel type used for proxies in this dialect.
    type ProxyChannel: ProxyChannelFor<Self>;

    /// Get a thread-local common instance of `TlsBuf`
    fn with_tls_buf<R>(f: impl FnOnce(&mut TlsBuf<Self>) -> R) -> R;
}

/// Indicates a type is encodable as a handle in a given resource dialect.
pub trait EncodableAsHandle: Into<<Self::Dialect as ResourceDialect>::Handle> {
    /// What resource dialect can encode this object as a handle.
    type Dialect: ResourceDialect<Handle: Into<Self>>;
}

/// A FIDL type marker.
///
/// This trait is only used for compile time dispatch. For example, we can
/// parameterize code on `T: TypeMarker`, but we would never write `value: T`.
/// In fact, `T` is often a zero-sized struct. From the user's perspective,
/// `T::Owned` is the FIDL type's "Rust type". For example, for the FIDL type
/// `string:10`, `T` is `BoundedString<10>` and `T::Owned` is `String`.
///
/// For primitive types and user-defined types, `Self` is actually the same as
/// `Self::Owned`. For all others (strings, arrays, vectors, handles, endpoints,
/// optionals, error results), `Self` is a zero-sized struct that uses generics
/// to represent FIDL type information such as the element type or constraints.
///
/// # Safety
///
/// * Implementations of `encode_is_copy` must only return true if it is safe to
///   transmute from `*const Self::Owned` to `*const u8` and read `inline_size`
///   bytes starting from that address.
///
/// * Implementations of `decode_is_copy` must only return true if it is safe to
///   transmute from `*mut Self::Owned` to `*mut u8` and write `inline_size`
///   bytes starting at that address.
pub unsafe trait TypeMarker: 'static + Sized {
    /// The owned Rust type which this FIDL type decodes into.
    type Owned;

    /// Returns the minimum required alignment of the inline portion of the
    /// encoded object. It must be a (nonzero) power of two.
    fn inline_align(context: Context) -> usize;

    /// Returns the size of the inline portion of the encoded object, including
    /// padding for alignment. Must be a multiple of `inline_align`.
    fn inline_size(context: Context) -> usize;

    /// Returns true if the memory layout of `Self::Owned` matches the FIDL wire
    /// format and encoding requires no validation. When true, we can optimize
    /// encoding arrays and vectors of `Self::Owned` to a single memcpy.
    ///
    /// This can be true even when `decode_is_copy` is false. For example, bools
    /// require validation when decoding, but they do not require validation
    /// when encoding because Rust guarantees a bool is either 0x00 or 0x01.
    #[inline(always)]
    fn encode_is_copy() -> bool {
        false
    }

    /// Returns true if the memory layout of `Self::Owned` matches the FIDL wire
    /// format and decoding requires no validation. When true, we can optimize
    /// decoding arrays and vectors of `Self::Owned` to a single memcpy.
    #[inline(always)]
    fn decode_is_copy() -> bool {
        false
    }
}

/// A FIDL value type marker.
///
/// Value types are guaranteed to never contain handles. As a result, they can
/// be encoded by immutable reference (or by value for `Copy` types).
pub trait ValueTypeMarker: TypeMarker {
    /// The Rust type to use for encoding. This is a particular `Encode<Self>`
    /// type cheaply obtainable from `&Self::Owned`. There are three cases:
    ///
    /// - Special cases such as `&[T]` for vectors.
    /// - For primitives, bits, and enums, it is `Owned`.
    /// - Otherwise, it is `&Owned`.
    type Borrowed<'a>;

    /// Cheaply converts from `&Self::Owned` to `Self::Borrowed`.
    fn borrow(value: &Self::Owned) -> Self::Borrowed<'_>;
}

/// A FIDL resource type marker.
///
/// Resource types are allowed to contain handles. As a result, they must be
/// encoded by mutable reference so that handles can be zeroed out.
pub trait ResourceTypeMarker: TypeMarker {
    /// The Rust type to use for encoding. This is a particular `Encode<Self>`
    /// type cheaply obtainable from `&mut Self::Owned`. There are three cases:
    ///
    /// - Special cases such as `&mut [T]` for vectors.
    /// - When `Owned: HandleBased`, it is `Owned`.
    /// - Otherwise, it is `&mut Owned`.
    type Borrowed<'a>;

    /// Cheaply converts from `&mut Self::Owned` to `Self::Borrowed`. For
    /// `HandleBased` types this is "take" (it returns an owned handle and
    /// replaces `value` with `Handle::invalid`), and for all other types it is
    /// "borrow" (just converts from one reference to another).
    fn take_or_borrow(value: &mut Self::Owned) -> Self::Borrowed<'_>;
}

/// A Rust type that can be encoded as the FIDL type `T`.
///
/// # Safety
///
/// Implementations of `encode` must write every byte in
/// `encoder.buf[offset..offset + T::inline_size(encoder.context)]` unless
/// returning an `Err` value.
pub unsafe trait Encode<T: TypeMarker, D: ResourceDialect>: Sized {
    /// Encodes the object into the encoder's buffers. Any handles stored in the
    /// object are swapped for `Handle::INVALID`.
    ///
    /// Implementations that encode out-of-line objects must call `depth.increment()?`.
    ///
    /// # Safety
    ///
    /// Callers must ensure `offset` is a multiple of `T::inline_align` and
    /// `encoder.buf` has room for writing `T::inline_size` bytes at `offset`.
    unsafe fn encode(self, encoder: &mut Encoder<'_, D>, offset: usize, depth: Depth)
        -> Result<()>;
}

/// A Rust type that can be decoded from the FIDL type `T`.
pub trait Decode<T: TypeMarker, D>: 'static + Sized {
    /// Creates a valid instance of `Self`. The specific value does not matter,
    /// since it will be overwritten by `decode`.
    // TODO(https://fxbug.dev/42069855): Take context parameter to discourage using this.
    fn new_empty() -> Self;

    /// Decodes an object of type `T` from the decoder's buffers into `self`.
    ///
    /// Implementations must validate every byte in
    /// `decoder.buf[offset..offset + T::inline_size(decoder.context)]` unless
    /// returning an `Err` value. Implementations that decode out-of-line
    /// objects must call `depth.increment()?`.
    ///
    /// # Safety
    ///
    /// Callers must ensure `offset` is a multiple of `T::inline_align` and
    /// `decoder.buf` has room for reading `T::inline_size` bytes at `offset`.
    unsafe fn decode(
        &mut self,
        decoder: &mut Decoder<'_, D>,
        offset: usize,
        depth: Depth,
    ) -> Result<()>
    where
        D: ResourceDialect;
}

////////////////////////////////////////////////////////////////////////////////
// Resource Dialects
////////////////////////////////////////////////////////////////////////////////

/// Box around an async channel. Needed to implement `ResourceDialect` for
/// `DefaultFuchsiaResourceDialect` but not so useful for that case.
#[derive(Debug)]
pub struct FuchsiaProxyBox(crate::AsyncChannel);

impl FuchsiaProxyBox {
    /// Future that returns when the channel is closed.
    pub fn on_closed(&self) -> crate::OnSignalsRef<'_> {
        self.0.on_closed()
    }

    /// See [`crate::AsyncChannel::read_etc`]
    pub fn read_etc(
        &self,
        cx: &mut std::task::Context<'_>,
        bytes: &mut Vec<u8>,
        handles: &mut Vec<crate::HandleInfo>,
    ) -> std::task::Poll<Result<(), crate::Status>> {
        self.0.read_etc(cx, bytes, handles)
    }

    /// Signal peer
    pub fn signal_peer(
        &self,
        clear: crate::Signals,
        set: crate::Signals,
    ) -> Result<(), zx_status::Status> {
        use crate::Peered;
        self.0.as_ref().signal_peer(clear, set)
    }
}

impl ProxyChannelBox<DefaultFuchsiaResourceDialect> for FuchsiaProxyBox {
    fn write_etc(
        &self,
        bytes: &[u8],
        handles: &mut [HandleDisposition<'static>],
    ) -> Result<(), Option<zx_status::Status>> {
        self.0
            .write_etc(bytes, handles)
            .map_err(|x| Some(x).filter(|x| *x != zx_status::Status::PEER_CLOSED))
    }

    fn recv_etc_from(
        &self,
        ctx: &mut std::task::Context<'_>,
        buf: &mut crate::MessageBufEtc,
    ) -> std::task::Poll<Result<(), Option<zx_status::Status>>> {
        self.0
            .recv_etc_from(ctx, buf)
            .map_err(|x| Some(x).filter(|x| *x != zx_status::Status::PEER_CLOSED))
    }

    fn is_closed(&self) -> bool {
        self.0.is_closed()
    }

    #[cfg(not(target_os = "fuchsia"))]
    fn closed_reason(&self) -> Option<String> {
        self.0.closed_reason()
    }

    fn unbox(self) -> <DefaultFuchsiaResourceDialect as ResourceDialect>::ProxyChannel {
        self.0
    }

    fn as_channel(&self) -> &<DefaultFuchsiaResourceDialect as ResourceDialect>::ProxyChannel {
        &self.0
    }
}

/// The default [`ResourceDialect`]. Encodes everything into a channel
/// MessageBuf for sending via channels between Fuchsia services.
#[derive(Debug, Default, Copy, Clone)]
pub struct DefaultFuchsiaResourceDialect;
impl ResourceDialect for DefaultFuchsiaResourceDialect {
    type Handle = Handle;
    type MessageBufEtc = crate::MessageBufEtc;
    type ProxyChannel = crate::AsyncChannel;

    #[inline]
    fn with_tls_buf<R>(f: impl FnOnce(&mut TlsBuf<Self>) -> R) -> R {
        thread_local!(static TLS_BUF: RefCell<TlsBuf<DefaultFuchsiaResourceDialect>> =
            RefCell::new(TlsBuf::default()));
        TLS_BUF.with(|buf| f(&mut buf.borrow_mut()))
    }
}

impl MessageBufFor<DefaultFuchsiaResourceDialect> for crate::MessageBufEtc {
    fn new() -> crate::MessageBufEtc {
        let mut ret = crate::MessageBufEtc::new();
        ret.ensure_capacity_bytes(MIN_BUF_BYTES_SIZE);
        ret
    }

    fn shrink_bytes_to_fit(&mut self) {
        self.shrink_bytes_to_fit();
    }

    fn split_mut(&mut self) -> (&mut Vec<u8>, &mut Vec<HandleInfo>) {
        self.split_mut()
    }
}

impl ProxyChannelFor<DefaultFuchsiaResourceDialect> for crate::AsyncChannel {
    type Boxed = FuchsiaProxyBox;
    type Error = zx_status::Status;
    type HandleDisposition = HandleDisposition<'static>;

    fn boxed(self) -> FuchsiaProxyBox {
        FuchsiaProxyBox(self)
    }

    fn write_etc(
        &self,
        bytes: &[u8],
        handles: &mut [HandleDisposition<'static>],
    ) -> Result<(), Option<zx_status::Status>> {
        self.write_etc(bytes, handles)
            .map_err(|x| Some(x).filter(|x| *x != zx_status::Status::PEER_CLOSED))
    }
}

impl HandleDispositionFor<DefaultFuchsiaResourceDialect> for HandleDisposition<'static> {
    fn from_handle(handle: Handle, object_type: ObjectType, rights: Rights) -> Self {
        HandleDisposition::new(HandleOp::Move(handle), object_type, rights, Status::OK)
    }
}

impl HandleFor<DefaultFuchsiaResourceDialect> for Handle {
    type HandleInfo = HandleInfo;

    fn invalid() -> Self {
        Handle::invalid()
    }

    fn is_invalid(&self) -> bool {
        Handle::is_invalid(self)
    }
}

impl HandleInfoFor<DefaultFuchsiaResourceDialect> for HandleInfo {
    fn consume(
        &mut self,
        expected_object_type: ObjectType,
        expected_rights: Rights,
    ) -> Result<Handle> {
        let handle_info = std::mem::replace(
            self,
            HandleInfo::new(Handle::invalid(), ObjectType::NONE, Rights::NONE),
        );
        let received_object_type = handle_info.object_type;
        if expected_object_type != ObjectType::NONE
            && received_object_type != ObjectType::NONE
            && expected_object_type != received_object_type
        {
            return Err(Error::IncorrectHandleSubtype {
                expected: expected_object_type,
                received: received_object_type,
            });
        }

        let received_rights = handle_info.rights;
        if expected_rights != Rights::SAME_RIGHTS
            && received_rights != Rights::SAME_RIGHTS
            && expected_rights != received_rights
        {
            if !received_rights.contains(expected_rights) {
                return Err(Error::MissingExpectedHandleRights {
                    missing_rights: expected_rights - received_rights,
                });
            }
            return match handle_info.handle.replace(expected_rights) {
                Ok(r) => Ok(r),
                Err(status) => Err(Error::HandleReplace(status)),
            };
        }
        Ok(handle_info.handle)
    }

    #[inline(always)]
    fn drop_in_place(&mut self) {
        *self = HandleInfo::new(Handle::invalid(), ObjectType::NONE, Rights::NONE);
    }
}

/// A never type for handles in `NoHandleResourceDialect`.
#[cfg(not(target_os = "fuchsia"))]
#[derive(Debug)]
pub enum NoHandles {}

#[cfg(not(target_os = "fuchsia"))]
impl ProxyChannelBox<NoHandleResourceDialect> for NoHandles {
    fn recv_etc_from(
        &self,
        _ctx: &mut std::task::Context<'_>,
        _buf: &mut <NoHandleResourceDialect as ResourceDialect>::MessageBufEtc,
    ) -> std::task::Poll<Result<(), Option<zx_status::Status>>> {
        unreachable!()
    }

    fn write_etc(
        &self,
        _bytes: &[u8],
        _handles: &mut [
            <<NoHandleResourceDialect as ResourceDialect>::ProxyChannel
            as ProxyChannelFor<NoHandleResourceDialect>>::HandleDisposition],
    ) -> Result<(), Option<zx_status::Status>> {
        unreachable!()
    }

    fn is_closed(&self) -> bool {
        unreachable!()
    }

    fn unbox(self) -> <NoHandleResourceDialect as ResourceDialect>::ProxyChannel {
        unreachable!()
    }

    fn as_channel(&self) -> &<NoHandleResourceDialect as ResourceDialect>::ProxyChannel {
        unreachable!()
    }
}

/// A resource dialect which doesn't support handles at all.
#[cfg(not(target_os = "fuchsia"))]
#[derive(Debug, Default, Copy, Clone)]
pub struct NoHandleResourceDialect;

#[cfg(not(target_os = "fuchsia"))]
impl ResourceDialect for NoHandleResourceDialect {
    type Handle = NoHandles;
    type MessageBufEtc = NoHandles;
    type ProxyChannel = NoHandles;

    #[inline]
    fn with_tls_buf<R>(f: impl FnOnce(&mut TlsBuf<Self>) -> R) -> R {
        thread_local!(static TLS_BUF: RefCell<TlsBuf<NoHandleResourceDialect>> =
            RefCell::new(TlsBuf::default()));
        TLS_BUF.with(|buf| f(&mut buf.borrow_mut()))
    }
}

#[cfg(not(target_os = "fuchsia"))]
impl MessageBufFor<NoHandleResourceDialect> for NoHandles {
    fn new() -> Self {
        unreachable!()
    }

    fn split_mut(&mut self) -> (&mut Vec<u8>, &mut Vec<NoHandles>) {
        unreachable!()
    }
}

#[cfg(not(target_os = "fuchsia"))]
impl ProxyChannelFor<NoHandleResourceDialect> for NoHandles {
    type Boxed = NoHandles;
    type Error = zx_status::Status;
    type HandleDisposition = NoHandles;

    fn boxed(self) -> NoHandles {
        unreachable!()
    }

    fn write_etc(
        &self,
        _bytes: &[u8],
        _handles: &mut [NoHandles],
    ) -> Result<(), Option<zx_status::Status>> {
        unreachable!()
    }
}

#[cfg(not(target_os = "fuchsia"))]
impl crate::epitaph::ChannelLike for NoHandles {
    fn write_epitaph(&self, _bytes: &[u8]) -> std::result::Result<(), crate::TransportError> {
        unreachable!()
    }
}

#[cfg(not(target_os = "fuchsia"))]
impl HandleFor<NoHandleResourceDialect> for NoHandles {
    type HandleInfo = NoHandles;

    fn invalid() -> Self {
        unreachable!()
    }

    fn is_invalid(&self) -> bool {
        unreachable!()
    }
}

#[cfg(not(target_os = "fuchsia"))]
impl HandleDispositionFor<NoHandleResourceDialect> for NoHandles {
    fn from_handle(
        _handle: <NoHandleResourceDialect as ResourceDialect>::Handle,
        _object_type: crate::ObjectType,
        _rights: crate::Rights,
    ) -> Self {
        unreachable!()
    }
}

#[cfg(not(target_os = "fuchsia"))]
impl HandleInfoFor<NoHandleResourceDialect> for NoHandles {
    fn consume(
        &mut self,
        _expected_object_type: crate::ObjectType,
        _expected_rights: crate::Rights,
    ) -> Result<<NoHandleResourceDialect as ResourceDialect>::Handle> {
        unreachable!()
    }

    fn drop_in_place(&mut self) {
        unreachable!()
    }
}

/// A resource dialect which doesn't support handles at all.
#[cfg(target_os = "fuchsia")]
pub type NoHandleResourceDialect = DefaultFuchsiaResourceDialect;

////////////////////////////////////////////////////////////////////////////////
// Constants
////////////////////////////////////////////////////////////////////////////////

/// The maximum recursion depth of encoding and decoding. Each pointer to an
/// out-of-line object counts as one step in the recursion depth.
pub const MAX_RECURSION: usize = 32;

/// The maximum number of handles allowed in a FIDL message.
///
/// Note that this number is one less for large messages for the time being. See
/// (https://fxbug.dev/42068341) for progress, or to report problems caused by
/// this specific limitation.
pub const MAX_HANDLES: usize = 64;

/// Indicates that an optional value is present.
pub const ALLOC_PRESENT_U64: u64 = u64::MAX;
/// Indicates that an optional value is present.
pub const ALLOC_PRESENT_U32: u32 = u32::MAX;
/// Indicates that an optional value is absent.
pub const ALLOC_ABSENT_U64: u64 = 0;
/// Indicates that an optional value is absent.
pub const ALLOC_ABSENT_U32: u32 = 0;

/// Special ordinal signifying an epitaph message.
pub const EPITAPH_ORDINAL: u64 = 0xffffffffffffffffu64;

/// The current wire format magic number
pub const MAGIC_NUMBER_INITIAL: u8 = 1;

////////////////////////////////////////////////////////////////////////////////
// Helper functions
////////////////////////////////////////////////////////////////////////////////

/// Rounds `x` up if necessary so that it is a multiple of `align`.
///
/// Requires `align` to be a (nonzero) power of two.
#[doc(hidden)] // only exported for use in macros or generated code
#[inline(always)]
pub fn round_up_to_align(x: usize, align: usize) -> usize {
    debug_assert_ne!(align, 0);
    debug_assert_eq!(align & (align - 1), 0);
    // https://en.wikipedia.org/wiki/Data_structure_alignment#Computing_padding
    (x + align - 1) & !(align - 1)
}

/// Resize a vector without zeroing added bytes.
///
/// The type `T` must be `Copy`. This is not enforced in the type signature
/// because it is used in generic contexts where verifying this requires looking
/// at control flow. See `decode_vector` for an example.
///
/// # Safety
///
/// This is unsafe when `new_len > old_len` because it leaves new elements at
/// indices `old_len..new_len` uninitialized. The caller must overwrite all the
/// new elements before reading them. "Reading" includes any operation that
/// extends the vector, such as `push`, because this could reallocate the vector
/// and copy the uninitialized bytes.
///
/// FIDL conformance tests are used to validate that there are no uninitialized
/// bytes in the output across a range of types and values.
// TODO(https://fxbug.dev/42075223): Fix safety issues, use MaybeUninit.
#[inline]
unsafe fn resize_vec_no_zeroing<T>(buf: &mut Vec<T>, new_len: usize) {
    if new_len > buf.capacity() {
        buf.reserve(new_len - buf.len());
    }
    // Safety:
    // - `new_len` must be less than or equal to `capacity()`:
    //   The if-statement above guarantees this.
    // - The elements at `old_len..new_len` must be initialized:
    //   They are purposely left uninitialized, making this function unsafe.
    buf.set_len(new_len);
}

/// Helper type for checking encoding/decoding recursion depth.
#[doc(hidden)] // only exported for use in macros or generated code
#[derive(Debug, Copy, Clone)]
#[repr(transparent)]
pub struct Depth(usize);

impl Depth {
    /// Increments the depth, and returns an error if it exceeds the limit.
    #[inline(always)]
    pub fn increment(&mut self) -> Result<()> {
        self.0 += 1;
        if self.0 > MAX_RECURSION {
            return Err(Error::MaxRecursionDepth);
        }
        Ok(())
    }
}

////////////////////////////////////////////////////////////////////////////////
// Helper macros
////////////////////////////////////////////////////////////////////////////////

/// Given `T: TypeMarker`, expands to a `T::Owned::new_empty` call.
#[doc(hidden)] // only exported for use in macros or generated code
#[macro_export]
macro_rules! new_empty {
    ($ty:ty) => {
        <<$ty as $crate::encoding::TypeMarker>::Owned as $crate::encoding::Decode<$ty, _>>::new_empty()
    };
    ($ty:ty, $d:path) => {
        <<$ty as $crate::encoding::TypeMarker>::Owned as $crate::encoding::Decode<$ty, $d>>::new_empty()
    };
}

/// Given `T: TypeMarker`, expands to a `T::Owned::decode` call.
#[doc(hidden)] // only exported for use in macros or generated code
#[macro_export]
macro_rules! decode {
    ($ty:ty, $out_value:expr, $decoder:expr, $offset:expr, $depth:expr) => {
        <<$ty as $crate::encoding::TypeMarker>::Owned as $crate::encoding::Decode<$ty, _>>::decode(
            $out_value, $decoder, $offset, $depth,
        )
    };
    ($ty:ty, $d:path, $out_value:expr, $decoder:expr, $offset:expr, $depth:expr) => {
        <<$ty as $crate::encoding::TypeMarker>::Owned as $crate::encoding::Decode<$ty, $d>>::decode(
            $out_value, $decoder, $offset, $depth,
        )
    };
}

////////////////////////////////////////////////////////////////////////////////
// Wire format
////////////////////////////////////////////////////////////////////////////////

/// Wire format version to use during encode / decode.
#[derive(Clone, Copy, Debug)]
pub enum WireFormatVersion {
    /// FIDL 2023 wire format.
    V2,
}

/// Context for encoding and decoding.
///
/// WARNING: Do not construct this directly unless you know what you're doing.
/// FIDL uses `Context` to coordinate soft migrations, so improper uses of it
/// could result in ABI breakage.
#[derive(Clone, Copy, Debug)]
pub struct Context {
    /// Wire format version to use when encoding / decoding.
    pub wire_format_version: WireFormatVersion,
}

// We only support one wire format right now, so context should be zero size.
const_assert_eq!(mem::size_of::<Context>(), 0);

impl Context {
    /// Returns the header flags to set when encoding with this context.
    #[inline]
    pub(crate) fn at_rest_flags(&self) -> AtRestFlags {
        match self.wire_format_version {
            WireFormatVersion::V2 => AtRestFlags::USE_V2_WIRE_FORMAT,
        }
    }
}

////////////////////////////////////////////////////////////////////////////////
// Encoder
////////////////////////////////////////////////////////////////////////////////

/// Encoding state
#[derive(Debug)]
pub struct Encoder<'a, D: ResourceDialect> {
    /// Encoding context.
    pub context: Context,

    /// Buffer to write output data into.
    pub buf: &'a mut Vec<u8>,

    /// Buffer to write output handles into.
    handles: &'a mut Vec<<D::ProxyChannel as ProxyChannelFor<D>>::HandleDisposition>,

    /// Phantom data for `D`, which is here to provide types not values.
    _dialect: PhantomData<D>,
}

/// The default context for encoding.
#[inline]
fn default_encode_context() -> Context {
    Context { wire_format_version: WireFormatVersion::V2 }
}

impl<'a, D: ResourceDialect> Encoder<'a, D> {
    /// FIDL-encodes `x` into the provided data and handle buffers.
    #[inline]
    pub fn encode<T: TypeMarker>(
        buf: &'a mut Vec<u8>,
        handles: &'a mut Vec<<D::ProxyChannel as ProxyChannelFor<D>>::HandleDisposition>,
        x: impl Encode<T, D>,
    ) -> Result<()> {
        let context = default_encode_context();
        Self::encode_with_context::<T>(context, buf, handles, x)
    }

    /// FIDL-encodes `x` into the provided data and handle buffers, using the
    /// specified encoding context.
    ///
    /// WARNING: Do not call this directly unless you know what you're doing.
    /// FIDL uses `Context` to coordinate soft migrations, so improper uses of
    /// this function could result in ABI breakage.
    #[inline]
    pub fn encode_with_context<T: TypeMarker>(
        context: Context,
        buf: &'a mut Vec<u8>,
        handles: &'a mut Vec<<D::ProxyChannel as ProxyChannelFor<D>>::HandleDisposition>,
        x: impl Encode<T, D>,
    ) -> Result<()> {
        fn prepare_for_encoding<'a, D: ResourceDialect>(
            context: Context,
            buf: &'a mut Vec<u8>,
            handles: &'a mut Vec<<D::ProxyChannel as ProxyChannelFor<D>>::HandleDisposition>,
            ty_inline_size: usize,
        ) -> Encoder<'a, D> {
            // An empty response can have size zero.
            // This if statement is needed to not break the padding write below.
            if ty_inline_size != 0 {
                let aligned_inline_size = round_up_to_align(ty_inline_size, 8);
                // Safety: The uninitialized elements are written by `x.encode`,
                // except for the trailing padding which is zeroed below.
                unsafe {
                    resize_vec_no_zeroing(buf, aligned_inline_size);

                    // Zero the last 8 bytes in the block to ensure padding bytes are zero.
                    let padding_ptr = buf.get_unchecked_mut(aligned_inline_size - 8) as *mut u8;
                    (padding_ptr as *mut u64).write_unaligned(0);
                }
            }
            handles.truncate(0);
            Encoder { buf, handles, context, _dialect: PhantomData }
        }
        let mut encoder = prepare_for_encoding(context, buf, handles, T::inline_size(context));
        // Safety: We reserve `T::inline_size` bytes in `encoder.buf` above.
        unsafe { x.encode(&mut encoder, 0, Depth(0)) }
    }

    /// In debug mode only, asserts that there is enough room in the buffer to
    /// write an object of type `T` at `offset`.
    #[inline(always)]
    pub fn debug_check_bounds<T: TypeMarker>(&self, offset: usize) {
        debug_assert!(offset + T::inline_size(self.context) <= self.buf.len());
    }

    /// Encodes a primitive numeric type.
    ///
    /// # Safety
    ///
    /// The caller must ensure that `self.buf` has room for writing
    /// `T::inline_size` bytes as `offset`.
    #[inline(always)]
    pub unsafe fn write_num<T: numeric::Numeric>(&mut self, num: T, offset: usize) {
        debug_assert!(offset + mem::size_of::<T>() <= self.buf.len());
        // Safety: The caller ensures `offset` is valid for writing
        // sizeof(T) bytes. Transmuting to a same-or-wider
        // integer or float pointer is safe because we use `write_unaligned`.
        let ptr = self.buf.get_unchecked_mut(offset) as *mut u8;
        (ptr as *mut T).write_unaligned(num);
    }

    /// Writes the given handle to the handles list.
    #[inline(always)]
    pub fn push_next_handle(
        &mut self,
        handle: <D::ProxyChannel as ProxyChannelFor<D>>::HandleDisposition,
    ) {
        self.handles.push(handle)
    }

    /// Returns an offset for writing `len` out-of-line bytes. Zeroes padding
    /// bytes at the end if `len` is not a multiple of 8.
    ///
    /// # Safety
    ///
    /// The caller must ensure that `len` is nonzero.
    #[inline]
    pub unsafe fn out_of_line_offset(&mut self, len: usize) -> usize {
        debug_assert!(len > 0);
        let new_offset = self.buf.len();
        let padded_len = round_up_to_align(len, 8);
        debug_assert!(padded_len >= 8);
        let new_len = self.buf.len() + padded_len;
        resize_vec_no_zeroing(self.buf, new_len);
        // Zero the last 8 bytes in the block to ensure padding bytes are zero.
        // It's more efficient to always write 8 bytes regardless of how much
        // padding is needed because we will overwrite non-padding afterwards.
        let padding_ptr = self.buf.get_unchecked_mut(new_len - 8) as *mut u8;
        (padding_ptr as *mut u64).write_unaligned(0);
        new_offset
    }

    /// Write padding at the specified offset.
    ///
    /// # Safety
    ///
    /// The caller must ensure that `self.buf` has room for writing `len` bytes
    /// as `offset`.
    #[inline(always)]
    pub unsafe fn padding(&mut self, offset: usize, len: usize) {
        if len == 0 {
            return;
        }
        debug_assert!(offset + len <= self.buf.len());
        // Safety:
        // - The caller ensures `offset` is valid for writing `len` bytes.
        // - All u8 pointers are properly aligned.
        ptr::write_bytes(self.buf.as_mut_ptr().add(offset), 0, len);
    }
}

unsafe impl<T: Timeline + 'static, U: 'static> TypeMarker for Instant<T, U> {
    type Owned = Self;

    #[inline(always)]
    fn inline_align(_context: Context) -> usize {
        mem::align_of::<Self>()
    }

    #[inline(always)]
    fn inline_size(_context: Context) -> usize {
        mem::size_of::<Self>()
    }
}

impl<T: Timeline + Copy + 'static, U: Copy + 'static> ValueTypeMarker for Instant<T, U> {
    type Borrowed<'a> = Self;
    fn borrow(value: &Self::Owned) -> Self::Borrowed<'_> {
        *value
    }
}

unsafe impl<T: Timeline + Copy + 'static, D: ResourceDialect> Encode<Instant<T>, D> for Instant<T> {
    #[inline]
    unsafe fn encode(
        self,
        encoder: &mut Encoder<'_, D>,
        offset: usize,
        _depth: Depth,
    ) -> Result<()> {
        encoder.debug_check_bounds::<Self>(offset);
        encoder.write_num(self.into_nanos(), offset);
        Ok(())
    }
}

unsafe impl<T: Timeline + 'static, D: ResourceDialect> Encode<Ticks<T>, D> for Ticks<T> {
    #[inline]
    unsafe fn encode(
        self,
        encoder: &mut Encoder<'_, D>,
        offset: usize,
        _depth: Depth,
    ) -> Result<()> {
        encoder.debug_check_bounds::<Self>(offset);
        encoder.write_num(self.into_raw(), offset);
        Ok(())
    }
}

////////////////////////////////////////////////////////////////////////////////
// Decoder
////////////////////////////////////////////////////////////////////////////////

/// Decoding state
#[derive(Debug)]
pub struct Decoder<'a, D: ResourceDialect> {
    /// Decoding context.
    pub context: Context,

    /// Buffer from which to read data.
    pub buf: &'a [u8],

    /// Next out of line block in buf.
    next_out_of_line: usize,

    /// Buffer from which to read handles.
    handles: &'a mut [<D::Handle as HandleFor<D>>::HandleInfo],

    /// Index of the next handle to read from the handle array
    next_handle: usize,

    /// The dialect determines how we encode resources.
    _dialect: PhantomData<D>,
}

impl<'a, D: ResourceDialect> Decoder<'a, D> {
    /// Decodes a value of FIDL type `T` into the Rust type `T::Owned` from the
    /// provided data and handle buffers. Assumes the buffers came from inside a
    /// transaction message wrapped by `header`.
    #[inline]
    pub fn decode_into<T: TypeMarker>(
        header: &TransactionHeader,
        buf: &'a [u8],
        handles: &'a mut [<D::Handle as HandleFor<D>>::HandleInfo],
        value: &mut T::Owned,
    ) -> Result<()>
    where
        T::Owned: Decode<T, D>,
    {
        Self::decode_with_context::<T>(header.decoding_context(), buf, handles, value)
    }

    /// Decodes a value of FIDL type `T` into the Rust type `T::Owned` from the
    /// provided data and handle buffers, using the specified context.
    ///
    /// WARNING: Do not call this directly unless you know what you're doing.
    /// FIDL uses `Context` to coordinate soft migrations, so improper uses of
    /// this function could result in ABI breakage.
    #[inline]
    pub fn decode_with_context<T: TypeMarker>(
        context: Context,
        buf: &'a [u8],
        handles: &'a mut [<D::Handle as HandleFor<D>>::HandleInfo],
        value: &mut T::Owned,
    ) -> Result<()>
    where
        T::Owned: Decode<T, D>,
    {
        let inline_size = T::inline_size(context);
        let next_out_of_line = round_up_to_align(inline_size, 8);
        if next_out_of_line > buf.len() {
            return Err(Error::OutOfRange);
        }
        let mut decoder = Decoder {
            next_out_of_line,
            buf,
            handles,
            next_handle: 0,
            context,
            _dialect: PhantomData,
        };
        // Safety: buf.len() >= inline_size based on the check above.
        unsafe {
            value.decode(&mut decoder, 0, Depth(0))?;
        }
        // Safety: next_out_of_line <= buf.len() based on the check above.
        unsafe { decoder.post_decoding(inline_size, next_out_of_line) }
    }

    /// Checks for errors after decoding. This is a separate function to reduce
    /// binary bloat.
    ///
    /// # Safety
    ///
    /// Requires `padding_end <= self.buf.len()`.
    unsafe fn post_decoding(&self, padding_start: usize, padding_end: usize) -> Result<()> {
        if self.next_out_of_line < self.buf.len() {
            return Err(Error::ExtraBytes);
        }
        if self.next_handle < self.handles.len() {
            return Err(Error::ExtraHandles);
        }

        let padding = padding_end - padding_start;
        if padding > 0 {
            // Safety:
            // padding_end <= self.buf.len() is guaranteed by the caller.
            let last_u64 = unsafe {
                let last_u64_ptr = self.buf.get_unchecked(padding_end - 8) as *const u8;
                (last_u64_ptr as *const u64).read_unaligned()
            };
            // padding == 0 => mask == 0x0000000000000000
            // padding == 1 => mask == 0xff00000000000000
            // padding == 2 => mask == 0xffff000000000000
            // ...
            let mask = !(!0u64 >> (padding * 8));
            if last_u64 & mask != 0 {
                return Err(self.end_of_block_padding_error(padding_start, padding_end));
            }
        }

        Ok(())
    }

    /// The position of the next out of line block and the end of the current
    /// blocks.
    #[inline(always)]
    pub fn next_out_of_line(&self) -> usize {
        self.next_out_of_line
    }

    /// The number of handles that have not yet been consumed.
    #[inline(always)]
    pub fn remaining_handles(&self) -> usize {
        self.handles.len() - self.next_handle
    }

    /// In debug mode only, asserts that there is enough room in the buffer to
    /// read an object of type `T` at `offset`.
    #[inline(always)]
    pub fn debug_check_bounds<T: TypeMarker>(&self, offset: usize) {
        debug_assert!(offset + T::inline_size(self.context) <= self.buf.len());
    }

    /// Decodes a primitive numeric type. The caller must ensure that `self.buf`
    /// has room for reading `T::inline_size` bytes as `offset`.
    #[inline(always)]
    pub fn read_num<T: numeric::Numeric>(&mut self, offset: usize) -> T {
        debug_assert!(offset + mem::size_of::<T>() <= self.buf.len());
        // Safety: The caller ensures `offset` is valid for reading
        // sizeof(T) bytes. Transmuting to a same-or-wider
        // integer pointer is safe because we use `read_unaligned`.
        unsafe {
            let ptr = self.buf.get_unchecked(offset) as *const u8;
            (ptr as *const T).read_unaligned()
        }
    }

    /// Returns an offset for reading `len` out-of-line bytes. Validates that
    /// padding bytes at the end are zero if `len` is not a multiple of 8.
    ///
    /// # Safety
    ///
    /// The caller must ensure that `len` is nonzero.
    #[inline(always)]
    pub unsafe fn out_of_line_offset(&mut self, len: usize) -> Result<usize> {
        debug_assert!(len > 0);
        let offset = self.next_out_of_line;
        let aligned_len = round_up_to_align(len, 8);
        self.next_out_of_line += aligned_len;
        debug_assert!(self.next_out_of_line >= 8);
        if self.next_out_of_line > self.buf.len() {
            return Err(Error::OutOfRange);
        }
        // Validate padding bytes at the end of the block.
        // Safety:
        // - The caller ensures `len > 0`, therefore `aligned_len >= 8`.
        // - After `self.next_out_of_line += aligned_len`, we know `self.next_out_of_line >= aligned_len >= 8`.
        // - Therefore `self.next_out_of_line - 8 >= 0` is a valid *const u64.
        let last_u64_ptr = self.buf.get_unchecked(self.next_out_of_line - 8) as *const u8;
        let last_u64 = (last_u64_ptr as *const u64).read_unaligned();
        let padding = aligned_len - len;
        // padding == 0 => mask == 0x0000000000000000
        // padding == 1 => mask == 0xff00000000000000
        // padding == 2 => mask == 0xffff000000000000
        // ...
        let mask = !(!0u64 >> (padding * 8));
        if last_u64 & mask != 0 {
            return Err(self.end_of_block_padding_error(offset + len, self.next_out_of_line));
        }

        Ok(offset)
    }

    /// Generates an error for bad padding bytes at the end of a block.
    /// Assumes it is already known that there is a nonzero padding byte.
    fn end_of_block_padding_error(&self, start: usize, end: usize) -> Error {
        for i in start..end {
            if self.buf[i] != 0 {
                return Error::NonZeroPadding { padding_start: start };
            }
        }
        // This should be unreachable because we only call this after finding
        // nonzero padding. Abort instead of panicking to save code size.
        std::process::abort();
    }

    /// Checks that the specified padding bytes are in fact zeroes. Like
    /// `Decode::decode`, the caller is responsible for bounds checks.
    #[inline]
    pub fn check_padding(&self, offset: usize, len: usize) -> Result<()> {
        if len == 0 {
            // Skip body (so it can be optimized out).
            return Ok(());
        }
        debug_assert!(offset + len <= self.buf.len());
        for i in offset..offset + len {
            // Safety: Caller guarantees offset..offset+len is in bounds.
            if unsafe { *self.buf.get_unchecked(i) } != 0 {
                return Err(Error::NonZeroPadding { padding_start: offset });
            }
        }
        Ok(())
    }

    /// Checks the padding of the inline value portion of an envelope. Like
    /// `Decode::decode`, the caller is responsible for bounds checks.
    ///
    /// Note: `check_padding` could be used instead, but doing so leads to long
    /// compilation times which is why this method exists.
    #[inline]
    pub fn check_inline_envelope_padding(
        &self,
        value_offset: usize,
        value_len: usize,
    ) -> Result<()> {
        // Safety: The caller ensures `value_offset` is valid for reading
        // `value_len` bytes.
        let valid_padding = unsafe {
            match value_len {
                1 => {
                    *self.buf.get_unchecked(value_offset + 1) == 0
                        && *self.buf.get_unchecked(value_offset + 2) == 0
                        && *self.buf.get_unchecked(value_offset + 3) == 0
                }
                2 => {
                    *self.buf.get_unchecked(value_offset + 2) == 0
                        && *self.buf.get_unchecked(value_offset + 3) == 0
                }
                3 => *self.buf.get_unchecked(value_offset + 3) == 0,
                4 => true,
                value_len => unreachable!("value_len={}", value_len),
            }
        };
        if valid_padding {
            Ok(())
        } else {
            Err(Error::NonZeroPadding { padding_start: value_offset + value_len })
        }
    }

    /// Take the next handle from the `handles` list.
    #[inline]
    pub fn take_next_handle(
        &mut self,
        expected_object_type: crate::ObjectType,
        expected_rights: crate::Rights,
    ) -> Result<D::Handle> {
        let Some(next_handle) = self.handles.get_mut(self.next_handle) else {
            return Err(Error::OutOfRange);
        };
        let handle = next_handle.consume(expected_object_type, expected_rights)?;
        self.next_handle += 1;
        Ok(handle)
    }

    /// Drops the next handle in the handle array.
    #[inline]
    pub fn drop_next_handle(&mut self) -> Result<()> {
        let Some(next_handle) = self.handles.get_mut(self.next_handle) else {
            return Err(Error::OutOfRange);
        };
        next_handle.drop_in_place();
        self.next_handle += 1;
        Ok(())
    }
}

impl<T: Timeline + 'static, D: ResourceDialect> Decode<Self, D> for Instant<T> {
    #[inline(always)]
    fn new_empty() -> Self {
        Instant::ZERO
    }

    #[inline]
    unsafe fn decode(
        &mut self,
        decoder: &mut Decoder<'_, D>,
        offset: usize,
        _depth: Depth,
    ) -> Result<()> {
        decoder.debug_check_bounds::<Self>(offset);
        *self = Self::from_nanos(decoder.read_num(offset));
        Ok(())
    }
}

impl<T: Timeline + 'static, D: ResourceDialect> Decode<Self, D> for Ticks<T> {
    #[inline(always)]
    fn new_empty() -> Self {
        Ticks::<T>::ZERO
    }

    #[inline]
    unsafe fn decode(
        &mut self,
        decoder: &mut Decoder<'_, D>,
        offset: usize,
        _depth: Depth,
    ) -> Result<()> {
        decoder.debug_check_bounds::<Self>(offset);
        *self = Self::from_raw(decoder.read_num(offset));
        Ok(())
    }
}

////////////////////////////////////////////////////////////////////////////////
// Ambiguous types
////////////////////////////////////////////////////////////////////////////////

/// A fake FIDL type that can encode from and decode into any Rust type.
///
/// This exists solely to prevent the compiler from inferring `T: TypeMarker`,
/// allowing us to add new generic impls without source breakage. It also
/// improves error messages when no suitable `T: TypeMarker` exists, preventing
/// spurious guesses about what you should do (e.g. implement `HandleBased`).
pub struct Ambiguous1;

/// Like `Ambiguous1`. There needs to be two of these types so that the compiler
/// doesn't infer one of them and generate a call to the panicking methods.
pub struct Ambiguous2;

/// An uninhabited type used as owned and borrowed type for ambiguous markers.
/// Can be replaced by `!` once that is stable.
pub enum AmbiguousNever {}

macro_rules! impl_ambiguous {
    ($ambiguous:ident) => {
        unsafe impl TypeMarker for $ambiguous {
            type Owned = AmbiguousNever;

            fn inline_align(_context: Context) -> usize {
                panic!("reached code for fake ambiguous type");
            }

            fn inline_size(_context: Context) -> usize {
                panic!("reached code for fake ambiguous type");
            }
        }

        impl ValueTypeMarker for $ambiguous {
            type Borrowed<'a> = AmbiguousNever;

            fn borrow(value: &<Self as TypeMarker>::Owned) -> Self::Borrowed<'_> {
                match *value {}
            }
        }

        impl ResourceTypeMarker for $ambiguous {
            type Borrowed<'a> = AmbiguousNever;
            fn take_or_borrow(value: &mut <Self as TypeMarker>::Owned) -> Self::Borrowed<'_>
            where
                Self: TypeMarker,
            {
                match *value {}
            }
        }

        unsafe impl<T, D: ResourceDialect> Encode<$ambiguous, D> for T {
            unsafe fn encode(
                self,
                _encoder: &mut Encoder<'_, D>,
                _offset: usize,
                _depth: Depth,
            ) -> Result<()> {
                panic!("reached code for fake ambiguous type");
            }
        }

        // TODO(https://fxbug.dev/42069855): impl for `T: 'static` this once user code has
        // migrated off new_empty(), which is meant to be internal.
        impl<D: ResourceDialect> Decode<$ambiguous, D> for AmbiguousNever {
            fn new_empty() -> Self {
                panic!("reached code for fake ambiguous type");
            }

            unsafe fn decode(
                &mut self,
                _decoder: &mut Decoder<'_, D>,
                _offset: usize,
                _depth: Depth,
            ) -> Result<()> {
                match *self {}
            }
        }
    };
}

impl_ambiguous!(Ambiguous1);
impl_ambiguous!(Ambiguous2);

////////////////////////////////////////////////////////////////////////////////
// Empty types
////////////////////////////////////////////////////////////////////////////////

/// A FIDL type representing an empty payload (0 bytes).
pub struct EmptyPayload;

unsafe impl TypeMarker for EmptyPayload {
    type Owned = ();
    #[inline(always)]
    fn inline_align(_context: Context) -> usize {
        1
    }

    #[inline(always)]
    fn inline_size(_context: Context) -> usize {
        0
    }
}

impl ValueTypeMarker for EmptyPayload {
    type Borrowed<'a> = ();
    #[inline(always)]
    fn borrow(value: &Self::Owned) -> Self::Borrowed<'_> {
        *value
    }
}

unsafe impl<D: ResourceDialect> Encode<EmptyPayload, D> for () {
    #[inline(always)]
    unsafe fn encode(
        self,
        _encoder: &mut Encoder<'_, D>,
        _offset: usize,
        _depth: Depth,
    ) -> Result<()> {
        Ok(())
    }
}

impl<D: ResourceDialect> Decode<EmptyPayload, D> for () {
    #[inline(always)]
    fn new_empty() -> Self {}

    #[inline(always)]
    unsafe fn decode(
        &mut self,
        _decoder: &mut Decoder<'_, D>,
        _offset: usize,
        _depth: Depth,
    ) -> Result<()> {
        Ok(())
    }
}

/// The FIDL type used for an empty success variant in a result union. Result
/// unions occur in two-way methods that are flexible or that use error syntax.
pub struct EmptyStruct;

unsafe impl TypeMarker for EmptyStruct {
    type Owned = ();
    #[inline(always)]
    fn inline_align(_context: Context) -> usize {
        1
    }

    #[inline(always)]
    fn inline_size(_context: Context) -> usize {
        1
    }
}

impl ValueTypeMarker for EmptyStruct {
    type Borrowed<'a> = ();
    #[inline(always)]
    fn borrow(value: &Self::Owned) -> Self::Borrowed<'_> {
        *value
    }
}

unsafe impl<D: ResourceDialect> Encode<EmptyStruct, D> for () {
    #[inline]
    unsafe fn encode(
        self,
        encoder: &mut Encoder<'_, D>,
        offset: usize,
        _depth: Depth,
    ) -> Result<()> {
        encoder.debug_check_bounds::<EmptyStruct>(offset);
        encoder.write_num(0u8, offset);
        Ok(())
    }
}

impl<D: ResourceDialect> Decode<EmptyStruct, D> for () {
    #[inline(always)]
    fn new_empty() -> Self {}

    #[inline]
    unsafe fn decode(
        &mut self,
        decoder: &mut Decoder<'_, D>,
        offset: usize,
        _depth: Depth,
    ) -> Result<()> {
        decoder.debug_check_bounds::<EmptyStruct>(offset);
        match decoder.read_num::<u8>(offset) {
            0 => Ok(()),
            _ => Err(Error::Invalid),
        }
    }
}

////////////////////////////////////////////////////////////////////////////////
// Primitive types
////////////////////////////////////////////////////////////////////////////////

// Private module to prevent others from implementing `Numeric`.
mod numeric {
    use super::*;

    /// Marker trait for primitive numeric types.
    pub trait Numeric {}

    /// Implements `Numeric`, `TypeMarker`, `ValueTypeMarker`, `Encode`, and
    /// `Decode` for a primitive numeric type (integer or float).
    macro_rules! impl_numeric {
        ($numeric_ty:ty) => {
            impl Numeric for $numeric_ty {}

            unsafe impl TypeMarker for $numeric_ty {
                type Owned = $numeric_ty;
                #[inline(always)]
                fn inline_align(_context: Context) -> usize {
                    mem::align_of::<$numeric_ty>()
                }

                #[inline(always)]
                fn inline_size(_context: Context) -> usize {
                    mem::size_of::<$numeric_ty>()
                }

                #[inline(always)]
                fn encode_is_copy() -> bool {
                    true
                }

                #[inline(always)]
                fn decode_is_copy() -> bool {
                    true
                }
            }

            impl ValueTypeMarker for $numeric_ty {
                type Borrowed<'a> = $numeric_ty;

                #[inline(always)]
                fn borrow(value: &Self::Owned) -> Self::Borrowed<'_> {
                    *value
                }
            }

            unsafe impl<D: ResourceDialect> Encode<$numeric_ty, D> for $numeric_ty {
                #[inline(always)]
                unsafe fn encode(
                    self,
                    encoder: &mut Encoder<'_, D>,
                    offset: usize,
                    _depth: Depth,
                ) -> Result<()> {
                    encoder.debug_check_bounds::<$numeric_ty>(offset);
                    encoder.write_num::<$numeric_ty>(self, offset);
                    Ok(())
                }
            }

            impl<D: ResourceDialect> Decode<$numeric_ty, D> for $numeric_ty {
                #[inline(always)]
                fn new_empty() -> Self {
                    0 as $numeric_ty
                }

                #[inline(always)]
                unsafe fn decode(
                    &mut self,
                    decoder: &mut Decoder<'_, D>,
                    offset: usize,
                    _depth: Depth,
                ) -> Result<()> {
                    decoder.debug_check_bounds::<$numeric_ty>(offset);
                    *self = decoder.read_num::<$numeric_ty>(offset);
                    Ok(())
                }
            }
        };
    }

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

unsafe impl TypeMarker for bool {
    type Owned = bool;

    #[inline(always)]
    fn inline_align(_context: Context) -> usize {
        mem::align_of::<bool>()
    }

    #[inline(always)]
    fn inline_size(_context: Context) -> usize {
        mem::size_of::<bool>()
    }

    #[inline(always)]
    fn encode_is_copy() -> bool {
        // Rust guarantees a bool is 0x00 or 0x01.
        // https://doc.rust-lang.org/reference/types/boolean.html
        true
    }

    #[inline(always)]
    fn decode_is_copy() -> bool {
        // Decoding isn't just a copy because we have to ensure it's 0x00 or 0x01.
        false
    }
}

impl ValueTypeMarker for bool {
    type Borrowed<'a> = bool;

    #[inline(always)]
    fn borrow(value: &Self::Owned) -> Self::Borrowed<'_> {
        *value
    }
}

unsafe impl<D: ResourceDialect> Encode<bool, D> for bool {
    #[inline]
    unsafe fn encode(
        self,
        encoder: &mut Encoder<'_, D>,
        offset: usize,
        _depth: Depth,
    ) -> Result<()> {
        encoder.debug_check_bounds::<bool>(offset);
        // From https://doc.rust-lang.org/std/primitive.bool.html: "If you
        // cast a bool into an integer, true will be 1 and false will be 0."
        encoder.write_num(self as u8, offset);
        Ok(())
    }
}

impl<D: ResourceDialect> Decode<bool, D> for bool {
    #[inline(always)]
    fn new_empty() -> Self {
        false
    }

    #[inline]
    unsafe fn decode(
        &mut self,
        decoder: &mut Decoder<'_, D>,
        offset: usize,
        _depth: Depth,
    ) -> Result<()> {
        decoder.debug_check_bounds::<bool>(offset);
        // Safety: The caller ensures `offset` is valid for reading 1 byte.
        *self = match unsafe { *decoder.buf.get_unchecked(offset) } {
            0 => false,
            1 => true,
            _ => return Err(Error::InvalidBoolean),
        };
        Ok(())
    }
}

////////////////////////////////////////////////////////////////////////////////
// Arrays
////////////////////////////////////////////////////////////////////////////////

/// The FIDL type `array<T, N>`.
pub struct Array<T: TypeMarker, const N: usize>(PhantomData<T>);

unsafe impl<T: TypeMarker, const N: usize> TypeMarker for Array<T, N> {
    type Owned = [T::Owned; N];
    #[inline(always)]
    fn inline_align(context: Context) -> usize {
        T::inline_align(context)
    }

    #[inline(always)]
    fn inline_size(context: Context) -> usize {
        N * T::inline_size(context)
    }

    #[inline(always)]
    fn encode_is_copy() -> bool {
        T::encode_is_copy()
    }

    #[inline(always)]
    fn decode_is_copy() -> bool {
        T::decode_is_copy()
    }
}

impl<T: ValueTypeMarker, const N: usize> ValueTypeMarker for Array<T, N> {
    type Borrowed<'a> = &'a [T::Owned; N];
    #[inline(always)]
    fn borrow(value: &Self::Owned) -> Self::Borrowed<'_> {
        value
    }
}

impl<T: ResourceTypeMarker, const N: usize> ResourceTypeMarker for Array<T, N> {
    type Borrowed<'a> = &'a mut [T::Owned; N];
    #[inline(always)]
    fn take_or_borrow(value: &mut <Self as TypeMarker>::Owned) -> Self::Borrowed<'_> {
        value
    }
}

unsafe impl<T: ValueTypeMarker, const N: usize, D: ResourceDialect> Encode<Array<T, N>, D>
    for &[T::Owned; N]
where
    for<'q> T::Borrowed<'q>: Encode<T, D>,
{
    #[inline]
    unsafe fn encode(
        self,
        encoder: &mut Encoder<'_, D>,
        offset: usize,
        depth: Depth,
    ) -> Result<()> {
        encoder.debug_check_bounds::<Array<T, N>>(offset);
        encode_array_value::<T, D>(self, encoder, offset, depth)
    }
}

unsafe impl<T: ResourceTypeMarker, const N: usize, D: ResourceDialect> Encode<Array<T, N>, D>
    for &mut [<T as TypeMarker>::Owned; N]
where
    for<'q> T::Borrowed<'q>: Encode<T, D>,
{
    #[inline]
    unsafe fn encode(
        self,
        encoder: &mut Encoder<'_, D>,
        offset: usize,
        depth: Depth,
    ) -> Result<()> {
        encoder.debug_check_bounds::<Array<T, N>>(offset);
        encode_array_resource::<T, D>(self, encoder, offset, depth)
    }
}

impl<T: TypeMarker, const N: usize, D: ResourceDialect> Decode<Array<T, N>, D> for [T::Owned; N]
where
    T::Owned: Decode<T, D>,
{
    #[inline]
    fn new_empty() -> Self {
        let mut arr = mem::MaybeUninit::<[T::Owned; N]>::uninit();
        unsafe {
            let arr_ptr = arr.as_mut_ptr() as *mut T::Owned;
            for i in 0..N {
                ptr::write(arr_ptr.add(i), T::Owned::new_empty());
            }
            arr.assume_init()
        }
    }

    #[inline]
    unsafe fn decode(
        &mut self,
        decoder: &mut Decoder<'_, D>,
        offset: usize,
        depth: Depth,
    ) -> Result<()> {
        decoder.debug_check_bounds::<Array<T, N>>(offset);
        decode_array::<T, D>(self, decoder, offset, depth)
    }
}

#[inline]
unsafe fn encode_array_value<T: ValueTypeMarker, D: ResourceDialect>(
    slice: &[T::Owned],
    encoder: &mut Encoder<'_, D>,
    offset: usize,
    depth: Depth,
) -> Result<()>
where
    for<'a> T::Borrowed<'a>: Encode<T, D>,
{
    let stride = T::inline_size(encoder.context);
    let len = slice.len();
    // Not a safety requirement, but len should be nonzero since FIDL does not allow empty arrays.
    debug_assert_ne!(len, 0);
    if T::encode_is_copy() {
        debug_assert_eq!(stride, mem::size_of::<T::Owned>());
        // Safety:
        // - The caller ensures `offset` if valid for writing `stride` bytes
        //   (inline size of `T`) `len` times, i.e. `len * stride`.
        // - Since T::inline_size is the same as mem::size_of for simple
        //   copy types, `slice` also has exactly `len * stride` bytes.
        // - Rust guarantees `slice` and `encoder.buf` do not alias.
        unsafe {
            let src = slice.as_ptr() as *const u8;
            let dst: *mut u8 = encoder.buf.as_mut_ptr().add(offset);
            ptr::copy_nonoverlapping(src, dst, len * stride);
        }
    } else {
        for i in 0..len {
            // Safety: `i` is in bounds since `len` is defined as `slice.len()`.
            let item = unsafe { slice.get_unchecked(i) };
            T::borrow(item).encode(encoder, offset + i * stride, depth)?;
        }
    }
    Ok(())
}

#[inline]
unsafe fn encode_array_resource<T: ResourceTypeMarker + TypeMarker, D: ResourceDialect>(
    slice: &mut [T::Owned],
    encoder: &mut Encoder<'_, D>,
    offset: usize,
    depth: Depth,
) -> Result<()>
where
    for<'a> T::Borrowed<'a>: Encode<T, D>,
{
    let stride = T::inline_size(encoder.context);
    let len = slice.len();
    // Not a safety requirement, but len should be nonzero since FIDL does not allow empty arrays.
    debug_assert_ne!(len, 0);
    if T::encode_is_copy() {
        debug_assert_eq!(stride, mem::size_of::<T::Owned>());
        // Safety:
        // - The caller ensures `offset` if valid for writing `stride` bytes
        //   (inline size of `T`) `len` times, i.e. `len * stride`.
        // - Since T::inline_size is the same as mem::size_of for simple
        //   copy types, `slice` also has exactly `len * stride` bytes.
        // - Rust guarantees `slice` and `encoder.buf` do not alias.
        unsafe {
            let src = slice.as_ptr() as *const u8;
            let dst: *mut u8 = encoder.buf.as_mut_ptr().add(offset);
            ptr::copy_nonoverlapping(src, dst, len * stride);
        }
    } else {
        for i in 0..len {
            // Safety: `i` is in bounds since `len` is defined as `slice.len()`.
            let item = unsafe { slice.get_unchecked_mut(i) };
            T::take_or_borrow(item).encode(encoder, offset + i * stride, depth)?;
        }
    }
    Ok(())
}

#[inline]
unsafe fn decode_array<T: TypeMarker, D: ResourceDialect>(
    slice: &mut [T::Owned],
    decoder: &mut Decoder<'_, D>,
    offset: usize,
    depth: Depth,
) -> Result<()>
where
    T::Owned: Decode<T, D>,
{
    let stride = T::inline_size(decoder.context);
    let len = slice.len();
    // Not a safety requirement, but len should be nonzero since FIDL does not allow empty arrays.
    debug_assert_ne!(len, 0);
    if T::decode_is_copy() {
        debug_assert_eq!(stride, mem::size_of::<T::Owned>());
        // Safety:
        // - The caller ensures `offset` if valid for reading `stride` bytes
        //   (inline size of `T`) `len` times, i.e. `len * stride`.
        // - Since T::inline_size is the same as mem::size_of for simple copy
        //   types, `slice` also has exactly `len * stride` bytes.
        // - Rust guarantees `slice` and `decoder.buf` do not alias.
        unsafe {
            let src: *const u8 = decoder.buf.as_ptr().add(offset);
            let dst = slice.as_mut_ptr() as *mut u8;
            ptr::copy_nonoverlapping(src, dst, len * stride);
        }
    } else {
        for i in 0..len {
            // Safety: `i` is in bounds since `len` is defined as `slice.len()`.
            let item = unsafe { slice.get_unchecked_mut(i) };
            item.decode(decoder, offset + i * stride, depth)?;
        }
    }
    Ok(())
}

////////////////////////////////////////////////////////////////////////////////
// Vectors
////////////////////////////////////////////////////////////////////////////////

/// The maximum vector bound, corresponding to the `MAX` constraint in FIDL.
pub const MAX_BOUND: usize = usize::MAX;

/// The FIDL type `vector<T>:N`.
pub struct Vector<T: TypeMarker, const N: usize>(PhantomData<T>);

/// The FIDL type `vector<T>` or `vector<T>:MAX`.
pub type UnboundedVector<T> = Vector<T, MAX_BOUND>;

unsafe impl<T: TypeMarker, const N: usize> TypeMarker for Vector<T, N> {
    type Owned = Vec<T::Owned>;

    #[inline(always)]
    fn inline_align(_context: Context) -> usize {
        8
    }

    #[inline(always)]
    fn inline_size(_context: Context) -> usize {
        16
    }
}

impl<T: ValueTypeMarker, const N: usize> ValueTypeMarker for Vector<T, N> {
    type Borrowed<'a> = &'a [T::Owned];
    #[inline(always)]
    fn borrow(value: &Self::Owned) -> Self::Borrowed<'_> {
        value
    }
}

impl<T: ResourceTypeMarker, const N: usize> ResourceTypeMarker for Vector<T, N> {
    type Borrowed<'a> = &'a mut [T::Owned];
    #[inline(always)]
    fn take_or_borrow(value: &mut <Self as TypeMarker>::Owned) -> Self::Borrowed<'_> {
        value.as_mut_slice()
    }
}

unsafe impl<T: ValueTypeMarker, const N: usize, D: ResourceDialect> Encode<Vector<T, N>, D>
    for &[<T as TypeMarker>::Owned]
where
    for<'q> T::Borrowed<'q>: Encode<T, D>,
{
    #[inline]
    unsafe fn encode(
        self,
        encoder: &mut Encoder<'_, D>,
        offset: usize,
        depth: Depth,
    ) -> Result<()> {
        encoder.debug_check_bounds::<Vector<T, N>>(offset);
        encode_vector_value::<T, D>(self, N, check_vector_length, encoder, offset, depth)
    }
}

unsafe impl<T: ResourceTypeMarker + TypeMarker, const N: usize, D: ResourceDialect>
    Encode<Vector<T, N>, D> for &mut [<T as TypeMarker>::Owned]
where
    for<'q> T::Borrowed<'q>: Encode<T, D>,
{
    #[inline]
    unsafe fn encode(
        self,
        encoder: &mut Encoder<'_, D>,
        offset: usize,
        depth: Depth,
    ) -> Result<()> {
        encoder.debug_check_bounds::<Vector<T, N>>(offset);
        encode_vector_resource::<T, D>(self, N, encoder, offset, depth)
    }
}

impl<T: TypeMarker, const N: usize, D: ResourceDialect> Decode<Vector<T, N>, D> for Vec<T::Owned>
where
    T::Owned: Decode<T, D>,
{
    #[inline(always)]
    fn new_empty() -> Self {
        Vec::new()
    }

    #[inline]
    unsafe fn decode(
        &mut self,
        decoder: &mut Decoder<'_, D>,
        offset: usize,
        depth: Depth,
    ) -> Result<()> {
        decoder.debug_check_bounds::<Vector<T, N>>(offset);
        decode_vector::<T, D>(self, N, decoder, offset, depth)
    }
}

#[inline]
unsafe fn encode_vector_value<T: ValueTypeMarker, D: ResourceDialect>(
    slice: &[<T as TypeMarker>::Owned],
    max_length: usize,
    check_length: impl Fn(usize, usize) -> Result<()>,
    encoder: &mut Encoder<'_, D>,
    offset: usize,
    mut depth: Depth,
) -> Result<()>
where
    for<'a> T::Borrowed<'a>: Encode<T, D>,
{
    encoder.write_num(slice.len() as u64, offset);
    encoder.write_num(ALLOC_PRESENT_U64, offset + 8);
    // Calling encoder.out_of_line_offset(0) is not allowed.
    if slice.is_empty() {
        return Ok(());
    }
    check_length(slice.len(), max_length)?;
    depth.increment()?;
    let bytes_len = slice.len() * T::inline_size(encoder.context);
    let offset = encoder.out_of_line_offset(bytes_len);
    encode_array_value::<T, D>(slice, encoder, offset, depth)
}

#[inline]
unsafe fn encode_vector_resource<T: ResourceTypeMarker + TypeMarker, D: ResourceDialect>(
    slice: &mut [T::Owned],
    max_length: usize,
    encoder: &mut Encoder<'_, D>,
    offset: usize,
    mut depth: Depth,
) -> Result<()>
where
    for<'a> T::Borrowed<'a>: Encode<T, D>,
{
    encoder.write_num(slice.len() as u64, offset);
    encoder.write_num(ALLOC_PRESENT_U64, offset + 8);
    // Calling encoder.out_of_line_offset(0) is not allowed.
    if slice.is_empty() {
        return Ok(());
    }
    check_vector_length(slice.len(), max_length)?;
    depth.increment()?;
    let bytes_len = slice.len() * T::inline_size(encoder.context);
    let offset = encoder.out_of_line_offset(bytes_len);
    encode_array_resource::<T, D>(slice, encoder, offset, depth)
}

#[inline]
unsafe fn decode_vector<T: TypeMarker, D: ResourceDialect>(
    vec: &mut Vec<T::Owned>,
    max_length: usize,
    decoder: &mut Decoder<'_, D>,
    offset: usize,
    mut depth: Depth,
) -> Result<()>
where
    T::Owned: Decode<T, D>,
{
    let Some(len) = decode_vector_header(decoder, offset)? else {
        return Err(Error::NotNullable);
    };
    // Calling decoder.out_of_line_offset(0) is not allowed.
    if len == 0 {
        return Ok(());
    }
    check_vector_length(len, max_length)?;
    depth.increment()?;
    let bytes_len = len * T::inline_size(decoder.context);
    let offset = decoder.out_of_line_offset(bytes_len)?;
    if T::decode_is_copy() {
        // Safety: The uninitialized elements are immediately written by
        // `decode_array`, which always succeeds in the simple copy case.
        unsafe {
            resize_vec_no_zeroing(vec, len);
        }
    } else {
        vec.resize_with(len, T::Owned::new_empty);
    }
    // Safety: `vec` has `len` elements based on the above code.
    decode_array::<T, D>(vec, decoder, offset, depth)?;
    Ok(())
}

/// Decodes and validates a 16-byte vector header. Returns `Some(len)` if
/// the vector is present (including empty vectors), otherwise `None`.
#[doc(hidden)] // only exported for use in macros or generated code
#[inline]
pub fn decode_vector_header<D: ResourceDialect>(
    decoder: &mut Decoder<'_, D>,
    offset: usize,
) -> Result<Option<usize>> {
    let len = decoder.read_num::<u64>(offset) as usize;
    match decoder.read_num::<u64>(offset + 8) {
        ALLOC_PRESENT_U64 => {
            // Check that the length does not exceed `u32::MAX` (per RFC-0059)
            // nor the total size of the message (to avoid a huge allocation
            // when the message cannot possibly be valid).
            if len <= u32::MAX as usize && len <= decoder.buf.len() {
                Ok(Some(len))
            } else {
                Err(Error::OutOfRange)
            }
        }
        ALLOC_ABSENT_U64 => {
            if len == 0 {
                Ok(None)
            } else {
                Err(Error::UnexpectedNullRef)
            }
        }
        _ => Err(Error::InvalidPresenceIndicator),
    }
}

#[inline(always)]
fn check_vector_length(actual_length: usize, max_length: usize) -> Result<()> {
    if actual_length > max_length {
        return Err(Error::VectorTooLong { max_length, actual_length });
    }
    Ok(())
}

////////////////////////////////////////////////////////////////////////////////
// Strings
////////////////////////////////////////////////////////////////////////////////

/// The FIDL type `string:N`.
pub struct BoundedString<const N: usize>;

/// The FIDL type `string` or `string:MAX`.
pub type UnboundedString = BoundedString<MAX_BOUND>;

unsafe impl<const N: usize> TypeMarker for BoundedString<N> {
    type Owned = String;

    #[inline(always)]
    fn inline_align(_context: Context) -> usize {
        8
    }

    #[inline(always)]
    fn inline_size(_context: Context) -> usize {
        16
    }
}

impl<const N: usize> ValueTypeMarker for BoundedString<N> {
    type Borrowed<'a> = &'a str;
    #[inline(always)]
    fn borrow(value: &Self::Owned) -> Self::Borrowed<'_> {
        value
    }
}

unsafe impl<const N: usize, D: ResourceDialect> Encode<BoundedString<N>, D> for &str {
    #[inline]
    unsafe fn encode(
        self,
        encoder: &mut Encoder<'_, D>,
        offset: usize,
        depth: Depth,
    ) -> Result<()> {
        encoder.debug_check_bounds::<BoundedString<N>>(offset);
        encode_vector_value::<u8, D>(
            self.as_bytes(),
            N,
            check_string_length,
            encoder,
            offset,
            depth,
        )
    }
}

impl<const N: usize, D: ResourceDialect> Decode<BoundedString<N>, D> for String {
    #[inline(always)]
    fn new_empty() -> Self {
        String::new()
    }

    #[inline]
    unsafe fn decode(
        &mut self,
        decoder: &mut Decoder<'_, D>,
        offset: usize,
        depth: Depth,
    ) -> Result<()> {
        decoder.debug_check_bounds::<BoundedString<N>>(offset);
        decode_string(self, N, decoder, offset, depth)
    }
}

#[inline]
fn decode_string<D: ResourceDialect>(
    string: &mut String,
    max_length: usize,
    decoder: &mut Decoder<'_, D>,
    offset: usize,
    mut depth: Depth,
) -> Result<()> {
    let Some(len) = decode_vector_header(decoder, offset)? else {
        return Err(Error::NotNullable);
    };
    // Calling decoder.out_of_line_offset(0) is not allowed.
    if len == 0 {
        return Ok(());
    }
    check_string_length(len, max_length)?;
    depth.increment()?;
    // Safety: we return early above if `len == 0`.
    let offset = unsafe { decoder.out_of_line_offset(len)? };
    // Safety: `out_of_line_offset` does this bounds check.
    let bytes = unsafe { &decoder.buf.get_unchecked(offset..offset + len) };
    let utf8 = str::from_utf8(bytes).map_err(|_| Error::Utf8Error)?;
    let boxed_utf8: Box<str> = utf8.into();
    *string = boxed_utf8.into_string();
    Ok(())
}

#[inline(always)]
fn check_string_length(actual_bytes: usize, max_bytes: usize) -> Result<()> {
    if actual_bytes > max_bytes {
        return Err(Error::StringTooLong { max_bytes, actual_bytes });
    }
    Ok(())
}

////////////////////////////////////////////////////////////////////////////////
// Handles
////////////////////////////////////////////////////////////////////////////////

impl<T: HandleBased> EncodableAsHandle for T {
    type Dialect = DefaultFuchsiaResourceDialect;
}

/// The FIDL type `zx.Handle:<OBJECT_TYPE, RIGHTS>`, or a `client_end` or `server_end`.
pub struct HandleType<T: EncodableAsHandle, const OBJECT_TYPE: u32, const RIGHTS: u32>(
    PhantomData<T>,
);

/// An abbreviation of `HandleType` that for channels with default rights, used
/// for the FIDL types `client_end:P` and `server_end:P`.
pub type Endpoint<T> = HandleType<
    T,
    { crate::ObjectType::CHANNEL.into_raw() },
    { crate::Rights::CHANNEL_DEFAULT.bits() },
>;

unsafe impl<T: 'static + EncodableAsHandle, const OBJECT_TYPE: u32, const RIGHTS: u32> TypeMarker
    for HandleType<T, OBJECT_TYPE, RIGHTS>
{
    type Owned = T;

    #[inline(always)]
    fn inline_align(_context: Context) -> usize {
        4
    }

    #[inline(always)]
    fn inline_size(_context: Context) -> usize {
        4
    }
}

impl<T: 'static + EncodableAsHandle, const OBJECT_TYPE: u32, const RIGHTS: u32> ResourceTypeMarker
    for HandleType<T, OBJECT_TYPE, RIGHTS>
{
    type Borrowed<'a> = T;
    #[inline(always)]
    fn take_or_borrow(value: &mut <Self as TypeMarker>::Owned) -> Self::Borrowed<'_> {
        mem::replace(value, <T::Dialect as ResourceDialect>::Handle::invalid().into())
    }
}

unsafe impl<T: 'static + EncodableAsHandle, const OBJECT_TYPE: u32, const RIGHTS: u32>
    Encode<HandleType<T, OBJECT_TYPE, RIGHTS>, T::Dialect> for T
{
    #[inline]
    unsafe fn encode(
        self,
        encoder: &mut Encoder<'_, T::Dialect>,
        offset: usize,
        _depth: Depth,
    ) -> Result<()> {
        encoder.debug_check_bounds::<HandleType<T, OBJECT_TYPE, RIGHTS>>(offset);
        encode_handle(
            self.into(),
            crate::ObjectType::from_raw(OBJECT_TYPE),
            crate::Rights::from_bits_retain(RIGHTS),
            encoder,
            offset,
        )
    }
}

impl<T: 'static + EncodableAsHandle, const OBJECT_TYPE: u32, const RIGHTS: u32>
    Decode<HandleType<T, OBJECT_TYPE, RIGHTS>, T::Dialect> for T
{
    #[inline(always)]
    fn new_empty() -> Self {
        <T::Dialect as ResourceDialect>::Handle::invalid().into()
    }

    #[inline]
    unsafe fn decode(
        &mut self,
        decoder: &mut Decoder<'_, T::Dialect>,
        offset: usize,
        _depth: Depth,
    ) -> Result<()> {
        decoder.debug_check_bounds::<HandleType<T, OBJECT_TYPE, RIGHTS>>(offset);
        *self = decode_handle(
            crate::ObjectType::from_raw(OBJECT_TYPE),
            crate::Rights::from_bits_retain(RIGHTS),
            decoder,
            offset,
        )?
        .into();
        Ok(())
    }
}

#[inline]
unsafe fn encode_handle<D: ResourceDialect>(
    handle: D::Handle,
    object_type: crate::ObjectType,
    rights: crate::Rights,
    encoder: &mut Encoder<'_, D>,
    offset: usize,
) -> Result<()> {
    if handle.is_invalid() {
        return Err(Error::NotNullable);
    }
    encoder.write_num(ALLOC_PRESENT_U32, offset);
    encoder.handles.push(<D::ProxyChannel as ProxyChannelFor<D>>::HandleDisposition::from_handle(
        handle,
        object_type,
        rights,
    ));
    Ok(())
}

#[inline]
unsafe fn decode_handle<D: ResourceDialect>(
    object_type: crate::ObjectType,
    rights: crate::Rights,
    decoder: &mut Decoder<'_, D>,
    offset: usize,
) -> Result<D::Handle> {
    match decoder.read_num::<u32>(offset) {
        ALLOC_PRESENT_U32 => {}
        ALLOC_ABSENT_U32 => return Err(Error::NotNullable),
        _ => return Err(Error::InvalidPresenceIndicator),
    }
    decoder.take_next_handle(object_type, rights)
}

////////////////////////////////////////////////////////////////////////////////
// Optionals
////////////////////////////////////////////////////////////////////////////////

/// The FIDL type `T:optional` where `T` is a vector, string, handle, or client/server end.
pub struct Optional<T: TypeMarker>(PhantomData<T>);

/// The FIDL type `T:optional` where `T` is a union.
pub struct OptionalUnion<T: TypeMarker>(PhantomData<T>);

/// The FIDL type `box<T>`.
pub struct Boxed<T: TypeMarker>(PhantomData<T>);

unsafe impl<T: TypeMarker> TypeMarker for Optional<T> {
    type Owned = Option<T::Owned>;

    #[inline(always)]
    fn inline_align(context: Context) -> usize {
        T::inline_align(context)
    }

    #[inline(always)]
    fn inline_size(context: Context) -> usize {
        T::inline_size(context)
    }
}

unsafe impl<T: TypeMarker> TypeMarker for OptionalUnion<T> {
    type Owned = Option<Box<T::Owned>>;

    #[inline(always)]
    fn inline_align(context: Context) -> usize {
        T::inline_align(context)
    }

    #[inline(always)]
    fn inline_size(context: Context) -> usize {
        T::inline_size(context)
    }
}

unsafe impl<T: TypeMarker> TypeMarker for Boxed<T> {
    type Owned = Option<Box<T::Owned>>;

    #[inline(always)]
    fn inline_align(_context: Context) -> usize {
        8
    }

    #[inline(always)]
    fn inline_size(_context: Context) -> usize {
        8
    }
}

impl<T: ValueTypeMarker> ValueTypeMarker for Optional<T> {
    type Borrowed<'a> = Option<T::Borrowed<'a>>;

    #[inline(always)]
    fn borrow(value: &Self::Owned) -> Self::Borrowed<'_> {
        value.as_ref().map(T::borrow)
    }
}

impl<T: ValueTypeMarker> ValueTypeMarker for OptionalUnion<T> {
    type Borrowed<'a> = Option<T::Borrowed<'a>>;

    #[inline(always)]
    fn borrow(value: &Self::Owned) -> Self::Borrowed<'_> {
        value.as_deref().map(T::borrow)
    }
}

impl<T: ValueTypeMarker> ValueTypeMarker for Boxed<T> {
    type Borrowed<'a> = Option<T::Borrowed<'a>>;

    #[inline(always)]
    fn borrow(value: &Self::Owned) -> Self::Borrowed<'_> {
        value.as_deref().map(T::borrow)
    }
}

impl<T: ResourceTypeMarker + TypeMarker> ResourceTypeMarker for Optional<T> {
    type Borrowed<'a> = Option<T::Borrowed<'a>>;
    #[inline(always)]
    fn take_or_borrow(value: &mut <Self as TypeMarker>::Owned) -> Self::Borrowed<'_> {
        value.as_mut().map(T::take_or_borrow)
    }
}

impl<T: ResourceTypeMarker + TypeMarker> ResourceTypeMarker for OptionalUnion<T> {
    type Borrowed<'a> = Option<T::Borrowed<'a>>;
    #[inline(always)]
    fn take_or_borrow(value: &mut <Self as TypeMarker>::Owned) -> Self::Borrowed<'_> {
        value.as_deref_mut().map(T::take_or_borrow)
    }
}

impl<T: ResourceTypeMarker + TypeMarker> ResourceTypeMarker for Boxed<T> {
    type Borrowed<'a> = Option<T::Borrowed<'a>>;
    #[inline(always)]
    fn take_or_borrow(value: &mut <Self as TypeMarker>::Owned) -> Self::Borrowed<'_> {
        value.as_deref_mut().map(T::take_or_borrow)
    }
}

unsafe impl<T: TypeMarker, E: Encode<T, D>, D: ResourceDialect> Encode<Optional<T>, D>
    for Option<E>
{
    #[inline]
    unsafe fn encode(
        self,
        encoder: &mut Encoder<'_, D>,
        offset: usize,
        depth: Depth,
    ) -> Result<()> {
        encoder.debug_check_bounds::<Optional<T>>(offset);
        encode_naturally_optional::<T, E, D>(self, encoder, offset, depth)
    }
}

unsafe impl<T: TypeMarker, E: Encode<T, D>, D: ResourceDialect> Encode<OptionalUnion<T>, D>
    for Option<E>
{
    #[inline]
    unsafe fn encode(
        self,
        encoder: &mut Encoder<'_, D>,
        offset: usize,
        depth: Depth,
    ) -> Result<()> {
        encoder.debug_check_bounds::<OptionalUnion<T>>(offset);
        encode_naturally_optional::<T, E, D>(self, encoder, offset, depth)
    }
}

unsafe impl<T: TypeMarker, E: Encode<T, D>, D: ResourceDialect> Encode<Boxed<T>, D> for Option<E> {
    #[inline]
    unsafe fn encode(
        self,
        encoder: &mut Encoder<'_, D>,
        offset: usize,
        mut depth: Depth,
    ) -> Result<()> {
        encoder.debug_check_bounds::<Boxed<T>>(offset);
        match self {
            Some(val) => {
                depth.increment()?;
                encoder.write_num(ALLOC_PRESENT_U64, offset);
                let offset = encoder.out_of_line_offset(T::inline_size(encoder.context));
                val.encode(encoder, offset, depth)?;
            }
            None => encoder.write_num(ALLOC_ABSENT_U64, offset),
        }
        Ok(())
    }
}

impl<T: TypeMarker, D: ResourceDialect> Decode<Optional<T>, D> for Option<T::Owned>
where
    T::Owned: Decode<T, D>,
{
    #[inline(always)]
    fn new_empty() -> Self {
        None
    }

    #[inline]
    unsafe fn decode(
        &mut self,
        decoder: &mut Decoder<'_, D>,
        offset: usize,
        depth: Depth,
    ) -> Result<()> {
        decoder.debug_check_bounds::<Optional<T>>(offset);
        let inline_size = T::inline_size(decoder.context);
        if check_for_presence(decoder, offset, inline_size) {
            self.get_or_insert(T::Owned::new_empty()).decode(decoder, offset, depth)
        } else {
            *self = None;
            decoder.check_padding(offset, inline_size)?;
            Ok(())
        }
    }
}

impl<T: TypeMarker, D: ResourceDialect> Decode<OptionalUnion<T>, D> for Option<Box<T::Owned>>
where
    T::Owned: Decode<T, D>,
{
    #[inline(always)]
    fn new_empty() -> Self {
        None
    }

    #[inline]
    unsafe fn decode(
        &mut self,
        decoder: &mut Decoder<'_, D>,
        offset: usize,
        depth: Depth,
    ) -> Result<()> {
        decoder.debug_check_bounds::<OptionalUnion<T>>(offset);
        let inline_size = T::inline_size(decoder.context);
        if check_for_presence(decoder, offset, inline_size) {
            decode!(
                T,
                self.get_or_insert_with(|| Box::new(T::Owned::new_empty())),
                decoder,
                offset,
                depth
            )
        } else {
            *self = None;
            decoder.check_padding(offset, inline_size)?;
            Ok(())
        }
    }
}

impl<T: TypeMarker, D: ResourceDialect> Decode<Boxed<T>, D> for Option<Box<T::Owned>>
where
    T::Owned: Decode<T, D>,
{
    #[inline(always)]
    fn new_empty() -> Self {
        None
    }

    #[inline]
    unsafe fn decode(
        &mut self,
        decoder: &mut Decoder<'_, D>,
        offset: usize,
        mut depth: Depth,
    ) -> Result<()> {
        decoder.debug_check_bounds::<Boxed<T>>(offset);
        match decoder.read_num::<u64>(offset) {
            ALLOC_PRESENT_U64 => {
                depth.increment()?;
                let offset = decoder.out_of_line_offset(T::inline_size(decoder.context))?;
                decode!(
                    T,
                    self.get_or_insert_with(|| Box::new(T::Owned::new_empty())),
                    decoder,
                    offset,
                    depth
                )?;
                Ok(())
            }
            ALLOC_ABSENT_U64 => {
                *self = None;
                Ok(())
            }
            _ => Err(Error::InvalidPresenceIndicator),
        }
    }
}

/// Encodes a "naturally optional" value, i.e. one where absence is represented
/// by a run of 0x00 bytes matching the type's inline size.
#[inline]
unsafe fn encode_naturally_optional<T: TypeMarker, E: Encode<T, D>, D: ResourceDialect>(
    value: Option<E>,
    encoder: &mut Encoder<'_, D>,
    offset: usize,
    depth: Depth,
) -> Result<()> {
    match value {
        Some(val) => val.encode(encoder, offset, depth)?,
        None => encoder.padding(offset, T::inline_size(encoder.context)),
    }
    Ok(())
}

/// Presence indicators always include at least one non-zero byte, while absence
/// indicators should always be entirely zeros. Like `Decode::decode`, the
/// caller is responsible for bounds checks.
#[inline]
fn check_for_presence<D: ResourceDialect>(
    decoder: &Decoder<'_, D>,
    offset: usize,
    inline_size: usize,
) -> bool {
    debug_assert!(offset + inline_size <= decoder.buf.len());
    let range = unsafe { decoder.buf.get_unchecked(offset..offset + inline_size) };
    range.iter().any(|byte| *byte != 0)
}

////////////////////////////////////////////////////////////////////////////////
// Envelopes
////////////////////////////////////////////////////////////////////////////////

#[doc(hidden)] // only exported for use in macros or generated code
#[inline]
pub unsafe fn encode_in_envelope<T: TypeMarker, D: ResourceDialect>(
    val: impl Encode<T, D>,
    encoder: &mut Encoder<'_, D>,
    offset: usize,
    mut depth: Depth,
) -> Result<()> {
    depth.increment()?;
    let bytes_before = encoder.buf.len();
    let handles_before = encoder.handles.len();
    let inline_size = T::inline_size(encoder.context);
    if inline_size <= 4 {
        // Zero out the 4 byte inlined region and set the flag at the same time.
        encoder.write_num(1u64 << 48, offset);
        val.encode(encoder, offset, depth)?;
        let handles_written = (encoder.handles.len() - handles_before) as u16;
        encoder.write_num(handles_written, offset + 4);
    } else {
        let out_of_line_offset = encoder.out_of_line_offset(inline_size);
        val.encode(encoder, out_of_line_offset, depth)?;
        let bytes_written = (encoder.buf.len() - bytes_before) as u32;
        let handles_written = (encoder.handles.len() - handles_before) as u32;
        debug_assert_eq!(bytes_written % 8, 0);
        encoder.write_num(bytes_written, offset);
        encoder.write_num(handles_written, offset + 4);
    }
    Ok(())
}

#[doc(hidden)] // only exported for use in macros or generated code
#[inline]
pub unsafe fn encode_in_envelope_optional<T: TypeMarker, D: ResourceDialect>(
    val: Option<impl Encode<T, D>>,
    encoder: &mut Encoder<'_, D>,
    offset: usize,
    depth: Depth,
) -> Result<()> {
    match val {
        None => encoder.write_num(0u64, offset),
        Some(val) => encode_in_envelope(val, encoder, offset, depth)?,
    }
    Ok(())
}

/// Decodes and validates an envelope header. Returns `None` if absent and
/// `Some((inlined, num_bytes, num_handles))` if present.
#[doc(hidden)] // only exported for use in macros or generated code
#[inline(always)]
pub unsafe fn decode_envelope_header<D: ResourceDialect>(
    decoder: &mut Decoder<'_, D>,
    offset: usize,
) -> Result<Option<(bool, u32, u32)>> {
    let num_bytes = decoder.read_num::<u32>(offset);
    let num_handles = decoder.read_num::<u16>(offset + 4) as u32;
    let inlined = decoder.read_num::<u16>(offset + 6);
    match (num_bytes, num_handles, inlined) {
        (0, 0, 0) => Ok(None),
        (_, _, 1) => Ok(Some((true, 4, num_handles))),
        (_, _, 0) if num_bytes % 8 == 0 => Ok(Some((false, num_bytes, num_handles))),
        (_, _, 0) => Err(Error::InvalidNumBytesInEnvelope),
        _ => Err(Error::InvalidInlineMarkerInEnvelope),
    }
}

/// Decodes a FIDL envelope and skips over any out-of-line bytes and handles.
#[doc(hidden)] // only exported for use in macros or generated code
#[inline]
pub unsafe fn decode_unknown_envelope<D: ResourceDialect>(
    decoder: &mut Decoder<'_, D>,
    offset: usize,
    mut depth: Depth,
) -> Result<()> {
    if let Some((inlined, num_bytes, num_handles)) = decode_envelope_header(decoder, offset)? {
        if !inlined {
            depth.increment()?;
            // Calling decoder.out_of_line_offset(0) is not allowed.
            if num_bytes != 0 {
                let _ = decoder.out_of_line_offset(num_bytes as usize)?;
            }
        }
        if num_handles != 0 {
            for _ in 0..num_handles {
                decoder.drop_next_handle()?;
            }
        }
    }
    Ok(())
}

////////////////////////////////////////////////////////////////////////////////
// Unions
////////////////////////////////////////////////////////////////////////////////

/// Decodes the inline portion of a union.
/// Returns `(ordinal, inlined, num_bytes, num_handles)`.
#[doc(hidden)] // only exported for use in macros or generated code
#[inline]
pub unsafe fn decode_union_inline_portion<D: ResourceDialect>(
    decoder: &mut Decoder<'_, D>,
    offset: usize,
) -> Result<(u64, bool, u32, u32)> {
    let ordinal = decoder.read_num::<u64>(offset);
    match decode_envelope_header(decoder, offset + 8)? {
        Some((inlined, num_bytes, num_handles)) => Ok((ordinal, inlined, num_bytes, num_handles)),
        None => Err(Error::NotNullable),
    }
}

////////////////////////////////////////////////////////////////////////////////
// Result unions
////////////////////////////////////////////////////////////////////////////////

/// The FIDL union generated for strict two-way methods with errors.
pub struct ResultType<T: TypeMarker, E: TypeMarker>(PhantomData<(T, E)>);

/// The FIDL union generated for flexible two-way methods without errors.
pub struct FlexibleType<T: TypeMarker>(PhantomData<T>);

/// The FIDL union generated for flexible two-way methods with errors.
pub struct FlexibleResultType<T: TypeMarker, E: TypeMarker>(PhantomData<(T, E)>);

/// Owned type for `FlexibleType`.
#[doc(hidden)] // only exported for use in macros or generated code
#[derive(Debug)]
pub enum Flexible<T> {
    Ok(T),
    FrameworkErr(FrameworkErr),
}

/// Owned type for `FlexibleResultType`.
#[doc(hidden)] // only exported for use in macros or generated code
#[derive(Debug)]
pub enum FlexibleResult<T, E> {
    Ok(T),
    DomainErr(E),
    FrameworkErr(FrameworkErr),
}

/// Internal FIDL framework error type used to identify unknown methods.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[repr(i32)]
pub enum FrameworkErr {
    /// Method was not recognized.
    UnknownMethod = zx_types::ZX_ERR_NOT_SUPPORTED,
}

impl FrameworkErr {
    #[inline]
    fn from_primitive(prim: i32) -> Option<Self> {
        match prim {
            zx_types::ZX_ERR_NOT_SUPPORTED => Some(Self::UnknownMethod),
            _ => None,
        }
    }

    #[inline(always)]
    const fn into_primitive(self) -> i32 {
        self as i32
    }
}

unsafe impl TypeMarker for FrameworkErr {
    type Owned = Self;
    #[inline(always)]
    fn inline_align(_context: Context) -> usize {
        std::mem::align_of::<i32>()
    }

    #[inline(always)]
    fn inline_size(_context: Context) -> usize {
        std::mem::size_of::<i32>()
    }

    #[inline(always)]
    fn encode_is_copy() -> bool {
        true
    }

    #[inline(always)]
    fn decode_is_copy() -> bool {
        false
    }
}

impl ValueTypeMarker for FrameworkErr {
    type Borrowed<'a> = Self;
    #[inline(always)]
    fn borrow(value: &Self::Owned) -> Self::Borrowed<'_> {
        *value
    }
}

unsafe impl<D: ResourceDialect> Encode<Self, D> for FrameworkErr {
    #[inline]
    unsafe fn encode(
        self,
        encoder: &mut Encoder<'_, D>,
        offset: usize,
        _depth: Depth,
    ) -> Result<()> {
        encoder.debug_check_bounds::<Self>(offset);
        encoder.write_num(self.into_primitive(), offset);
        Ok(())
    }
}

impl<D: ResourceDialect> Decode<Self, D> for FrameworkErr {
    #[inline(always)]
    fn new_empty() -> Self {
        Self::UnknownMethod
    }

    #[inline]
    unsafe fn decode(
        &mut self,
        decoder: &mut Decoder<'_, D>,
        offset: usize,
        _depth: Depth,
    ) -> Result<()> {
        decoder.debug_check_bounds::<Self>(offset);
        let prim = decoder.read_num::<i32>(offset);
        *self = Self::from_primitive(prim).ok_or(Error::InvalidEnumValue)?;
        Ok(())
    }
}

impl<T> Flexible<T> {
    /// Creates a new instance from the underlying value.
    pub fn new(value: T) -> Self {
        Self::Ok(value)
    }

    /// Converts to a `fidl::Result`, mapping framework errors to `fidl::Error`.
    pub fn into_result<P: ProtocolMarker>(self, method_name: &'static str) -> Result<T> {
        match self {
            Flexible::Ok(ok) => Ok(ok),
            Flexible::FrameworkErr(FrameworkErr::UnknownMethod) => {
                Err(Error::UnsupportedMethod { method_name, protocol_name: P::DEBUG_NAME })
            }
        }
    }
}

impl<T, E> FlexibleResult<T, E> {
    /// Creates a new instance from an `std::result::Result`.
    pub fn new(result: std::result::Result<T, E>) -> Self {
        match result {
            Ok(value) => Self::Ok(value),
            Err(err) => Self::DomainErr(err),
        }
    }

    /// Converts to a `fidl::Result`, mapping framework errors to `fidl::Error`.
    pub fn into_result<P: ProtocolMarker>(
        self,
        method_name: &'static str,
    ) -> Result<std::result::Result<T, E>> {
        match self {
            FlexibleResult::Ok(ok) => Ok(Ok(ok)),
            FlexibleResult::DomainErr(err) => Ok(Err(err)),
            FlexibleResult::FrameworkErr(FrameworkErr::UnknownMethod) => {
                Err(Error::UnsupportedMethod { method_name, protocol_name: P::DEBUG_NAME })
            }
        }
    }
}

/// Implements `TypeMarker`, `Encode`, and `Decode` for a result union type.
macro_rules! impl_result_union {
    (
        params: [$($encode_param:ident: Encode<$type_param:ident>),*],
        ty: $ty:ty,
        owned: $owned:ty,
        encode: $encode:ty,
        members: [$(
            {
                ctor: { $($member_ctor:tt)* },
                ty: $member_ty:ty,
                ordinal: $member_ordinal:tt,
            },
        )*]
    ) => {
        unsafe impl<$($type_param: TypeMarker),*> TypeMarker for $ty {
            type Owned = $owned;

            #[inline(always)]
            fn inline_align(_context: Context) -> usize {
                8
            }

            #[inline(always)]
            fn inline_size(_context: Context) -> usize {
                16
            }
        }

        unsafe impl<D: ResourceDialect, $($type_param: TypeMarker, $encode_param: Encode<$type_param, D>),*> Encode<$ty, D> for $encode {
            #[inline]
            unsafe fn encode(self, encoder: &mut Encoder<'_, D>, offset: usize, depth: Depth) -> Result<()> {
                encoder.debug_check_bounds::<$ty>(offset);
                match self {
                    $(
                        $($member_ctor)*(val) => {
                            encoder.write_num::<u64>($member_ordinal, offset);
                            encode_in_envelope::<$member_ty, D>(val, encoder, offset + 8, depth)
                        }
                    )*
                }
            }
        }

        impl<D: ResourceDialect, $($type_param: TypeMarker),*> Decode<$ty, D> for $owned
        where $($type_param::Owned: Decode<$type_param, D>),*
        {
            #[inline(always)]
            fn new_empty() -> Self {
                #![allow(unreachable_code)]
                $(
                    return $($member_ctor)*(new_empty!($member_ty, D));
                )*
            }

            #[inline]
            unsafe fn decode(&mut self, decoder: &mut Decoder<'_, D>, offset: usize, mut depth: Depth) -> Result<()> {
                decoder.debug_check_bounds::<$ty>(offset);
                let next_out_of_line = decoder.next_out_of_line();
                let handles_before = decoder.remaining_handles();
                let (ordinal, inlined, num_bytes, num_handles) = decode_union_inline_portion(decoder, offset)?;
                let member_inline_size = match ordinal {
                    $(
                        $member_ordinal => <$member_ty as TypeMarker>::inline_size(decoder.context),
                    )*
                    _ => return Err(Error::UnknownUnionTag),
                };
                if inlined != (member_inline_size <= 4) {
                    return Err(Error::InvalidInlineBitInEnvelope);
                }
                let inner_offset;
                if inlined {
                    decoder.check_inline_envelope_padding(offset + 8, member_inline_size)?;
                    inner_offset = offset + 8;
                } else {
                    depth.increment()?;
                    inner_offset = decoder.out_of_line_offset(member_inline_size)?;
                }
                match ordinal {
                    $(
                        $member_ordinal => {
                            #[allow(irrefutable_let_patterns)]
                            if let $($member_ctor)*(_) = self {
                                // Do nothing, read the value into the object
                            } else {
                                // Initialize `self` to the right variant
                                *self = $($member_ctor)*(new_empty!($member_ty, D));
                            }
                            #[allow(irrefutable_let_patterns)]
                            if let $($member_ctor)*(ref mut val) = self {
                                decode!($member_ty, D, val, decoder, inner_offset, depth)?;
                            } else {
                                unreachable!()
                            }
                        }
                    )*
                    ordinal => panic!("unexpected ordinal {:?}", ordinal)
                }
                if !inlined && decoder.next_out_of_line() != next_out_of_line + (num_bytes as usize) {
                    return Err(Error::InvalidNumBytesInEnvelope);
                }
                if handles_before != decoder.remaining_handles() + (num_handles as usize) {
                    return Err(Error::InvalidNumHandlesInEnvelope);
                }
                Ok(())
            }
        }
    };
}

impl_result_union! {
    params: [X: Encode<T>, Y: Encode<E>],
    ty: ResultType<T, E>,
    owned: std::result::Result<T::Owned, E::Owned>,
    encode: std::result::Result<X, Y>,
    members: [
        { ctor: { Ok }, ty: T, ordinal: 1, },
        { ctor: { Err }, ty: E, ordinal: 2, },
    ]
}

impl_result_union! {
    params: [X: Encode<T>],
    ty: FlexibleType<T>,
    owned: Flexible<T::Owned>,
    encode: Flexible<X>,
    members: [
        { ctor: { Flexible::Ok }, ty: T, ordinal: 1, },
        { ctor: { Flexible::FrameworkErr }, ty: FrameworkErr, ordinal: 3, },
    ]
}

impl_result_union! {
    params: [X: Encode<T>, Y: Encode<E>],
    ty: FlexibleResultType<T, E>,
    owned: FlexibleResult<T::Owned, E::Owned>,
    encode: FlexibleResult<X, Y>,
    members: [
        { ctor: { FlexibleResult::Ok }, ty: T, ordinal: 1, },
        { ctor: { FlexibleResult::DomainErr }, ty: E, ordinal: 2, },
        { ctor: { FlexibleResult::FrameworkErr }, ty: FrameworkErr, ordinal: 3, },
    ]
}

////////////////////////////////////////////////////////////////////////////////
// Epitaphs
////////////////////////////////////////////////////////////////////////////////

/// The body of a FIDL Epitaph
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct EpitaphBody {
    /// The error status.
    pub error: zx_status::Status,
}

unsafe impl TypeMarker for EpitaphBody {
    type Owned = Self;

    #[inline(always)]
    fn inline_align(_context: Context) -> usize {
        4
    }

    #[inline(always)]
    fn inline_size(_context: Context) -> usize {
        4
    }
}

impl ValueTypeMarker for EpitaphBody {
    type Borrowed<'a> = &'a Self;

    fn borrow(value: &Self::Owned) -> Self::Borrowed<'_> {
        value
    }
}

unsafe impl<D: ResourceDialect> Encode<EpitaphBody, D> for &EpitaphBody {
    #[inline]
    unsafe fn encode(
        self,
        encoder: &mut Encoder<'_, D>,
        offset: usize,
        _depth: Depth,
    ) -> Result<()> {
        encoder.debug_check_bounds::<EpitaphBody>(offset);
        encoder.write_num::<i32>(self.error.into_raw(), offset);
        Ok(())
    }
}

impl<D: ResourceDialect> Decode<Self, D> for EpitaphBody {
    #[inline(always)]
    fn new_empty() -> Self {
        Self { error: zx_status::Status::from_raw(0) }
    }

    #[inline]
    unsafe fn decode(
        &mut self,
        decoder: &mut Decoder<'_, D>,
        offset: usize,
        _depth: Depth,
    ) -> Result<()> {
        decoder.debug_check_bounds::<Self>(offset);
        self.error = zx_status::Status::from_raw(decoder.read_num::<i32>(offset));
        Ok(())
    }
}

////////////////////////////////////////////////////////////////////////////////
// Zircon types
////////////////////////////////////////////////////////////////////////////////

unsafe impl TypeMarker for ObjectType {
    type Owned = Self;

    #[inline(always)]
    fn inline_align(_context: Context) -> usize {
        mem::align_of::<Self>()
    }

    #[inline(always)]
    fn inline_size(_context: Context) -> usize {
        mem::size_of::<Self>()
    }
}

impl ValueTypeMarker for ObjectType {
    type Borrowed<'a> = Self;

    fn borrow(value: &Self::Owned) -> Self::Borrowed<'_> {
        *value
    }
}

unsafe impl<D: ResourceDialect> Encode<ObjectType, D> for ObjectType {
    #[inline]
    unsafe fn encode(
        self,
        encoder: &mut Encoder<'_, D>,
        offset: usize,
        _depth: Depth,
    ) -> Result<()> {
        encoder.debug_check_bounds::<Self>(offset);
        encoder.write_num(self.into_raw(), offset);
        Ok(())
    }
}

impl<D: ResourceDialect> Decode<Self, D> for ObjectType {
    #[inline(always)]
    fn new_empty() -> Self {
        ObjectType::NONE
    }

    #[inline]
    unsafe fn decode(
        &mut self,
        decoder: &mut Decoder<'_, D>,
        offset: usize,
        _depth: Depth,
    ) -> Result<()> {
        decoder.debug_check_bounds::<Self>(offset);
        *self = Self::from_raw(decoder.read_num(offset));
        Ok(())
    }
}

unsafe impl TypeMarker for Rights {
    type Owned = Self;

    #[inline(always)]
    fn inline_align(_context: Context) -> usize {
        mem::align_of::<Self>()
    }

    #[inline(always)]
    fn inline_size(_context: Context) -> usize {
        mem::size_of::<Self>()
    }
}

impl ValueTypeMarker for Rights {
    type Borrowed<'a> = Self;

    fn borrow(value: &Self::Owned) -> Self::Borrowed<'_> {
        *value
    }
}

unsafe impl<D: ResourceDialect> Encode<Rights, D> for Rights {
    #[inline]
    unsafe fn encode(
        self,
        encoder: &mut Encoder<'_, D>,
        offset: usize,
        _depth: Depth,
    ) -> Result<()> {
        encoder.debug_check_bounds::<Self>(offset);
        if self.bits() & Self::all().bits() != self.bits() {
            return Err(Error::InvalidBitsValue);
        }
        encoder.write_num(self.bits(), offset);
        Ok(())
    }
}

impl<D: ResourceDialect> Decode<Self, D> for Rights {
    #[inline(always)]
    fn new_empty() -> Self {
        Rights::empty()
    }

    #[inline]
    unsafe fn decode(
        &mut self,
        decoder: &mut Decoder<'_, D>,
        offset: usize,
        _depth: Depth,
    ) -> Result<()> {
        decoder.debug_check_bounds::<Self>(offset);
        *self = Self::from_bits(decoder.read_num(offset)).ok_or(Error::InvalidBitsValue)?;
        Ok(())
    }
}

////////////////////////////////////////////////////////////////////////////////
// Messages
////////////////////////////////////////////////////////////////////////////////

/// The FIDL type for a message consisting of a header `H` and body `T`.
pub struct GenericMessageType<H: ValueTypeMarker, T: TypeMarker>(PhantomData<(H, T)>);

/// A struct which encodes as `GenericMessageType<H, T>` where `E: Encode<T>`.
pub struct GenericMessage<H, E> {
    /// Header of the message.
    pub header: H,
    /// Body of the message.
    pub body: E,
}

/// The owned type for `GenericMessageType`.
///
/// Uninhabited because we never decode full messages. We decode the header and
/// body separately, as we usually we don't know the body's type until after
/// we've decoded the header.
pub enum GenericMessageOwned {}

unsafe impl<H: ValueTypeMarker, T: TypeMarker> TypeMarker for GenericMessageType<H, T> {
    type Owned = GenericMessageOwned;

    #[inline(always)]
    fn inline_align(context: Context) -> usize {
        std::cmp::max(H::inline_align(context), T::inline_align(context))
    }

    #[inline(always)]
    fn inline_size(context: Context) -> usize {
        H::inline_size(context) + T::inline_size(context)
    }
}

unsafe impl<H: ValueTypeMarker, T: TypeMarker, E: Encode<T, D>, D: ResourceDialect>
    Encode<GenericMessageType<H, T>, D> for GenericMessage<<H as TypeMarker>::Owned, E>
where
    for<'a> H::Borrowed<'a>: Encode<H, D>,
{
    #[inline]
    unsafe fn encode(
        self,
        encoder: &mut Encoder<'_, D>,
        offset: usize,
        depth: Depth,
    ) -> Result<()> {
        encoder.debug_check_bounds::<GenericMessageType<H, T>>(offset);
        H::borrow(&self.header).encode(encoder, offset, depth)?;
        self.body.encode(encoder, offset + H::inline_size(encoder.context), depth)
    }
}

impl<H: ValueTypeMarker, T: TypeMarker, D: ResourceDialect> Decode<GenericMessageType<H, T>, D>
    for GenericMessageOwned
{
    fn new_empty() -> Self {
        panic!("cannot create GenericMessageOwned");
    }

    unsafe fn decode(
        &mut self,
        _decoder: &mut Decoder<'_, D>,
        _offset: usize,
        _depth: Depth,
    ) -> Result<()> {
        match *self {}
    }
}

////////////////////////////////////////////////////////////////////////////////
// Transaction messages
////////////////////////////////////////////////////////////////////////////////

/// The FIDL type for a transaction message with body `T`.
pub type TransactionMessageType<T> = GenericMessageType<TransactionHeader, T>;

/// A struct which encodes as `TransactionMessageType<T>` where `E: Encode<T>`.
pub type TransactionMessage<E> = GenericMessage<TransactionHeader, E>;

/// Header for transactional FIDL messages
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[repr(C)]
pub struct TransactionHeader {
    /// Transaction ID which identifies a request-response pair
    pub tx_id: u32,
    /// Flags set for this message. MUST NOT be validated by bindings. Usually
    /// temporarily during migrations.
    pub at_rest_flags: [u8; 2],
    /// Flags used for dynamically interpreting the request if it is unknown to
    /// the receiver.
    pub dynamic_flags: u8,
    /// Magic number indicating the message's wire format. Two sides with
    /// different magic numbers are incompatible with each other.
    pub magic_number: u8,
    /// Ordinal which identifies the FIDL method
    pub ordinal: u64,
}

impl TransactionHeader {
    /// Returns whether the message containing this TransactionHeader is in a
    /// compatible wire format
    #[inline]
    pub fn is_compatible(&self) -> bool {
        self.magic_number == MAGIC_NUMBER_INITIAL
    }
}

bitflags! {
    /// Bitflags type for transaction header at-rest flags.
    #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
    pub struct AtRestFlags: u16 {
        /// Indicates that the V2 wire format should be used instead of the V1
        /// wire format.
        /// This includes the following RFCs:
        /// - Efficient envelopes
        /// - Inlining small values in FIDL envelopes
        const USE_V2_WIRE_FORMAT = 2;
    }
}

bitflags! {
    /// Bitflags type to flags that aid in dynamically identifying features of
    /// the request.
    #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
    pub struct DynamicFlags: u8 {
        /// Indicates that the request is for a flexible method.
        const FLEXIBLE = 1 << 7;
    }
}

impl From<AtRestFlags> for [u8; 2] {
    #[inline]
    fn from(value: AtRestFlags) -> Self {
        value.bits().to_le_bytes()
    }
}

impl TransactionHeader {
    /// Creates a new transaction header with the default encode context and magic number.
    #[inline]
    pub fn new(tx_id: u32, ordinal: u64, dynamic_flags: DynamicFlags) -> Self {
        TransactionHeader::new_full(
            tx_id,
            ordinal,
            default_encode_context(),
            dynamic_flags,
            MAGIC_NUMBER_INITIAL,
        )
    }

    /// Creates a new transaction header with a specific context and magic number.
    #[inline]
    pub fn new_full(
        tx_id: u32,
        ordinal: u64,
        context: Context,
        dynamic_flags: DynamicFlags,
        magic_number: u8,
    ) -> Self {
        TransactionHeader {
            tx_id,
            at_rest_flags: context.at_rest_flags().into(),
            dynamic_flags: dynamic_flags.bits(),
            magic_number,
            ordinal,
        }
    }

    /// Returns true if the header is for an epitaph message.
    #[inline]
    pub fn is_epitaph(&self) -> bool {
        self.ordinal == EPITAPH_ORDINAL
    }

    /// Returns an error if this header has an incompatible wire format.
    #[inline]
    pub fn validate_wire_format(&self) -> Result<()> {
        if self.magic_number != MAGIC_NUMBER_INITIAL {
            return Err(Error::IncompatibleMagicNumber(self.magic_number));
        }
        if !self.at_rest_flags().contains(AtRestFlags::USE_V2_WIRE_FORMAT) {
            return Err(Error::UnsupportedWireFormatVersion);
        }
        Ok(())
    }

    /// Returns an error if this request header has an incorrect transaction id
    /// for the given method type.
    #[inline]
    pub fn validate_request_tx_id(&self, method_type: MethodType) -> Result<()> {
        match method_type {
            MethodType::OneWay if self.tx_id != 0 => Err(Error::InvalidRequestTxid),
            MethodType::TwoWay if self.tx_id == 0 => Err(Error::InvalidRequestTxid),
            _ => Ok(()),
        }
    }

    /// Returns the header's migration flags as a `AtRestFlags` value.
    #[inline]
    pub fn at_rest_flags(&self) -> AtRestFlags {
        AtRestFlags::from_bits_truncate(u16::from_le_bytes(self.at_rest_flags))
    }

    /// Returns the header's dynamic flags as a `DynamicFlags` value.
    #[inline]
    pub fn dynamic_flags(&self) -> DynamicFlags {
        DynamicFlags::from_bits_truncate(self.dynamic_flags)
    }

    /// Returns the context to use for decoding the message body associated with
    /// this header. During migrations, this is dependent on `self.flags()` and
    /// controls dynamic behavior in the read path.
    #[inline]
    pub fn decoding_context(&self) -> Context {
        Context { wire_format_version: WireFormatVersion::V2 }
    }
}

/// Decodes the transaction header from a message.
/// Returns the header and a reference to the tail of the message.
pub fn decode_transaction_header(bytes: &[u8]) -> Result<(TransactionHeader, &[u8])> {
    let mut header = new_empty!(TransactionHeader, NoHandleResourceDialect);
    let context = Context { wire_format_version: WireFormatVersion::V2 };
    let header_len = <TransactionHeader as TypeMarker>::inline_size(context);
    if bytes.len() < header_len {
        return Err(Error::OutOfRange);
    }
    let (header_bytes, body_bytes) = bytes.split_at(header_len);
    Decoder::<NoHandleResourceDialect>::decode_with_context::<TransactionHeader>(
        context,
        header_bytes,
        &mut [],
        &mut header,
    )
    .map_err(|_| Error::InvalidHeader)?;
    header.validate_wire_format()?;
    Ok((header, body_bytes))
}

unsafe impl TypeMarker for TransactionHeader {
    type Owned = Self;

    #[inline(always)]
    fn inline_align(_context: Context) -> usize {
        8
    }

    #[inline(always)]
    fn inline_size(_context: Context) -> usize {
        16
    }
}

impl ValueTypeMarker for TransactionHeader {
    type Borrowed<'a> = &'a Self;

    fn borrow(value: &Self::Owned) -> Self::Borrowed<'_> {
        value
    }
}

unsafe impl<D: ResourceDialect> Encode<TransactionHeader, D> for &TransactionHeader {
    #[inline]
    unsafe fn encode(
        self,
        encoder: &mut Encoder<'_, D>,
        offset: usize,
        _depth: Depth,
    ) -> Result<()> {
        encoder.debug_check_bounds::<TransactionHeader>(offset);
        unsafe {
            let buf_ptr = encoder.buf.as_mut_ptr().add(offset);
            (buf_ptr as *mut TransactionHeader).write_unaligned(*self);
        }
        Ok(())
    }
}

impl<D: ResourceDialect> Decode<Self, D> for TransactionHeader {
    #[inline(always)]
    fn new_empty() -> Self {
        Self { tx_id: 0, at_rest_flags: [0; 2], dynamic_flags: 0, magic_number: 0, ordinal: 0 }
    }

    #[inline]
    unsafe fn decode(
        &mut self,
        decoder: &mut Decoder<'_, D>,
        offset: usize,
        _depth: Depth,
    ) -> Result<()> {
        decoder.debug_check_bounds::<Self>(offset);
        unsafe {
            let buf_ptr = decoder.buf.as_ptr().add(offset);
            let obj_ptr = self as *mut TransactionHeader;
            std::ptr::copy_nonoverlapping(buf_ptr, obj_ptr as *mut u8, 16);
        }
        Ok(())
    }
}

////////////////////////////////////////////////////////////////////////////////
// TLS buffer
////////////////////////////////////////////////////////////////////////////////

/// Thread-local buffer for encoding and decoding FIDL transactions. Needed to
/// implement `ResourceDialect`.
pub struct TlsBuf<D: ResourceDialect> {
    bytes: Vec<u8>,
    encode_handles: Vec<<D::ProxyChannel as ProxyChannelFor<D>>::HandleDisposition>,
    decode_handles: Vec<<D::Handle as HandleFor<D>>::HandleInfo>,
}

impl<D: ResourceDialect> Default for TlsBuf<D> {
    /// Create a new `TlsBuf`
    fn default() -> TlsBuf<D> {
        TlsBuf {
            bytes: Vec::with_capacity(MIN_BUF_BYTES_SIZE),
            encode_handles: Vec::new(),
            decode_handles: Vec::new(),
        }
    }
}

#[inline]
fn with_tls_buf<D: ResourceDialect, R>(f: impl FnOnce(&mut TlsBuf<D>) -> R) -> R {
    D::with_tls_buf(f)
}

pub(crate) const MIN_BUF_BYTES_SIZE: usize = 512;

/// Acquire a mutable reference to the thread-local buffers used for encoding.
///
/// This function may not be called recursively.
#[inline]
pub fn with_tls_encode_buf<R, D: ResourceDialect>(
    f: impl FnOnce(
        &mut Vec<u8>,
        &mut Vec<<D::ProxyChannel as ProxyChannelFor<D>>::HandleDisposition>,
    ) -> R,
) -> R {
    with_tls_buf::<D, R>(|buf| {
        let res = f(&mut buf.bytes, &mut buf.encode_handles);
        buf.bytes.clear();
        buf.encode_handles.clear();
        res
    })
}

/// Acquire a mutable reference to the thread-local buffers used for decoding.
///
/// This function may not be called recursively.
#[inline]
pub fn with_tls_decode_buf<R, D: ResourceDialect>(
    f: impl FnOnce(&mut Vec<u8>, &mut Vec<<D::Handle as HandleFor<D>>::HandleInfo>) -> R,
) -> R {
    with_tls_buf::<D, R>(|buf| {
        let res = f(&mut buf.bytes, &mut buf.decode_handles);
        buf.bytes.clear();
        buf.decode_handles.clear();
        res
    })
}

/// Encodes the provided type into the thread-local encoding buffers.
///
/// This function may not be called recursively.
#[inline]
pub fn with_tls_encoded<T: TypeMarker, D: ResourceDialect, Out>(
    val: impl Encode<T, D>,
    f: impl FnOnce(
        &mut Vec<u8>,
        &mut Vec<<D::ProxyChannel as ProxyChannelFor<D>>::HandleDisposition>,
    ) -> Result<Out>,
) -> Result<Out> {
    with_tls_encode_buf::<Result<Out>, D>(|bytes, handles| {
        Encoder::<D>::encode(bytes, handles, val)?;
        f(bytes, handles)
    })
}

////////////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////////////

#[cfg(test)]
mod test {
    // Silence dead code errors from unused functions produced by macros like
    // `fidl_bits!`, `fidl_union!`, etc. To the compiler, it's as if we defined
    // a pub fn in a private mod and never used it. Unfortunately placing this
    // attribute directly on the macro invocations does not work.
    #![allow(dead_code)]

    use super::*;
    use crate::handle::{convert_handle_dispositions_to_infos, AsHandleRef};
    use crate::time::{BootInstant, BootTicks, MonotonicInstant, MonotonicTicks};
    use assert_matches::assert_matches;
    use std::fmt;

    const CONTEXTS: [Context; 1] = [Context { wire_format_version: WireFormatVersion::V2 }];

    const OBJECT_TYPE_NONE: u32 = crate::handle::ObjectType::NONE.into_raw();
    const SAME_RIGHTS: u32 = crate::handle::Rights::SAME_RIGHTS.bits();

    #[track_caller]
    fn to_infos(dispositions: &mut Vec<HandleDisposition<'_>>) -> Vec<HandleInfo> {
        convert_handle_dispositions_to_infos(mem::take(dispositions)).unwrap()
    }

    #[track_caller]
    pub fn encode_decode<T: TypeMarker>(
        ctx: Context,
        start: impl Encode<T, DefaultFuchsiaResourceDialect>,
    ) -> T::Owned
    where
        T::Owned: Decode<T, DefaultFuchsiaResourceDialect>,
    {
        let buf = &mut Vec::new();
        let handle_buf = &mut Vec::new();
        Encoder::encode_with_context::<T>(ctx, buf, handle_buf, start).expect("Encoding failed");
        let mut out = T::Owned::new_empty();
        Decoder::<DefaultFuchsiaResourceDialect>::decode_with_context::<T>(
            ctx,
            buf,
            &mut to_infos(handle_buf),
            &mut out,
        )
        .expect("Decoding failed");
        out
    }

    #[track_caller]
    fn encode_assert_bytes<T: TypeMarker>(
        ctx: Context,
        data: impl Encode<T, DefaultFuchsiaResourceDialect>,
        encoded_bytes: &[u8],
    ) {
        let buf = &mut Vec::new();
        let handle_buf = &mut Vec::new();
        Encoder::encode_with_context::<T>(ctx, buf, handle_buf, data).expect("Encoding failed");
        assert_eq!(buf, encoded_bytes);
    }

    #[track_caller]
    fn identity<T>(data: &T::Owned)
    where
        T: ValueTypeMarker,
        T::Owned: fmt::Debug + PartialEq + Decode<T, DefaultFuchsiaResourceDialect>,
        for<'a> T::Borrowed<'a>: Encode<T, DefaultFuchsiaResourceDialect>,
    {
        for ctx in CONTEXTS {
            assert_eq!(*data, encode_decode(ctx, T::borrow(data)));
        }
    }

    #[track_caller]
    fn identities<T>(values: &[T::Owned])
    where
        T: ValueTypeMarker,
        T::Owned: fmt::Debug + PartialEq + Decode<T, DefaultFuchsiaResourceDialect>,
        for<'a> T::Borrowed<'a>: Encode<T, DefaultFuchsiaResourceDialect>,
    {
        for value in values {
            identity::<T>(value);
        }
    }

    #[test]
    fn encode_decode_byte() {
        identities::<u8>(&[0u8, 57u8, 255u8]);
        identities::<i8>(&[0i8, -57i8, 12i8]);
        identity::<Optional<Vector<i32, 3>>>(&None::<Vec<i32>>);
    }

    #[test]
    fn encode_decode_multibyte() {
        identities::<u64>(&[0u64, 1u64, u64::MAX, u64::MIN]);
        identities::<i64>(&[0i64, 1i64, i64::MAX, i64::MIN]);
        identities::<f32>(&[0f32, 1f32, f32::MAX, f32::MIN]);
        identities::<f64>(&[0f64, 1f64, f64::MAX, f64::MIN]);
    }

    #[test]
    fn encode_decode_nan() {
        for ctx in CONTEXTS {
            assert!(encode_decode::<f32>(ctx, f32::NAN).is_nan());
            assert!(encode_decode::<f64>(ctx, f64::NAN).is_nan());
        }
    }

    #[test]
    fn encode_decode_instants() {
        let monotonic = MonotonicInstant::from_nanos(987654321);
        let boot = BootInstant::from_nanos(987654321);
        let monotonic_ticks = MonotonicTicks::from_raw(111111111);
        let boot_ticks = BootTicks::from_raw(22222222);
        for ctx in CONTEXTS {
            assert_eq!(encode_decode::<BootInstant>(ctx, boot), boot);
            assert_eq!(encode_decode::<MonotonicInstant>(ctx, monotonic), monotonic);
            assert_eq!(encode_decode::<BootTicks>(ctx, boot_ticks), boot_ticks);
            assert_eq!(encode_decode::<MonotonicTicks>(ctx, monotonic_ticks), monotonic_ticks);
        }
    }

    #[test]
    fn encode_decode_out_of_line() {
        type V<T> = UnboundedVector<T>;
        type S = UnboundedString;
        type O<T> = Optional<T>;

        identity::<V<i32>>(&Vec::<i32>::new());
        identity::<V<i32>>(&vec![1, 2, 3]);
        identity::<O<V<i32>>>(&None::<Vec<i32>>);
        identity::<O<V<i32>>>(&Some(Vec::<i32>::new()));
        identity::<O<V<i32>>>(&Some(vec![1, 2, 3]));
        identity::<O<V<V<i32>>>>(&Some(vec![vec![1, 2, 3]]));
        identity::<O<V<O<V<i32>>>>>(&Some(vec![Some(vec![1, 2, 3])]));
        identity::<S>(&"".to_string());
        identity::<S>(&"foo".to_string());
        identity::<O<S>>(&None::<String>);
        identity::<O<S>>(&Some("".to_string()));
        identity::<O<S>>(&Some("foo".to_string()));
        identity::<O<V<O<S>>>>(&Some(vec![None, Some("foo".to_string())]));
        identity::<V<S>>(&vec!["foo".to_string(), "bar".to_string()]);
    }

    #[test]
    fn array_of_arrays() {
        identity::<Array<Array<u32, 5>, 2>>(&[[1, 2, 3, 4, 5], [5, 4, 3, 2, 1]]);
    }

    fn slice_identity<T>(start: &[T::Owned])
    where
        T: ValueTypeMarker,
        T::Owned: fmt::Debug + PartialEq + Decode<T, DefaultFuchsiaResourceDialect>,
        for<'a> T::Borrowed<'a>: Encode<T, DefaultFuchsiaResourceDialect>,
    {
        for ctx in CONTEXTS {
            let decoded = encode_decode::<UnboundedVector<T>>(ctx, start);
            assert_eq!(start, UnboundedVector::<T>::borrow(&decoded));
        }
    }

    #[test]
    fn encode_slices_of_primitives() {
        slice_identity::<u8>(&[]);
        slice_identity::<u8>(&[0]);
        slice_identity::<u8>(&[1, 2, 3, 4, 5, 255]);

        slice_identity::<i8>(&[]);
        slice_identity::<i8>(&[0]);
        slice_identity::<i8>(&[1, 2, 3, 4, 5, -128, 127]);

        slice_identity::<u64>(&[]);
        slice_identity::<u64>(&[0]);
        slice_identity::<u64>(&[1, 2, 3, 4, 5, u64::MAX]);

        slice_identity::<f32>(&[]);
        slice_identity::<f32>(&[0.0]);
        slice_identity::<f32>(&[1.0, 2.0, 3.0, 4.0, 5.0, f32::MIN, f32::MAX]);

        slice_identity::<f64>(&[]);
        slice_identity::<f64>(&[0.0]);
        slice_identity::<f64>(&[1.0, 2.0, 3.0, 4.0, 5.0, f64::MIN, f64::MAX]);
    }

    #[test]
    fn result_encode_empty_ok_value() {
        for ctx in CONTEXTS {
            // An empty response is represented by () and has zero size.
            encode_assert_bytes::<EmptyPayload>(ctx, (), &[]);
        }
        // But in the context of an error result type Result<(), ErrorType>, the
        // () in Ok(()) represents an empty struct (with size 1).
        encode_assert_bytes::<ResultType<EmptyStruct, i32>>(
            Context { wire_format_version: WireFormatVersion::V2 },
            Ok::<(), i32>(()),
            &[
                0x01, 0x00, 0x00, 0x00, // success ordinal
                0x00, 0x00, 0x00, 0x00, // success ordinal [cont.]
                0x00, 0x00, 0x00, 0x00, // inline value: empty struct + 3 bytes padding
                0x00, 0x00, 0x01, 0x00, // 0 handles, flags (inlined)
            ],
        );
    }

    #[test]
    fn result_decode_empty_ok_value() {
        let mut result = Err(0);
        Decoder::<DefaultFuchsiaResourceDialect>::decode_with_context::<ResultType<EmptyStruct, u32>>(
            Context { wire_format_version: WireFormatVersion::V2 },
            &[
                0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // success ordinal
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, // empty struct inline
            ],
            &mut [],
            &mut result,
        )
        .expect("Decoding failed");
        assert_matches!(result, Ok(()));
    }

    #[test]
    fn encode_decode_result() {
        type Res = ResultType<UnboundedString, u32>;
        for ctx in CONTEXTS {
            assert_eq!(encode_decode::<Res>(ctx, Ok::<&str, u32>("foo")), Ok("foo".to_string()));
            assert_eq!(encode_decode::<Res>(ctx, Err::<&str, u32>(5)), Err(5));
        }
    }

    #[test]
    fn result_validates_num_bytes() {
        type Res = ResultType<u64, u64>;
        for ctx in CONTEXTS {
            for ordinal in [1, 2] {
                // Envelope should have num_bytes set to 8, not 16.
                let bytes = [
                    ordinal, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ordinal
                    0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 16 bytes, 0 handles
                    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, // present
                    0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, // number
                ];
                let mut out = new_empty!(Res, DefaultFuchsiaResourceDialect);
                assert_matches!(
                    Decoder::<DefaultFuchsiaResourceDialect>::decode_with_context::<Res>(
                        ctx,
                        &bytes,
                        &mut [],
                        &mut out
                    ),
                    Err(Error::InvalidNumBytesInEnvelope)
                );
            }
        }
    }

    #[test]
    fn result_validates_num_handles() {
        type Res = ResultType<u64, u64>;
        for ctx in CONTEXTS {
            for ordinal in [1, 2] {
                // Envelope should have num_handles set to 0, not 1.
                let bytes = [
                    ordinal, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ordinal
                    0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, // 16 bytes, 1 handle
                    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, // present
                    0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, // number
                ];
                let mut out = new_empty!(Res, DefaultFuchsiaResourceDialect);
                assert_matches!(
                    Decoder::<DefaultFuchsiaResourceDialect>::decode_with_context::<Res>(
                        ctx,
                        &bytes,
                        &mut [],
                        &mut out
                    ),
                    Err(Error::InvalidNumHandlesInEnvelope)
                );
            }
        }
    }

    #[test]
    fn decode_result_unknown_tag() {
        type Res = ResultType<u32, u32>;
        let ctx = Context { wire_format_version: WireFormatVersion::V2 };

        let bytes: &[u8] = &[
            // Ordinal 3 (not known to result) ----------|
            0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            // inline value -----|  NHandles |  Flags ---|
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00,
        ];
        let handle_buf = &mut Vec::<HandleInfo>::new();

        let mut out = new_empty!(Res, DefaultFuchsiaResourceDialect);
        let res = Decoder::<DefaultFuchsiaResourceDialect>::decode_with_context::<Res>(
            ctx, bytes, handle_buf, &mut out,
        );
        assert_matches!(res, Err(Error::UnknownUnionTag));
    }

    #[test]
    fn decode_result_success_invalid_empty_struct() {
        type Res = ResultType<EmptyStruct, u32>;
        let ctx = Context { wire_format_version: WireFormatVersion::V2 };

        let bytes: &[u8] = &[
            // Ordinal 1 (success) ----------------------|
            0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            // inline value -----|  NHandles |  Flags ---|
            0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00,
        ];
        let handle_buf = &mut Vec::<HandleInfo>::new();

        let mut out = new_empty!(Res, DefaultFuchsiaResourceDialect);
        let res = Decoder::<DefaultFuchsiaResourceDialect>::decode_with_context::<Res>(
            ctx, bytes, handle_buf, &mut out,
        );
        assert_matches!(res, Err(Error::Invalid));
    }

    #[test]
    fn encode_decode_transaction_msg() {
        for ctx in CONTEXTS {
            let header = TransactionHeader {
                tx_id: 4,
                ordinal: 6,
                at_rest_flags: [2, 0],
                dynamic_flags: 0,
                magic_number: 1,
            };
            type Body = UnboundedString;
            let body = "hello";

            let start = TransactionMessage { header, body };

            let buf = &mut Vec::new();
            let handle_buf = &mut Vec::new();
            Encoder::<DefaultFuchsiaResourceDialect>::encode_with_context::<
                TransactionMessageType<Body>,
            >(ctx, buf, handle_buf, start)
            .expect("Encoding failed");

            let (out_header, out_buf) =
                decode_transaction_header(buf).expect("Decoding header failed");
            assert_eq!(header, out_header);

            let mut body_out = String::new();
            Decoder::<DefaultFuchsiaResourceDialect>::decode_into::<Body>(
                &header,
                out_buf,
                &mut to_infos(handle_buf),
                &mut body_out,
            )
            .expect("Decoding body failed");
            assert_eq!(body, body_out);
        }
    }

    #[test]
    fn direct_encode_transaction_header_strict() {
        let bytes = &[
            0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //
            0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
        ];
        let header = TransactionHeader {
            tx_id: 4,
            ordinal: 6,
            at_rest_flags: [0; 2],
            dynamic_flags: DynamicFlags::empty().bits(),
            magic_number: 1,
        };

        for ctx in CONTEXTS {
            encode_assert_bytes::<TransactionHeader>(ctx, &header, bytes);
        }
    }

    #[test]
    fn direct_decode_transaction_header_strict() {
        let bytes = &[
            0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //
            0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
        ];
        let header = TransactionHeader {
            tx_id: 4,
            ordinal: 6,
            at_rest_flags: [0; 2],
            dynamic_flags: DynamicFlags::empty().bits(),
            magic_number: 1,
        };

        for ctx in CONTEXTS {
            let mut out = new_empty!(TransactionHeader, DefaultFuchsiaResourceDialect);
            Decoder::<DefaultFuchsiaResourceDialect>::decode_with_context::<TransactionHeader>(
                ctx,
                bytes,
                &mut [],
                &mut out,
            )
            .expect("Decoding failed");
            assert_eq!(out, header);
        }
    }

    #[test]
    fn direct_encode_transaction_header_flexible() {
        let bytes = &[
            0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x01, //
            0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
        ];
        let header = TransactionHeader {
            tx_id: 4,
            ordinal: 6,
            at_rest_flags: [0; 2],
            dynamic_flags: DynamicFlags::FLEXIBLE.bits(),
            magic_number: 1,
        };

        for ctx in CONTEXTS {
            encode_assert_bytes::<TransactionHeader>(ctx, &header, bytes);
        }
    }

    #[test]
    fn direct_decode_transaction_header_flexible() {
        let bytes = &[
            0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x01, //
            0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
        ];
        let header = TransactionHeader {
            tx_id: 4,
            ordinal: 6,
            at_rest_flags: [0; 2],
            dynamic_flags: DynamicFlags::FLEXIBLE.bits(),
            magic_number: 1,
        };

        for ctx in CONTEXTS {
            let mut out = new_empty!(TransactionHeader, DefaultFuchsiaResourceDialect);
            Decoder::<DefaultFuchsiaResourceDialect>::decode_with_context::<TransactionHeader>(
                ctx,
                bytes,
                &mut [],
                &mut out,
            )
            .expect("Decoding failed");
            assert_eq!(out, header);
        }
    }

    #[test]
    fn extra_data_is_disallowed() {
        for ctx in CONTEXTS {
            assert_matches!(
                Decoder::<DefaultFuchsiaResourceDialect>::decode_with_context::<EmptyPayload>(
                    ctx,
                    &[0],
                    &mut [],
                    &mut ()
                ),
                Err(Error::ExtraBytes)
            );
            assert_matches!(
                Decoder::<DefaultFuchsiaResourceDialect>::decode_with_context::<EmptyPayload>(
                    ctx,
                    &[],
                    &mut [HandleInfo::new(Handle::invalid(), ObjectType::NONE, Rights::NONE,)],
                    &mut ()
                ),
                Err(Error::ExtraHandles)
            );
        }
    }

    #[test]
    fn encode_default_context() {
        let buf = &mut Vec::new();
        Encoder::<DefaultFuchsiaResourceDialect>::encode::<u8>(buf, &mut Vec::new(), 1u8)
            .expect("Encoding failed");
        assert_eq!(buf, &[1u8, 0, 0, 0, 0, 0, 0, 0]);
    }

    #[test]
    fn encode_handle() {
        type T = HandleType<Handle, OBJECT_TYPE_NONE, SAME_RIGHTS>;
        for ctx in CONTEXTS {
            let handle = crate::handle::Event::create().into_handle();
            let raw_handle = handle.raw_handle();
            let buf = &mut Vec::new();
            let handle_buf = &mut Vec::new();
            Encoder::<DefaultFuchsiaResourceDialect>::encode_with_context::<T>(
                ctx, buf, handle_buf, handle,
            )
            .expect("Encoding failed");

            assert_eq!(handle_buf.len(), 1);
            assert!(handle_buf[0].is_move());
            assert_eq!(handle_buf[0].raw_handle(), raw_handle);

            let mut handle_out = new_empty!(T);
            Decoder::<DefaultFuchsiaResourceDialect>::decode_with_context::<T>(
                ctx,
                buf,
                &mut to_infos(handle_buf),
                &mut handle_out,
            )
            .expect("Decoding failed");
            assert_eq!(
                handle_out.raw_handle(),
                raw_handle,
                "decoded handle must match encoded handle"
            );
        }
    }

    #[test]
    fn decode_too_few_handles() {
        type T = HandleType<Handle, OBJECT_TYPE_NONE, SAME_RIGHTS>;
        for ctx in CONTEXTS {
            let bytes: &[u8] = &[0xff; 8];
            let handle_buf = &mut Vec::new();
            let mut handle_out = Handle::invalid();
            let res = Decoder::<DefaultFuchsiaResourceDialect>::decode_with_context::<T>(
                ctx,
                bytes,
                handle_buf,
                &mut handle_out,
            );
            assert_matches!(res, Err(Error::OutOfRange));
        }
    }

    #[test]
    fn encode_epitaph() {
        for ctx in CONTEXTS {
            let buf = &mut Vec::new();
            let handle_buf = &mut Vec::new();
            Encoder::<DefaultFuchsiaResourceDialect>::encode_with_context::<EpitaphBody>(
                ctx,
                buf,
                handle_buf,
                &EpitaphBody { error: zx_status::Status::UNAVAILABLE },
            )
            .expect("encoding failed");
            assert_eq!(buf, &[0xe4, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00]);

            let mut out = new_empty!(EpitaphBody, DefaultFuchsiaResourceDialect);
            Decoder::<DefaultFuchsiaResourceDialect>::decode_with_context::<EpitaphBody>(
                ctx,
                buf,
                &mut to_infos(handle_buf),
                &mut out,
            )
            .expect("Decoding failed");
            assert_eq!(EpitaphBody { error: zx_status::Status::UNAVAILABLE }, out);
        }
    }
}