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
// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

use std::mem;
use std::ptr;
use std::cell::Cell;

use crate::data;
use crate::text;
use crate::private::capability::{ClientHook};
use crate::private::arena::{BuilderArena, ReaderArena, NullArena, SegmentId};
use crate::private::endian::{WireValue, Endian};
use crate::private::mask::Mask;
use crate::private::units::*;
use crate::private::zero;
use crate::{MessageSize, Result, Word};

pub use self::ElementSize::{Void, Bit, Byte, TwoBytes, FourBytes, EightBytes, Pointer, InlineComposite};

#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ElementSize {
    Void = 0,
    Bit = 1,
    Byte = 2,
    TwoBytes = 3,
    FourBytes = 4,
    EightBytes = 5,
    Pointer = 6,
    InlineComposite = 7
}

impl ElementSize {
    fn from(val: u8) -> ElementSize {
        match val {
            0 => ElementSize::Void,
            1 => ElementSize::Bit,
            2 => ElementSize::Byte,
            3 => ElementSize::TwoBytes,
            4 => ElementSize::FourBytes,
            5 => ElementSize::EightBytes,
            6 => ElementSize::Pointer,
            7 => ElementSize::InlineComposite,
            _ => panic!("illegal element size: {}", val),
        }
    }
}

pub fn data_bits_per_element(size: ElementSize) -> BitCount32 {
    match size {
        Void => 0,
        Bit => 1,
        Byte => 8,
        TwoBytes => 16,
        FourBytes => 32,
        EightBytes => 64,
        Pointer => 0,
        InlineComposite => 0
    }
}

pub fn pointers_per_element(size: ElementSize) -> WirePointerCount32 {
    match size {
        Pointer => 1,
        _ => 0
    }
}

#[derive(Clone, Copy)]
pub struct StructSize {
    pub data: WordCount16,
    pub pointers: WirePointerCount16,
}

impl StructSize {
    pub fn total(&self) -> WordCount32 {
        self.data as WordCount32
            + self.pointers as WordCount32
            * WORDS_PER_POINTER as WordCount32
    }
}

#[repr(u8)]
#[derive(Clone, Copy, PartialEq)]
pub enum WirePointerKind {
    Struct = 0,
    List = 1,
    Far = 2,
    Other = 3
}

pub enum PointerType {
    Null,
    Struct,
    List,
    Capability,
}

impl WirePointerKind {
    fn from(val: u8) -> WirePointerKind {
        match val {
            0 => WirePointerKind::Struct,
            1 => WirePointerKind::List,
            2 => WirePointerKind::Far,
            3 => WirePointerKind::Other,
            _ => panic!("illegal element size: {}", val),
        }
    }
}

#[repr(C)]
pub struct WirePointer {
    offset_and_kind: WireValue<u32>,
    upper32bits: WireValue<u32>,
}

impl WirePointer {

    #[inline]
    pub fn kind(&self) -> WirePointerKind {
        WirePointerKind::from(self.offset_and_kind.get() as u8 & 3)
    }

    #[inline]
    pub fn is_positional(&self) -> bool {
        (self.offset_and_kind.get() & 2) == 0 // match Struct and List but not Far and Other.
    }

    #[inline]
    pub fn is_capability(&self) -> bool {
        self.offset_and_kind.get() == WirePointerKind::Other as u32
    }

    #[inline]
    pub fn target(&self) -> *const Word {
        let this_addr: *const Word = self as *const _ as *const _;
        unsafe { this_addr.offset((1 + ((self.offset_and_kind.get() as i32) >> 2)) as isize) }
    }

    #[inline]
    pub fn target_from_segment(&self, arena: &dyn ReaderArena, segment_id: u32) -> Result<*const Word> {
        let this_addr: *const Word = self as *const _ as *const _;
        let offset = 1 + ((self.offset_and_kind.get() as i32) >> 2);
        arena.check_offset(segment_id, this_addr, offset)
    }

    #[inline]
    pub fn mut_target(&mut self) -> *mut Word {
        let this_addr: *mut Word = self as *mut _ as *mut _;
        unsafe { this_addr.offset((1 + ((self.offset_and_kind.get() as i32) >> 2)) as isize) }
    }

    #[inline]
    pub fn set_kind_and_target(&mut self, kind: WirePointerKind, target: *mut Word) {
        let this_addr: isize = self as *const _ as isize;
        let target_addr: isize = target as *const _ as isize;
        self.offset_and_kind.set(
            ((((target_addr - this_addr) / BYTES_PER_WORD as isize) as i32 - 1) << 2) as u32
                | (kind as u32))
    }

    #[inline]
    pub fn set_kind_with_zero_offset(&mut self, kind: WirePointerKind) {
        self.offset_and_kind.set(kind as u32)
    }

    #[inline]
    pub fn set_kind_and_target_for_empty_struct(&mut self) {
        //# This pointer points at an empty struct. Assuming the
        //# WirePointer itself is in-bounds, we can set the target to
        //# point either at the WirePointer itself or immediately after
        //# it. The latter would cause the WirePointer to be "null"
        //# (since for an empty struct the upper 32 bits are going to
        //# be zero). So we set an offset of -1, as if the struct were
        //# allocated immediately before this pointer, to distinguish
        //# it from null.

        self.offset_and_kind.set(0xfffffffc);
    }

    #[inline]
    pub fn inline_composite_list_element_count(&self) -> ElementCount32 {
        self.offset_and_kind.get() >> 2
    }

    #[inline]
    pub fn set_kind_and_inline_composite_list_element_count(&mut self,
                                                            kind: WirePointerKind,
                                                            element_count: ElementCount32) {
        self.offset_and_kind.set(( element_count << 2) | (kind as u32))
    }

    #[inline]
    pub fn far_position_in_segment(&self) -> WordCount32 {
        self.offset_and_kind.get() >> 3
    }

    #[inline]
    pub fn is_double_far(&self) -> bool {
        ((self.offset_and_kind.get() >> 2) & 1) != 0
    }

    #[inline]
    pub fn set_far(&mut self, is_double_far: bool, pos: WordCount32) {
        self.offset_and_kind
            .set(( pos << 3) | ((is_double_far as u32) << 2) | WirePointerKind::Far as u32);
    }

    #[inline]
    pub fn set_cap(&mut self, index: u32) {
        self.offset_and_kind.set(WirePointerKind::Other as u32);
        self.upper32bits.set(index);
    }

    #[inline]
    pub fn struct_data_size(&self) -> WordCount16 {
        (self.upper32bits.get() & 0xffffffff) as WordCount16
    }

    #[inline]
    pub fn struct_ptr_count(&self) -> WordCount16 {
        (self.upper32bits.get() >> 16) as WordCount16
    }

    #[inline]
    pub fn struct_word_size(&self) -> WordCount32 {
        self.struct_data_size() as WordCount32 +
            self.struct_ptr_count() as WordCount32 * WORDS_PER_POINTER as u32
    }

    #[inline]
    pub fn set_struct_size(&mut self, size: StructSize) {
        self.upper32bits.set(size.data as u32 | ((size.pointers as u32) << 16))
    }

    #[inline]
    pub fn set_struct_size_from_pieces(&mut self, ds: WordCount16, rc: WirePointerCount16) {
        self.set_struct_size(StructSize { data: ds, pointers: rc })
    }

    #[inline]
    pub fn list_element_size(&self) -> ElementSize {
        ElementSize::from(self.upper32bits.get() as u8 & 7)
    }

    #[inline]
    pub fn list_element_count(&self) -> ElementCount32 {
        self.upper32bits.get() >> 3
    }

    #[inline]
    pub fn list_inline_composite_word_count(&self) -> WordCount32 {
        self.list_element_count()
    }

    #[inline]
    pub fn set_list_size_and_count(&mut self, es: ElementSize, ec: ElementCount32) {
        assert!(ec < (1 << 29), "Lists are limited to 2**29 elements");
        self.upper32bits.set((ec << 3 ) | (es as u32));
    }

    #[inline]
    pub fn set_list_inline_composite(&mut self, wc: WordCount32) {
        assert!(wc < (1 << 29), "Inline composite lists are limited to 2**29 words");
        self.upper32bits.set((wc << 3) | (InlineComposite as u32));
    }

    #[inline]
    pub fn far_segment_id(&self) -> SegmentId {
        self.upper32bits.get() as SegmentId
    }

    #[inline]
    pub fn set_far_segment_id(&mut self, si: SegmentId) {
        self.upper32bits.set(si)
    }

    #[inline]
    pub fn cap_index(&self) -> u32 {
        self.upper32bits.get()
    }

    #[inline]
    pub fn set_cap_index(&mut self, index: u32) {
        self.upper32bits.set(index)
    }

    #[inline]
    pub fn is_null(&self) -> bool {
        self.offset_and_kind.get() == 0 && self.upper32bits.get() == 0
    }
}

mod wire_helpers {
    use std::{mem, ptr, slice};

    use crate::private::capability::ClientHook;
    use crate::private::arena::*;
    use crate::private::layout::{
        CapTableBuilder, CapTableReader, ElementSize, ListBuilder, ListReader,
        StructBuilder, StructReader, StructSize, WirePointer, WirePointerKind};
    use crate::private::layout::{data_bits_per_element, pointers_per_element};
    use crate::private::layout::ElementSize::*;
    use crate::private::units::*;
    use crate::data;
    use crate::text;
    use crate::{Error, MessageSize, Result, Word};

    pub struct SegmentAnd<T> {
        #[allow(dead_code)]
        segment_id: u32,
        pub value: T,
    }

    #[inline]
    pub fn round_bytes_up_to_words(bytes: ByteCount32) -> WordCount32 {
        //# This code assumes 64-bit words.
        (bytes + 7) / BYTES_PER_WORD as u32
    }

    //# The maximum object size is 4GB - 1 byte. If measured in bits,
    //# this would overflow a 32-bit counter, so we need to accept
    //# BitCount64. However, 32 bits is enough for the returned
    //# ByteCounts and WordCounts.
    #[inline]
    pub fn round_bits_up_to_words(bits: BitCount64) -> WordCount32 {
        //# This code assumes 64-bit words.
        ((bits + 63) / (BITS_PER_WORD as u64)) as WordCount32
    }

    #[allow(dead_code)]
    #[inline]
    pub fn round_bits_up_to_bytes(bits: BitCount64) -> ByteCount32 {
        ((bits + 7) / (BITS_PER_BYTE as u64)) as ByteCount32
    }

    #[inline]
    pub fn bounds_check(arena: &dyn ReaderArena,
                        segment_id: u32,
                        start: *const Word, size_in_words: usize,
                        _kind: WirePointerKind) -> Result<()> {
        arena.contains_interval(segment_id, start, size_in_words)
    }

    #[inline]
    pub fn amplified_read(arena: &dyn ReaderArena,
                          virtual_amount: u64) -> Result<()> {
        arena.amplified_read(virtual_amount)
    }

    #[inline]
    pub unsafe fn allocate(
        arena: &dyn BuilderArena,
        reff: *mut WirePointer,
        segment_id: u32,
        amount: WordCount32, kind: WirePointerKind) -> (*mut Word, *mut WirePointer, u32)
    {
        let is_null = (*reff).is_null();
        if !is_null {
            zero_object(arena, segment_id, reff)
        }

        if amount == 0 && kind == WirePointerKind::Struct {
            (*reff).set_kind_and_target_for_empty_struct();
            return (reff as *mut _, reff, segment_id);
        }

        match arena.allocate(segment_id, amount) {
            None => {

                //# Need to allocate in a different segment. We'll need to
                //# allocate an extra pointer worth of space to act as
                //# the landing pad for a far pointer.

                let amount_plus_ref = amount + POINTER_SIZE_IN_WORDS as u32;
                let (segment_id, word_idx) = arena.allocate_anywhere(amount_plus_ref);
                let (seg_start, _seg_len) = arena.get_segment_mut(segment_id);
                let ptr: *mut Word = seg_start.offset(word_idx as isize);

                //# Set up the original pointer to be a far pointer to
                //# the new segment.
                (*reff).set_far(false, word_idx);
                (*reff).set_far_segment_id(segment_id);

                //# Initialize the landing pad to indicate that the
                //# data immediately follows the pad.
                let reff = ptr as *mut WirePointer;

                let ptr1 = ptr.offset(POINTER_SIZE_IN_WORDS as isize);
                (*reff).set_kind_and_target(kind, ptr1);
                (ptr1, reff, segment_id)
            }
            Some(idx) => {
                let (seg_start, _seg_len) = arena.get_segment_mut(segment_id);
                let ptr: *mut Word = seg_start.offset(idx as isize);
                (*reff).set_kind_and_target(kind, ptr);
                (ptr, reff, segment_id)
            }
        }
    }

    #[inline]
    pub unsafe fn follow_builder_fars(
        arena: &dyn BuilderArena,
        reff: *mut WirePointer,
        ref_target: *mut Word,
        segment_id: u32) -> Result<(*mut Word, *mut WirePointer, u32)>
    {
        // If `ref` is a far pointer, follow it. On return, `ref` will have been updated to point at
        // a WirePointer that contains the type information about the target object, and a pointer
        // to the object contents is returned. The caller must NOT use `ref->target()` as this may
        // or may not actually return a valid pointer. `segment` is also updated to point at the
        // segment which actually contains the object.
        //
        // If `ref` is not a far pointer, this simply returns `ref_target`. Usually, `ref_target`
        // should be the same as `ref->target()`, but may not be in cases where `ref` is only a tag.

        if (*reff).kind() == WirePointerKind::Far {
            let segment_id = (*reff).far_segment_id();
            let (seg_start, _seg_len) = arena.get_segment_mut(segment_id);
            let pad: *mut WirePointer =
                seg_start.offset((*reff).far_position_in_segment() as isize) as *mut _;
            if !(*reff).is_double_far() {
                Ok(((*pad).mut_target(), pad, segment_id))
            } else {
                //# Landing pad is another far pointer. It is followed by a
                //# tag describing the pointed-to object.
                let reff = pad.offset(1);

                let segment_id = (*pad).far_segment_id();
                let (segment_start, _segment_len) = arena.get_segment_mut(segment_id);
                let ptr = segment_start.offset((*pad).far_position_in_segment() as isize);
                Ok((ptr, reff, segment_id))
            }
        } else {
            Ok((ref_target, reff, segment_id))
        }
    }

    /// Follows a WirePointer to get a triple containing:
    ///   - the pointed-to object
    ///   - the resolved WirePointer, whose kind is something other than WirePointerKind::Far
    ///   - the segment on which the pointed-to object lives
    #[inline]
    pub unsafe fn follow_fars(
        arena: &dyn ReaderArena,
        reff: *const WirePointer,
        segment_id: u32)
        -> Result<(*const Word, *const WirePointer, u32)>
    {
        if (*reff).kind() == WirePointerKind::Far {
            let far_segment_id = (*reff).far_segment_id();

            let (seg_start, _seg_len) = arena.get_segment(far_segment_id)?;
            let ptr: *const Word = seg_start.offset((*reff).far_position_in_segment() as isize);

            let pad_words: usize = if (*reff).is_double_far() { 2 } else { 1 };
            bounds_check(arena, far_segment_id, ptr, pad_words, WirePointerKind::Far)?;

            let pad: *const WirePointer = ptr as *const _;

            if !(*reff).is_double_far() {
                Ok(((*pad).target_from_segment(arena, far_segment_id)?, pad, far_segment_id))
            } else {
                // Landing pad is another far pointer. It is followed by a tag describing the
                // pointed-to object.

                let tag = pad.offset(1);
                let double_far_segment_id = (*pad).far_segment_id();
                let (segment_start, _segment_len) = arena.get_segment(double_far_segment_id)?;
                let ptr = segment_start.offset((*pad).far_position_in_segment() as isize);
                Ok((ptr, tag, double_far_segment_id))
            }
        } else {
            Ok(((*reff).target_from_segment(arena, segment_id)?, reff, segment_id))
        }
    }

    pub unsafe fn zero_object(
        arena: &dyn BuilderArena,
        segment_id: u32,
        reff: *mut WirePointer)
    {
        //# Zero out the pointed-to object. Use when the pointer is
        //# about to be overwritten making the target object no longer
        //# reachable.

        match (*reff).kind() {
            WirePointerKind::Struct | WirePointerKind::List | WirePointerKind::Other => {
                zero_object_helper(arena, segment_id, reff, (*reff).mut_target())
            }
            WirePointerKind::Far => {
                let segment_id = (*reff).far_segment_id();
                let (seg_start, _seg_len) = arena.get_segment_mut(segment_id);
                let pad: *mut WirePointer =
                    seg_start.offset((*reff).far_position_in_segment() as isize) as *mut _;

                if (*reff).is_double_far() {
                    let segment_id = (*pad).far_segment_id();

                    let (seg_start, _seg_len) = arena.get_segment_mut(segment_id);
                    let ptr: *mut Word = seg_start.offset((*pad).far_position_in_segment() as isize);
                    zero_object_helper(arena,
                                       segment_id,
                                       pad.offset(1),
                                       ptr);

                    ptr::write_bytes(pad, 0u8, 2);

                } else {
                    zero_object(arena, segment_id, pad);
                    ptr::write_bytes(pad, 0u8, 1);
                }
            }
        }
    }

    pub unsafe fn zero_object_helper(
        arena: &dyn BuilderArena,
        segment_id: u32,
        tag: *mut WirePointer,
        ptr: *mut Word)
    {
        match (*tag).kind() {
            WirePointerKind::Other => { panic!("Don't know how to handle OTHER") }
            WirePointerKind::Struct => {
                let pointer_section: *mut WirePointer =
                    ptr.offset((*tag).struct_data_size() as isize) as *mut _;

                let count = (*tag).struct_ptr_count() as isize;
                for i in 0..count {
                    zero_object(arena, segment_id, pointer_section.offset(i));
                }
                ptr::write_bytes(ptr, 0u8, (*tag).struct_word_size() as usize);
            }
            WirePointerKind::List => {
                match (*tag).list_element_size() {
                    Void =>  { }
                    Bit | Byte | TwoBytes | FourBytes | EightBytes => {
                        ptr::write_bytes(
                            ptr, 0u8,
                            round_bits_up_to_words((
                                    (*tag).list_element_count() *
                                        data_bits_per_element(
                                        (*tag).list_element_size())) as u64) as usize)
                    }
                    Pointer => {
                        let count = (*tag).list_element_count() as usize;
                        for i in 0..count as isize {
                            zero_object(arena, segment_id, ptr.offset(i) as *mut _);
                        }
                        ptr::write_bytes(ptr, 0u8, count);
                    }
                    InlineComposite => {
                        let element_tag: *mut WirePointer = ptr as *mut _;

                        assert!((*element_tag).kind() == WirePointerKind::Struct,
                                "Don't know how to handle non-STRUCT inline composite");

                        let data_size = (*element_tag).struct_data_size();
                        let pointer_count = (*element_tag).struct_ptr_count();
                        let mut pos: *mut Word = ptr.offset(1);
                        let count = (*element_tag).inline_composite_list_element_count();
                        if pointer_count > 0 {
                            for _ in 0..count {
                                pos = pos.offset(data_size as isize);
                                for _ in 0..pointer_count {
                                    zero_object(arena, segment_id, pos as *mut WirePointer);
                                    pos = pos.offset(1);
                                }
                            }
                        }
                        ptr::write_bytes(ptr, 0u8,
                                         ((*element_tag).struct_word_size() * count + 1) as usize);
                    }
                }
            }
            WirePointerKind::Far => { panic!("Unexpected FAR pointer") }
        }
    }

    #[inline]
    pub unsafe fn zero_pointer_and_fars(
        arena: &dyn BuilderArena,
        _segment_id: u32,
        reff: *mut WirePointer) -> Result<()>
    {
        // Zero out the pointer itself and, if it is a far pointer, zero the landing pad as well,
        // but do not zero the object body. Used when upgrading.

        if (*reff).kind() == WirePointerKind::Far {
            let far_segment_id = (*reff).far_segment_id();
            let (seg_start, _seg_len) = arena.get_segment_mut(far_segment_id);
            let pad: *mut Word = seg_start.offset((*reff).far_position_in_segment() as isize);
            let num_elements = if (*reff).is_double_far() { 2 } else { 1 };
            ptr::write_bytes(pad, 0, num_elements);
        }
        ptr::write_bytes(reff, 0, 1);
        Ok(())
    }

    pub unsafe fn total_size(
        arena: &dyn ReaderArena,
        segment_id: u32,
        reff: *const WirePointer,
        mut nesting_limit: i32) -> Result<MessageSize>
    {
        let mut result = MessageSize { word_count: 0, cap_count: 0};

        if (*reff).is_null() { return Ok(result) };

        if nesting_limit <= 0 {
            return Err(Error::failed("Message is too deeply nested.".to_string()));
        }

        nesting_limit -= 1;

        let (ptr, reff, segment_id) = follow_fars(arena, reff, segment_id)?;

        match (*reff).kind() {
            WirePointerKind::Struct => {
                bounds_check(arena, segment_id,
                             ptr, (*reff).struct_word_size() as usize,
                             WirePointerKind::Struct)?;
                result.word_count += (*reff).struct_word_size() as u64;

                let pointer_section: *const WirePointer =
                    ptr.offset((*reff).struct_data_size() as isize) as *const _;
                let count: isize = (*reff).struct_ptr_count() as isize;
                for i in 0..count {
                    result.plus_eq(total_size(arena, segment_id, pointer_section.offset(i), nesting_limit)?);
                }
            }
            WirePointerKind::List => {
                match (*reff).list_element_size() {
                    Void => {}
                    Bit | Byte | TwoBytes | FourBytes | EightBytes => {
                        let total_words = round_bits_up_to_words(
                            (*reff).list_element_count() as u64 *
                                data_bits_per_element((*reff).list_element_size()) as u64);
                        bounds_check(
                            arena, segment_id, ptr, total_words as usize, WirePointerKind::List)?;
                        result.word_count += total_words as u64;
                    }
                    Pointer => {
                        let count = (*reff).list_element_count();
                        bounds_check(
                            arena, segment_id, ptr, count as usize * WORDS_PER_POINTER,
                            WirePointerKind::List)?;

                        result.word_count += count as u64 * WORDS_PER_POINTER as u64;

                        for i in 0..count as isize {
                            result.plus_eq(
                                total_size(arena, segment_id,
                                           (ptr as *const WirePointer).offset(i),
                                           nesting_limit)?);
                        }
                    }
                    InlineComposite => {
                        let word_count = (*reff).list_inline_composite_word_count();
                        bounds_check(arena, segment_id, ptr,
                                     word_count as usize + POINTER_SIZE_IN_WORDS,
                                     WirePointerKind::List)?;

                        let element_tag: *const WirePointer = ptr as *const _;
                        let count = (*element_tag).inline_composite_list_element_count();

                        if (*element_tag).kind() != WirePointerKind::Struct {
                            return Err(Error::failed(
                                "Don't know how to handle non-STRUCT inline composite.".to_string()));
                        }

                        let actual_size = (*element_tag).struct_word_size() as u64 * count as u64;
                        if actual_size > word_count as u64 {
                            return Err(Error::failed(
                                "InlineComposite list's elements overrun its word count.".to_string()));
                        }

                        // Count the actual size rather than the claimed word count because
                        // that's what we end up with if we make a copy.
                        result.word_count += actual_size as u64 + POINTER_SIZE_IN_WORDS as u64;

                        let data_size = (*element_tag).struct_data_size();
                        let pointer_count = (*element_tag).struct_ptr_count();

                        if pointer_count > 0 {
                            let mut pos: *const Word = ptr.offset(POINTER_SIZE_IN_WORDS as isize);
                            for _ in 0..count {
                                pos = pos.offset(data_size as isize);

                                for _ in 0..pointer_count {
                                    result.plus_eq(
                                        total_size(arena, segment_id,
                                                   pos as *const WirePointer, nesting_limit)?);
                                    pos = pos.offset(POINTER_SIZE_IN_WORDS as isize);
                                }
                            }
                        }
                    }
                }
            }
            WirePointerKind::Far => {
                return Err(Error::failed("Malformed double-far pointer.".to_string()));
            }
            WirePointerKind::Other => {
                if (*reff).is_capability() {
                    result.cap_count += 1;
                } else {
                    return Err(Error::failed("Unknown pointer type.".to_string()));
                }
            }
        }

        Ok(result)
    }

    // Helper for copy_message().
    unsafe fn copy_struct(
        arena: &dyn BuilderArena,
        segment_id: u32,
        cap_table: CapTableBuilder,
        dst: *mut Word,
        src: *const Word,
        data_size: isize,
        pointer_count: isize) {
        ptr::copy_nonoverlapping(src, dst, data_size as usize);

        let src_refs: *const WirePointer = mem::transmute(src.offset(data_size));
        let dst_refs: *mut WirePointer = mem::transmute(dst.offset(data_size));

        for ii in 0..pointer_count {
            copy_message(arena, segment_id, cap_table, dst_refs.offset(ii), src_refs.offset(ii));
        }
    }

    // Copies from a trusted message.
    // Returns (new_dst_ptr, new_dst, new_segment_id).
    pub unsafe fn copy_message(
        arena: &dyn BuilderArena,
        segment_id: u32,
        cap_table: CapTableBuilder,
        dst: *mut WirePointer,
        src: *const WirePointer) -> (*mut Word, *mut WirePointer, u32)
    {
        match (*src).kind() {
            WirePointerKind::Struct => {
                if (*src).is_null() {
                    ptr::write_bytes(dst, 0, 1);
                    (ptr::null_mut(), dst, segment_id)
                } else {
                    let src_ptr = (*src).target();
                    let (dst_ptr, dst, segment_id) = allocate(
                        arena, dst, segment_id, (*src).struct_word_size(), WirePointerKind::Struct);
                    copy_struct(arena,
                                segment_id,
                                cap_table,
                                dst_ptr,
                                src_ptr,
                                (*src).struct_data_size() as isize,
                                (*src).struct_ptr_count() as isize);
                    (*dst).set_struct_size_from_pieces((*src).struct_data_size(), (*src).struct_ptr_count());
                    (dst_ptr, dst, segment_id)
                }
            }
            WirePointerKind::List => {
                match (*src).list_element_size() {
                    ElementSize::Void |
                    ElementSize::Bit |
                    ElementSize::Byte |
                    ElementSize::TwoBytes |
                    ElementSize::FourBytes |
                    ElementSize::EightBytes => {
                        let word_count = round_bits_up_to_words(
                            (*src).list_element_count() as u64 *
                                data_bits_per_element((*src).list_element_size()) as u64);
                        let src_ptr = (*src).target();
                        let (dst_ptr, dst, segment_id) = allocate(
                            arena, dst, segment_id, word_count, WirePointerKind::List);
                        ptr::copy_nonoverlapping(src_ptr, dst_ptr, word_count as usize);
                        (*dst).set_list_size_and_count((*src).list_element_size(),
                                                       (*src).list_element_count());
                        (dst_ptr, dst, segment_id)
                    }

                    ElementSize::Pointer => {
                        let src_refs: *const WirePointer = mem::transmute((*src).target());
                        let (dst_refs, dst, segment_id) = allocate(
                            arena, dst, segment_id,
                            (*src).list_element_count(),
                            WirePointerKind::List);
                        for ii in 0 .. ((*src).list_element_count() as isize) {
                            copy_message(arena,
                                         segment_id,
                                         cap_table,
                                         mem::transmute(dst_refs.offset(ii)),
                                         src_refs.offset(ii));
                        }
                        (*dst).set_list_size_and_count(ElementSize::Pointer, (*src).list_element_count());
                        (mem::transmute(dst_refs), dst, segment_id)
                    }
                    ElementSize::InlineComposite => {
                        let src_ptr = (*src).target();
                        let (dst_ptr, dst, segment_id) = allocate(
                            arena,
                            dst,
                            segment_id,
                            (*src).list_inline_composite_word_count() + 1,
                            WirePointerKind::List);

                        (*dst).set_list_inline_composite((*src).list_inline_composite_word_count());

                        let src_tag: *const WirePointer = mem::transmute(src_ptr);
                        ptr::copy_nonoverlapping(src_tag, mem::transmute(dst_ptr), 1);

                        let mut src_element = src_ptr.offset(1);
                        let mut dst_element = dst_ptr.offset(1);

                        if (*src_tag).kind() != WirePointerKind::Struct {
                            panic!("unsupported INLINE_COMPOSITE list");
                        }
                        for _ in 0 .. (*src_tag).inline_composite_list_element_count() {
                            copy_struct(arena,
                                        segment_id,
                                        cap_table,
                                        dst_element,
                                        src_element,
                                        (*src_tag).struct_data_size() as isize,
                                        (*src_tag).struct_ptr_count() as isize);
                            src_element = src_element.offset((*src_tag).struct_word_size() as isize);
                            dst_element = dst_element.offset((*src_tag).struct_word_size() as isize);
                        }
                        (dst_ptr, dst, segment_id)
                    }
                }
            }
            WirePointerKind::Other => {
                panic!("Unchecked message contained an OTHER pointer.")
            }
            WirePointerKind::Far => {
                panic!("Unchecked message contained a far pointer.")
            }
        }
    }

    pub unsafe fn transfer_pointer(
        arena: &dyn BuilderArena,
        dst_segment_id: u32, dst: *mut WirePointer,
        src_segment_id: u32, src: *mut WirePointer)
    {
        //# Make *dst point to the same object as *src. Both must
        //# reside in the same message, but can be in different
        //# segments. Not always-inline because this is rarely used.
        //
        //# Caller MUST zero out the source pointer after calling this,
        //# to make sure no later code mistakenly thinks the source
        //# location still owns the object. transferPointer() doesn't
        //# do this zeroing itself because many callers transfer
        //# several pointers in a loop then zero out the whole section.

        assert!((*dst).is_null());
        // We expect the caller to ensure the target is already null so won't leak.

        if (*src).is_null() {
            ptr::write_bytes(dst, 0, 1);
        } else if (*src).is_positional() {
            transfer_pointer_split(arena, dst_segment_id, dst, src_segment_id, src, (*src).mut_target());
        } else {
            ptr::copy_nonoverlapping(src, dst, 1);
        }
    }

    pub unsafe fn transfer_pointer_split(
        arena: &dyn BuilderArena,
        dst_segment_id: u32, dst: *mut WirePointer,
        src_segment_id: u32, src_tag: *mut WirePointer,
        src_ptr: *mut Word)
    {
        // Like the other transfer_pointer, but splits src into a tag and a
        // target. Particularly useful for OrphanBuilder.

        if dst_segment_id == src_segment_id {
            // Same segment, so create a direct pointer.

            if (*src_tag).kind() == WirePointerKind::Struct && (*src_tag).struct_word_size() == 0 {
                (*dst).set_kind_and_target_for_empty_struct();
            } else {
                (*dst).set_kind_and_target((*src_tag).kind(), src_ptr);
            }
            // We can just copy the upper 32 bits. (Use memcpy() to comply with aliasing rules.)
            ptr::copy_nonoverlapping(&(*src_tag).upper32bits, &mut (*dst).upper32bits, 1);
        } else {
            // Need to create a far pointer. Try to allocate it in the same segment as the source,
            // so that it doesn't need to be a double-far.

            match arena.allocate(src_segment_id, 1) {
                None => {
                    //# Darn, need a double-far.
                    let (far_segment_id, word_idx) = arena.allocate_anywhere(2);
                    let (seg_start, _seg_len) = arena.get_segment_mut(far_segment_id);
                    let landing_pad: *mut WirePointer = seg_start.offset(word_idx as isize) as *mut _;

                    let (src_seg_start, _seg_len) = arena.get_segment_mut(src_segment_id);

                    (*landing_pad).set_far(
                        false,
                        ((src_ptr as usize - src_seg_start as usize) / BYTES_PER_WORD) as u32);
                    (*landing_pad).set_far_segment_id(src_segment_id);

                    let landing_pad1 = landing_pad.offset(1);
                    (*landing_pad1).set_kind_with_zero_offset((*src_tag).kind());

                    ptr::copy_nonoverlapping(
                        &(*src_tag).upper32bits,
                        &mut (*landing_pad1).upper32bits,
                        1);

                    (*dst).set_far(true, word_idx);
                    (*dst).set_far_segment_id(far_segment_id);
                }
                Some(landing_pad_word) => {
                    //# Simple landing pad is just a pointer.
                    let (seg_start, seg_len) = arena.get_segment_mut(src_segment_id);
                    assert!(landing_pad_word < seg_len);
                    let landing_pad: *mut WirePointer = seg_start.offset(landing_pad_word as isize) as *mut _;
                    (*landing_pad).set_kind_and_target((*src_tag).kind(), src_ptr);
                    ptr::copy_nonoverlapping(&(*src_tag).upper32bits,
                                             &mut (*landing_pad).upper32bits, 1);

                    (*dst).set_far(false, landing_pad_word);
                    (*dst).set_far_segment_id(src_segment_id);
                }
            }
        }
    }

    #[inline]
    pub unsafe fn init_struct_pointer<'a>(
        arena: &'a dyn BuilderArena,
        reff: *mut WirePointer,
        segment_id: u32,
        cap_table: CapTableBuilder,
        size: StructSize) -> StructBuilder<'a>
    {
        let (ptr, reff, segment_id) = allocate(
            arena,
            reff,
            segment_id,
            size.total(),
            WirePointerKind::Struct);
        (*reff).set_struct_size(size);

        StructBuilder {
            arena: arena,
            segment_id: segment_id,
            cap_table: cap_table,
            data: ptr as *mut _,
            pointers: ptr.offset((size.data as usize) as isize) as *mut _,
            data_size: size.data as WordCount32 * (BITS_PER_WORD as BitCount32),
            pointer_count: size.pointers,
        }
    }

    #[inline]
    pub unsafe fn get_writable_struct_pointer<'a>(
        arena: &'a dyn BuilderArena,
        mut reff: *mut WirePointer,
        mut segment_id: u32,
        cap_table: CapTableBuilder,
        size: StructSize,
        default: Option<&'a [Word]>) -> Result<StructBuilder<'a>>
    {
        let mut ref_target = (*reff).mut_target();

        if (*reff).is_null() {
            match default {
                None => return Ok(init_struct_pointer(arena, reff, segment_id, cap_table, size)),
                Some(d) if (*(d.as_ptr() as *const WirePointer)).is_null() =>
                    return Ok(init_struct_pointer(arena, reff, segment_id, cap_table, size)),
                Some(d) => {
                    let (new_ref_target, new_reff, new_segment_id) =
                        copy_message(arena, segment_id, cap_table, reff, mem::transmute(d.as_ptr()));
                    reff = new_reff;
                    segment_id = new_segment_id;
                    ref_target = new_ref_target;
                }
            }
        }

        let (old_ptr, old_ref, old_segment_id) = follow_builder_fars(arena, reff, ref_target, segment_id)?;
        if (*old_ref).kind() != WirePointerKind::Struct {
            return Err(Error::failed(
                "Message contains non-struct pointer where struct pointer was expected.".to_string()));
        }

        let old_data_size = (*old_ref).struct_data_size();
        let old_pointer_count = (*old_ref).struct_ptr_count();
        let old_pointer_section: *mut WirePointer = old_ptr.offset(old_data_size as isize) as *mut _;

        if old_data_size < size.data || old_pointer_count < size.pointers {
            //# The space allocated for this struct is too small.
            //# Unlike with readers, we can't just run with it and do
            //# bounds checks at access time, because how would we
            //# handle writes? Instead, we have to copy the struct to a
            //# new space now.

            let new_data_size = ::std::cmp::max(old_data_size, size.data);
            let new_pointer_count = ::std::cmp::max(old_pointer_count, size.pointers);
            let total_size = new_data_size as u32 + new_pointer_count as u32 * WORDS_PER_POINTER as u32;

            //# Don't let allocate() zero out the object just yet.
            zero_pointer_and_fars(arena, segment_id, reff)?;

            let (ptr, reff, segment_id) = allocate(arena, reff, segment_id, total_size, WirePointerKind::Struct);
            (*reff).set_struct_size_from_pieces(new_data_size, new_pointer_count);

            // Copy data section.
            // Note: copy_nonoverlapping's third argument is an element count, not a byte count.
            ptr::copy_nonoverlapping(old_ptr, ptr, old_data_size as usize);

            //# Copy pointer section.
            let new_pointer_section: *mut WirePointer = ptr.offset(new_data_size as isize) as *mut _;
            for i in 0..old_pointer_count as isize {
                transfer_pointer(arena, segment_id, new_pointer_section.offset(i),
                                 old_segment_id, old_pointer_section.offset(i));
            }

            ptr::write_bytes(old_ptr, 0, old_data_size as usize + old_pointer_count as usize);

            Ok(StructBuilder {
                arena: arena,
                segment_id: segment_id,
                cap_table: cap_table,
                data: ptr as *mut _,
                pointers: new_pointer_section,
                data_size: new_data_size as u32 * BITS_PER_WORD as u32,
                pointer_count: new_pointer_count
            })
        } else {
            Ok(StructBuilder {
                arena: arena,
                segment_id: old_segment_id,
                cap_table: cap_table,
                data: old_ptr as *mut _,
                pointers: old_pointer_section,
                data_size: old_data_size as u32 * BITS_PER_WORD as u32,
                pointer_count: old_pointer_count
            })
        }
    }

    #[inline]
    pub unsafe fn init_list_pointer<'a>(
        arena: &'a dyn BuilderArena,
        reff: *mut WirePointer,
        segment_id: u32,
        cap_table: CapTableBuilder,
        element_count: ElementCount32,
        element_size: ElementSize) -> ListBuilder<'a>
    {
        assert!(element_size != InlineComposite,
                "Should have called initStructListPointer() instead");

        let data_size = data_bits_per_element(element_size);
        let pointer_count = pointers_per_element(element_size);
        let step = data_size + pointer_count * BITS_PER_POINTER as u32;
        let word_count = round_bits_up_to_words(element_count as ElementCount64 * (step as u64));
        let (ptr, reff, segment_id) = allocate(arena, reff, segment_id, word_count, WirePointerKind::List);

        (*reff).set_list_size_and_count(element_size, element_count);

        ListBuilder {
            arena: arena,
            segment_id: segment_id,
            cap_table: cap_table,
            ptr: ptr as *mut _,
            step: step,
            element_count: element_count,
            element_size: element_size,
            struct_data_size: data_size,
            struct_pointer_count: pointer_count as u16
        }
    }

    #[inline]
    pub unsafe fn init_struct_list_pointer<'a>(
        arena: &'a dyn BuilderArena,
        reff: *mut WirePointer,
        segment_id: u32,
        cap_table: CapTableBuilder,
        element_count: ElementCount32,
        element_size: StructSize) -> ListBuilder<'a>
    {
        let words_per_element = element_size.total();

        //# Allocate the list, prefixed by a single WirePointer.
        let word_count: WordCount32 = element_count * words_per_element;
        let (ptr, reff, segment_id) = allocate(arena,
                                               reff,
                                               segment_id,
                                               POINTER_SIZE_IN_WORDS as u32 + word_count,
                                               WirePointerKind::List);
        let ptr = ptr as *mut WirePointer;

        //# Initialize the pointer.
        (*reff).set_list_inline_composite(word_count);
        (*ptr).set_kind_and_inline_composite_list_element_count(WirePointerKind::Struct, element_count);
        (*ptr).set_struct_size(element_size);

        let ptr1 = ptr.offset(POINTER_SIZE_IN_WORDS as isize);

        ListBuilder {
            arena: arena,
            segment_id: segment_id,
            cap_table: cap_table,
            ptr: ptr1 as *mut _,
            step: words_per_element * BITS_PER_WORD as u32,
            element_count: element_count,
            element_size: ElementSize::InlineComposite,
            struct_data_size: element_size.data as u32 * (BITS_PER_WORD as u32),
            struct_pointer_count: element_size.pointers
        }
    }

    #[inline]
    pub unsafe fn get_writable_list_pointer<'a>(
        arena: &'a dyn BuilderArena,
        mut orig_ref: *mut WirePointer,
        mut orig_segment_id: u32,
        cap_table: CapTableBuilder,
        element_size: ElementSize,
        default_value: *const Word) -> Result<ListBuilder<'a>>
    {
        assert!(element_size != InlineComposite,
                "Use get_writable_struct_list_pointer() for struct lists");

        let mut orig_ref_target = (*orig_ref).mut_target();

        if (*orig_ref).is_null() {
            if default_value.is_null() || (*(default_value as *const WirePointer)).is_null() {
                return Ok(ListBuilder::new_default());
            }
            let (new_orig_ref_target, new_orig_ref, new_orig_segment_id) = copy_message(
                arena, orig_segment_id, cap_table, orig_ref, mem::transmute(default_value));
            orig_ref_target = new_orig_ref_target;
            orig_ref = new_orig_ref;
            orig_segment_id = new_orig_segment_id;
        }

        // We must verify that the pointer has the right size. Unlike in
        // get_writable_struct_list_pointer(), we never need to "upgrade" the data, because this
        // method is called only for non-struct lists, and there is no allowed upgrade path *to* a
        // non-struct list, only *from* them.

        let (mut ptr, reff, segment_id) =
            follow_builder_fars(arena, orig_ref, orig_ref_target, orig_segment_id)?;

        if (*reff).kind() != WirePointerKind::List {
            return Err(Error::failed(
                "Called get_writable_list_pointer() but existing pointer is not a list.".to_string()));
        }

        let old_size = (*reff).list_element_size();

        if old_size == InlineComposite {
            // The existing element size is InlineComposite, which means that it is at least two
            // words, which makes it bigger than the expected element size. Since fields can only
            // grow when upgraded, the existing data must have been written with a newer version of
            // the protocol. We therefore never need to upgrade the data in this case, but we do
            // need to validate that it is a valid upgrade from what we expected.

            // Read the tag to get the actual element count.
            let tag: *const WirePointer = ptr as *const _;

            if (*tag).kind() != WirePointerKind::Struct {
                return Err(Error::failed(
                    "InlineComposite list with non-STRUCT elements not supported.".to_string()));
            }

            ptr = ptr.offset(POINTER_SIZE_IN_WORDS as isize);

            let data_size = (*tag).struct_data_size();
            let pointer_count = (*tag).struct_ptr_count();

            match element_size {
                Void => {} // Anything is a valid upgrade from Void.
                Bit => {
                    return Err(Error::failed(
                        "Found struct list where bit list was expected.".to_string()));
                }
                Byte | TwoBytes | FourBytes | EightBytes => {
                    if data_size < 1 {
                        return Err(Error::failed(
                            "Existing list value is incompatible with expected type.".to_string()));
                    }
                }
                Pointer => {
                    if pointer_count < 1 {
                        return Err(Error::failed(
                            "Existing list value is incompatible with expected type.".to_string()));
                    }
                    // Adjust the pointer to point at the reference segment.
                    ptr = ptr.offset(data_size as isize);
                }
                InlineComposite => {
                    unreachable!()
                }
            }
            // OK, looks valid.

            Ok(ListBuilder {
                arena: arena,
                segment_id: segment_id,
                cap_table: cap_table,
                ptr: ptr as *mut _,
                element_count: (*tag).inline_composite_list_element_count(),
                element_size: ElementSize::InlineComposite,
                step: (*tag).struct_word_size() * BITS_PER_WORD as u32,
                struct_data_size: data_size as u32 * BITS_PER_WORD as u32,
                struct_pointer_count: pointer_count
            })
        } else {
            let data_size = data_bits_per_element(old_size);
            let pointer_count = pointers_per_element(old_size);

            if data_size < data_bits_per_element(element_size) ||
                pointer_count < pointers_per_element(element_size) {
                return Err(Error::failed(
                    "Existing list value is incompatible with expected type.".to_string()));
            }

            let step = data_size + pointer_count * BITS_PER_POINTER as u32;

            Ok(ListBuilder {
                arena: arena,
                segment_id: segment_id,
                cap_table: cap_table,
                ptr: ptr as *mut _,
                step: step,
                element_count: (*reff).list_element_count(),
                element_size: old_size,
                struct_data_size: data_size,
                struct_pointer_count: pointer_count as u16
            })
        }
    }

    #[inline]
    pub unsafe fn get_writable_struct_list_pointer<'a>(
        arena: &'a dyn BuilderArena,
        mut orig_ref: *mut WirePointer,
        mut orig_segment_id: u32,
        cap_table: CapTableBuilder,
        element_size: StructSize,
        default_value: *const Word) -> Result<ListBuilder<'a>>
    {
        let mut orig_ref_target = (*orig_ref).mut_target();

        if (*orig_ref).is_null() {
            if default_value.is_null() || (*(default_value as *const WirePointer)).is_null() {
                return Ok(ListBuilder::new_default());
            }
            let (new_orig_ref_target, new_orig_ref, new_orig_segment_id) = copy_message(
                arena, orig_segment_id, cap_table, orig_ref, mem::transmute(default_value));
            orig_ref_target = new_orig_ref_target;
            orig_ref = new_orig_ref;
            orig_segment_id = new_orig_segment_id;
        }

        // We must verify that the pointer has the right size and potentially upgrade it if not.

        let (mut old_ptr, old_ref, old_segment_id) =
            follow_builder_fars(arena, orig_ref, orig_ref_target, orig_segment_id)?;

        if (*old_ref).kind() != WirePointerKind::List {
            return Err(Error::failed(
                "Called get_writable_struct_list_pointer() but existing pointer is not a list.".to_string()));
        }

        let old_size = (*old_ref).list_element_size();

        if old_size == InlineComposite {
            // Existing list is InlineComposite, but we need to verify that the sizes match.

            let old_tag: *const WirePointer = old_ptr as *const _;
            old_ptr = old_ptr.offset(POINTER_SIZE_IN_WORDS as isize);
            if (*old_tag).kind() != WirePointerKind::Struct {
                return Err(Error::failed(
                    "InlineComposite list with non-STRUCT elements not supported.".to_string()));
            }

            let old_data_size = (*old_tag).struct_data_size();
            let old_pointer_count = (*old_tag).struct_ptr_count();
            let old_step = old_data_size as u32 + old_pointer_count as u32 * WORDS_PER_POINTER as u32;
            let element_count = (*old_tag).inline_composite_list_element_count();

            if old_data_size >= element_size.data && old_pointer_count >= element_size.pointers {
                // Old size is at least as large as we need. Ship it.
                return Ok(ListBuilder {
                    arena: arena,
                    segment_id: old_segment_id,
                    cap_table: cap_table,
                    ptr: old_ptr as *mut _,
                    element_count: element_count,
                    element_size: ElementSize::InlineComposite,
                    step: old_step * BITS_PER_WORD as u32,
                    struct_data_size: old_data_size as u32 * BITS_PER_WORD as u32,
                    struct_pointer_count: old_pointer_count
                });
            }

            // The structs in this list are smaller than expected, probably written using an older
            // version of the protocol. We need to make a copy and expand them.

            let new_data_size = ::std::cmp::max(old_data_size, element_size.data);
            let new_pointer_count = ::std::cmp::max(old_pointer_count, element_size.pointers);
            let new_step = new_data_size as u32 + new_pointer_count as u32 * WORDS_PER_POINTER as u32;
            let total_size = new_step * element_count;

            // Don't let allocate() zero out the object just yet.
            zero_pointer_and_fars(arena, orig_segment_id, orig_ref)?;

            let (mut new_ptr, new_ref, new_segment_id) =
                allocate(arena, orig_ref, orig_segment_id,
                         total_size + POINTER_SIZE_IN_WORDS as u32, WirePointerKind::List);
            (*new_ref).set_list_inline_composite(total_size);

            let new_tag: *mut WirePointer = new_ptr as *mut _;
            (*new_tag).set_kind_and_inline_composite_list_element_count(WirePointerKind::Struct, element_count);
            (*new_tag).set_struct_size_from_pieces(new_data_size, new_pointer_count);
            new_ptr = new_ptr.offset(POINTER_SIZE_IN_WORDS as isize);

            let mut src: *mut Word = old_ptr as *mut _;
            let mut dst: *mut Word = new_ptr;
            for _ in 0..element_count {
                // Copy data section.
                ptr::copy_nonoverlapping(src, dst, old_data_size as usize);

                // Copy pointer section
                let new_pointer_section: *mut WirePointer = dst.offset(new_data_size as isize) as *mut _;
                let old_pointer_section: *mut WirePointer = src.offset(old_data_size as isize) as *mut _;
                for jj in 0..(old_pointer_count as isize) {
                    transfer_pointer(arena, new_segment_id,
                                     new_pointer_section.offset(jj),
                                     old_segment_id, old_pointer_section.offset(jj));
                }

                dst = dst.offset(new_step as isize);
                src = src.offset(old_step as isize);
            }

            ptr::write_bytes(old_ptr.offset(-1), 0,
                             (old_step as u64 * element_count as u64) as usize);

            Ok(ListBuilder {
                arena: arena,
                segment_id: new_segment_id,
                cap_table: cap_table,
                ptr: new_ptr as *mut _,
                element_count: element_count,
                element_size: ElementSize::InlineComposite,
                step: new_step * BITS_PER_WORD as u32,
                struct_data_size: new_data_size as u32 * BITS_PER_WORD as u32,
                struct_pointer_count: new_pointer_count,
            })
        } else {
            // We're upgrading from a non-struct list.

            let old_data_size = data_bits_per_element(old_size);
            let old_pointer_count = pointers_per_element(old_size);
            let old_step = old_data_size + old_pointer_count * BITS_PER_POINTER as u32;
            let element_count = (*old_ref).list_element_count();

            if old_size == ElementSize::Void {
                // Nothing to copy, just allocate a new list.
                Ok(init_struct_list_pointer(
                    arena, orig_ref, orig_segment_id, cap_table, element_count, element_size))
            } else {
                // Upgrade to an inline composite list.

                if old_size == ElementSize::Bit {
                    return Err(Error::failed(
                        "Found bit list where struct list was expected; upgrading boolean \
                         lists to struct lists is no longer supported.".to_string()));
                }

                let mut new_data_size = element_size.data;
                let mut new_pointer_count = element_size.pointers;

                if old_size == ElementSize::Pointer {
                    new_pointer_count = ::std::cmp::max(new_pointer_count, 1);
                } else {
                    // Old list contains data elements, so we need at least one word of data.
                    new_data_size = ::std::cmp::max(new_data_size, 1);
                }

                let new_step = new_data_size as u32 + new_pointer_count as u32 * WORDS_PER_POINTER as u32;
                let total_words = element_count * new_step;

                // Don't let allocate() zero out the object just yet.
                zero_pointer_and_fars(arena, orig_segment_id, orig_ref)?;

                let (mut new_ptr, new_ref, new_segment_id) =
                    allocate(arena, orig_ref, orig_segment_id,
                             total_words + POINTER_SIZE_IN_WORDS as u32, WirePointerKind::List);
                (*new_ref).set_list_inline_composite(total_words);

                let tag: *mut WirePointer = new_ptr as *mut _;
                (*tag).set_kind_and_inline_composite_list_element_count(WirePointerKind::Struct, element_count);
                (*tag).set_struct_size_from_pieces(new_data_size, new_pointer_count);
                new_ptr = new_ptr.offset(POINTER_SIZE_IN_WORDS as isize);

                if old_size == ElementSize::Pointer {
                    let mut dst: *mut Word = new_ptr.offset(new_data_size as isize);
                    let mut src: *mut WirePointer = old_ptr as *mut _;
                    for _ in 0..element_count {
                        transfer_pointer(arena, new_segment_id, dst as *mut _, old_segment_id, src);
                        dst = dst.offset(new_step as isize / WORDS_PER_POINTER as isize);
                        src = src.offset(1);
                    }
                } else {
                    let mut dst: *mut Word = new_ptr;
                    let mut src: *mut u8 = old_ptr as *mut u8;
                    let old_byte_step = old_data_size / BITS_PER_BYTE as u32;
                    for _ in 0..element_count {
                        ptr::copy_nonoverlapping(src, dst as *mut _, old_byte_step as usize);
                        src = src.offset(old_byte_step as isize);
                        dst = dst.offset(new_step as isize);
                    }
                }

                // Zero out old location.
                ptr::write_bytes(old_ptr as *mut u8, 0,
                                 round_bits_up_to_bytes(old_step as u64 * element_count as u64) as usize);

                Ok(ListBuilder {
                    arena: arena,
                    segment_id: new_segment_id,
                    cap_table: cap_table,
                    ptr: new_ptr as *mut _,
                    element_count: element_count,
                    element_size: ElementSize::InlineComposite,
                    step: new_step * BITS_PER_WORD as u32,
                    struct_data_size: new_data_size as u32 * BITS_PER_WORD as u32,
                    struct_pointer_count: new_pointer_count
                })
            }
        }
    }

    #[inline]
    pub unsafe fn init_text_pointer<'a>(
        arena: &'a dyn BuilderArena,
        reff: *mut WirePointer,
        segment_id: u32,
        size: ByteCount32) -> SegmentAnd<text::Builder<'a>>
    {
        //# The byte list must include a NUL terminator.
        let byte_size = size + 1;

        //# Allocate the space.
        let (ptr, reff, segment_id) =
            allocate(arena, reff, segment_id, round_bytes_up_to_words(byte_size), WirePointerKind::List);

        //# Initialize the pointer.
        (*reff).set_list_size_and_count(Byte, byte_size);

        SegmentAnd {
            segment_id: segment_id,
            value: text::Builder::new(slice::from_raw_parts_mut(ptr as *mut _, size as usize), 0)
                .expect("empty text builder should be valid utf-8")
        }
    }

    #[inline]
    pub unsafe fn set_text_pointer<'a>(
        arena: &'a dyn BuilderArena,
        reff: *mut WirePointer,
        segment_id: u32,
        value: &str) -> SegmentAnd<text::Builder<'a>>
    {
        let value_bytes = value.as_bytes();
        // TODO make sure the string is not longer than 2 ** 29.
        let mut allocation = init_text_pointer(arena, reff, segment_id, value_bytes.len() as u32);
        allocation.value.push_str(value);
        allocation
    }

    #[inline]
    pub unsafe fn get_writable_text_pointer<'a>(
        arena: &'a dyn BuilderArena,
        mut reff: *mut WirePointer,
        mut segment_id: u32,
        default: Option<&'a [Word]>) -> Result<text::Builder<'a>>
    {
        let ref_target = if (*reff).is_null() {
            match default {
                None => return text::Builder::new(&mut [], 0),
                Some(d) => {
                    let (new_ref_target, new_reff, new_segment_id) =
                        copy_message(arena, segment_id, CapTableBuilder::Plain(::std::ptr::null_mut()), reff, d.as_ptr() as *const _);
                    reff = new_reff;
                    segment_id = new_segment_id;
                    new_ref_target
                }
            }
        } else {
            (*reff).mut_target()
        };

        let (ptr, reff, _segment_id) = follow_builder_fars(arena, reff, ref_target, segment_id)?;
        let cptr: *mut u8 = ptr as *mut _;

        if (*reff).kind() != WirePointerKind::List {
            return Err(Error::failed(
                "Called get_writable_text_pointer() but existing pointer is not a list.".to_string()));
        }
        if (*reff).list_element_size() != Byte {
            return Err(Error::failed(
                "Called get_writable_text_pointer() but existing list pointer is not byte-sized.".to_string()));
        }

        let count = (*reff).list_element_count();
        if count <= 0 || *cptr.offset((count - 1) as isize) != 0 {
            return Err(Error::failed(
                "Text blob missing NUL terminator.".to_string()));
        }

        // Subtract 1 from the size for the NUL terminator.
        text::Builder::new(slice::from_raw_parts_mut(cptr, (count - 1) as usize), count - 1)
    }

    #[inline]
    pub unsafe fn init_data_pointer<'a>(
        arena: &'a dyn BuilderArena,
        reff: *mut WirePointer,
        segment_id: u32,
        size: ByteCount32) -> SegmentAnd<data::Builder<'a>>
    {
        //# Allocate the space.
        let (ptr, reff, segment_id) =
            allocate(arena, reff, segment_id, round_bytes_up_to_words(size), WirePointerKind::List);

        //# Initialize the pointer.
        (*reff).set_list_size_and_count(Byte, size);

        SegmentAnd { segment_id: segment_id, value: data::new_builder(ptr as *mut _, size) }
    }

    #[inline]
    pub unsafe fn set_data_pointer<'a>(
        arena: &'a dyn BuilderArena,
        reff: *mut WirePointer,
        segment_id: u32,
        value: &[u8]) -> SegmentAnd<data::Builder<'a>>
    {
        let allocation = init_data_pointer(arena, reff, segment_id, value.len() as u32);
        ptr::copy_nonoverlapping(value.as_ptr(), allocation.value.as_mut_ptr(),
                                 value.len());
        allocation
    }

    #[inline]
    pub unsafe fn get_writable_data_pointer<'a>(
        arena: &'a dyn BuilderArena,
        mut reff: *mut WirePointer,
        mut segment_id: u32,
        default: Option<&'a [Word]>) -> Result<data::Builder<'a>>
    {
        let ref_target = if (*reff).is_null() {
            match default {
                None => return Ok(&mut []),
                Some(d) => {
                    let (new_ref_target, new_reff, new_segment_id) =
                        copy_message(arena, segment_id, CapTableBuilder::Plain(::std::ptr::null_mut()), reff, d.as_ptr() as *const _);
                    reff = new_reff;
                    segment_id = new_segment_id;
                    new_ref_target
                }
            }
        } else {
            (*reff).mut_target()
        };

        let (ptr, reff, _segment_id) = follow_builder_fars(arena, reff, ref_target, segment_id)?;

        if (*reff).kind() != WirePointerKind::List {
            return Err(Error::failed(
                "Called get_writable_data_pointer() but existing pointer is not a list.".to_string()));
        }
        if (*reff).list_element_size() != Byte {
            return Err(Error::failed(
                "Called get_writable_data_pointer() but existing list pointer is not byte-sized.".to_string()));
        }

        Ok(data::new_builder(ptr as *mut _, (*reff).list_element_count()))
    }

    pub unsafe fn set_struct_pointer(
        arena: &dyn BuilderArena,
        segment_id: u32,
        cap_table: CapTableBuilder,
        reff: *mut WirePointer,
        value: StructReader,
        canonicalize: bool) -> Result<SegmentAnd<*mut Word>>
    {
        let mut data_size: ByteCount32 = round_bits_up_to_bytes(value.data_size as u64);
        let mut ptr_count = value.pointer_count;

        if canonicalize {
            // StructReaders should not have bitwidths other than 1, but let's be safe
            if !(value.data_size == 1 || value.data_size % BITS_PER_BYTE as u32 == 0) {
                return Err(Error::failed("struct reader had bitwidth other than 1".to_string()))
            }

            if value.data_size == 1 {
                if !value.get_bool_field(0) {
                    data_size = 0;
                }
            } else {
                'chop: while data_size != 0 {
                    let end = data_size;
                    let mut window = data_size % BYTES_PER_WORD as u32;
                    if window == 0 {
                        window = BYTES_PER_WORD as u32;
                    }
                    let start = end - window;
                    let last_word = &value.get_data_section_as_blob()[start as usize..end as usize];
                    if last_word == &[0; 8] {
                        data_size -= window;
                    } else {
                        break 'chop
                    }
                }
            }

            while ptr_count != 0 && value.get_pointer_field(ptr_count as usize - 1).is_null() {
                ptr_count -= 1;
            }
        }

        let data_words = round_bytes_up_to_words(data_size);
        let total_size: WordCount32 = data_words + ptr_count as u32 * WORDS_PER_POINTER as u32;

        let (ptr, reff, segment_id) =
            allocate(arena, reff, segment_id, total_size, WirePointerKind::Struct);
        (*reff).set_struct_size_from_pieces(data_words as u16, ptr_count);

        if value.data_size == 1 {
            // Data size could be made 0 by truncation
            if data_size != 0 {
                *(ptr as *mut u8) = value.get_bool_field(0) as u8
            }
        } else {
            ptr::copy_nonoverlapping::<u8>(value.data, ptr as *mut u8, data_size as usize);
        }

        let pointer_section: *mut WirePointer = ptr.offset(data_words as isize) as *mut _;
        for i in 0..ptr_count as isize {
            copy_pointer(arena, segment_id, cap_table, pointer_section.offset(i),
                         value.arena,
                         value.segment_id, value.cap_table, value.pointers.offset(i),
                         value.nesting_limit,
                         canonicalize)?;
        }

        Ok(SegmentAnd { segment_id: segment_id, value: ptr })
    }

    pub fn set_capability_pointer(
        _arena: &dyn BuilderArena,
        _segment_id: u32,
        mut cap_table: CapTableBuilder,
        reff: *mut WirePointer,
        cap: Box<dyn ClientHook>)
    {
        // TODO if ref is not null, zero object.
        unsafe { (*reff).set_cap(cap_table.inject_cap(cap) as u32); }
    }

    pub unsafe fn set_list_pointer<'a>(
        arena: &'a dyn BuilderArena,
        segment_id: u32,
        cap_table: CapTableBuilder,
        reff: *mut WirePointer,
        value: ListReader,
        canonicalize: bool) -> Result<SegmentAnd<*mut Word>>
    {
        let total_size = round_bits_up_to_words((value.element_count * value.step) as u64);

        if value.element_size != ElementSize::InlineComposite {
            //# List of non-structs.
            let (ptr, reff, segment_id) =
                allocate(arena, reff, segment_id, total_size, WirePointerKind::List);

            if value.struct_pointer_count == 1 {
                //# List of pointers.
                (*reff).set_list_size_and_count(Pointer, value.element_count);
                for i in 0.. value.element_count as isize {
                    copy_pointer(arena, segment_id, cap_table,
                                 (ptr as *mut WirePointer).offset(i),
                                 value.arena,
                                 value.segment_id, value.cap_table,
                                 (value.ptr as *const WirePointer).offset(i),
                                 value.nesting_limit,
                                 canonicalize)?;
                }
            } else {
                //# List of data.
                let element_size = match value.step {
                    0 => Void,
                    1 => Bit,
                    8 => Byte,
                    16 => TwoBytes,
                    32 => FourBytes,
                    64 => EightBytes,
                    _ => { panic!("invalid list step size: {}", value.step) }
                };

                (*reff).set_list_size_and_count(element_size, value.element_count);

                // Be careful to avoid coping any bytes past the end of the list.
                // TODO(perf) Is ptr::copy_nonoverlapping faster if word-aligned?
                // If so, then perhaps we should only drop to the byte-index level
                // in the canonicalize=true case.
                let whole_byte_size = value.element_count as u64 * value.step as u64 / BITS_PER_BYTE as u64;
                ptr::copy_nonoverlapping(value.ptr as *const u8,
                                         ptr as *mut u8,
                                         whole_byte_size as usize);
                let leftover_bits = value.element_count as u64 * value.step as u64 % BITS_PER_BYTE as u64;
                if leftover_bits > 0 {
                    let mask: u8 = (1 << leftover_bits as u8) - 1;

                    *(ptr as *mut u8).offset(whole_byte_size as isize) =
                        mask & (*(value.ptr as *const u8).offset(whole_byte_size as isize))
                }
            }

            Ok(SegmentAnd { segment_id: segment_id, value: ptr })
        } else {
            //# List of structs.

            let decl_data_size = value.struct_data_size as u32 / BITS_PER_WORD as u32;
            let decl_pointer_count = value.struct_pointer_count;

            let mut data_size = 0;
            let mut ptr_count = 0;
            let mut total_size = total_size;

            if canonicalize {
                for ec in 0..value.element_count {
                    let se = value.get_struct_element(ec);
                    let mut local_data_size = decl_data_size;
                    'data_chop: while local_data_size != 0 {
                        let end = local_data_size * BYTES_PER_WORD as u32;
                        let window = BYTES_PER_WORD as u32;
                        let start = end - window;
                        let last_word = &se.get_data_section_as_blob()[start as usize..end as usize];
                        if last_word != &[0; 8] {
                            break 'data_chop
                        } else {
                            local_data_size -= 1;
                        }
                    }
                    if local_data_size > data_size {
                        data_size = local_data_size;
                    }
                    let mut local_ptr_count = decl_pointer_count;
                    while local_ptr_count != 0 && se.get_pointer_field(local_ptr_count as usize - 1).is_null() {
                        local_ptr_count -= 1;
                    }
                    if local_ptr_count > ptr_count {
                        ptr_count = local_ptr_count;
                    }
                }
                total_size = (data_size as u32 + ptr_count as u32) * value.element_count as u32;
            } else {
                data_size = decl_data_size;
                ptr_count = decl_pointer_count;
            }

            let (ptr, reff, segment_id) =
                allocate(arena, reff, segment_id,
                         total_size + POINTER_SIZE_IN_WORDS as u32, WirePointerKind::List);
            (*reff).set_list_inline_composite(total_size);

            let tag: *mut WirePointer = ptr as *mut _;
            (*tag).set_kind_and_inline_composite_list_element_count(WirePointerKind::Struct, value.element_count);
            (*tag).set_struct_size_from_pieces(data_size as u16, ptr_count);
            let mut dst = ptr.offset(POINTER_SIZE_IN_WORDS as isize);

            let mut src: *const Word = value.ptr as *const _;
            for _ in 0.. value.element_count {
                ptr::copy_nonoverlapping(src, dst, data_size as usize);
                dst = dst.offset(data_size as isize);
                src = src.offset(decl_data_size as isize);

                for _ in 0..ptr_count {
                    copy_pointer(arena, segment_id, cap_table, dst as *mut _,
                                 value.arena, value.segment_id, value.cap_table, src as *const _,
                                 value.nesting_limit, canonicalize)?;
                    dst = dst.offset(POINTER_SIZE_IN_WORDS as isize);
                    src = src.offset(POINTER_SIZE_IN_WORDS as isize);
                }

                src = src.offset((decl_pointer_count - ptr_count) as isize);
            }
            Ok(SegmentAnd { segment_id: segment_id, value: ptr })
        }
    }

    pub unsafe fn copy_pointer(
        dst_arena: &dyn BuilderArena,
        dst_segment_id: u32, dst_cap_table: CapTableBuilder,
        dst: *mut WirePointer,
        src_arena: &dyn ReaderArena,
        src_segment_id: u32, src_cap_table: CapTableReader,
        src: *const WirePointer,
        nesting_limit: i32,
        canonicalize: bool) -> Result<SegmentAnd<*mut Word>>
    {
        if (*src).is_null() {
            ptr::write_bytes(dst, 0, 1);
            return Ok(SegmentAnd { segment_id: dst_segment_id, value: ptr::null_mut() });
        }

        let (mut ptr, src, src_segment_id) = follow_fars(src_arena, src, src_segment_id)?;

        match (*src).kind() {
            WirePointerKind::Struct => {
                if nesting_limit <= 0 {
                    return Err(Error::failed(
                        "Message is too deeply-nested or contains cycles. See ReaderOptions.".to_string()));
                }

                bounds_check(src_arena, src_segment_id,
                             ptr, (*src).struct_word_size() as usize,
                             WirePointerKind::Struct)?;

                set_struct_pointer(
                    dst_arena,
                    dst_segment_id, dst_cap_table, dst,
                    StructReader {
                        arena: src_arena,
                        segment_id: src_segment_id,
                        cap_table: src_cap_table,
                        data: ptr as *const _,
                        pointers: ptr.offset((*src).struct_data_size() as isize) as *const _,
                        data_size: (*src).struct_data_size() as u32 * BITS_PER_WORD as u32,
                        pointer_count: (*src).struct_ptr_count(),
                        nesting_limit: nesting_limit - 1
                    },
                    canonicalize)
            }
            WirePointerKind::List => {
                let element_size = (*src).list_element_size();
                if nesting_limit <= 0 {
                    return Err(Error::failed(
                        "Message is too deeply-nested or contains cycles. See ReaderOptions.".to_string()));
                }

                if element_size == InlineComposite {
                    let word_count = (*src).list_inline_composite_word_count();
                    let tag: *const WirePointer = ptr as *const _;
                    ptr = ptr.offset(POINTER_SIZE_IN_WORDS as isize);

                    bounds_check(
                        src_arena, src_segment_id, ptr.offset(-1), word_count as usize + 1,
                        WirePointerKind::List)?;

                    if (*tag).kind() != WirePointerKind::Struct {
                        return Err(Error::failed(
                            "InlineComposite lists of non-STRUCT type are not supported.".to_string()));
                    }

                    let element_count = (*tag).inline_composite_list_element_count();
                    let words_per_element = (*tag).struct_word_size();

                    if words_per_element as u64 * element_count as u64 > word_count as u64 {
                        return Err(Error::failed(
                            "InlineComposite list's elements overrun its word count.".to_string()));
                    }

                    if words_per_element == 0 {
                        // Watch out for lists of zero-sized structs, which can claim to be
                        // arbitrarily large without having sent actual data.
                        amplified_read(src_arena, element_count as u64)?;
                    }

                    set_list_pointer(
                        dst_arena,
                        dst_segment_id, dst_cap_table, dst,
                        ListReader {
                            arena: src_arena,
                            segment_id: src_segment_id,
                            cap_table: src_cap_table,
                            ptr: ptr as *const _,
                            element_count: element_count,
                            element_size: element_size,
                            step: words_per_element * BITS_PER_WORD as u32,
                            struct_data_size: (*tag).struct_data_size() as u32 * BITS_PER_WORD as u32,
                            struct_pointer_count: (*tag).struct_ptr_count(),
                            nesting_limit: nesting_limit - 1
                        },
                        canonicalize)
                } else {
                    let data_size = data_bits_per_element(element_size);
                    let pointer_count = pointers_per_element(element_size);
                    let step = data_size + pointer_count * BITS_PER_POINTER as u32;
                    let element_count = (*src).list_element_count();
                    let word_count = round_bits_up_to_words(element_count as u64 * step as u64);

                    bounds_check(src_arena,
                                 src_segment_id, ptr,
                                 word_count as usize, WirePointerKind::List)?;

                    if element_size == Void {
                        // Watch out for lists of void, which can claim to be arbitrarily large
                        // without having sent actual data.
                        amplified_read(src_arena, element_count as u64)?;
                    }

                    set_list_pointer(
                        dst_arena,
                        dst_segment_id, dst_cap_table, dst,
                        ListReader {
                            arena: src_arena,
                            segment_id: src_segment_id,
                            cap_table : src_cap_table,
                            ptr: ptr as *const _,
                            element_count: element_count,
                            element_size: element_size,
                            step: step,
                            struct_data_size: data_size,
                            struct_pointer_count: pointer_count as u16,
                            nesting_limit: nesting_limit - 1
                        },
                        canonicalize)
                }
            }
            WirePointerKind::Far => {
                Err(Error::failed("Malformed double-far pointer.".to_string()))
            }
            WirePointerKind::Other => {
                if !(*src).is_capability() {
                    return Err(Error::failed("Unknown pointer type.".to_string()));
                }
                if canonicalize {
                    return Err(Error::failed("Cannot create a canonical message with a capability".to_string()));
                }
                match src_cap_table.extract_cap((*src).cap_index() as usize) {
                    Some(cap) => {
                        set_capability_pointer(dst_arena, dst_segment_id, dst_cap_table, dst, cap);
                        Ok(SegmentAnd { segment_id: dst_segment_id, value: ptr::null_mut() })
                    }
                    None => {
                        Err(Error::failed(
                            "Message contained invalid capability pointer.".to_string()))
                    }
                }
            }
        }
    }

    #[inline]
    pub unsafe fn read_struct_pointer<'a>(
        mut arena: &'a dyn ReaderArena,
        mut segment_id: u32,
        cap_table: CapTableReader,
        mut reff: *const WirePointer,
        default: Option<&'a [Word]>,
        nesting_limit: i32) -> Result<StructReader<'a>>
    {
        if (*reff).is_null() {
            match default {
                None => return Ok(StructReader::new_default()),
                Some(d) if (*(d.as_ptr() as *const WirePointer)).is_null() =>
                    return Ok(StructReader::new_default()),
                Some(d) => {
                    reff = d.as_ptr() as *const _;
                    arena = &super::NULL_ARENA;
                    segment_id = 0;
                }
            }
        }

        if nesting_limit <= 0 {
            return Err(Error::failed("Message is too deeply-nested or contains cycles.".to_string()));
        }

        let (ptr, reff, segment_id) = follow_fars(arena, reff, segment_id)?;

        let data_size_words = (*reff).struct_data_size();

        if (*reff).kind() != WirePointerKind::Struct {
            return Err(Error::failed(
                "Message contains non-struct pointer where struct pointer was expected.".to_string()));
        }

        bounds_check(arena, segment_id, ptr,
                     (*reff).struct_word_size() as usize,
                     WirePointerKind::Struct)?;

        Ok(StructReader {
            arena: arena,
            segment_id: segment_id,
            cap_table: cap_table,
            data: ptr as *const _,
            pointers: ptr.offset(data_size_words as isize) as *const _,
            data_size: data_size_words as u32 * BITS_PER_WORD as BitCount32,
            pointer_count: (*reff).struct_ptr_count(),
            nesting_limit: nesting_limit - 1,
        })
     }

    #[inline]
    pub unsafe fn read_capability_pointer(
        _arena: &dyn ReaderArena,
        _segment_id: u32,
        cap_table: CapTableReader,
        reff: *const WirePointer,
        _nesting_limit: i32) -> Result<Box<dyn ClientHook>>
    {
        if (*reff).is_null() {
            Err(Error::failed(
                "Message contains null capability pointer.".to_string()))
        } else if !(*reff).is_capability() {
            Err(Error::failed(
                "Message contains non-capability pointer where capability pointer was expected.".to_string()))
        } else {
            let n = (*reff).cap_index() as usize;
            match cap_table.extract_cap(n) {
                Some(client_hook) => { Ok(client_hook) }
                None => {
                    Err(Error::failed(
                        format!("Message contains invalid capability pointer. Index: {}", n)))
                }
            }
        }
    }

    #[inline]
    pub unsafe fn read_list_pointer<'a>(
        mut arena: &'a dyn ReaderArena,
        mut segment_id: u32,
        cap_table: CapTableReader,
        mut reff: *const WirePointer,
        default_value: *const Word,
        expected_element_size: Option<ElementSize>,
        nesting_limit: i32) -> Result<ListReader<'a>>
    {
        if (*reff).is_null() {
            if default_value.is_null() || (*(default_value as *const WirePointer)).is_null() {
                return Ok(ListReader::new_default());
            }
            reff = default_value as *const _;
            arena = &super::NULL_ARENA;
            segment_id = 0;
        }

        if nesting_limit <= 0 {
            return Err(Error::failed("nesting limit exceeded".to_string()));
        }
        let (mut ptr, reff, segment_id) = follow_fars(arena, reff, segment_id)?;

        if (*reff).kind() != WirePointerKind::List {
            return Err(Error::failed(
                "Message contains non-list pointer where list pointer was expected".to_string()));
        }

        let element_size = (*reff).list_element_size();
        match element_size {
            InlineComposite => {
                let word_count = (*reff).list_inline_composite_word_count();

                let tag: *const WirePointer = mem::transmute(ptr);

                ptr = ptr.offset(1);

                bounds_check(arena, segment_id, ptr.offset(-1),
                             word_count as usize + 1,
                             WirePointerKind::List)?;

                if (*tag).kind() != WirePointerKind::Struct {
                    return Err(Error::failed(
                        "InlineComposite lists of non-STRUCT type are not supported.".to_string()));
                }

                let size = (*tag).inline_composite_list_element_count();
                let data_size = (*tag).struct_data_size();
                let ptr_count = (*tag).struct_ptr_count();
                let words_per_element = (*tag).struct_word_size();

                if size as u64 * words_per_element as u64 > word_count as u64 {
                    return Err(Error::failed(
                         "InlineComposite list's elements overrun its word count.".to_string()));
                }

                if words_per_element == 0 {
                    // Watch out for lists of zero-sized structs, which can claim to be
                    // arbitrarily large without having sent actual data.
                    amplified_read(arena, size as u64)?;
                }

                // If a struct list was not expected, then presumably a non-struct list was upgraded
                // to a struct list. We need to manipulate the pointer to point at the first field
                // of the struct. Together with the `step` field, this will allow the struct list to
                // be accessed as if it were a primitive list without branching.

                // Check whether the size is compatible.
                match expected_element_size {
                    None | Some(Void) | Some(InlineComposite) => (),
                    Some(Bit) => {
                        return Err(Error::failed(
                            "Found struct list where bit list was expected.".to_string()));
                    }
                    Some(Byte) | Some(TwoBytes) | Some(FourBytes) | Some(EightBytes) => {
                        if data_size == 0 {
                            return Err(Error::failed(
                                "Expected a primitive list, but got a list of pointer-only structs".to_string()));
                        }
                    }
                    Some(Pointer) => {
                        // We expected a list of pointers but got a list of structs. Assuming the
                        // first field in the struct is the pointer we were looking for, we want to
                        // munge the pointer to point at the first element's pointer section.
                        ptr = ptr.offset(data_size as isize);
                        if ptr_count <= 0 {
                            return Err(Error::failed(
                                "Expected a pointer list, but got a list of data-only structs".to_string()));
                        }
                    }
                }

                Ok(ListReader {
                    arena: arena,
                    segment_id: segment_id,
                    cap_table: cap_table,
                    ptr: ptr as *const _,
                    element_count: size,
                    element_size: element_size,
                    step: words_per_element * BITS_PER_WORD as u32,
                    struct_data_size: data_size as u32 * (BITS_PER_WORD as u32),
                    struct_pointer_count: ptr_count,
                    nesting_limit: nesting_limit - 1,
                })
            }
            _ => {
                // This is a primitive or pointer list, but all such lists can also be interpreted
                // as struct lists. We need to compute the data size and pointer count for such
                // structs.
                let data_size = data_bits_per_element((*reff).list_element_size());
                let pointer_count = pointers_per_element((*reff).list_element_size());
                let element_count = (*reff).list_element_count();
                let step = data_size + pointer_count * BITS_PER_POINTER as u32;

                let word_count = round_bits_up_to_words(element_count as u64 * step as u64);
                bounds_check(
                    arena, segment_id, ptr, word_count as usize, WirePointerKind::List)?;

                if element_size == Void {
                    // Watch out for lists of void, which can claim to be arbitrarily large
                    // without having sent actual data.
                    amplified_read(arena, element_count as u64)?;
                }

                if let Some(expected_element_size) = expected_element_size {
                    if element_size == ElementSize::Bit && expected_element_size != ElementSize::Bit {
                        return Err(Error::failed(
                            "Found bit list where struct list was expected; upgrade boolean lists to\
                             structs is no longer supported".to_string()));
                    }

                    // Verify that the elements are at least as large as the expected type. Note that if
                    // we expected InlineComposite, the expected sizes here will be zero, because bounds
                    // checking will be performed at field access time. So this check here is for the
                    // case where we expected a list of some primitive or pointer type.

                    let expected_data_bits_per_element = data_bits_per_element(expected_element_size);
                    let expected_pointers_per_element = pointers_per_element(expected_element_size);

                    if expected_data_bits_per_element > data_size ||
                        expected_pointers_per_element > pointer_count {
                            return Err(Error::failed(
                                "Message contains list with incompatible element type.".to_string()));
                        }
                }

                Ok(ListReader {
                    arena: arena,
                    segment_id: segment_id,
                    cap_table: cap_table,
                    ptr: ptr as *const _,
                    element_count: element_count,
                    element_size: element_size,
                    step: step,
                    struct_data_size: data_size,
                    struct_pointer_count: pointer_count as u16,
                    nesting_limit: nesting_limit - 1,
                })
            }
        }
    }

    #[inline]
    pub unsafe fn read_text_pointer<'a>(
        mut arena: &'a dyn ReaderArena,
        mut segment_id: u32,
        mut reff: *const WirePointer,
        default: Option<&[Word]>) -> Result<text::Reader<'a>>
    {
        if (*reff).is_null() {
            match default {
                None => return Ok(&""),
                Some(d) => {
                    reff = d.as_ptr() as *const _;
                    arena = &super::NULL_ARENA;
                    segment_id = 0;
                }
            }
        }

        let (ptr, reff, segment_id) = follow_fars(arena, reff, segment_id)?;
        let size = (*reff).list_element_count();

        if (*reff).kind() != WirePointerKind::List {
            return Err(Error::failed(
                "Message contains non-list pointer where text was expected.".to_string()));
        }

        if (*reff).list_element_size() != Byte {
            return Err(Error::failed(
                "Message contains list pointer of non-bytes where text was expected.".to_string()));
        }

        bounds_check(arena, segment_id, ptr,
                     round_bytes_up_to_words(size) as usize,
                     WirePointerKind::List)?;

        if size <= 0 {
            return Err(Error::failed("Message contains text that is not NUL-terminated.".to_string()));
        }

        let str_ptr = ptr as *const u8;

        if (*str_ptr.offset((size - 1) as isize)) != 0u8 {
            return Err(Error::failed(
                "Message contains text that is not NUL-terminated".to_string()));
        }

        text::new_reader(slice::from_raw_parts(str_ptr, size as usize -1))
    }

    #[inline]
    pub unsafe fn read_data_pointer<'a>(
        mut arena: &'a dyn ReaderArena,
        mut segment_id: u32,
        mut reff: *const WirePointer,
        default: Option<&'a[Word]>) -> Result<data::Reader<'a>>
    {
        if (*reff).is_null() {
            match default {
                None => return Ok(&[]),
                Some(d) => {
                    reff = d.as_ptr() as *const _;
                    arena = &super::NULL_ARENA;
                    segment_id = 0;
                }
            }
        }

        let (ptr, reff, segment_id) = follow_fars(arena, reff, segment_id)?;

        let size: u32 = (*reff).list_element_count();

        if (*reff).kind() != WirePointerKind::List {
            return Err(Error::failed(
                "Message contains non-list pointer where data was expected.".to_string()));
        }

        if (*reff).list_element_size() != Byte {
            return Err(Error::failed(
                "Message contains list pointer of non-bytes where data was expected.".to_string()));
        }

        bounds_check(arena, segment_id, ptr,
                     round_bytes_up_to_words(size) as usize,
                     WirePointerKind::List)?;

        Ok(data::new_reader(ptr as *const _, size))
    }
}

static ZERO: u64 = 0;
fn zero_pointer() -> *const WirePointer { &ZERO as *const _ as *const _ }

static NULL_ARENA: NullArena = NullArena;

pub type CapTable = Vec<Option<Box<dyn ClientHook>>>;

#[derive(Copy, Clone)]
pub enum CapTableReader {
    // At one point, we had a `Dummy` variant here, but that ended up
    // making values of this type take 16 bytes of memory. Now we instead
    // represent a null CapTableReader with `Plain(ptr::null())`.

    Plain(*const Vec<Option<Box<dyn ClientHook>>>),
}

impl CapTableReader {
    pub fn extract_cap(&self, index: usize) -> Option<Box<dyn ClientHook>> {
        match *self {
            CapTableReader::Plain(hooks) => {
                if hooks.is_null() { return None }
                let hooks: &Vec<Option<Box<dyn ClientHook>>> = unsafe { &*hooks };
                if index >= hooks.len() { None }
                else {
                    match hooks[index] {
                        None => None,
                        Some(ref hook) => Some(hook.add_ref())
                    }
                }
            }
        }
    }
}

#[derive(Copy, Clone)]
pub enum CapTableBuilder {
    // At one point, we had a `Dummy` variant here, but that ended up
    // making values of this type take 16 bytes of memory. Now we instead
    // represent a null CapTableBuilder with `Plain(ptr::null_mut())`.

    Plain(*mut Vec<Option<Box<dyn ClientHook>>>),
}

impl CapTableBuilder {
    pub fn into_reader(self) -> CapTableReader {
        match self {
            CapTableBuilder::Plain(hooks) => CapTableReader::Plain(hooks),
        }
    }

    pub fn extract_cap(&self, index: usize) -> Option<Box<dyn ClientHook>> {
        match *self {
            CapTableBuilder::Plain(hooks) => {
                if hooks.is_null() { return None }
                let hooks: &Vec<Option<Box<dyn ClientHook>>> = unsafe { &*hooks };
                if index >= hooks.len() { None }
                else {
                    match hooks[index] {
                        None => None,
                        Some(ref hook) => Some(hook.add_ref())
                    }
                }
            }
        }
    }

    pub fn inject_cap(&mut self, cap: Box<dyn ClientHook>) -> usize {
        match *self {
            CapTableBuilder::Plain(hooks) => {
                if hooks.is_null() {
                    panic!("Called inject_cap() on a null capability table. You need \
                            to call imbue_mut() on this message before adding capabilities.");
                }
                let hooks: &mut Vec<Option<Box<dyn ClientHook>>> = unsafe { &mut *hooks };
                hooks.push(Some(cap));
                hooks.len() - 1
            }
        }
    }

    pub fn drop_cap(&mut self, index: usize) {
        match *self {
            CapTableBuilder::Plain(hooks) => {
                if hooks.is_null() {
                    panic!("Called drop_cap() on a null capability table. You need \
                            to call imbue_mut() on this message before adding capabilities.");
                }
                let hooks: &mut Vec<Option<Box<dyn ClientHook>>> = unsafe { &mut *hooks };
                if index < hooks.len() { hooks[index] = None; }
            }
        }
    }
}


#[derive(Clone, Copy)]
pub struct PointerReader<'a>  {
    arena: &'a dyn ReaderArena,
    cap_table: CapTableReader,
    pointer: *const WirePointer,
    segment_id: u32,
    nesting_limit: i32,
}

impl <'a> PointerReader<'a> {
    pub fn new_default<'b>() -> PointerReader<'b> {
        PointerReader {
            arena: &NULL_ARENA,
            segment_id: 0,
            cap_table: CapTableReader::Plain(ptr::null()),
            pointer: ptr::null(),
            nesting_limit: 0x7fffffff }
    }

    pub fn get_root(arena: &'a dyn ReaderArena,
                    segment_id: u32,
                    location: *const Word,
                    nesting_limit: i32) -> Result<Self>
    {
        wire_helpers::bounds_check(arena, segment_id, location,
                                   POINTER_SIZE_IN_WORDS,
                                   WirePointerKind::Struct)?;

        Ok(PointerReader {
            arena: arena,
            segment_id: segment_id,
            cap_table: CapTableReader::Plain(ptr::null()),
            pointer: location as *const _,
            nesting_limit: nesting_limit,
        })
    }

    pub fn borrow<'b>(&'b self) -> PointerReader<'b> {
        PointerReader { arena: self.arena, .. *self }
    }

    pub fn get_root_unchecked<'b>(location: *const Word) -> PointerReader<'b> {
        PointerReader {
            arena: &NULL_ARENA,
            segment_id: 0,
            cap_table: CapTableReader::Plain(ptr::null()),
            pointer: location as *const _,
            nesting_limit: 0x7fffffff }
    }

    pub fn imbue(&mut self, cap_table: CapTableReader) {
        self.cap_table = cap_table;
    }

    pub fn is_null(&self) -> bool {
        self.pointer.is_null() || unsafe { (*self.pointer).is_null() }
    }

    pub fn total_size(&self) -> Result<MessageSize> {
        if self.pointer.is_null() {
            Ok( MessageSize { word_count: 0, cap_count: 0 } )
        } else {
            unsafe { wire_helpers::total_size(self.arena, self.segment_id, self.pointer, self.nesting_limit) }
        }
    }

    pub fn get_struct(self, default: Option<&'a [Word]>) -> Result<StructReader<'a>> {
        let reff: *const WirePointer = if self.pointer.is_null() { zero_pointer() } else { self.pointer };
        unsafe {
            wire_helpers::read_struct_pointer(self.arena,
                                              self.segment_id, self.cap_table, reff,
                                              default, self.nesting_limit)
        }
    }

    pub fn get_list(self, expected_element_size: ElementSize,
                    default: Option<&'a [Word]>) -> Result<ListReader<'a>> {
        let default_value: *const Word = match default { None => std::ptr::null(), Some(d) => d.as_ptr() };
        let reff = if self.pointer.is_null() { zero_pointer() } else { self.pointer };
        unsafe {
            wire_helpers::read_list_pointer(
                self.arena,
                self.segment_id,
                self.cap_table,
                reff,
                default_value,
                Some(expected_element_size), self.nesting_limit)
        }
    }

    fn get_list_any_size(self, default_value: *const Word) -> Result<ListReader<'a>> {
        let reff = if self.pointer.is_null() { zero_pointer() } else { self.pointer };
        unsafe {
            wire_helpers::read_list_pointer(
                self.arena,
                self.segment_id,
                self.cap_table,
                reff,
                default_value,
                None, self.nesting_limit)
        }
    }

    pub fn get_text(self, default: Option<&[Word]>) -> Result<text::Reader<'a>> {
        let reff = if self.pointer.is_null() { zero_pointer() } else { self.pointer };
        unsafe {
            wire_helpers::read_text_pointer(self.arena, self.segment_id, reff, default)
        }
    }

    pub fn get_data(&self, default: Option<&'a [Word]>) -> Result<data::Reader<'a>> {
        let reff = if self.pointer.is_null() { zero_pointer() } else { self.pointer };
        unsafe {
            wire_helpers::read_data_pointer(self.arena, self.segment_id, reff, default)
        }
    }

    pub fn get_capability(&self) -> Result<Box<dyn ClientHook>> {
        let reff: *const WirePointer = if self.pointer.is_null() { zero_pointer() } else { self.pointer };
        unsafe {
            wire_helpers::read_capability_pointer(
                self.arena, self.segment_id, self.cap_table, reff, self.nesting_limit)
        }
    }

    pub fn get_pointer_type(&self) -> Result<PointerType> {
        if self.is_null() {
            Ok(PointerType::Null)
        } else {
            let (_, reff, _) = unsafe {
                wire_helpers::follow_fars(self.arena, self.pointer, self.segment_id)?
            };

            match unsafe { (*reff).kind() } {
                WirePointerKind::Far =>
                    Err(crate::Error::failed(format!("Unexpected FAR pointer"))),
                WirePointerKind::Struct => Ok(PointerType::Struct),
                WirePointerKind::List => Ok(PointerType::List),
                WirePointerKind::Other => {
                    if unsafe { (*reff).is_capability() } {
                        Ok(PointerType::Capability)
                    } else {
                        Err(crate::Error::failed(format!("Unknown pointer type")))
                    }
                }
            }
        }
    }

    pub fn is_canonical(&self, read_head: &Cell<*const Word>) -> Result<bool> {
        if self.pointer.is_null() || unsafe { !(*self.pointer).is_positional() } {
            return Ok(false)
        }

        match self.get_pointer_type()? {
            PointerType::Null => Ok(true),
            PointerType::Struct => {
                let mut data_trunc = false;
                let mut ptr_trunc = false;
                let st = self.get_struct(None)?;
                if st.get_data_section_size() == 0 && st.get_pointer_section_size() == 0 {
                    Ok(self.pointer as *const _ == st.get_location())
                } else {
                    let result = st.is_canonical(read_head, read_head, &mut data_trunc, &mut ptr_trunc)?;
                    Ok(result && data_trunc && ptr_trunc)
                }
            }
            PointerType::List => {
                self.get_list_any_size(ptr::null())?.is_canonical(read_head, self.pointer)
            }
            PointerType::Capability => Ok(false),
        }
    }
}

#[derive(Clone, Copy)]
pub struct PointerBuilder<'a> {
    arena: &'a dyn BuilderArena,
    segment_id: u32,
    cap_table: CapTableBuilder,
    pointer: *mut WirePointer
}

impl <'a> PointerBuilder<'a> {
    #[inline]
    pub fn get_root(
        arena: &'a dyn BuilderArena,
        segment_id: u32,
        location: *mut Word)
        -> Self
    {
        PointerBuilder {
            arena: arena,
            cap_table: CapTableBuilder::Plain(ptr::null_mut()),
            segment_id: segment_id,
            pointer: location as *mut _,
        }
    }

    pub fn borrow<'b>(&'b mut self) -> PointerBuilder<'b> {
        PointerBuilder { arena: self.arena, .. *self }
    }

    pub fn imbue(&mut self, cap_table: CapTableBuilder) {
        self.cap_table = cap_table;
    }

    pub fn is_null(&self) -> bool {
        unsafe { (*self.pointer).is_null() }
    }

    pub fn get_struct(self, size: StructSize, default: Option<&'a [Word]>) -> Result<StructBuilder<'a>> {
        unsafe {
            wire_helpers::get_writable_struct_pointer(
                self.arena,
                self.pointer,
                self.segment_id,
                self.cap_table,
                size,
                default)
        }
    }

    pub fn get_list(self, element_size: ElementSize, default: Option<&'a [Word]>)
                    -> Result<ListBuilder<'a>>
    {
        let default_value: *const Word = match default { None => std::ptr::null(), Some(d) => d.as_ptr() };
        unsafe {
            wire_helpers::get_writable_list_pointer(
                self.arena, self.pointer, self.segment_id, self.cap_table, element_size, default_value)
        }
    }

    pub fn get_struct_list(self, element_size: StructSize,
                           default: Option<&'a [Word]>) -> Result<ListBuilder<'a>>
    {
        let default_value: *const Word = match default { None => std::ptr::null(), Some(d) => d.as_ptr() };
        unsafe {
            wire_helpers::get_writable_struct_list_pointer(
                self.arena, self.pointer, self.segment_id, self.cap_table, element_size, default_value)
        }
    }

    pub fn get_text(self, default: Option<&'a [Word]>) -> Result<text::Builder<'a>>
    {
        unsafe {
            wire_helpers::get_writable_text_pointer(
                self.arena,
                self.pointer, self.segment_id, default)
        }
    }

    pub fn get_data(self, default: Option<&'a [Word]>)
                    -> Result<data::Builder<'a>>
    {
        unsafe {
            wire_helpers::get_writable_data_pointer(
                self.arena, self.pointer, self.segment_id, default)
        }
    }

    pub fn get_capability(&self) -> Result<Box<dyn ClientHook>> {
        unsafe {
            wire_helpers::read_capability_pointer(
                self.arena.as_reader(),
                self.segment_id, self.cap_table.into_reader(), self.pointer, ::std::i32::MAX)
        }
    }

    pub fn init_struct(self, size: StructSize) -> StructBuilder<'a> {
        unsafe {
            wire_helpers::init_struct_pointer(self.arena, self.pointer, self.segment_id, self.cap_table, size)
        }
    }

    pub fn init_list(self, element_size: ElementSize, element_count: ElementCount32) -> ListBuilder<'a> {
        unsafe {
            wire_helpers::init_list_pointer(
                self.arena, self.pointer, self.segment_id, self.cap_table, element_count, element_size)
        }
    }

    pub fn init_struct_list(self, element_count: ElementCount32, element_size: StructSize)
                            -> ListBuilder<'a> {
        unsafe {
            wire_helpers::init_struct_list_pointer(
                self.arena,
                self.pointer, self.segment_id,
                self.cap_table, element_count, element_size)
        }
    }

    pub fn init_text(self, size: ByteCount32) -> text::Builder<'a> {
        unsafe {
            wire_helpers::init_text_pointer(self.arena, self.pointer, self.segment_id, size).value
        }
    }

    pub fn init_data(self, size: ByteCount32) -> data::Builder<'a> {
        unsafe {
            wire_helpers::init_data_pointer(self.arena, self.pointer, self.segment_id, size).value
        }
    }

    pub fn set_struct(&self, value: &StructReader, canonicalize: bool) -> Result<()> {
        unsafe {
            wire_helpers::set_struct_pointer(
                self.arena,
                self.segment_id, self.cap_table, self.pointer, *value, canonicalize)?;
            Ok(())
        }
    }

    pub fn set_list(&self, value: &ListReader, canonicalize: bool) -> Result<()> {
        unsafe {
            wire_helpers::set_list_pointer(self.arena, self.segment_id,
                                           self.cap_table, self.pointer, *value, canonicalize)?;
            Ok(())
        }
    }

    pub fn set_text(&self, value: &str) {
        unsafe {
            wire_helpers::set_text_pointer(self.arena, self.pointer, self.segment_id, value);
        }
    }

    pub fn set_data(&self, value: &[u8]) {
        unsafe {
            wire_helpers::set_data_pointer(self.arena, self.pointer, self.segment_id, value);
        }
    }

    pub fn set_capability(&self, cap: Box<dyn ClientHook>) {
        wire_helpers::set_capability_pointer(
            self.arena, self.segment_id, self.cap_table, self.pointer, cap);
    }

    pub fn copy_from(&mut self, other: PointerReader, canonicalize: bool) -> Result<()> {
        if other.pointer.is_null()  {
            if !self.pointer.is_null() {
                unsafe {
                    wire_helpers::zero_object(self.arena, self.segment_id, self.pointer);
                    *self.pointer = mem::zeroed();
                }
            }
        } else {
            unsafe {
                wire_helpers::copy_pointer(self.arena, self.segment_id, self.cap_table, self.pointer,
                                           other.arena,
                                           other.segment_id, other.cap_table, other.pointer,
                                           other.nesting_limit, canonicalize)?;
            }
        }
        Ok(())
    }

    pub fn clear(&mut self) {
        unsafe {
            wire_helpers::zero_object(self.arena, self.segment_id, self.pointer);
            ptr::write_bytes(self.pointer, 0, 1);
        }
    }

    pub fn into_reader(self) -> PointerReader<'a> {
        PointerReader {
            arena: self.arena.as_reader(),
            segment_id: self.segment_id,
            cap_table: self.cap_table.into_reader(),
            pointer: self.pointer,
            nesting_limit: 0x7fffffff
        }
    }
}

#[derive(Clone, Copy)]
pub struct StructReader<'a> {
    arena: &'a dyn ReaderArena,
    cap_table: CapTableReader,
    data: *const u8,
    pointers: *const WirePointer,
    segment_id: u32,
    data_size: BitCount32,
    pointer_count: WirePointerCount16,
    nesting_limit: i32,
}

impl <'a> StructReader<'a> {
    pub fn new_default<'b>() -> StructReader<'b> {
        StructReader {
            arena: &NULL_ARENA,
            segment_id: 0,
            cap_table: CapTableReader::Plain(ptr::null()),
            data: ptr::null(),
            pointers: ptr::null(),
            data_size: 0,
            pointer_count: 0,
            nesting_limit: 0x7fffffff}
    }

    pub fn imbue(&mut self, cap_table: CapTableReader) {
        self.cap_table = cap_table
    }

    pub fn get_data_section_size(&self) -> BitCount32 { self.data_size }

    pub fn get_pointer_section_size(&self) -> WirePointerCount16 { self.pointer_count }

    pub fn get_pointer_section_as_list(&self) -> ListReader<'a> {
        ListReader {
            arena: self.arena,
            segment_id: self.segment_id,
            cap_table: self.cap_table,
            ptr: self.pointers as *const _,
            element_count: self.pointer_count as ElementCount32,
            element_size: ElementSize::Pointer,
            step: 1 * BITS_PER_WORD as BitCount32,
            struct_data_size: 0,
            struct_pointer_count: 0,
            nesting_limit: self.nesting_limit,
        }
    }

    pub fn get_data_section_as_blob(&self) -> &'a [u8] {
        if self.data_size == 0 {
            // Explictly handle this case to avoid forming a slice to a null pointer,
            // which would be undefined behavior.
            &[]
        } else {
            unsafe {
                ::std::slice::from_raw_parts(self.data, self.data_size as usize / BITS_PER_BYTE)
            }
        }
    }

    #[inline]
    pub fn get_data_field<T: Endian + zero::Zero>(&self, offset: ElementCount) -> T {
        // We need to check the offset because the struct may have
        // been created with an old version of the protocol that did
        // not contain the field.
        if (offset + 1) * bits_per_element::<T>() <= self.data_size as usize {
            unsafe {
                let dwv: *const WireValue<T> = self.data as *const _;
                (*dwv.offset(offset as isize)).get()
            }
        } else {
            T::zero()
        }
    }

    #[inline]
    pub fn get_bool_field(&self, offset: ElementCount) -> bool {
        let boffset: BitCount32 = offset as BitCount32;
        if boffset < self.data_size {
            unsafe {
                let b: *const u8 = self.data.offset((boffset as usize / BITS_PER_BYTE) as isize);
                ((*b) & (1u8 << (boffset % BITS_PER_BYTE as u32) as usize)) != 0
            }
        } else {
            false
        }
    }

    #[inline]
    pub fn get_data_field_mask<T:Endian + zero::Zero + Mask>(&self,
                                                             offset: ElementCount,
                                                             mask: <T as Mask>::T) -> T {
        Mask::mask(self.get_data_field(offset), mask)
    }

    #[inline]
    pub fn get_bool_field_mask(&self,
                               offset: ElementCount,
                               mask: bool) -> bool {
       self.get_bool_field(offset) ^ mask
    }

    #[inline]
    pub fn get_pointer_field(&self, ptr_index: WirePointerCount) -> PointerReader<'a> {
        if ptr_index < self.pointer_count as WirePointerCount {
            PointerReader {
                arena: self.arena,
                segment_id: self.segment_id,
                cap_table: self.cap_table,
                pointer: unsafe { self.pointers.offset(ptr_index as isize) },
                nesting_limit: self.nesting_limit
            }
        } else {
            PointerReader::new_default()
        }
    }

    pub fn total_size(&self) -> Result<MessageSize> {
        let mut result = MessageSize {
            word_count: wire_helpers::round_bits_up_to_words(self.data_size as u64) as u64 +
                self.pointer_count as u64 * WORDS_PER_POINTER as u64,
            cap_count: 0 };

        for i in 0.. self.pointer_count as isize {
            unsafe {
                result.plus_eq(wire_helpers::total_size(
                    self.arena, self.segment_id, self.pointers.offset(i),
                    self.nesting_limit)?);
            }
        }

        // TODO when we have read limiting: segment->unread()

        Ok(result)
    }

    fn get_location(&self) -> *const Word {
        self.data as * const _
    }

    pub fn is_canonical(
        &self,
        read_head: &Cell<*const Word>,
        ptr_head: &Cell<*const Word>,
        data_trunc: &mut bool,
        ptr_trunc: &mut bool,
    )
        -> Result<bool>
    {
        if self.get_location() != read_head.get() {
            return Ok(false)
        }

        if self.get_data_section_size() % BITS_PER_WORD as u32 != 0 {
            // legacy non-word-size struct
            return Ok(false)
        }

        let data_size = self.get_data_section_size() / BITS_PER_WORD as u32;

        // mark whether the struct is properly truncated
        if data_size != 0 {
            *data_trunc = self.get_data_field::<u64>((data_size - 1) as usize) != 0;
        } else {
            *data_trunc = true;
        }

        if self.pointer_count != 0 {
            *ptr_trunc = !self.get_pointer_field(self.pointer_count as usize - 1).is_null();
        } else {
            *ptr_trunc = true;
        }

        read_head.set(
            unsafe { (read_head.get()).offset(data_size as isize + self.pointer_count as isize) });

        for ptr_idx in 0..self.pointer_count {
            if !self.get_pointer_field(ptr_idx as usize).is_canonical(ptr_head)? {
                return Ok(false)
            }
        }

        Ok(true)
    }
}

#[derive(Clone, Copy)]
pub struct StructBuilder<'a> {
    arena: &'a dyn BuilderArena,
    cap_table: CapTableBuilder,
    data: *mut u8,
    pointers: *mut WirePointer,
    segment_id: u32,
    data_size: BitCount32,
    pointer_count: WirePointerCount16,
}

impl <'a> StructBuilder<'a> {
    pub fn into_reader(self) -> StructReader<'a> {
        StructReader {
            arena: self.arena.as_reader(),
            cap_table: self.cap_table.into_reader(),
            data: self.data,
            pointers: self.pointers,
            pointer_count: self.pointer_count,
            segment_id: self.segment_id,
            data_size: self.data_size,
            nesting_limit: 0x7fffffff,
        }
    }

    pub fn imbue(&mut self, cap_table: CapTableBuilder) {
        self.cap_table = cap_table
    }

    #[inline]
    pub fn set_data_field<T:Endian>(&self, offset: ElementCount, value: T) {
        unsafe {
            let ptr: *mut WireValue<T> = self.data as *mut _;
            (*ptr.offset(offset as isize)).set(value)
        }
    }

    #[inline]
    pub fn set_data_field_mask<T:Endian + Mask>(&self,
                                                offset: ElementCount,
                                                value: T,
                                                mask: <T as Mask>::T) {
        self.set_data_field(offset, Mask::mask(value, mask));
    }

    #[inline]
    pub fn get_data_field<T: Endian>(&self, offset: ElementCount) -> T {
        unsafe {
            let ptr: *mut WireValue<T> = self.data as *mut _;
            (*ptr.offset(offset as isize)).get()
        }
    }

    #[inline]
    pub fn get_data_field_mask<T:Endian + Mask>(&self,
                                                offset: ElementCount,
                                                mask: <T as Mask>::T) -> T {
        Mask::mask(self.get_data_field(offset), mask)
    }


    #[inline]
    pub fn set_bool_field(&self, offset: ElementCount, value: bool) {
        //# This branch should be compiled out whenever this is
        //# inlined with a constant offset.
        let boffset: BitCount0 = offset;
        let b = unsafe { self.data.offset((boffset / BITS_PER_BYTE) as isize)};
        let bitnum = boffset % BITS_PER_BYTE;
        unsafe { (*b) = ( (*b) & !(1 << bitnum)) | ((value as u8) << bitnum) }
    }

    #[inline]
    pub fn set_bool_field_mask(&self,
                               offset: ElementCount,
                               value: bool,
                               mask: bool) {
       self.set_bool_field(offset , value ^ mask);
    }

    #[inline]
    pub fn get_bool_field(&self, offset: ElementCount) -> bool {
        let boffset: BitCount0 = offset;
        let b = unsafe { self.data.offset((boffset / BITS_PER_BYTE) as isize) };
        unsafe { ((*b) & (1 << (boffset % BITS_PER_BYTE ))) != 0 }
    }

    #[inline]
    pub fn get_bool_field_mask(&self,
                               offset: ElementCount,
                               mask: bool) -> bool {
       self.get_bool_field(offset) ^ mask
    }


    #[inline]
    pub fn get_pointer_field(self, ptr_index: WirePointerCount) -> PointerBuilder<'a> {
        PointerBuilder {
            arena: self.arena,
            segment_id: self.segment_id,
            cap_table: self.cap_table,
            pointer: unsafe { self.pointers.offset(ptr_index as isize) }
        }
    }

    pub fn copy_content_from(&mut self, other: &StructReader) -> Result<()> {
        use std::cmp::min;
        // Determine the amount of data the builders have in common.
        let shared_data_size = min(self.data_size, other.data_size);
        let shared_pointer_count = min(self.pointer_count, other.pointer_count);

        if (shared_data_size > 0 && other.data == self.data) ||
            (shared_pointer_count > 0 && other.pointers == self.pointers) {
            // At least one of the section pointers is pointing to ourself. Verify that the other is too
            // (but ignore empty sections).
            if (shared_data_size == 0 || other.data == self.data) &&
                (shared_pointer_count == 0 || other.pointers == self.pointers) {
                return Err(crate::Error::failed(format!("Only one of the section pointers is pointing to ourself")))
            }

            // So `other` appears to be a reader for this same struct. No copying is needed.
            return Ok(())
        }

        unsafe {
            if self.data_size > shared_data_size {
                // Since the target is larger than the source, make sure to zero out the extra bits that the
                // source doesn't have.
                if self.data_size == 1 {
                    self.set_bool_field(0, false);
                } else {
                    let unshared = self.data.offset((shared_data_size / BITS_PER_BYTE as u32) as isize);
                    ptr::write_bytes(unshared, 0, ((self.data_size - shared_data_size) / BITS_PER_BYTE as u32) as usize);
                }
            }

            // Copy over the shared part.
            if shared_data_size == 1 {
                self.set_bool_field(0, other.get_bool_field(0));
            } else {
                ptr::copy_nonoverlapping(other.data, self.data, (shared_data_size / BITS_PER_BYTE as u32) as usize);
            }

            // Zero out all pointers in the target.
            for i in 0..self.pointer_count as isize {
                wire_helpers::zero_object(self.arena, self.segment_id, self.pointers.offset(i) as *mut _);
            }
            ptr::write_bytes(self.pointers, 0u8, self.pointer_count as usize);

            for i in 0..shared_pointer_count as isize {
                wire_helpers::copy_pointer(self.arena,
                                           self.segment_id,
                                           self.cap_table,
                                           self.pointers.offset(i),
                                           other.arena,
                                           other.segment_id,
                                           other.cap_table,
                                           other.pointers.offset(i),
                                           other.nesting_limit,
                                           false)?;
            }
        }

        Ok(())
    }
}

#[derive(Clone, Copy)]
pub struct ListReader<'a> {
    arena: &'a dyn ReaderArena,
    cap_table: CapTableReader,
    ptr: *const u8,
    segment_id: u32,
    element_count: ElementCount32,
    step: BitCount32,
    struct_data_size: BitCount32,
    nesting_limit: i32,
    struct_pointer_count: WirePointerCount16,
    element_size: ElementSize,
}

impl <'a> ListReader<'a> {
    pub fn new_default<'b>() -> ListReader<'b> {
        ListReader {
            arena: &NULL_ARENA,
            segment_id: 0,
            cap_table: CapTableReader::Plain(ptr::null()),
            ptr: ptr::null(),
            element_count: 0,
            element_size: ElementSize::Void,
            step: 0,
            struct_data_size: 0,
            struct_pointer_count: 0,
            nesting_limit: 0x7fffffff,
        }
    }

    pub fn imbue(&mut self, cap_table: CapTableReader) {
        self.cap_table = cap_table
    }

    #[inline]
    pub fn len(&self) -> ElementCount32 { self.element_count }

    pub(crate) fn get_step_size_in_bits(&self) -> u32 {
        self.step
    }

    pub(crate) fn get_element_size(&self) -> ElementSize {
        self.element_size
    }

    pub(crate) fn into_raw_bytes(self) -> &'a [u8] {
        if self.element_count == 0 {
            // Explictly handle this case to avoid forming a slice to a null pointer,
            // which would be undefined behavior.
            &[]
        } else {
            let num_bytes = wire_helpers::round_bits_up_to_bytes(
                self.step as u64 * self.element_count as u64) as usize;
            unsafe {
                ::std::slice::from_raw_parts(self.ptr, num_bytes)
            }
        }
    }

    #[inline]
    pub fn get_struct_element(&self, index: ElementCount32) -> StructReader<'a> {
        let index_byte: ByteCount32 =
            ((index as ElementCount64 * (self.step as BitCount64)) / BITS_PER_BYTE as u64) as u32;

        let struct_data: *const u8 = unsafe { self.ptr.offset(index_byte as isize) };

        let struct_pointers: *const WirePointer = unsafe {
            struct_data.offset((self.struct_data_size as usize / BITS_PER_BYTE) as isize) as *const _
        };

        StructReader {
            arena: self.arena,
            segment_id: self.segment_id,
            cap_table: self.cap_table,
            data: struct_data,
            pointers: struct_pointers,
            data_size: self.struct_data_size,
            pointer_count: self.struct_pointer_count,
            nesting_limit: self.nesting_limit - 1,
        }
    }

    #[inline]
    pub fn get_pointer_element(self, index: ElementCount32) -> PointerReader<'a> {
        let offset = (index as u64 * self.step as u64 / BITS_PER_BYTE as u64) as u32;
        PointerReader {
            arena: self.arena,
            segment_id: self.segment_id,
            cap_table: self.cap_table,
            pointer: unsafe { self.ptr.offset(offset as isize) } as *const _,
            nesting_limit: self.nesting_limit
        }
    }

    pub fn is_canonical(
        &self,
        read_head: &Cell<*const Word>,
        reff: *const WirePointer)
        -> Result<bool>
    {
        match self.element_size {
            ElementSize::InlineComposite => {
                read_head.set(unsafe { read_head.get().offset(1) }); // tag word
                if self.ptr as *const _ != read_head.get() {
                    return Ok(false)
                }
                if self.struct_data_size % BITS_PER_WORD as u32 != 0 {
                    return Ok(false)
                }
                let struct_size = (self.struct_data_size / BITS_PER_WORD as u32) +
                    self.struct_pointer_count as u32;
                let word_count = unsafe { (*reff).list_inline_composite_word_count() };
                if struct_size * self.element_count != word_count {
                    return Ok(false)
                }
                if struct_size == 0 {
                    return Ok(true)
                }
                let list_end =
                    unsafe { read_head.get().offset((self.element_count * struct_size) as isize) };
                let pointer_head = Cell::new(list_end);
                let mut list_data_trunc = false;
                let mut list_ptr_trunc = false;
                for idx in 0..self.element_count {
                    let mut data_trunc = false;
                    let mut ptr_trunc = false;
                    if !self.get_struct_element(idx).is_canonical(read_head,
                                                                  &pointer_head,
                                                                  &mut data_trunc,
                                                                  &mut ptr_trunc)? {
                        return Ok(false)
                    }
                    list_data_trunc |= data_trunc;
                    list_ptr_trunc |= ptr_trunc;
                }
                assert_eq!(read_head.get(), list_end);
                read_head.set(pointer_head.get());
                Ok(list_data_trunc && list_ptr_trunc)
            }
            ElementSize::Pointer => {
                if self.ptr as *const _ != read_head.get() {
                    return Ok(false)
                }
                read_head.set(unsafe {
                    read_head.get().offset(self.element_count as isize) });
                for idx in 0..self.element_count {
                    if !self.get_pointer_element(idx).is_canonical(read_head)? {
                        return Ok(false)
                    }
                }
                Ok(true)
            }
            element_size => {
                if self.ptr != read_head.get() as *const _ {
                    return Ok(false)
                }
                let bit_size = self.element_count as u64 * data_bits_per_element(element_size) as u64;
                let mut word_size = bit_size / BITS_PER_WORD as u64;
                if bit_size % BITS_PER_WORD as u64 != 0 {
                    word_size += 1
                }

                let byte_size = bit_size / BITS_PER_BYTE as u64;
                let mut byte_read_head: *const u8 = read_head.get() as *const u8;
                byte_read_head = unsafe { byte_read_head.offset(byte_size as isize) };
                let read_head_end = unsafe { read_head.get().offset(word_size as isize) };

                let leftover_bits = bit_size % BITS_PER_BYTE as u64;
                if leftover_bits > 0 {
                    let mask: u8 = !((1 << leftover_bits as u8) - 1);
                    let partial_byte = unsafe { *byte_read_head };

                    if partial_byte & mask != 0 {
                        return Ok(false)
                    }
                    byte_read_head = unsafe { byte_read_head.offset(1 as isize) };
                }

                while byte_read_head != read_head_end as *const u8 {
                    if unsafe { *byte_read_head } != 0 {
                        return Ok(false)
                    }
                    byte_read_head = unsafe { byte_read_head.offset(1 as isize) };
                }

                read_head.set(read_head_end);
                Ok(true)
            }
        }
    }
}

#[derive(Clone, Copy)]
pub struct ListBuilder<'a> {
    arena: &'a dyn BuilderArena,
    cap_table: CapTableBuilder,
    ptr: *mut u8,
    segment_id: u32,
    element_count: ElementCount32,
    step: BitCount32,
    struct_data_size: BitCount32,
    struct_pointer_count: WirePointerCount16,
    element_size: ElementSize,
}

impl <'a> ListBuilder<'a> {

    #[inline]
    pub fn new_default<'b>() -> ListBuilder<'b> {
        ListBuilder {
            arena: &NULL_ARENA,
            segment_id: 0,
            cap_table: CapTableBuilder::Plain(ptr::null_mut()),
            ptr: ptr::null_mut(),
            element_count: 0,
            element_size: ElementSize::Void,
            step: 0,
            struct_data_size: 0,
            struct_pointer_count: 0,
        }
    }

    pub fn into_reader(self) -> ListReader<'a> {
        ListReader {
            arena: self.arena.as_reader(),
            segment_id: self.segment_id,
            cap_table: self.cap_table.into_reader(),
            ptr: self.ptr as *const _,
            element_count: self.element_count,
            element_size: self.element_size,
            step: self.step,
            struct_data_size: self.struct_data_size,
            struct_pointer_count: self.struct_pointer_count,
            nesting_limit: 0x7fffffff,
        }
    }

    pub fn borrow<'b>(&'b mut self) -> ListBuilder<'b> {
        ListBuilder { arena: self.arena, ..*self }
    }

    pub fn imbue(&mut self, cap_table: CapTableBuilder) {
        self.cap_table = cap_table
    }

    #[inline]
    pub fn len(&self) -> ElementCount32 { self.element_count }

    #[inline]
    pub fn get_struct_element(self, index: ElementCount32) -> StructBuilder<'a> {
        let index_byte = ((index as u64 * self.step as u64) / BITS_PER_BYTE as u64) as u32;
        let struct_data = unsafe{ self.ptr.offset(index_byte as isize)};
        let struct_pointers = unsafe {
            struct_data.offset(((self.struct_data_size as usize) / BITS_PER_BYTE) as isize) as *mut _
        };
        StructBuilder {
            arena: self.arena,
            segment_id: self.segment_id,
            cap_table: self.cap_table,
            data: struct_data,
            pointers: struct_pointers,
            data_size: self.struct_data_size,
            pointer_count: self.struct_pointer_count,
        }
    }

    #[inline]
    pub fn get_pointer_element(self, index: ElementCount32) -> PointerBuilder<'a> {
        let offset = (index as u64 * self.step as u64 / BITS_PER_BYTE as u64) as u32;
        PointerBuilder {
            arena: self.arena,
            segment_id: self.segment_id,
            cap_table: self.cap_table,
            pointer: unsafe { self.ptr.offset(offset as isize) } as *mut _,
        }
    }
}


pub trait PrimitiveElement: Endian {
    #[inline]
    fn get(list_reader: &ListReader, index: ElementCount32) -> Self {
        let offset = (index as u64 * list_reader.step as u64 / BITS_PER_BYTE as u64) as u32;
        unsafe {
            let ptr: *const u8 = list_reader.ptr.offset(offset as isize);
            (*(ptr as *const WireValue<Self>)).get()
        }
    }

    #[inline]
    fn get_from_builder(list_builder: &ListBuilder, index: ElementCount32) -> Self {
        let offset = (index as u64 * list_builder.step as u64 / BITS_PER_BYTE as u64) as u32;
        unsafe {
            let ptr: *mut WireValue<Self> = list_builder.ptr.offset(offset as isize) as *mut _;
            (*ptr).get()
        }
    }

    #[inline]
    fn set(list_builder: &ListBuilder, index: ElementCount32, value: Self) {
        let offset = (index as u64 * list_builder.step as u64 / BITS_PER_BYTE as u64) as u32;
        unsafe {
            let ptr: *mut WireValue<Self> = list_builder.ptr.offset(offset as isize) as *mut _;
            (*ptr).set(value);
        }
    }

    fn element_size() -> ElementSize {
        match mem::size_of::<Self>() {
            0 => Void,
            1 => Byte,
            2 => TwoBytes,
            4 => FourBytes,
            8 => EightBytes,
            _ => unreachable!(),
        }
    }
}

impl PrimitiveElement for u8 { }
impl PrimitiveElement for u16 { }
impl PrimitiveElement for u32 { }
impl PrimitiveElement for u64 { }
impl PrimitiveElement for i8 { }
impl PrimitiveElement for i16 { }
impl PrimitiveElement for i32 { }
impl PrimitiveElement for i64 { }
impl PrimitiveElement for f32 { }
impl PrimitiveElement for f64 { }

impl PrimitiveElement for bool {
    #[inline]
    fn get(list: &ListReader, index: ElementCount32) -> bool {
        let bindex = index as u64 * list.step as u64;
        unsafe {
            let b: *const u8 = list.ptr.offset((bindex / BITS_PER_BYTE as u64) as isize);
            ((*b) & (1 << (bindex % BITS_PER_BYTE as u64))) != 0
        }
    }
    #[inline]
    fn get_from_builder(list: &ListBuilder, index: ElementCount32) -> bool {
        let bindex = index as u64 * list.step as u64;
        let b = unsafe { list.ptr.offset((bindex / BITS_PER_BYTE as u64) as isize) };
        unsafe { ((*b) & (1 << (bindex % BITS_PER_BYTE as u64 ))) != 0 }
    }
    #[inline]
    fn set(list: &ListBuilder, index: ElementCount32, value: bool) {
        let bindex = index as u64 * list.step as u64;
        let b = unsafe { list.ptr.offset((bindex / BITS_PER_BYTE as u64) as isize) };

        let bitnum = bindex % BITS_PER_BYTE as u64;
        unsafe { (*b) = ((*b) & !(1 << bitnum)) | ((value as u8) << bitnum) }
    }
    fn element_size() -> ElementSize { Bit }
}

impl PrimitiveElement for () {
    #[inline]
    fn get(_list: &ListReader, _index: ElementCount32) -> () { () }

    #[inline]
    fn get_from_builder(_list: &ListBuilder, _index: ElementCount32) -> () { () }

    #[inline]
    fn set(_list: &ListBuilder, _index: ElementCount32, _value: ()) { }
}