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

/// Mapped to i32::MIN + 1.
impl convert::From<()> for Reject {
    #[inline(always)]
    fn from(_: ()) -> Self { unsafe { num::NonZeroI32::new_unchecked(i32::MIN + 1) }.into() }
}

/// Mapped to i32::MIN + 2.
impl convert::From<ParseError> for Reject {
    #[inline(always)]
    fn from(_: ParseError) -> Self {
        unsafe { num::NonZeroI32::new_unchecked(i32::MIN + 2) }.into()
    }
}

/// Full is mapped to i32::MIN + 3,
/// Malformed is mapped to i32::MIN + 4.
impl From<LogError> for Reject {
    #[inline(always)]
    fn from(le: LogError) -> Self {
        match le {
            LogError::Full => unsafe { crate::num::NonZeroI32::new_unchecked(i32::MIN + 3) }.into(),
            LogError::Malformed => {
                unsafe { crate::num::NonZeroI32::new_unchecked(i32::MIN + 4) }.into()
            }
        }
    }
}

/// MissingInitPrefix is mapped to i32::MIN + 5,
/// TooLong to i32::MIN + 6,
/// ContainsDot to i32::MIN + 9, and
/// InvalidCharacters to i32::MIN + 10.
impl From<NewContractNameError> for Reject {
    fn from(nre: NewContractNameError) -> Self {
        match nre {
            NewContractNameError::MissingInitPrefix => unsafe {
                crate::num::NonZeroI32::new_unchecked(i32::MIN + 5).into()
            },
            NewContractNameError::TooLong => unsafe {
                crate::num::NonZeroI32::new_unchecked(i32::MIN + 6).into()
            },
            NewContractNameError::ContainsDot => unsafe {
                crate::num::NonZeroI32::new_unchecked(i32::MIN + 9).into()
            },
            NewContractNameError::InvalidCharacters => unsafe {
                crate::num::NonZeroI32::new_unchecked(i32::MIN + 10).into()
            },
        }
    }
}

/// MissingDotSeparator is mapped to i32::MIN + 7,
/// TooLong to i32::MIN + 8, and
/// InvalidCharacters to i32::MIN + 11.
impl From<NewReceiveNameError> for Reject {
    fn from(nre: NewReceiveNameError) -> Self {
        match nre {
            NewReceiveNameError::MissingDotSeparator => unsafe {
                crate::num::NonZeroI32::new_unchecked(i32::MIN + 7).into()
            },
            NewReceiveNameError::TooLong => unsafe {
                crate::num::NonZeroI32::new_unchecked(i32::MIN + 8).into()
            },
            NewReceiveNameError::InvalidCharacters => unsafe {
                crate::num::NonZeroI32::new_unchecked(i32::MIN + 11).into()
            },
        }
    }
}

/// The error code is i32::MIN + 12.
impl From<NotPayableError> for Reject {
    #[inline(always)]
    fn from(_: NotPayableError) -> Self {
        unsafe { crate::num::NonZeroI32::new_unchecked(i32::MIN + 12) }.into()
    }
}

/// AmountTooLarge is i32::MIN + 13,
/// MissingAccount is i32::MIN + 14.
impl From<TransferError> for Reject {
    #[inline(always)]
    fn from(te: TransferError) -> Self {
        match te {
            TransferError::AmountTooLarge => unsafe {
                crate::num::NonZeroI32::new_unchecked(i32::MIN + 13).into()
            },
            TransferError::MissingAccount => unsafe {
                crate::num::NonZeroI32::new_unchecked(i32::MIN + 14).into()
            },
        }
    }
}

/// AmountTooLarge is i32::MIN + 15,
/// MissingAccount is i32::MIN + 16,
/// MissingContract is i32::MIN + 17,
/// MissingEntrypoint is i32::MIN + 18,
/// MessageFailed is i32::MIN + 19,
/// LogicReject is i32::MIN + 20,
/// Trap is i32::MIN + 21.
impl<T> From<CallContractError<T>> for Reject {
    #[inline(always)]
    fn from(cce: CallContractError<T>) -> Self {
        match cce {
            CallContractError::AmountTooLarge => unsafe {
                crate::num::NonZeroI32::new_unchecked(i32::MIN + 15).into()
            },
            CallContractError::MissingAccount => unsafe {
                crate::num::NonZeroI32::new_unchecked(i32::MIN + 16).into()
            },
            CallContractError::MissingContract => unsafe {
                crate::num::NonZeroI32::new_unchecked(i32::MIN + 17).into()
            },
            CallContractError::MissingEntrypoint => unsafe {
                crate::num::NonZeroI32::new_unchecked(i32::MIN + 18).into()
            },
            CallContractError::MessageFailed => unsafe {
                crate::num::NonZeroI32::new_unchecked(i32::MIN + 19).into()
            },
            CallContractError::LogicReject {
                ..
            } => unsafe { crate::num::NonZeroI32::new_unchecked(i32::MIN + 20).into() },
            CallContractError::Trap => unsafe {
                crate::num::NonZeroI32::new_unchecked(i32::MIN + 21).into()
            },
        }
    }
}

/// MissingModule is i32::MIN + 22,
/// MissingContract is i32::MIN + 23,
/// UnsupportedModuleVersion is i32::MIN + 24.
impl From<UpgradeError> for Reject {
    #[inline(always)]
    fn from(te: UpgradeError) -> Self {
        match te {
            UpgradeError::MissingModule => unsafe {
                crate::num::NonZeroI32::new_unchecked(i32::MIN + 22).into()
            },
            UpgradeError::MissingContract => unsafe {
                crate::num::NonZeroI32::new_unchecked(i32::MIN + 23).into()
            },
            UpgradeError::UnsupportedModuleVersion => unsafe {
                crate::num::NonZeroI32::new_unchecked(i32::MIN + 24).into()
            },
        }
    }
}

/// Query account balance error missing account is i32::MIN + 25.
impl From<QueryAccountBalanceError> for Reject {
    #[inline(always)]
    fn from(_: QueryAccountBalanceError) -> Self {
        unsafe { crate::num::NonZeroI32::new_unchecked(i32::MIN + 25).into() }
    }
}

/// Query contract balance error missing contract is i32::MIN + 26.
impl From<QueryContractBalanceError> for Reject {
    #[inline(always)]
    fn from(_: QueryContractBalanceError) -> Self {
        unsafe { crate::num::NonZeroI32::new_unchecked(i32::MIN + 26).into() }
    }
}

/// Return values are intended to be produced by writing to the
/// [ExternReturnValue] buffer, either in a high-level interface via
/// serialization, or in a low-level interface by manually using the [Write]
/// trait's interface.
impl Write for ExternReturnValue {
    type Err = ();

    fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Err> {
        let len: u32 = {
            match buf.len().try_into() {
                Ok(v) => v,
                _ => return Err(()),
            }
        };
        if self.current_position.checked_add(len).is_none() {
            return Err(());
        }
        let num_bytes = unsafe { prims::write_output(buf.as_ptr(), len, self.current_position) };
        self.current_position += num_bytes; // safe because of check above that len + pos is small enough
        Ok(num_bytes as usize)
    }
}

impl ExternReturnValue {
    #[inline(always)]
    /// Create a return value cursor that starts at the beginning.
    /// Note that there is a single return value per contract invocation, so
    /// multiple calls to open will give access to writing the same return
    /// value. Thus this function should only be used once per contract
    /// invocation.
    pub fn open() -> Self {
        Self {
            current_position: 0,
        }
    }
}

impl StateEntry {
    /// Open a new state entry with its `current_position` set to `0`.
    pub(crate) fn open(state_entry_id: StateEntryId, key: Vec<u8>) -> Self {
        Self {
            state_entry_id,
            key,
            current_position: 0,
        }
    }
}

impl HasStateEntry for StateEntry {
    type Error = ();
    type StateEntryData = ();
    type StateEntryKey = ();

    #[inline(always)]
    fn move_to_start(&mut self) { self.current_position = 0; }

    #[inline(always)]
    fn size(&self) -> Result<u32, Self::Error> {
        let res = unsafe { prims::state_entry_size(self.state_entry_id) };
        match res {
            u32::MAX => Err(()),
            _ => Ok(res),
        }
    }

    fn truncate(&mut self, new_size: u32) -> Result<(), Self::Error> {
        let cur_size = self.size()?;
        if cur_size > new_size {
            self.resize(new_size)?;
        }
        Ok(())
    }

    fn get_key(&self) -> &[u8] { &self.key }

    fn resize(&mut self, new_size: u32) -> Result<(), Self::Error> {
        let res = unsafe { prims::state_entry_resize(self.state_entry_id, new_size) };
        match res {
            1 => {
                if self.current_position > new_size {
                    self.current_position = new_size;
                }
                Ok(())
            }
            _ => Err(()),
        }
    }
}

impl Seek for StateEntry {
    type Err = ();

    #[inline]
    // Make sure the inline is OK. This is a relatively big function, but once
    // specialized to one of the branches it should benefit from inlining.
    fn seek(&mut self, pos: SeekFrom) -> Result<u32, Self::Err> {
        use SeekFrom::*;
        let end = self.size()?;
        match pos {
            Start(offset) => {
                if offset <= end {
                    self.current_position = offset;
                    Ok(offset)
                } else {
                    Err(())
                }
            }
            End(delta) => {
                if delta > 0 {
                    Err(()) // cannot seek beyond the end
                } else {
                    // due to two's complement representation of values we do not have to
                    // distinguish on whether we go forward or backwards. Reinterpreting the bits
                    // and adding unsigned values is the same as subtracting the
                    // absolute value.
                    let new_offset = end.wrapping_add(delta as u32);
                    if new_offset <= end {
                        self.current_position = new_offset;
                        Ok(new_offset)
                    } else {
                        Err(())
                    }
                }
            }
            Current(delta) => {
                // due to two's complement representation of values we do not have to
                // distinguish on whether we go forward or backwards.
                let new_offset = self.current_position + delta as u32;
                if new_offset <= end {
                    self.current_position = new_offset;
                    Ok(new_offset)
                } else {
                    Err(())
                }
            }
        }
    }

    #[inline(always)]
    fn cursor_position(&self) -> u32 { self.current_position }
}

impl Read for StateEntry {
    fn read(&mut self, buf: &mut [u8]) -> ParseResult<usize> {
        let len: u32 = buf.len().try_into().map_err(|_| ParseError::default())?;
        let num_read = unsafe {
            prims::state_entry_read(
                self.state_entry_id,
                buf.as_mut_ptr(),
                len,
                self.current_position,
            )
        };
        if num_read == u32::MAX {
            return Err(ParseError::default()); // Entry did not exist.
        }
        self.current_position += num_read;
        Ok(num_read as usize)
    }

    /// Read a `u64` in little-endian format. This is optimized to not
    /// initialize a dummy value before calling an external function.
    fn read_u64(&mut self) -> ParseResult<u64> {
        let mut bytes: MaybeUninit<[u8; 8]> = MaybeUninit::uninit();
        let num_read = unsafe {
            prims::state_entry_read(
                self.state_entry_id,
                bytes.as_mut_ptr() as *mut u8,
                8,
                self.current_position,
            )
        };
        if num_read == u32::MAX {
            return Err(ParseError::default()); // Entry did not exist.
        }
        self.current_position += num_read;
        if num_read == 8 {
            unsafe { Ok(u64::from_le_bytes(bytes.assume_init())) }
        } else {
            Err(ParseError::default())
        }
    }

    /// Read a `u32` in little-endian format. This is optimized to not
    /// initialize a dummy value before calling an external function.
    fn read_u32(&mut self) -> ParseResult<u32> {
        let mut bytes: MaybeUninit<[u8; 4]> = MaybeUninit::uninit();
        let num_read = unsafe {
            prims::state_entry_read(
                self.state_entry_id,
                bytes.as_mut_ptr() as *mut u8,
                4,
                self.current_position,
            )
        };
        if num_read == u32::MAX {
            return Err(ParseError::default()); // Entry did not exist.
        }
        self.current_position += num_read;
        if num_read == 4 {
            unsafe { Ok(u32::from_le_bytes(bytes.assume_init())) }
        } else {
            Err(ParseError::default())
        }
    }

    /// Read a `u8` in little-endian format. This is optimized to not
    /// initialize a dummy value before calling an external function.
    fn read_u8(&mut self) -> ParseResult<u8> {
        let mut bytes: MaybeUninit<[u8; 1]> = MaybeUninit::uninit();
        let num_read = unsafe {
            prims::state_entry_read(
                self.state_entry_id,
                bytes.as_mut_ptr() as *mut u8,
                1,
                self.current_position,
            )
        };
        if num_read == u32::MAX {
            return Err(ParseError::default()); // Entry did not exist.
        }
        self.current_position += num_read;
        if num_read == 1 {
            unsafe { Ok(bytes.assume_init()[0]) }
        } else {
            Err(ParseError::default())
        }
    }
}

impl Write for StateEntry {
    type Err = ();

    fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Err> {
        let len: u32 = {
            match buf.len().try_into() {
                Ok(v) => v,
                _ => return Err(()),
            }
        };
        if self.current_position.checked_add(len).is_none() {
            return Err(());
        }
        let num_bytes = unsafe {
            prims::state_entry_write(self.state_entry_id, buf.as_ptr(), len, self.current_position)
        };
        if num_bytes == u32::MAX {
            return Err(()); // Entry did not exist.
        }
        self.current_position += num_bytes; // safe because of check above that len + pos is small enough
        Ok(num_bytes as usize)
    }
}

impl<StateApi: HasStateApi> VacantEntryRaw<StateApi> {
    /// Create a new `VacantEntryRaw`.
    pub(crate) fn new(key: Key, state_api: StateApi) -> Self {
        Self {
            key,
            state_api,
        }
    }

    /// Gets a reference to the key that would be used when inserting a value
    /// through the `VacantEntryRaw`.
    #[inline(always)]
    pub fn key(&self) -> &[u8] { &self.key }

    /// Sets the value of the entry with the [`VacantEntryRaw`’s](Self) key.
    pub fn insert_raw(mut self, value: &[u8]) -> Result<StateApi::EntryType, StateError> {
        let mut entry = self.state_api.create_entry(&self.key)?;
        entry.write_all(value).unwrap_abort(); // Writing to state cannot fail.
        entry.move_to_start(); // Reset cursor.
        Ok(entry)
    }

    /// Sets the value of the entry with the `VacantEntryRaw`’s key.
    /// This differs from
    /// [`insert_raw`](Self::insert_raw) in that it automatically serializes
    /// the provided value. [`insert`](Self::insert) should be preferred
    /// for values that can be directly converted to byte arrays, e.g., any
    /// value that implements [`AsRef<[u8]>`](AsRef).
    pub fn insert<V: Serial>(mut self, value: &V) -> Result<StateApi::EntryType, StateError> {
        let mut entry = self.state_api.create_entry(&self.key)?;
        // Writing to state cannot fail unless the value is too large (more than 2^31
        // bytes). We can't do much about that.
        value.serial(&mut entry).unwrap_abort();
        entry.move_to_start(); // Reset cursor.
        Ok(entry)
    }
}

impl<StateApi: HasStateApi> OccupiedEntryRaw<StateApi> {
    /// Create a new `OccupiedEntryRaw`.
    pub(crate) fn new(state_entry: StateApi::EntryType) -> Self {
        Self {
            state_entry,
        }
    }

    /// Gets a reference to the key that would be used when inserting a value
    /// through the `OccupiedEntryRaw`.
    #[inline(always)]
    pub fn key(&self) -> &[u8] { self.state_entry.get_key() }

    /// Gets a reference to the [`HasStateEntry`] type in the entry.
    #[inline(always)]
    pub fn get_ref(&self) -> &StateApi::EntryType { &self.state_entry }

    /// Converts the entry into its [`HasStateEntry`] type.
    ///
    /// If you need multiple mutable references to the `OccupiedEntryRaw`, see
    /// [`get_mut`][Self::get_mut].
    #[inline(always)]
    pub fn get(self) -> StateApi::EntryType { self.state_entry }

    /// Gets a mutable reference to the [`HasStateEntry`] type in the entry.
    ///
    /// If you need access to a [`HasStateEntry`], which can outlive the
    /// `OccupiedEntryRaw`, see [`get`][Self::get].
    #[inline(always)]
    pub fn get_mut(&mut self) -> &mut StateApi::EntryType { &mut self.state_entry }

    /// Sets the value of the entry with the `OccupiedEntryRaw`'s key.
    pub fn insert_raw(&mut self, value: &[u8]) {
        self.state_entry.move_to_start();
        self.state_entry.write_all(value).unwrap_abort();

        // Truncate any data leftover from previous value.
        self.state_entry.truncate(value.len() as u32).unwrap_abort();
    }

    /// Sets the value of the entry with the [`OccupiedEntryRaw`'s](Self) key.
    /// This differs from [`insert_raw`](Self::insert_raw) in that it
    /// automatically serializes the value. The [`insert`](Self::insert)
    /// should be preferred if the value is already a byte array.
    pub fn insert<V: Serial>(&mut self, value: &V) {
        // Truncate so that no data is leftover from previous value.
        self.state_entry.truncate(0).unwrap_abort();
        self.state_entry.move_to_start();
        value.serial(&mut self.state_entry).unwrap_abort()
    }
}

impl<StateApi: HasStateApi> EntryRaw<StateApi> {
    /// Ensures a value is in the entry by inserting the default if empty, and
    /// returns the [`HasStateEntry`] type for the entry.
    pub fn or_insert_raw(self, default: &[u8]) -> Result<StateApi::EntryType, StateError> {
        match self {
            EntryRaw::Vacant(vac) => vac.insert_raw(default),
            EntryRaw::Occupied(occ) => Ok(occ.get()),
        }
    }

    /// Ensures a value is in the entry by inserting the default if empty, and
    /// returns the [`HasStateEntry`] type. This differs from
    /// [`or_insert_raw`](Self::or_insert_raw) in that it automatically
    /// serializes the provided value. [`or_insert`](Self::or_insert) should
    /// be preferred for values that can be directly converted to byte
    /// arrays, e.g., any value that implements [`AsRef<[u8]>`](AsRef).
    pub fn or_insert<V: Serial>(self, default: &V) -> StateApi::EntryType {
        match self {
            EntryRaw::Vacant(vac) => vac.insert(default).unwrap_abort(),
            EntryRaw::Occupied(occ) => occ.get(),
        }
    }

    /// Returns a reference to this entry's key.
    pub fn key(&self) -> &[u8] {
        match self {
            EntryRaw::Vacant(vac) => vac.key(),
            EntryRaw::Occupied(occ) => occ.key(),
        }
    }
}

impl<'a, K, V, StateApi> VacantEntry<'a, K, V, StateApi>
where
    K: Serial,
    V: Serial,
    StateApi: HasStateApi,
{
    /// Create a new `VacantEntry`.
    pub(crate) fn new(key: K, key_bytes: Vec<u8>, state_api: StateApi) -> Self {
        Self {
            key,
            key_bytes,
            state_api,
            _lifetime_marker: PhantomData,
        }
    }

    /// Get a reference to the `VacantEntry`'s key.
    #[inline(always)]
    pub fn key(&self) -> &K { &self.key }

    /// Take ownership of the key.
    #[inline(always)]
    pub fn into_key(self) -> K { self.key }

    /// Sets the value of the entry with the `VacantEntry`'s key.
    pub fn insert(mut self, value: V) -> OccupiedEntry<'a, K, V, StateApi> {
        // Writing to state cannot fail.
        let mut state_entry = self.state_api.create_entry(&self.key_bytes).unwrap_abort();
        value.serial(&mut state_entry).unwrap_abort();
        state_entry.move_to_start(); // Reset cursor.
        OccupiedEntry {
            key: self.key,
            value,
            modified: false,
            state_entry,
            _lifetime_marker: self._lifetime_marker,
        }
    }
}

impl<'a, K, V, StateApi> OccupiedEntry<'a, K, V, StateApi>
where
    K: Serial,
    V: Serial,
    StateApi: HasStateApi,
{
    /// Create a new `OccupiedEntry`.
    pub(crate) fn new(key: K, value: V, state_entry: StateApi::EntryType) -> Self {
        Self {
            key,
            value,
            modified: false,
            state_entry,
            _lifetime_marker: PhantomData,
        }
    }

    /// Get a reference to the key that is associated with this entry.
    #[inline(always)]
    pub fn key(&self) -> &K { &self.key }

    /// Get an immutable reference to the value contained in this entry.
    #[inline(always)]
    pub fn get_ref(&self) -> &V { &self.value }

    /// Modify the value in the entry, and possibly return
    /// some information.
    #[inline]
    pub fn modify<F, A>(&mut self, f: F) -> A
    where
        // NB: This closure cannot return a reference to V. The reason for this is
        // that the type of the closure is really `for<'b>FnOnce<&'b mut V> -> A`.
        // In particular, the lifetime of the reference the closure gets is not tied directly to the
        // lifetime of `Self`.
        F: FnOnce(&mut V) -> A, {
        let res = f(&mut self.value);
        self.store_value();
        res
    }

    /// Like [`modify`](Self::modify), but allows the closure to signal failure,
    /// aborting the update.
    pub fn try_modify<F, A, E>(&mut self, f: F) -> Result<A, E>
    where
        F: FnOnce(&mut V) -> Result<A, E>, {
        let res = f(&mut self.value)?;
        self.store_value();
        Ok(res)
    }
}

impl<'a, K, V, StateApi> OccupiedEntry<'a, K, V, StateApi>
where
    V: Serial,
    StateApi: HasStateApi,
{
    pub(crate) fn store_value(&mut self) {
        // First truncate it back to 0. This is not ideal in some cases, since
        // it is a needless call.
        // An alternative would be to first write to a temporary buffer,
        // resize the entry to the size of that buffer, and then copy that buffer in.
        // That has the disadvantage of allocating an intermediate buffer.
        self.state_entry.truncate(0).unwrap_abort();
        // If we did not manage to serialize we just abort. This can only happen
        // if (1) one of the serial implementations raises an error, which it should not
        // in normal circumstances or (2) we have run of out of space to write
        // the entry. However the limit to entry size is 2^31 so this
        // will not happen in practice.
        self.value.serial(&mut self.state_entry).unwrap_abort();
    }
}

impl<'a, K, V, StateApi> Entry<'a, K, V, StateApi>
where
    K: Serial,
    V: Serial,
    StateApi: HasStateApi,
{
    /// Return whether the entry is vacant.
    #[inline(always)]
    pub fn is_vacant(&self) -> bool { matches!(self, Entry::Vacant(_)) }

    /// Return whether the entry is occupied.
    #[inline(always)]
    pub fn is_occupied(&self) -> bool { matches!(self, Entry::Occupied(_)) }

    /// If the entry is [`Occupied`](Entry::Occupied) return `Ok`. Otherwise
    /// return the supplied error.
    #[inline]
    pub fn occupied_or<E>(self, e: E) -> Result<OccupiedEntry<'a, K, V, StateApi>, E> {
        match self {
            Entry::Vacant(_) => Err(e),
            Entry::Occupied(oe) => Ok(oe),
        }
    }

    /// If the entry is [`Vacant`](Entry::Vacant) return `Ok`. Otherwise return
    /// the supplied error.
    #[inline]
    pub fn vacant_or<E>(self, e: E) -> Result<VacantEntry<'a, K, V, StateApi>, E> {
        match self {
            Entry::Vacant(vac) => Ok(vac),
            Entry::Occupied(_) => Err(e),
        }
    }

    /// Ensure a value is in the entry by inserting the provided value if the
    /// entry is vacant.
    pub fn or_insert(self, value: V) -> OccupiedEntry<'a, K, V, StateApi> {
        match self {
            Entry::Vacant(vac) => vac.insert(value),
            Entry::Occupied(oe) => oe,
        }
    }

    /// Ensures a value is in the entry by inserting the result of the default
    /// function if empty.
    pub fn or_insert_with<F>(self, default: F) -> OccupiedEntry<'a, K, V, StateApi>
    where
        F: FnOnce() -> V, {
        match self {
            Entry::Vacant(vac) => vac.insert(default()),
            Entry::Occupied(oe) => oe,
        }
    }

    /// If the entry is occupied apply the given function to its contents.
    /// If the function returns an error the contents are not updated.
    /// **If the supplied function returns an error then it should not modify
    /// the given value. If it does so than the map will become
    /// inconsistent.** If the entry is vacant no changes are made.
    pub fn and_try_modify<F, E>(mut self, f: F) -> Result<Entry<'a, K, V, StateApi>, E>
    where
        F: FnOnce(&mut V) -> Result<(), E>, {
        if let Entry::Occupied(ref mut occ) = self {
            occ.try_modify(f)?;
        }
        Ok(self)
    }

    /// If the entry is occupied apply the given function to its contents.
    /// If the entry is vacant no changes are made.
    pub fn and_modify<F>(mut self, f: F) -> Entry<'a, K, V, StateApi>
    where
        F: FnOnce(&mut V), {
        if let Entry::Occupied(ref mut occ) = self {
            occ.modify(f);
        }
        self
    }

    /// Return a reference to this entry's key.
    pub fn key(&self) -> &K {
        match self {
            Entry::Vacant(vac) => vac.key(),
            Entry::Occupied(occ) => occ.key(),
        }
    }
}

impl<'a, K, V, StateApi> Entry<'a, K, V, StateApi>
where
    K: Serial,
    V: Serial + Default,
    StateApi: HasStateApi,
{
    /// Ensures a value is in the entry by inserting the default value if empty.
    #[allow(clippy::unwrap_or_default)]
    pub fn or_default(self) -> OccupiedEntry<'a, K, V, StateApi> {
        self.or_insert_with(Default::default)
    }
}

/// The (i.e., location in the contract state trie) at which the
/// "allocator"/state builder stores "next location". The values stored at this
/// location are 64-bit integers.
const NEXT_ITEM_PREFIX_KEY: [u8; 8] = 0u64.to_le_bytes();
/// Initial location to store in [NEXT_ITEM_PREFIX_KEY]. For example, the
/// initial call to "new_state_box" will allocate the box at this location.
pub(crate) const INITIAL_NEXT_ITEM_PREFIX: [u8; 8] = 2u64.to_le_bytes();

impl HasStateApi for ExternStateApi {
    type EntryType = StateEntry;
    type IterType = ExternStateIter;

    fn create_entry(&mut self, key: &[u8]) -> Result<Self::EntryType, StateError> {
        let key_start = key.as_ptr();
        let key_len = key.len() as u32; // Wasm usize == 32bit.
        let entry_id = unsafe { prims::state_create_entry(key_start, key_len) };
        if entry_id == u64::MAX {
            return Err(StateError::SubtreeLocked);
        }
        Ok(StateEntry::open(entry_id, key.to_vec()))
    }

    fn lookup_entry(&self, key: &[u8]) -> Option<Self::EntryType> {
        let key_start = key.as_ptr();
        let key_len = key.len() as u32; // Wasm usize == 32bit.
        let entry_id = unsafe { prims::state_lookup_entry(key_start, key_len) };
        if entry_id == u64::MAX {
            None
        } else {
            Some(StateEntry::open(entry_id, key.to_vec()))
        }
    }

    fn delete_entry(&mut self, entry: Self::EntryType) -> Result<(), StateError> {
        let key = entry.get_key();
        let res = unsafe { prims::state_delete_entry(key.as_ptr(), key.len() as u32) };
        match res {
            0 => Err(StateError::SubtreeLocked),
            1 => Err(StateError::EntryNotFound),
            2 => Ok(()),
            _ => crate::trap(), // cannot happen
        }
    }

    fn delete_prefix(&mut self, prefix: &[u8]) -> Result<bool, StateError> {
        let res = unsafe { prims::state_delete_prefix(prefix.as_ptr(), prefix.len() as u32) };
        match res {
            0 => Err(StateError::SubtreeLocked),
            1 => Ok(false),
            2 => Ok(true),
            _ => crate::trap(), // cannot happen
        }
    }

    fn iterator(&self, prefix: &[u8]) -> Result<Self::IterType, StateError> {
        let prefix_start = prefix.as_ptr();
        let prefix_len = prefix.len() as u32; // Wasm usize == 32bit.
        let iterator_id = unsafe { prims::state_iterate_prefix(prefix_start, prefix_len) };
        match iterator_id {
            OK_NONE => Err(StateError::SubtreeWithPrefixNotFound),
            ERR => Err(StateError::IteratorLimitForPrefixExceeded),
            iterator_id => Ok(ExternStateIter {
                iterator_id,
            }),
        }
    }

    fn delete_iterator(&mut self, iter: Self::IterType) {
        // This call can never fail because the only way to get an `ExternStateIter`
        // is through `StateApi::iterator(..)`. And this call consumes
        // the iterator.
        // These conditions rule out the two types of errors that the prims
        // call can return, iterator not found and iterator already deleted.
        // The iterator can also be deleted with `delete_iterator_by_id`, but that is
        // only called when a [StateMapIter] or [StateSetIter] is dropped (which
        // also drops the [ExternStateIter]). Again ruling out the already
        // deleted error.
        unsafe { prims::state_iterator_delete(iter.iterator_id) };
    }
}

/// Encoding of Ok(None) that is returned by some host functions.
const OK_NONE: u64 = u64::MAX;
/// Encoding of Err that is returned by some host functions.
const ERR: u64 = u64::MAX & !(1u64 << 62);

impl Iterator for ExternStateIter {
    type Item = StateEntry;

    fn next(&mut self) -> Option<Self::Item> {
        let res = unsafe { prims::state_iterator_next(self.iterator_id) };
        match res {
            OK_NONE => None,
            // This next case means that an iterator never existed or was deleted.
            // In both cases, it is not possible to call `next` on such an iterator with the current
            // API. The only way to get an iterator is through
            // [HasStateApi::iterator] and the only way to delete it is through
            // [HasStateApi::delete_iterator].
            ERR => None,
            _ => {
                // This will always return a valid size, because the iterator is guaranteed to
                // exist.
                let key_size = unsafe { prims::state_iterator_key_size(self.iterator_id) };
                let mut key = Vec::with_capacity(key_size as usize);
                // The key will always be read, because the iterator is guaranteed to exist.
                unsafe {
                    let num_read = prims::state_iterator_key_read(
                        self.iterator_id,
                        key.as_mut_ptr(),
                        key_size,
                        0,
                    );
                    key.set_len(num_read as usize);
                };
                Some(StateEntry::open(res, key))
            }
        }
    }
}

impl<K, V, S> StateMap<K, V, S>
where
    S: HasStateApi,
    K: Serialize,
    V: Serial + DeserialWithState<S>,
{
    /// Lookup the value with the given key. Return [None] if there is no value
    /// with the given key.
    pub fn get(&self, key: &K) -> Option<StateRef<V>> {
        let k = self.key_with_map_prefix(key);
        self.state_api.lookup_entry(&k).map(|mut entry| {
            // Unwrapping is safe when using only the high-level API.
            StateRef::new(V::deserial_with_state(&self.state_api, &mut entry).unwrap_abort())
        })
    }

    /// Lookup a mutable reference to the value with the given key. Return
    /// [None] if there is no value with the given key.

    pub fn get_mut(&mut self, key: &K) -> Option<StateRefMut<V, S>> {
        let k = self.key_with_map_prefix(key);
        let entry = self.state_api.lookup_entry(&k)?;
        Some(StateRefMut::new(entry, self.state_api.clone()))
    }

    /// Inserts the value with the given key. If a value already exists at the
    /// given key it is replaced and the old value is returned.
    /// This only borrows the key, needed internally to avoid the need to clone
    /// it first.
    pub(crate) fn insert_borrowed(&mut self, key: &K, value: V) -> Option<V> {
        let key_bytes = self.key_with_map_prefix(key);
        // Unwrapping is safe because iter() holds a reference to the stateset.
        match self.state_api.entry(key_bytes) {
            EntryRaw::Vacant(vac) => {
                let _ = vac.insert(&value).unwrap_abort();
                None
            }
            EntryRaw::Occupied(mut occ) => {
                // Unwrapping is safe when using only the high-level API.
                let old_value =
                    V::deserial_with_state(&self.state_api, occ.get_mut()).unwrap_abort();
                occ.insert(&value);
                Some(old_value)
            }
        }
    }

    /// Inserts the value with the given key. If a value already exists at the
    /// given key it is replaced and the old value is returned.
    ///
    /// *Caution*: If `Option<V>` is to be deleted and contains a data structure
    /// prefixed with `State` (such as [StateBox](crate::StateBox) or
    /// [StateMap](crate::StateMap)), then it is important to call
    /// [`Deletable::delete`](crate::Deletable::delete) on the value returned
    /// when you're finished with it. Otherwise, it will remain in the
    /// contract state.
    #[must_use]
    pub fn insert(&mut self, key: K, value: V) -> Option<V> { self.insert_borrowed(&key, value) }

    /// Get an entry for the given key.
    pub fn entry(&mut self, key: K) -> Entry<'_, K, V, S> {
        let key_bytes = self.key_with_map_prefix(&key);
        // Unwrapping is safe because iter() holds a reference to the stateset.
        match self.state_api.lookup_entry(&key_bytes) {
            None => Entry::Vacant(VacantEntry::new(key, key_bytes, self.state_api.clone())),
            Some(mut state_entry) => {
                // Unwrapping is safe when using only the high-level API.
                let value =
                    V::deserial_with_state(&self.state_api, &mut state_entry).unwrap_abort();
                Entry::Occupied(OccupiedEntry::new(key, value, state_entry))
            }
        }
    }

    /// Return `true` if the map contains no elements.
    pub fn is_empty(&self) -> bool { self.state_api.lookup_entry(&self.prefix).is_none() }

    /// Clears the map, removing all key-value pairs.
    /// This also includes values pointed at, if `V`, for example, is a
    /// [StateBox]. **If applicable use [`clear_flat`](Self::clear_flat)
    /// instead.**
    pub fn clear(&mut self)
    where
        V: Deletable, {
        // Delete all values pointed at by the statemap. This is necessary if `V` is a
        // StateBox/StateMap.
        for (_, value) in self.iter() {
            value.value.delete()
        }

        // Then delete the map itself.
        // Unwrapping is safe when only using the high-level API.
        self.state_api.delete_prefix(&self.prefix).unwrap_abort();
    }

    /// Clears the map, removing all key-value pairs.
    /// **This should be used over [`clear`](Self::clear) if it is
    /// applicable.** It avoids recursive deletion of values since the
    /// values are required to be _flat_.
    ///
    /// Unfortunately it is not possible to automatically choose between these
    /// implementations. Once Rust gets trait specialization then this might
    /// be possible.
    pub fn clear_flat(&mut self)
    where
        V: Deserial, {
        // Delete only the map itself since the values have no pointers to state.
        // Thus there will be no dangling references.
        // Unwrapping is safe when only using the high-level API.
        self.state_api.delete_prefix(&self.prefix).unwrap_abort();
    }

    /// Remove a key from the map, returning the value at the key if the key was
    /// previously in the map.
    ///
    /// *Caution*: If `V` is a [StateBox], [StateMap], then it is
    /// important to call [`Deletable::delete`] on the value returned when
    /// you're finished with it. Otherwise, it will remain in the contract
    /// state.
    #[must_use]
    pub fn remove_and_get(&mut self, key: &K) -> Option<V> {
        let key_bytes = self.key_with_map_prefix(key);
        // Unwrapping is safe because iter() holds a reference to the stateset.
        let entry_raw = self.state_api.entry(key_bytes);
        match entry_raw {
            EntryRaw::Vacant(_) => None,
            EntryRaw::Occupied(mut occ) => {
                // Unwrapping safe in high-level API.
                let old_value =
                    V::deserial_with_state(&self.state_api, occ.get_mut()).unwrap_abort();
                let _existed = self.state_api.delete_entry(occ.state_entry);
                Some(old_value)
            }
        }
    }

    /// Remove a key from the map.
    /// This also deletes the value in the state.
    pub fn remove(&mut self, key: &K)
    where
        V: Deletable, {
        if let Some(v) = self.remove_and_get(key) {
            v.delete()
        }
    }

    /// Serializes the key and prepends the unique map prefix to it.
    fn key_with_map_prefix(&self, key: &K) -> Vec<u8> {
        let mut key_with_prefix = self.prefix.to_vec();
        key.serial(&mut key_with_prefix).unwrap_abort();
        key_with_prefix
    }
}

impl<'a, K, V, S: HasStateApi> Drop for StateMapIter<'a, K, V, S> {
    fn drop(&mut self) {
        // Delete the iterator to unlock the subtree.
        if let Some(valid) = self.state_iter.take() {
            self.state_api.delete_iterator(valid);
        }
    }
}

impl<K, V, S> StateMap<K, V, S>
where
    S: HasStateApi,
{
    pub(crate) fn open(state_api: S, prefix: [u8; 8]) -> Self {
        Self {
            _marker_key: PhantomData,
            _marker_value: PhantomData,
            prefix,
            state_api,
        }
    }

    /// Get an iterator over the key-value pairs of the map. The iterator
    /// returns values in increasing order of keys, where keys are ordered
    /// lexicographically via their serializations.
    pub fn iter(&self) -> StateMapIter<'_, K, V, S> {
        match self.state_api.iterator(&self.prefix) {
            Ok(state_iter) => StateMapIter {
                state_iter:       Some(state_iter),
                state_api:        self.state_api.clone(),
                _lifetime_marker: PhantomData,
            },
            Err(StateError::SubtreeWithPrefixNotFound) => StateMapIter {
                state_iter:       None,
                state_api:        self.state_api.clone(),
                _lifetime_marker: PhantomData,
            },
            _ => crate::trap(),
        }
    }

    /// Like [iter](Self::iter), but allows modifying the values during
    /// iteration.
    pub fn iter_mut(&mut self) -> StateMapIterMut<'_, K, V, S> {
        match self.state_api.iterator(&self.prefix) {
            Ok(state_iter) => StateMapIterMut {
                state_iter:       Some(state_iter),
                state_api:        self.state_api.clone(),
                _lifetime_marker: PhantomData,
            },
            Err(StateError::SubtreeWithPrefixNotFound) => StateMapIterMut {
                state_iter:       None,
                state_api:        self.state_api.clone(),
                _lifetime_marker: PhantomData,
            },
            _ => crate::trap(),
        }
    }
}

impl<'a, K, V, S: HasStateApi> Iterator for StateMapIter<'a, K, V, S>
where
    K: Deserial + 'a,
    V: DeserialWithState<S> + 'a,
{
    type Item = (StateRef<'a, K>, StateRef<'a, V>);

    fn next(&mut self) -> Option<Self::Item> {
        let mut entry = self.state_iter.as_mut()?.next()?;
        let key = entry.get_key();
        let mut key_cursor = Cursor {
            data:   key,
            offset: 8, // Items in a map always start with the set prefix which is 8 bytes.
        };
        // Unwrapping is safe when only using the high-level API.
        let k = K::deserial(&mut key_cursor).unwrap_abort();
        let v = V::deserial_with_state(&self.state_api, &mut entry).unwrap_abort();
        Some((StateRef::new(k), StateRef::new(v)))
    }
}

impl<'a, K, V: Serial, S: HasStateApi> Iterator for StateMapIterMut<'a, K, V, S>
where
    K: Deserial + 'a,
    V: DeserialWithState<S> + 'a,
    S::EntryType: 'a,
{
    type Item = (StateRef<'a, K>, StateRefMut<'a, V, S>);

    fn next(&mut self) -> Option<Self::Item> {
        let entry = self.state_iter.as_mut()?.next()?;

        let key_bytes = entry.get_key();
        let mut key_cursor = Cursor {
            data:   key_bytes,
            offset: 8, // Items in a map always start with the set prefix which is 8 bytes.
        };
        // Unwrapping is safe when only using the high-level API.
        let k = K::deserial(&mut key_cursor).unwrap_abort();
        // we do not load the value here, only on demand. This allows iteration over
        // keys to be reasonably efficient.
        Some((StateRef::new(k), StateRefMut::new(entry, self.state_api.clone())))
    }
}

impl<'a, S: HasStateApi, V: Serial + DeserialWithState<S>> crate::ops::Deref
    for StateRefMut<'a, V, S>
{
    type Target = V;

    #[inline(always)]
    fn deref(&self) -> &Self::Target { self.get() }
}

impl<'a, S: HasStateApi, V: Serial + DeserialWithState<S>> crate::ops::DerefMut
    for StateRefMut<'a, V, S>
{
    #[inline(always)]
    fn deref_mut(&mut self) -> &mut Self::Target { self.get_mut() }
}

/// When dropped, the value, `V`, is written to the entry in the contract state.
impl<'a, V: Serial, S: HasStateApi> Drop for StateRefMut<'a, V, S> {
    fn drop(&mut self) { self.store_mutations() }
}

impl<'a, V, S> StateRefMut<'a, V, S>
where
    V: Serial,
    S: HasStateApi,
{
    /// Get a shared reference to the value. Note that [StateRefMut](Self) also
    /// implements [Deref](crate::ops::Deref) so this conversion can happen
    /// implicitly.
    pub fn get(&self) -> &V
    where
        V: DeserialWithState<S>, {
        let lv = unsafe { &mut *self.lazy_value.get() };
        if let Some(v) = lv {
            v
        } else {
            lv.insert(self.load_value())
        }
    }

    /// Get a unique reference to the value. Note that [StateRefMut](Self) also
    /// implements [DerefMut](crate::ops::DerefMut) so this conversion can
    /// happen implicitly.
    pub fn get_mut(&mut self) -> &mut V
    where
        V: DeserialWithState<S>, {
        let lv = unsafe { &mut *self.lazy_value.get() };
        if let Some(v) = lv {
            v
        } else {
            lv.insert(self.load_value())
        }
    }

    /// Load the value referenced by the entry from the chain data.
    fn load_value(&self) -> V
    where
        V: DeserialWithState<S>, {
        // Safe to unwrap below, since the entry can only be `None`, using methods which
        // are consuming self.
        let entry = unsafe { &mut *self.entry.get() };
        entry.move_to_start();
        V::deserial_with_state(&self.state_api, entry).unwrap_abort()
    }

    /// Set the value. Overwrites the existing one.
    pub fn set(&mut self, new_val: V) {
        // Safe to unwrap below, since the entry can only be `None`, using methods which
        // are consuming self.
        let entry = self.entry.get_mut();
        entry.move_to_start();
        new_val.serial(entry).unwrap_abort();
        let _ = self.lazy_value.get_mut().insert(new_val);
    }

    /// Update the existing value with the given function.
    pub fn update<F>(&mut self, f: F)
    where
        V: DeserialWithState<S>,
        F: FnOnce(&mut V), {
        let lv = self.lazy_value.get_mut();
        // Safe to unwrap below, since the entry can only be `None`, using methods which
        // are consuming self.
        let entry = self.entry.get_mut();
        let value = if let Some(v) = lv {
            v
        } else {
            entry.move_to_start();
            let value = V::deserial_with_state(&self.state_api, entry).unwrap_abort();
            lv.insert(value)
        };

        // Mutate the value (perhaps only in memory, depends on the type).
        f(value);
        entry.move_to_start();
        value.serial(entry).unwrap_abort()
    }

    /// Write to the state entry if the value is loaded.
    pub(crate) fn store_mutations(&mut self) {
        if let Some(value) = self.lazy_value.get_mut() {
            // Safe to unwrap below, since the entry can only be `None`, using methods which
            // are consuming self.
            let entry = self.entry.get_mut();
            entry.move_to_start();
            value.serial(entry).unwrap_abort();
        }
    }

    /// Drop the ref without storing mutations to the state entry.
    pub(crate) fn drop_without_storing(mut self) { *self.lazy_value.get_mut() = None; }
}

impl<K, V, S> Serial for StateMap<K, V, S> {
    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> { out.write_all(&self.prefix) }
}

impl<T, S> StateSet<T, S>
where
    T: Serialize,
    S: HasStateApi,
{
    /// Adds a value to the set.
    /// If the set did not have this value, `true` is returned. Otherwise,
    /// `false`.
    pub fn insert(&mut self, value: T) -> bool {
        let key_bytes = self.key_with_set_prefix(&value);
        match self.state_api.entry(key_bytes) {
            EntryRaw::Vacant(vac) => {
                let _ = vac.insert_raw(&[]);
                true
            }
            EntryRaw::Occupied(_) => false,
        }
    }

    /// Returns `true` if the set contains no elements.
    pub fn is_empty(&self) -> bool { self.state_api.lookup_entry(&self.prefix).is_none() }

    /// Returns `true` if the set contains a value.
    pub fn contains(&self, value: &T) -> bool {
        let key_bytes = self.key_with_set_prefix(value);
        self.state_api.lookup_entry(&key_bytes).is_some()
    }

    /// Clears the set, removing all values.
    /// This also includes values pointed at, if `V`, for example, is a
    /// [StateBox].
    // Note: This does not use delete() because delete consumes self.
    pub fn clear(&mut self) {
        // Delete all values in the stateset. Since `T` is serializable
        // there is no need to recursively delete the values since
        // serializable values cannot have pointers to other parts of state.
        // Unwrapping is safe when only using the high-level API.
        self.state_api.delete_prefix(&self.prefix).unwrap_abort();
    }

    /// Removes a value from the set. Returns whether the value was present in
    /// the set.
    pub fn remove(&mut self, value: &T) -> bool {
        let key_bytes = self.key_with_set_prefix(value);

        // Unwrapping is safe, because iter() keeps a reference to the stateset.
        match self.state_api.entry(key_bytes) {
            EntryRaw::Vacant(_) => false,
            EntryRaw::Occupied(occ) => {
                // Unwrapping is safe, because iter() keeps a reference to the stateset.
                self.state_api.delete_entry(occ.get()).unwrap_abort();
                true
            }
        }
    }

    fn key_with_set_prefix(&self, key: &T) -> Vec<u8> {
        let mut key_with_prefix = self.prefix.to_vec();
        key.serial(&mut key_with_prefix).unwrap_abort();
        key_with_prefix
    }
}

impl<T, S: HasStateApi> StateSet<T, S> {
    pub(crate) fn open(state_api: S, prefix: [u8; 8]) -> Self {
        Self {
            _marker: PhantomData,
            prefix,
            state_api,
        }
    }

    /// Get an iterator over the elements in the `StateSet`. The iterator
    /// returns elements in increasing order, where elements are ordered
    /// lexicographically via their serializations.
    pub fn iter(&self) -> StateSetIter<T, S> {
        match self.state_api.iterator(&self.prefix) {
            Ok(state_iter) => StateSetIter {
                state_iter:       Some(state_iter),
                state_api:        self.state_api.clone(),
                _marker_lifetime: PhantomData,
            },
            Err(StateError::SubtreeWithPrefixNotFound) => StateSetIter {
                state_iter:       None,
                state_api:        self.state_api.clone(),
                _marker_lifetime: PhantomData,
            },
            _ => crate::trap(),
        }
    }
}

impl<T: Serial, S: HasStateApi> StateBox<T, S> {
    /// Create a new statebox.
    pub(crate) fn new(value: T, state_api: S, entry: S::EntryType) -> Self {
        StateBox {
            state_api,
            inner: UnsafeCell::new(StateBoxInner::Loaded {
                entry,
                modified: true,
                value,
            }),
        }
    }

    /// Return the key under which the value is stored in the contract state
    /// trie.
    pub(crate) fn get_location(&self) -> &[u8] {
        match unsafe { &*self.inner.get() } {
            StateBoxInner::Loaded {
                entry,
                ..
            } => entry.get_key(),
            StateBoxInner::Reference {
                prefix,
            } => &prefix[..],
        }
    }
}

impl<S: HasStateApi, T: Serial + DeserialWithState<S>> crate::ops::Deref for StateBox<T, S> {
    type Target = T;

    #[inline(always)]
    fn deref(&self) -> &Self::Target { self.get() }
}

impl<S: HasStateApi, T: Serial + DeserialWithState<S>> crate::ops::DerefMut for StateBox<T, S> {
    #[inline(always)]
    fn deref_mut(&mut self) -> &mut Self::Target { self.get_mut() }
}

impl<T: Serial, S: HasStateApi> Drop for StateBox<T, S> {
    fn drop(&mut self) {
        if let StateBoxInner::Loaded {
            entry,
            modified,
            value,
        } = self.inner.get_mut()
        {
            if *modified {
                entry.move_to_start();
                value.serial(entry).unwrap_abort();
            }
        }
    }
}

/// Return a reference to the value stored inside the [`StateBoxInner`], as well
/// as a reference to the flag that indicates whether the value has been
/// modified or not.
fn get_with_inner<'a, T: Serial + DeserialWithState<S>, S: HasStateApi>(
    state_api: &S,
    inner: &'a mut StateBoxInner<T, S>,
) -> (&'a mut T, &'a mut bool) {
    let (entry, value) = match inner {
        StateBoxInner::Loaded {
            value,
            modified,
            ..
        } => return (value, modified),
        StateBoxInner::Reference {
            prefix,
        } => {
            let mut entry = state_api.lookup_entry(prefix).unwrap_abort();
            // new entry, positioned at the start.
            let value = T::deserial_with_state(state_api, &mut entry).unwrap_abort();
            (entry, value)
        }
    };
    *inner = StateBoxInner::Loaded {
        entry,
        modified: false,
        value,
    };
    match inner {
        StateBoxInner::Loaded {
            value,
            modified,
            ..
        } => (value, modified),
        StateBoxInner::Reference {
            ..
        } => {
            // We just set it to loaded.
            unsafe { crate::hint::unreachable_unchecked() }
        }
    }
}

impl<T, S> StateBox<T, S>
where
    T: Serial + DeserialWithState<S>,
    S: HasStateApi,
{
    /// Get a reference to the value.
    pub fn get(&self) -> &T {
        let inner = unsafe { &mut *self.inner.get() };
        get_with_inner(&self.state_api, inner).0
    }

    /// Get a mutable reference to the value. If the value is modified in-memory
    /// then it will be stored when the box is dropped.
    pub fn get_mut(&mut self) -> &mut T {
        let inner = self.inner.get_mut();
        let (value, modified) = get_with_inner(&self.state_api, inner);
        *modified = true;
        value
    }

    /// Replace the value with the provided one. The current value is returned.
    /// Note that if the type `T` contains references to state, e.g., is a
    /// [`StateBox`], then it must be [deleted](Deletable::delete) to avoid
    /// space leaks.
    #[must_use]
    pub fn replace(&mut self, new_val: T) -> T {
        let (entry, value) = self.ensure_cached();
        entry.move_to_start();
        new_val.serial(entry).unwrap_abort();
        mem::replace(value, new_val)
    }

    /// Update the existing value with the given function.
    /// The supplied function may return some data, which is then returned by
    /// [`update`](Self::update).
    pub fn update<F, A>(&mut self, f: F) -> A
    where
        F: FnOnce(&mut T) -> A, {
        let (entry, value) = self.ensure_cached();
        // Mutate the value (perhaps only in memory, depends on the type).
        let res = f(value);
        entry.move_to_start();
        value.serial(entry).unwrap_abort();
        res
    }

    /// If the value isn't cached, load the value from the state. Return a
    /// reference to the entry, and the value. Note that **if the value is
    /// modified, the entry should be used to write it.**
    fn ensure_cached(&mut self) -> (&mut S::EntryType, &mut T) {
        let inner = self.inner.get_mut();
        let (entry, modified, value) = match inner {
            StateBoxInner::Loaded {
                entry,
                value,
                ..
            } => return (entry, value),
            StateBoxInner::Reference {
                prefix,
            } => {
                let mut entry = self.state_api.lookup_entry(prefix).unwrap_abort();
                // new entry, positioned at the start.
                let value = T::deserial_with_state(&self.state_api, &mut entry).unwrap_abort();
                (entry, false, value)
            }
        };
        *inner = StateBoxInner::Loaded {
            entry,
            modified,
            value,
        };
        match inner {
            StateBoxInner::Loaded {
                entry,
                value,
                ..
            } => (entry, value),
            StateBoxInner::Reference {
                ..
            } => {
                // We just set it to loaded
                unsafe { crate::hint::unreachable_unchecked() }
            }
        }
    }
}

impl<T: Serial, S: HasStateApi> Serial for StateBox<T, S> {
    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
        out.write_all(self.get_location())
    }
}

impl<T, S> Serial for StateSet<T, S> {
    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> { out.write_all(&self.prefix) }
}

/// Unlock the part of the tree locked by the iterator.
impl<'a, T, S: HasStateApi> Drop for StateSetIter<'a, T, S> {
    #[inline]
    fn drop(&mut self) {
        // Delete the iterator to unlock the subtree.
        if let Some(valid) = self.state_iter.take() {
            self.state_api.delete_iterator(valid);
        }
    }
}

impl<'a, T, S: HasStateApi> Iterator for StateSetIter<'a, T, S>
where
    T: DeserialWithState<S>,
{
    type Item = StateRef<'a, T>;

    #[inline(always)]
    fn next(&mut self) -> Option<Self::Item> {
        let entry = self.state_iter.as_mut()?.next()?;
        let key = entry.get_key();
        let mut key_cursor = Cursor {
            data:   key,
            offset: 8, // Items in a set always start with the set prefix which is 8 bytes.
        };
        // Unwrapping is safe when only using the high-level API.
        let t = T::deserial_with_state(&self.state_api, &mut key_cursor).unwrap_abort();
        Some(StateRef::new(t))
    }
}

// # Trait implementations for Parameter

impl Default for ExternParameter {
    #[inline(always)]
    fn default() -> Self {
        ExternParameter {
            cursor: Cursor::new(ExternParameterDataPlaceholder {}),
        }
    }
}

impl Read for ExternParameter {
    fn read(&mut self, buf: &mut [u8]) -> ParseResult<usize> {
        let len: u32 = {
            match buf.len().try_into() {
                Ok(v) => v,
                _ => return Err(ParseError::default()),
            }
        };
        let num_read = unsafe {
            // parameter 0 always exists, so this is safe.
            prims::get_parameter_section(0, buf.as_mut_ptr(), len, self.cursor.offset as u32)
        };

        self.cursor.offset += num_read as usize;
        Ok(num_read as usize)
    }
}

impl HasSize for ExternParameterDataPlaceholder {
    #[inline(always)]
    // parameter 0 always exists so this is correct
    fn size(&self) -> u32 { unsafe { prims::get_parameter_size(0) as u32 } }
}

impl HasSize for ExternParameter {
    #[inline(always)]
    fn size(&self) -> u32 { self.cursor.data.size() }
}

impl Seek for ExternParameter {
    type Err = ();

    #[inline(always)]
    fn seek(&mut self, pos: SeekFrom) -> Result<u32, Self::Err> { self.cursor.seek(pos) }

    #[inline(always)]
    fn cursor_position(&self) -> u32 { self.cursor.cursor_position() }
}

impl HasParameter for ExternParameter {}

/// The read implementation uses host functions to read chunks of return value
/// on demand.
impl Read for ExternCallResponse {
    fn read(&mut self, buf: &mut [u8]) -> ParseResult<usize> {
        let len: u32 = {
            match buf.len().try_into() {
                Ok(v) => v,
                _ => return Err(ParseError::default()),
            }
        };
        let num_read = unsafe {
            prims::get_parameter_section(
                self.i.into(),
                buf.as_mut_ptr(),
                len,
                self.current_position,
            )
        };
        if num_read >= 0 {
            self.current_position += num_read as u32;
            Ok(num_read as usize)
        } else {
            Err(ParseError::default())
        }
    }
}

impl HasCallResponse for ExternCallResponse {
    // CallResponse can only be constured in this crate. As a result whenever it is
    // constructed it will point to a valid parameter, which means that
    // `get_parameter_size` will always return a non-negative value.
    fn size(&self) -> u32 { unsafe { prims::get_parameter_size(self.i.get()) as u32 } }
}

/// # Trait implementations for the chain metadata.
impl HasChainMetadata for ExternChainMeta {
    #[inline(always)]
    fn slot_time(&self) -> SlotTime {
        Timestamp::from_timestamp_millis(unsafe { prims::get_slot_time() })
    }
}

impl AttributesCursor {
    fn next_item(&mut self, buf: &mut [u8]) -> Option<(AttributeTag, u8)> {
        if self.remaining_items == 0 {
            return None;
        }

        let (tag_value_len, num_read) = unsafe {
            let mut tag_value_len = MaybeUninit::<[u8; 2]>::uninit();
            // Should succeed, otherwise host violated precondition.
            let num_read = prims::get_policy_section(
                tag_value_len.as_mut_ptr() as *mut u8,
                2,
                self.current_position,
            );
            (tag_value_len.assume_init(), num_read)
        };
        self.current_position += num_read;
        if tag_value_len[1] > 31 {
            // Should not happen because all attributes fit into 31 bytes.
            return None;
        }
        let num_read = unsafe {
            prims::get_policy_section(
                buf.as_mut_ptr(),
                u32::from(tag_value_len[1]),
                self.current_position,
            )
        };
        self.current_position += num_read;
        self.remaining_items -= 1;
        Some((AttributeTag(tag_value_len[0]), tag_value_len[1]))
    }
}

impl HasPolicy for Policy<AttributesCursor> {
    type Iterator = PolicyAttributesIter;

    fn identity_provider(&self) -> IdentityProvider { self.identity_provider }

    fn created_at(&self) -> Timestamp { self.created_at }

    fn valid_to(&self) -> Timestamp { self.valid_to }

    #[inline(always)]
    fn next_item(&mut self, buf: &mut [u8; 31]) -> Option<(AttributeTag, u8)> {
        self.items.next_item(buf)
    }

    fn attributes(&self) -> Self::Iterator {
        PolicyAttributesIter {
            cursor: AttributesCursor {
                current_position: 0,
                remaining_items:  self.items.total_items,
                total_items:      self.items.total_items,
            },
        }
    }
}

impl Iterator for PolicyAttributesIter {
    type Item = (AttributeTag, AttributeValue);

    fn next(&mut self) -> Option<Self::Item> {
        let mut inner = [0u8; 32];
        let (tag, len) = self.cursor.next_item(&mut inner[1..])?;
        inner[0] = len;
        Some((tag, unsafe { AttributeValue::new_unchecked(inner) }))
    }
}

impl ExactSizeIterator for PolicyAttributesIter {
    fn len(&self) -> usize { self.cursor.remaining_items as usize }
}

/// An iterator over policies using host functions to supply the data.
/// The main interface to using this type is via the methods of the [Iterator](https://doc.rust-lang.org/std/iter/trait.Iterator.html)
/// and [ExactSizeIterator](https://doc.rust-lang.org/std/iter/trait.ExactSizeIterator.html) traits.
pub struct PoliciesIterator {
    /// Position in the policies binary serialization.
    pos:             u32,
    /// Number of remaining items in the stream.
    remaining_items: u16,
}

impl Iterator for PoliciesIterator {
    type Item = Policy<AttributesCursor>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.remaining_items == 0 {
            return None;
        }
        // 2 for total size of this section, 4 for identity_provider,
        // 8 bytes for created_at, 8 for valid_to, and 2 for
        // the length
        let mut buf: MaybeUninit<[u8; 2 + 4 + 8 + 8 + 2]> = MaybeUninit::uninit();
        let buf = unsafe {
            prims::get_policy_section(buf.as_mut_ptr() as *mut u8, 2 + 4 + 8 + 8 + 2, self.pos);
            buf.assume_init()
        };
        let skip_part: [u8; 2] = buf[0..2].try_into().unwrap_abort();
        let ip_part: [u8; 4] = buf[2..2 + 4].try_into().unwrap_abort();
        let created_at_part: [u8; 8] = buf[2 + 4..2 + 4 + 8].try_into().unwrap_abort();
        let valid_to_part: [u8; 8] = buf[2 + 4 + 8..2 + 4 + 8 + 8].try_into().unwrap_abort();
        let len_part: [u8; 2] = buf[2 + 4 + 8 + 8..2 + 4 + 8 + 8 + 2].try_into().unwrap_abort();
        let identity_provider = IdentityProvider::from_le_bytes(ip_part);
        let created_at = Timestamp::from_timestamp_millis(u64::from_le_bytes(created_at_part));
        let valid_to = Timestamp::from_timestamp_millis(u64::from_le_bytes(valid_to_part));
        let remaining_items = u16::from_le_bytes(len_part);
        let attributes_start = self.pos + 2 + 4 + 8 + 8 + 2;
        self.pos += u32::from(u16::from_le_bytes(skip_part)) + 2;
        self.remaining_items -= 1;
        Some(Policy {
            identity_provider,
            created_at,
            valid_to,
            items: AttributesCursor {
                current_position: attributes_start,
                remaining_items,
                total_items: remaining_items,
            },
        })
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let rem = self.remaining_items as usize;
        (rem, Some(rem))
    }
}

impl ExactSizeIterator for PoliciesIterator {
    #[inline(always)]
    fn len(&self) -> usize { self.remaining_items as usize }
}

impl<T: sealed::ContextType> HasCommonData for ExternContext<T> {
    type MetadataType = ExternChainMeta;
    type ParamType = ExternParameter;
    type PolicyIteratorType = PoliciesIterator;
    type PolicyType = Policy<AttributesCursor>;

    #[inline(always)]
    fn metadata(&self) -> &Self::MetadataType { &ExternChainMeta {} }

    fn policies(&self) -> PoliciesIterator {
        let mut buf: MaybeUninit<[u8; 2]> = MaybeUninit::uninit();
        let buf = unsafe {
            prims::get_policy_section(buf.as_mut_ptr() as *mut u8, 2, 0);
            buf.assume_init()
        };
        PoliciesIterator {
            pos:             2, // 2 because we already read 2 bytes.
            remaining_items: u16::from_le_bytes(buf),
        }
    }

    #[inline(always)]
    fn parameter_cursor(&self) -> Self::ParamType { ExternParameter::default() }
}

/// Tag of the transfer operation expected by the host. See [prims::invoke].
const INVOKE_TRANSFER_TAG: u32 = 0;
/// Tag of the call operation expected by the host. See [prims::invoke].
const INVOKE_CALL_TAG: u32 = 1;
/// Tag of the query account balance operation expected by the host. See
/// [prims::invoke].
const INVOKE_QUERY_ACCOUNT_BALANCE_TAG: u32 = 2;
/// Tag of the query contract balance operation expected by the host. See
/// [prims::invoke].
const INVOKE_QUERY_CONTRACT_BALANCE_TAG: u32 = 3;
/// Tag of the query exchange rates operation expected by the host. See
/// [prims::invoke].
const INVOKE_QUERY_EXCHANGE_RATES_TAG: u32 = 4;
/// Tag of the operation to check the account's signature [prims::invoke].
const INVOKE_CHECK_ACCOUNT_SIGNATURE_TAG: u32 = 5;
/// Tag of the query account's public keys [prims::invoke].
const INVOKE_QUERY_ACCOUNT_PUBLIC_KEYS_TAG: u32 = 6;
/// Tag of the query contract module reference operation. See [prims::invoke].
#[cfg(feature = "p7")]
const INVOKE_QUERY_CONTRACT_MODULE_REFERENCE_TAG: u32 = 7;
/// Tag of the query contract name operation. See [prims::invoke].
#[cfg(feature = "p7")]
const INVOKE_QUERY_CONTRACT_NAME_TAG: u32 = 8;

/// Check whether the response code from calling `invoke` is encoding a failure
/// and map out the byte used for the error code.
/// A successful response code has the last 5 bytes unset.
#[inline(always)]
fn get_invoke_failure_code(code: u64) -> Option<u8> {
    if code & 0xff_ffff_ffff == 0 {
        None
    } else {
        let error_code = (code & 0xff_0000_0000) >> 32;
        Some(error_code as u8)
    }
}

/// Decode the the response code.
///
/// The response is encoded as follows.
/// - Success if the last 5 bytes are all zero:
///   - the first 3 bytes encodes the return value index, except the first bit,
///     which is used to indicate whether the contract state was modified.
/// - In case of failure the 4th byte is used, and encodes the environment
///   failure, where:
///   - 0x01 encodes amount too large.
///   - 0x02 encodes missing account.
fn parse_transfer_response_code(code: u64) -> TransferResult {
    if let Some(error_code) = get_invoke_failure_code(code) {
        match error_code {
            0x01 => Err(TransferError::AmountTooLarge),
            0x02 => Err(TransferError::MissingAccount),
            _ => crate::trap(), // host precondition violation
        }
    } else {
        Ok(())
    }
}

/// Decode the response code from calling upgrade.
///
/// The response is encoded as follows.
/// - Success if the last 5 bytes are all zero:
///   - the first 3 bytes encodes the return value index, except the first bit,
///     which is used to indicate whether the contract state was modified.
/// - In case of failure the 4th byte is used, and encodes the environment
///   failure, where:
///   - 0x07 encodes missing module.
///   - 0x08 encodes missing contract.
///   - 0x09 encodes module being an unsupported version.
#[inline(always)]
fn parse_upgrade_response_code(code: u64) -> UpgradeResult {
    if let Some(error_code) = get_invoke_failure_code(code) {
        match error_code {
            0x07 => Err(UpgradeError::MissingModule),
            0x08 => Err(UpgradeError::MissingContract),
            0x09 => Err(UpgradeError::UnsupportedModuleVersion),
            _ => crate::trap(), // host precondition violation
        }
    } else {
        Ok(())
    }
}

/// Decode the the response code.
///
/// The response is encoded as follows.
/// - Success if the last 5 bytes are all zero:
///   - the first 3 bytes encodes the return value index, except the first bit,
///     which is used to indicate whether the contract state was modified.
/// - In case of failure:
///   - if the 4th byte is 0 then the remaining 4 bytes encode the rejection
///     reason from the contract
///   - otherwise only the 4th byte is used, and encodes the environment
///     failure.
///     - 0x01 encodes amount too large.
///     - 0x02 encodes missing account.
///     - 0x03 encodes missing contract.
///     - 0x04 encodes missing entrypoint.
///     - 0x05 encodes message failed.
///     - 0x06 encodes trap.
fn parse_call_response_code(code: u64) -> CallContractResult<ExternCallResponse> {
    if let Some(error_code) = get_invoke_failure_code(code) {
        match error_code {
            0x00 =>
            // response with logic error and return value.
            {
                let reason = (0x0000_0000_ffff_ffff & code) as u32 as i32;
                if reason == 0 {
                    crate::trap()
                } else {
                    let rv = (code >> 40) as u32;
                    if rv > 0 {
                        Err(CallContractError::LogicReject {
                            reason,
                            return_value: ExternCallResponse::new(unsafe {
                                NonZeroU32::new_unchecked(rv)
                            }),
                        })
                    } else {
                        unsafe { crate::hint::unreachable_unchecked() } // host precondition violation.
                    }
                }
            }
            0x01 => Err(CallContractError::AmountTooLarge),
            0x02 => Err(CallContractError::MissingAccount),
            0x03 => Err(CallContractError::MissingContract),
            0x04 => Err(CallContractError::MissingEntrypoint),
            0x05 => Err(CallContractError::MessageFailed),
            0x06 => Err(CallContractError::Trap),
            _ => unsafe { crate::hint::unreachable_unchecked() }, // host precondition violation
        }
    } else {
        // Map out the 3 bytes encoding the return value index.
        let rv = (code >> 40) as u32;

        let tag = 0x80_0000u32; // Mask for the first bit.
        if tag & rv != 0 {
            // Check the bit, indicating a contract state change.
            Ok((true, NonZeroU32::new(rv & !tag).map(ExternCallResponse::new)))
        } else {
            Ok((false, NonZeroU32::new(rv).map(ExternCallResponse::new)))
        }
    }
}

/// Decode the account balance response code.
///
/// - Success if the last 5 bytes are all zero:
///   - the first 3 bytes encodes the return value index.
/// - In case of failure the 4th byte is used, and encodes the environment
///   failure where:
///    - '0x02' encodes missing account.
fn parse_query_account_balance_response_code(
    code: u64,
) -> Result<ExternCallResponse, QueryAccountBalanceError> {
    if let Some(error_code) = get_invoke_failure_code(code) {
        if error_code == 0x02 {
            Err(QueryAccountBalanceError)
        } else {
            unsafe { crate::hint::unreachable_unchecked() }
        }
    } else {
        // Map out the 3 bytes encoding the return value index.
        let return_value_index = NonZeroU32::new((code >> 40) as u32).unwrap_abort();
        Ok(ExternCallResponse::new(return_value_index))
    }
}

/// Decode the contract balance response code.
///
/// - Success if the last 5 bytes are all zero:
///   - the first 3 bytes encodes the return value index.
/// - In case of failure the 4th byte is used, and encodes the environment
///   failure where:
///    - '0x03' encodes missing contract.
fn parse_query_contract_balance_response_code(
    code: u64,
) -> Result<ExternCallResponse, QueryContractBalanceError> {
    if let Some(error_code) = get_invoke_failure_code(code) {
        if error_code == 0x03 {
            Err(QueryContractBalanceError)
        } else {
            unsafe { crate::hint::unreachable_unchecked() }
        }
    } else {
        // Map out the 3 bytes encoding the return value index.
        let return_value_index = NonZeroU32::new((code >> 40) as u32).unwrap_abort();
        Ok(ExternCallResponse::new(return_value_index))
    }
}

/// Decode the account public keys query response code.
///
/// - Success if the last 5 bytes are all zero:
///   - the first 3 bytes encodes the return value index.
/// - In case of failure the 4th byte is used, and encodes the environment
///   failure where:
///    - '0x02' encodes missing account.
fn parse_query_account_public_keys_response_code(
    code: u64,
) -> Result<ExternCallResponse, QueryAccountPublicKeysError> {
    if let Some(error_code) = get_invoke_failure_code(code) {
        if error_code == 0x02 {
            Err(QueryAccountPublicKeysError)
        } else {
            unsafe { crate::hint::unreachable_unchecked() }
        }
    } else {
        // Map out the 3 bytes encoding the return value index.
        let return_value_index = NonZeroU32::new((code >> 40) as u32).unwrap_abort();
        Ok(ExternCallResponse::new(return_value_index))
    }
}

/// Decode the response from checking account signatures.
///
/// - Success if the last 5 bytes are all zero:
/// - In case of failure the 4th byte is used, and encodes the environment
///   failure where:
///    - '0x02' encodes missing account.
///    - '0x0a' encodes malformed data, i.e., the call was made with incorrect
///      data.
///    - '0x0b' encodes that signature validation failed.
fn parse_check_account_signature_response_code(
    code: u64,
) -> Result<bool, CheckAccountSignatureError> {
    if let Some(error_code) = get_invoke_failure_code(code) {
        if error_code == 0x02 {
            Err(CheckAccountSignatureError::MissingAccount)
        } else if error_code == 0x0a {
            Err(CheckAccountSignatureError::MalformedData)
        } else if error_code == 0x0b {
            Ok(false)
        } else {
            unsafe { crate::hint::unreachable_unchecked() }
        }
    } else {
        Ok(true)
    }
}

/// Decode the exchange rate response code.
///
/// - Success if the last 5 bytes are all zero:
///   - the first 3 bytes encodes the return value index.
/// - In case of failure we throw a runtime error, since this query is not
///   expected to fail.
fn parse_query_exchange_rates_response_code(code: u64) -> ExternCallResponse {
    if get_invoke_failure_code(code).is_some() {
        // Querying the exchange rates should never produce a failure response code.
        unsafe { crate::hint::unreachable_unchecked() }
    } else {
        // Map out the 3 bytes encoding the return value index.
        let return_value_index = NonZeroU32::new((code >> 40) as u32).unwrap_abort();
        ExternCallResponse::new(return_value_index)
    }
}

/// Decode the contract module reference response code.
///
/// - Success if the last 5 bytes are all zero:
///   - the first 3 bytes encodes the return value index.
/// - In case of failure the 4th byte is used, and encodes the environment
///   failure where:
///    - '0x03' encodes missing contract.
#[cfg(feature = "p7")]
fn parse_query_contract_module_reference_response_code(
    code: u64,
) -> Result<ExternCallResponse, QueryContractModuleReferenceError> {
    if let Some(error_code) = get_invoke_failure_code(code) {
        if error_code == 0x03 {
            Err(QueryContractModuleReferenceError)
        } else {
            unsafe { crate::hint::unreachable_unchecked() }
        }
    } else {
        // Map out the 3 bytes encoding the return value index.
        let return_value_index = NonZeroU32::new((code >> 40) as u32).unwrap_abort();
        Ok(ExternCallResponse::new(return_value_index))
    }
}

/// Decode the contract name response code.
///
/// - Success if the last 5 bytes are all zero:
///   - the first 3 bytes encodes the return value index.
/// - In case of failure the 4th byte is used, and encodes the environment
///   failure where:
///    - '0x03' encodes missing contract.
#[cfg(feature = "p7")]
fn parse_query_contract_name_response_code(
    code: u64,
) -> Result<OwnedContractName, QueryContractNameError> {
    if let Some(error_code) = get_invoke_failure_code(code) {
        if error_code == 0x03 {
            Err(QueryContractNameError)
        } else {
            unsafe { crate::hint::unreachable_unchecked() }
        }
    } else {
        // Map out the 3 bytes encoding the return value index.
        let return_value_index = (code >> 40) as u32;
        let name = unsafe {
            let name_size = prims::get_parameter_size(return_value_index);
            if name_size < 0 {
                crate::hint::unreachable_unchecked()
            }
            let mut buf = vec![0; name_size as usize];
            prims::get_parameter_section(return_value_index, buf.as_mut_ptr(), name_size as u32, 0);
            String::from_utf8_unchecked(buf)
        };
        Ok(OwnedContractName::new_unchecked(name))
    }
}

/// Helper factoring out the common behaviour of invoke_transfer for the two
/// extern hosts below.
fn invoke_transfer_worker(receiver: &AccountAddress, amount: Amount) -> TransferResult {
    let mut bytes: MaybeUninit<[u8; ACCOUNT_ADDRESS_SIZE + 8]> = MaybeUninit::uninit();
    let data = unsafe {
        (bytes.as_mut_ptr() as *mut u8).copy_from_nonoverlapping(
            receiver.as_ref() as *const [u8; ACCOUNT_ADDRESS_SIZE] as *const u8,
            ACCOUNT_ADDRESS_SIZE,
        );
        (bytes.as_mut_ptr() as *mut u8).add(ACCOUNT_ADDRESS_SIZE).copy_from_nonoverlapping(
            &amount.micro_ccd.to_le_bytes() as *const [u8; 8] as *const u8,
            8,
        );
        bytes.assume_init()
    };
    let response = unsafe {
        prims::invoke(INVOKE_TRANSFER_TAG, data.as_ptr(), (ACCOUNT_ADDRESS_SIZE + 8) as u32)
    };
    parse_transfer_response_code(response)
}

/// A helper that constructs the parameter to invoke_contract.
fn invoke_contract_construct_parameter(
    to: &ContractAddress,
    parameter: Parameter,
    method: EntrypointName,
    amount: Amount,
) -> Vec<u8> {
    let mut data =
        Vec::with_capacity(16 + parameter.as_ref().len() + 2 + method.size() as usize + 2 + 8);
    let mut cursor = Cursor::new(&mut data);
    to.serial(&mut cursor).unwrap_abort();
    parameter.serial(&mut cursor).unwrap_abort();
    method.serial(&mut cursor).unwrap_abort();
    amount.serial(&mut cursor).unwrap_abort();
    data
}

/// Helper factoring out the common behaviour of account_balance for the
/// two extern hosts below.
fn query_account_balance_worker(address: &AccountAddress) -> QueryAccountBalanceResult {
    let response = unsafe {
        prims::invoke(
            INVOKE_QUERY_ACCOUNT_BALANCE_TAG,
            AsRef::<[u8]>::as_ref(&address).as_ptr(),
            32,
        )
    };
    let mut return_value = parse_query_account_balance_response_code(response)?;
    Ok(AccountBalance::deserial(&mut return_value).unwrap_abort())
}

/// Helper factoring out the common behaviour of contract_balance for the
/// two extern hosts below.
fn query_contract_balance_worker(address: &ContractAddress) -> QueryContractBalanceResult {
    let data = [address.index.to_le_bytes(), address.subindex.to_le_bytes()];
    let response =
        unsafe { prims::invoke(INVOKE_QUERY_CONTRACT_BALANCE_TAG, data.as_ptr() as *const u8, 16) };
    let mut return_value = parse_query_contract_balance_response_code(response)?;
    Ok(Amount::deserial(&mut return_value).unwrap_abort())
}

/// Helper factoring out the common behaviour of exchange_rates for the
/// two extern hosts below.
fn query_exchange_rates_worker() -> ExchangeRates {
    let response_code = unsafe { prims::invoke(INVOKE_QUERY_EXCHANGE_RATES_TAG, [].as_ptr(), 0) };

    let mut response = parse_query_exchange_rates_response_code(response_code);
    ExchangeRates::deserial(&mut response).unwrap_abort()
}

/// Helper factoring out the common behaviour of `account_public_keys` for the
/// two extern hosts below.
fn query_account_public_keys_worker(address: AccountAddress) -> QueryAccountPublicKeysResult {
    let data: &[u8] = address.as_ref();
    let response =
        unsafe { prims::invoke(INVOKE_QUERY_ACCOUNT_PUBLIC_KEYS_TAG, data.as_ptr(), 32) };
    let mut return_value = parse_query_account_public_keys_response_code(response)?;
    Ok(crate::AccountPublicKeys::deserial(&mut return_value).unwrap_abort())
}

fn check_account_signature_worker(
    address: AccountAddress,
    signatures: &AccountSignatures,
    data: &[u8],
) -> CheckAccountSignatureResult {
    let mut buffer = address.0.to_vec();
    (data.len() as u32).serial(&mut buffer).unwrap_abort();
    buffer.extend_from_slice(data);
    signatures.serial(&mut buffer).unwrap_abort();

    let response = unsafe {
        prims::invoke(INVOKE_CHECK_ACCOUNT_SIGNATURE_TAG, buffer.as_ptr(), buffer.len() as u32)
    };
    // Be explicit that the buffer must survive up to here.
    drop(buffer);
    parse_check_account_signature_response_code(response)
}

/// Helper factoring out the common behaviour of contract_module_reference for
/// the two extern hosts below.
#[cfg(feature = "p7")]
fn query_contract_module_reference_worker(
    address: &ContractAddress,
) -> QueryContractModuleReferenceResult {
    let data = [address.index.to_le_bytes(), address.subindex.to_le_bytes()];
    let response = unsafe {
        prims::invoke(INVOKE_QUERY_CONTRACT_MODULE_REFERENCE_TAG, data.as_ptr() as *const u8, 16)
    };
    let mut return_value = parse_query_contract_module_reference_response_code(response)?;
    Ok(ModuleReference::deserial(&mut return_value).unwrap_abort())
}

/// Helper factoring out the common behaviour of contract_name for
/// the two extern hosts below.
#[cfg(feature = "p7")]
fn query_contract_name_worker(address: &ContractAddress) -> QueryContractNameResult {
    let data = [address.index.to_le_bytes(), address.subindex.to_le_bytes()];
    let response =
        unsafe { prims::invoke(INVOKE_QUERY_CONTRACT_NAME_TAG, data.as_ptr() as *const u8, 16) };
    parse_query_contract_name_response_code(response)
}

impl<S> StateBuilder<S>
where
    S: HasStateApi,
{
    /// Open a new state_builder. Only a single instance of the state_builder
    /// should exist during contract execution, thus this should only be
    /// called at the very beginning of execution.
    pub fn open(state: S) -> Self {
        Self {
            state_api: state,
        }
    }

    /// Provide clone of [`HasStateApi`] instance and new key prefix
    /// for any container-like type wishing to store its data on blockchain.
    ///
    /// Container types [`StateBox`], [`StateSet`], [`StateMap`] provided by
    /// Concordium SDK are created using this method internally.
    /// Contract developers can use it to implement their own
    /// containers.
    ///
    /// Any container type which provides more ergonomic APIs and behavior atop
    /// raw storage is expected to have two items:
    /// * Handle-like object which implements [`HasStateApi`]. It provides
    ///   access to contract VM features, including storage management. This
    ///   object is not serialized, instead it's provided by executon
    ///   environment. Can be treated as handle, relatively cheap to clone.
    /// * Prefix for keys of all entries managed by new container. Storage of
    ///   Concordium contract behaves like flat key-value dictionary, so each
    ///   container must have unique prefix for the keys of any entries it
    ///   stores to avoid collisions with other containers. This prefix is
    ///   serialized as (part of) persistent representation of container.
    ///
    /// # Returns
    /// A pair of:
    /// * Object which gives access to low-level storage API. Same as the one
    ///   held by [`StateBuilder`] itself and usually the one which refers to
    ///   current contract storage.
    /// * New unique key prefix for this container.
    #[must_use]
    pub fn new_state_container(&mut self) -> (S, [u8; 8]) {
        (self.state_api.clone(), self.get_and_update_item_prefix())
    }

    /// Create a new empty [`StateMap`].
    pub fn new_map<K, V>(&mut self) -> StateMap<K, V, S> {
        let (state_api, prefix) = self.new_state_container();
        StateMap::open(state_api, prefix)
    }

    /// Create a new empty [`StateSet`].
    pub fn new_set<T>(&mut self) -> StateSet<T, S> {
        let (state_api, prefix) = self.new_state_container();
        StateSet::open(state_api, prefix)
    }

    /// Create a new [`StateBox`] and insert the `value` into the state.
    /// This stores the serialized value in the contract state. Thus **if the
    /// `StateBox` is dropped without calling [`delete`](StateBox::delete)
    /// then the value will remain in contract state, leading to a space leak.**
    ///
    /// Note that this dropping can happen implicitly via assignment. For
    /// example,
    ///
    /// ```no_run
    /// # use concordium_std::*;
    /// struct MyState<S: HasStateApi> {
    ///     inner: StateBox<u64, S>,
    /// }
    /// fn incorrect_replace<S: HasStateApi>(
    ///     state_builder: &mut StateBuilder<S>,
    ///     state: &mut MyState<S>,
    /// ) {
    ///     // The following is incorrect. The old value of `inner` is not properly deleted.
    ///     // from the state.
    ///     state.inner = state_builder.new_box(0); // ⚠️
    /// }
    /// ```
    /// Instead, the old value should be manually deleted.
    /// ```no_run
    /// # use concordium_std::*;
    /// # struct MyState<S: HasStateApi> {
    /// #    inner: StateBox<u64, S>
    /// # }
    /// fn correct_replace<S: HasStateApi>(
    ///     state_builder: &mut StateBuilder<S>,
    ///     state: &mut MyState<S>,
    /// ) {
    ///     let old_box = mem::replace(&mut state.inner, state_builder.new_box(0));
    ///     old_box.delete()
    /// }
    /// ```
    #[must_use]
    pub fn new_box<T: Serial>(&mut self, value: T) -> StateBox<T, S> {
        let (state_api, prefix) = self.new_state_container();

        // Insert the value into the state
        let mut state_entry = self.state_api.create_entry(&prefix).unwrap_abort();
        value.serial(&mut state_entry).unwrap_abort();
        StateBox::new(value, state_api, state_entry)
    }

    fn get_and_update_item_prefix(&mut self) -> [u8; 8] {
        // Get the next prefix or insert and use the initial one.
        // Unwrapping is safe when using the high-level API because it is not possible
        // to get an iterator that locks this entry.
        let mut next_collection_prefix_entry = self
            .state_api
            .entry(NEXT_ITEM_PREFIX_KEY)
            .or_insert_raw(&INITIAL_NEXT_ITEM_PREFIX)
            .unwrap_abort();

        // Get the next collection prefix
        let collection_prefix = next_collection_prefix_entry.read_u64().unwrap_abort(); // Unwrapping is safe if only using the high-level API.

        // Rewind state entry position.
        next_collection_prefix_entry.move_to_start();

        // Increment the collection prefix
        next_collection_prefix_entry.write_u64(collection_prefix + 1).unwrap_abort(); // Writing to state cannot fail.

        collection_prefix.to_le_bytes()
    }
}

impl StateBuilder<StateApi> {
    /// Create a new empty [`StateBTreeSet`](crate::StateBTreeSet).
    pub fn new_btree_set<K>(&mut self) -> state_btree::StateBTreeSet<K> {
        let (state_api, prefix) = self.new_state_container();
        state_btree::StateBTreeSet::new(state_api, prefix)
    }

    /// Create a new empty [`StateBTreeMap`](crate::StateBTreeMap).
    pub fn new_btree_map<K, V>(&mut self) -> state_btree::StateBTreeMap<K, V> {
        state_btree::StateBTreeMap {
            key_value: self.new_map(),
            key_order: self.new_btree_set(),
        }
    }

    /// Create a new empty [`StateBTreeSet`](crate::StateBTreeSet), setting the
    /// minimum degree `M` of the B-Tree explicitly. `M` must be 2 or higher
    /// otherwise constructing the B-Tree results in aborting.
    pub fn new_btree_set_degree<const M: usize, K>(&mut self) -> state_btree::StateBTreeSet<K, M> {
        if M >= 2 {
            let (state_api, prefix) = self.new_state_container();
            state_btree::StateBTreeSet::new(state_api, prefix)
        } else {
            crate::fail!(
                "Invalid minimum degree used for StateBTreeSet, must be >=2 instead got {}",
                M
            )
        }
    }

    /// Create a new empty [`StateBTreeMap`](crate::StateBTreeMap), setting the
    /// minimum degree `M` of the B-Tree explicitly. `M` must be 2 or higher
    /// otherwise constructing the B-Tree results in aborting.
    pub fn new_btree_map_degree<const M: usize, K, V>(
        &mut self,
    ) -> state_btree::StateBTreeMap<K, V, M> {
        if M >= 2 {
            state_btree::StateBTreeMap {
                key_value: self.new_map(),
                key_order: self.new_btree_set_degree(),
            }
        } else {
            crate::fail!(
                "Invalid minimum degree used for StateBTreeMap, must be >=2 instead got {}",
                M
            )
        }
    }
}

impl<S> HasHost<S> for ExternHost<S>
where
    S: Serial + DeserialWithState<ExternStateApi>,
{
    type ReturnValueType = ExternCallResponse;
    type StateApiType = ExternStateApi;

    fn invoke_transfer(&self, receiver: &AccountAddress, amount: Amount) -> TransferResult {
        invoke_transfer_worker(receiver, amount)
    }

    fn invoke_contract_raw(
        &mut self,
        to: &ContractAddress,
        parameter: Parameter,
        method: EntrypointName,
        amount: Amount,
    ) -> CallContractResult<Self::ReturnValueType> {
        let data = invoke_contract_construct_parameter(to, parameter, method, amount);
        let len = data.len();
        // save the state before the out-call to reflect any changes we might have done.
        // this is not optimal, and ideally we'd keep track of changes. But that is more
        // error prone for the programmer.
        self.commit_state();
        let response = unsafe { prims::invoke(INVOKE_CALL_TAG, data.as_ptr(), len as u32) };
        let (state_modified, res) = parse_call_response_code(response)?;
        if state_modified {
            // The state of the contract changed as a result of the call.
            // So we refresh it.
            if let Ok(new_state) = S::deserial_with_state(
                &self.state_builder.state_api,
                &mut self.state_builder.state_api.lookup_entry(&[]).unwrap_abort(),
            ) {
                self.state = new_state;
            } else {
                crate::trap()
            }
        }
        Ok((state_modified, res))
    }

    fn invoke_contract_raw_read_only(
        &self,
        to: &ContractAddress,
        parameter: Parameter,
        method: EntrypointName,
        amount: Amount,
    ) -> ReadOnlyCallContractResult<Self::ReturnValueType> {
        let data = invoke_contract_construct_parameter(to, parameter, method, amount);
        let len = data.len();
        let response = unsafe { prims::invoke(INVOKE_CALL_TAG, data.as_ptr(), len as u32) };
        let (state_modified, res) = parse_call_response_code(response)?;
        if state_modified {
            crate::trap()
        } else {
            Ok(res)
        }
    }

    #[inline(always)]
    fn account_balance(&self, address: AccountAddress) -> QueryAccountBalanceResult {
        query_account_balance_worker(&address)
    }

    #[inline(always)]
    fn contract_balance(&self, address: ContractAddress) -> QueryContractBalanceResult {
        query_contract_balance_worker(&address)
    }

    #[inline(always)]
    fn exchange_rates(&self) -> ExchangeRates { query_exchange_rates_worker() }

    fn upgrade(&mut self, module: ModuleReference) -> UpgradeResult {
        let response = unsafe { prims::upgrade(module.as_ref().as_ptr()) };
        parse_upgrade_response_code(response)
    }

    fn account_public_keys(&self, address: AccountAddress) -> QueryAccountPublicKeysResult {
        query_account_public_keys_worker(address)
    }

    fn check_account_signature(
        &self,
        address: AccountAddress,
        signatures: &AccountSignatures,
        data: &[u8],
    ) -> CheckAccountSignatureResult {
        check_account_signature_worker(address, signatures, data)
    }

    #[cfg(feature = "p7")]
    #[inline(always)]
    fn contract_module_reference(
        &self,
        address: ContractAddress,
    ) -> QueryContractModuleReferenceResult {
        query_contract_module_reference_worker(&address)
    }

    #[cfg(feature = "p7")]
    #[inline(always)]
    fn contract_name(&self, address: ContractAddress) -> QueryContractNameResult {
        query_contract_name_worker(&address)
    }

    fn state(&self) -> &S { &self.state }

    fn state_mut(&mut self) -> &mut S { &mut self.state }

    fn commit_state(&mut self) {
        let mut root_entry = self.state_builder.state_api.lookup_entry(&[]).unwrap_abort();
        self.state.serial(&mut root_entry).unwrap_abort();
        let new_state_size = root_entry.size().unwrap_abort();
        root_entry.truncate(new_state_size).unwrap_abort();
    }

    #[inline(always)]
    fn self_balance(&self) -> Amount {
        Amount::from_micro_ccd(unsafe { prims::get_receive_self_balance() })
    }

    #[inline(always)]
    fn state_builder(&mut self) -> &mut StateBuilder<Self::StateApiType> { &mut self.state_builder }

    #[inline(always)]
    fn state_and_builder(&mut self) -> (&mut S, &mut StateBuilder<Self::StateApiType>) {
        (&mut self.state, &mut self.state_builder)
    }
}
impl HasHost<ExternStateApi> for ExternLowLevelHost {
    type ReturnValueType = ExternCallResponse;
    type StateApiType = ExternStateApi;

    #[inline(always)]
    fn invoke_transfer(&self, receiver: &AccountAddress, amount: Amount) -> TransferResult {
        invoke_transfer_worker(receiver, amount)
    }

    fn invoke_contract_raw(
        &mut self,
        to: &ContractAddress,
        parameter: Parameter,
        method: EntrypointName,
        amount: Amount,
    ) -> CallContractResult<Self::ReturnValueType> {
        let data = invoke_contract_construct_parameter(to, parameter, method, amount);
        let len = data.len();
        let response = unsafe { prims::invoke(INVOKE_CALL_TAG, data.as_ptr(), len as u32) };
        parse_call_response_code(response)
    }

    #[inline(always)]
    fn account_balance(&self, address: AccountAddress) -> QueryAccountBalanceResult {
        query_account_balance_worker(&address)
    }

    #[inline(always)]
    fn contract_balance(&self, address: ContractAddress) -> QueryContractBalanceResult {
        query_contract_balance_worker(&address)
    }

    #[inline(always)]
    fn exchange_rates(&self) -> ExchangeRates { query_exchange_rates_worker() }

    fn upgrade(&mut self, module: ModuleReference) -> UpgradeResult {
        let response = unsafe { prims::upgrade(module.as_ref().as_ptr()) };
        parse_upgrade_response_code(response)
    }

    fn account_public_keys(&self, address: AccountAddress) -> QueryAccountPublicKeysResult {
        query_account_public_keys_worker(address)
    }

    fn check_account_signature(
        &self,
        address: AccountAddress,
        signatures: &AccountSignatures,
        data: &[u8],
    ) -> CheckAccountSignatureResult {
        check_account_signature_worker(address, signatures, data)
    }

    #[cfg(feature = "p7")]
    #[inline(always)]
    fn contract_module_reference(
        &self,
        address: ContractAddress,
    ) -> QueryContractModuleReferenceResult {
        query_contract_module_reference_worker(&address)
    }

    #[cfg(feature = "p7")]
    #[inline(always)]
    fn contract_name(&self, address: ContractAddress) -> QueryContractNameResult {
        query_contract_name_worker(&address)
    }

    #[inline(always)]
    fn state(&self) -> &ExternStateApi { &self.state_api }

    #[inline(always)]
    fn state_mut(&mut self) -> &mut ExternStateApi { &mut self.state_api }

    #[inline(always)]
    fn commit_state(&mut self) {
        // do nothing since the low level host does not maintain any state
    }

    #[inline(always)]
    fn self_balance(&self) -> Amount {
        Amount::from_micro_ccd(unsafe { prims::get_receive_self_balance() })
    }

    #[inline(always)]
    fn state_builder(&mut self) -> &mut StateBuilder<Self::StateApiType> { &mut self.state_builder }

    #[inline(always)]
    fn state_and_builder(
        &mut self,
    ) -> (&mut ExternStateApi, &mut StateBuilder<Self::StateApiType>) {
        (&mut self.state_api, &mut self.state_builder)
    }

    fn invoke_contract_raw_read_only(
        &self,
        to: &ContractAddress,
        parameter: Parameter<'_>,
        method: EntrypointName<'_>,
        amount: Amount,
    ) -> ReadOnlyCallContractResult<Self::ReturnValueType> {
        let data = invoke_contract_construct_parameter(to, parameter, method, amount);
        let len = data.len();
        let response = unsafe { prims::invoke(INVOKE_CALL_TAG, data.as_ptr(), len as u32) };
        let (state_modified, res) = parse_call_response_code(response)?;
        if state_modified {
            crate::trap()
        } else {
            Ok(res)
        }
    }
}

impl HasCryptoPrimitives for ExternCryptoPrimitives {
    fn verify_ed25519_signature(
        &self,
        public_key: PublicKeyEd25519,
        signature: SignatureEd25519,
        message: &[u8],
    ) -> bool {
        let res = unsafe {
            prims::verify_ed25519_signature(
                public_key.0.as_ptr(),
                signature.0.as_ptr(),
                message.as_ptr(),
                message.len() as u32,
            )
        };
        res == 1
    }

    fn verify_ecdsa_secp256k1_signature(
        &self,
        public_key: PublicKeyEcdsaSecp256k1,
        signature: SignatureEcdsaSecp256k1,
        message_hash: [u8; 32],
    ) -> bool {
        let res = unsafe {
            prims::verify_ecdsa_secp256k1_signature(
                public_key.0.as_ptr(),
                signature.0.as_ptr(),
                message_hash.as_ptr(),
            )
        };
        res == 1
    }

    fn hash_sha2_256(&self, data: &[u8]) -> HashSha2256 {
        let mut output: MaybeUninit<[u8; 32]> = MaybeUninit::uninit();
        unsafe {
            prims::hash_sha2_256(data.as_ptr(), data.len() as u32, output.as_mut_ptr() as *mut u8);
            HashSha2256(output.assume_init())
        }
    }

    fn hash_sha3_256(&self, data: &[u8]) -> HashSha3256 {
        let mut output: MaybeUninit<[u8; 32]> = MaybeUninit::uninit();
        unsafe {
            prims::hash_sha3_256(data.as_ptr(), data.len() as u32, output.as_mut_ptr() as *mut u8);
            HashSha3256(output.assume_init())
        }
    }

    fn hash_keccak_256(&self, data: &[u8]) -> HashKeccak256 {
        let mut output: MaybeUninit<[u8; 32]> = MaybeUninit::uninit();
        unsafe {
            prims::hash_keccak_256(
                data.as_ptr(),
                data.len() as u32,
                output.as_mut_ptr() as *mut u8,
            );
            HashKeccak256(output.assume_init())
        }
    }
}

/// # Trait implementations for the init context
impl HasInitContext for ExternContext<crate::types::ExternInitContext> {
    type InitData = ();

    /// Create a new init context by using an external call.
    fn open(_: Self::InitData) -> Self { ExternContext::default() }

    #[inline(always)]
    fn init_origin(&self) -> AccountAddress {
        let mut bytes: MaybeUninit<[u8; ACCOUNT_ADDRESS_SIZE]> = MaybeUninit::uninit();
        let ptr = bytes.as_mut_ptr();
        let address = unsafe {
            prims::get_init_origin(ptr as *mut u8);
            bytes.assume_init()
        };
        AccountAddress(address)
    }
}

/// # Trait implementations for the receive context
impl HasReceiveContext for ExternContext<crate::types::ExternReceiveContext> {
    type ReceiveData = ();

    /// Create a new receive context
    fn open(_: Self::ReceiveData) -> Self { ExternContext::default() }

    #[inline(always)]
    fn invoker(&self) -> AccountAddress {
        let mut bytes: MaybeUninit<[u8; ACCOUNT_ADDRESS_SIZE]> = MaybeUninit::uninit();
        let ptr = bytes.as_mut_ptr();
        let address = unsafe {
            prims::get_receive_invoker(ptr as *mut u8);
            bytes.assume_init()
        };
        AccountAddress(address)
    }

    #[inline(always)]
    fn self_address(&self) -> ContractAddress {
        let mut bytes: MaybeUninit<[u8; 16]> = MaybeUninit::uninit();
        let ptr = bytes.as_mut_ptr();
        let address = unsafe {
            prims::get_receive_self_address(ptr as *mut u8);
            bytes.assume_init()
        };
        match from_bytes(&address) {
            Ok(v) => v,
            Err(_) => crate::trap(),
        }
    }

    #[inline(always)]
    fn sender(&self) -> Address {
        let mut bytes: MaybeUninit<[u8; 33]> = MaybeUninit::uninit();
        let ptr = bytes.as_mut_ptr() as *mut u8;
        unsafe {
            prims::get_receive_sender(ptr);
            let tag = *ptr;
            match tag {
                0u8 => {
                    match from_bytes(core::slice::from_raw_parts(ptr.add(1), ACCOUNT_ADDRESS_SIZE))
                    {
                        Ok(v) => Address::Account(v),
                        Err(_) => crate::trap(),
                    }
                }
                1u8 => match from_bytes(core::slice::from_raw_parts(ptr.add(1), 16)) {
                    Ok(v) => Address::Contract(v),
                    Err(_) => crate::trap(),
                },
                _ => crate::trap(), // unreachable!("Host violated precondition."),
            }
        }
    }

    #[inline(always)]
    fn owner(&self) -> AccountAddress {
        let mut bytes: MaybeUninit<[u8; ACCOUNT_ADDRESS_SIZE]> = MaybeUninit::uninit();
        let ptr = bytes.as_mut_ptr();
        let address = unsafe {
            prims::get_receive_owner(ptr as *mut u8);
            bytes.assume_init()
        };
        AccountAddress(address)
    }

    fn named_entrypoint(&self) -> OwnedEntrypointName {
        let mut data = crate::vec![0u8; unsafe { prims::get_receive_entrypoint_size() as usize }];
        unsafe { prims::get_receive_entrypoint(data.as_mut_ptr()) };
        OwnedEntrypointName::new_unchecked(unsafe { String::from_utf8_unchecked(data) })
    }
}

/// #Implementations of the logger.

impl HasLogger for Logger {
    #[inline(always)]
    fn init() -> Self {
        Self {
            _private: (),
        }
    }

    fn log_raw(&mut self, event: &[u8]) -> Result<(), LogError> {
        let res = unsafe { prims::log_event(event.as_ptr(), event.len() as u32) };
        match res {
            1 => Ok(()),
            0 => Err(LogError::Full),
            _ => Err(LogError::Malformed),
        }
    }
}

/// Allocates a Vec of bytes prepended with its length as a `u32` into memory,
/// and prevents them from being dropped. Returns the pointer.
/// Used to pass bytes from a Wasm module to its host.
#[doc(hidden)]
pub fn put_in_memory(input: &[u8]) -> *mut u8 {
    let bytes_length = input.len() as u32;
    let mut bytes = to_bytes(&bytes_length);
    bytes.extend_from_slice(input);
    let ptr = bytes.as_mut_ptr();
    #[cfg(feature = "std")]
    ::std::mem::forget(bytes);
    #[cfg(not(feature = "std"))]
    core::mem::forget(bytes);
    ptr
}

impl<A, E> UnwrapAbort for Result<A, E> {
    type Unwrap = A;

    #[inline]
    fn unwrap_abort(self) -> Self::Unwrap {
        match self {
            Ok(x) => x,
            Err(_) => crate::trap(),
        }
    }
}

impl<A, E: fmt::Debug> ExpectReport for Result<A, E> {
    type Unwrap = A;

    fn expect_report(self, msg: &str) -> Self::Unwrap {
        match self {
            Ok(x) => x,
            Err(e) => crate::fail!("{}: {:?}", msg, e),
        }
    }
}

impl<A: fmt::Debug, E> ExpectErrReport for Result<A, E> {
    type Unwrap = E;

    fn expect_err_report(self, msg: &str) -> Self::Unwrap {
        match self {
            Ok(a) => crate::fail!("{}: {:?}", msg, a),
            Err(e) => e,
        }
    }
}

impl<A> UnwrapAbort for Option<A> {
    type Unwrap = A;

    #[inline(always)]
    #[allow(clippy::redundant_closure)]
    // The redundant_closure here is needed since there is an implicit coercion from
    // ! to A. This does not happen if we just use unwrap_or_else(crate::trap).
    fn unwrap_abort(self) -> Self::Unwrap { self.unwrap_or_else(|| crate::trap()) }
}

impl<A> ExpectReport for Option<A> {
    type Unwrap = A;

    fn expect_report(self, msg: &str) -> Self::Unwrap {
        match self {
            Some(v) => v,
            None => crate::fail!("{}", msg),
        }
    }
}

impl<A: fmt::Debug> ExpectNoneReport for Option<A> {
    fn expect_none_report(self, msg: &str) {
        if let Some(x) = self {
            crate::fail!("{}: {:?}", msg, x)
        }
    }
}

/// Blanket implementation of [DeserialWithState] for any [Deserial] types,
/// which simply does not use the state argument.
impl<D: Deserial, S: HasStateApi> DeserialWithState<S> for D {
    #[inline(always)]
    fn deserial_with_state<R: Read>(_state: &S, source: &mut R) -> ParseResult<Self> {
        Self::deserial(source)
    }
}

/// Blanket implementation of [DeserialCtxWithState] for any [DeserialCtx]
/// types, which simply does not use the state argument.
impl<D: DeserialCtx, S: HasStateApi> DeserialCtxWithState<S> for D {
    #[inline(always)]
    fn deserial_ctx_with_state<R: Read>(
        size_length: schema::SizeLength,
        ensure_ordered: bool,
        _state: &S,
        source: &mut R,
    ) -> ParseResult<Self> {
        Self::deserial_ctx(size_length, ensure_ordered, source)
    }
}

impl<K, V, S> DeserialWithState<S> for StateMap<K, V, S>
where
    S: HasStateApi,
{
    fn deserial_with_state<R: Read>(state: &S, source: &mut R) -> ParseResult<Self> {
        source.read_array().map(|map_prefix| StateMap::open(state.clone(), map_prefix))
    }
}

impl<T, S> DeserialWithState<S> for StateSet<T, S>
where
    S: HasStateApi,
    T: Serial + DeserialWithState<S>,
{
    fn deserial_with_state<R: Read>(state: &S, source: &mut R) -> ParseResult<Self> {
        source.read_array().map(|set_prefix| StateSet::open(state.clone(), set_prefix))
    }
}

impl<T, S> DeserialWithState<S> for StateBox<T, S>
where
    S: HasStateApi,
    T: Serial + DeserialWithState<S>,
{
    fn deserial_with_state<R: Read>(state: &S, source: &mut R) -> ParseResult<Self> {
        let prefix = source.read_array()?;
        Ok(StateBox {
            state_api: state.clone(),
            inner:     UnsafeCell::new(StateBoxInner::Reference {
                prefix,
            }),
        })
    }
}

impl<T: Serialize> Deletable for T {
    #[inline(always)]
    fn delete(self) {} // Types that are Serialize have nothing to delete!
}

impl<T, S> Deletable for StateBox<T, S>
where
    T: Serial + DeserialWithState<S> + Deletable,
    S: HasStateApi,
{
    fn delete(mut self) {
        // replace the value with a dummy one for which drop is a no-op.
        let inner = mem::replace(
            &mut self.inner,
            UnsafeCell::new(StateBoxInner::Reference {
                prefix: [0u8; 8],
            }),
        );
        let (entry, value) = match inner.into_inner() {
            StateBoxInner::Loaded {
                entry,
                value,
                ..
            } => (entry, value),
            StateBoxInner::Reference {
                prefix,
            } => {
                // we load the value first because it might be necessary to delete
                // the nested value.
                // TODO: This is pretty bad for performance, but we cannot specialize the
                // implementation for flat values. Once rust supports specialization we might be
                // able to have a more precise implementation for flat values,
                // i.e., ones which are Deserial.
                let mut entry = self.state_api.lookup_entry(&prefix).unwrap_abort();
                let value = T::deserial_with_state(&self.state_api, &mut entry).unwrap_abort();
                (entry, value)
            }
        };
        self.state_api.delete_entry(entry).unwrap_abort();
        value.delete()
    }
}

impl<T, S> Deletable for StateSet<T, S>
where
    S: HasStateApi,
{
    fn delete(mut self) {
        // Statesets cannot contain state types (e.g. StateBox), so there is nothing to
        // delete, apart from the set itself.

        // Unwrapping is safe when only using the high-level API.
        self.state_api.delete_prefix(&self.prefix).unwrap_abort();
    }
}

impl<K, V, S> Deletable for StateMap<K, V, S>
where
    S: HasStateApi,
    K: Serialize,
    V: Serial + DeserialWithState<S> + Deletable,
{
    fn delete(mut self) { self.clear(); }
}

impl Serial for HashSha2256 {
    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> { self.0.serial(out) }
}

impl Deserial for HashSha2256 {
    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
        Ok(HashSha2256(Deserial::deserial(source)?))
    }
}

impl schema::SchemaType for HashSha2256 {
    fn get_type() -> concordium_contracts_common::schema::Type { schema::Type::ByteArray(32) }
}

impl Serial for HashSha3256 {
    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> { self.0.serial(out) }
}

impl Deserial for HashSha3256 {
    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
        Ok(HashSha3256(Deserial::deserial(source)?))
    }
}

impl schema::SchemaType for HashSha3256 {
    fn get_type() -> concordium_contracts_common::schema::Type { schema::Type::ByteArray(32) }
}

impl Serial for HashKeccak256 {
    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> { self.0.serial(out) }
}

impl Deserial for HashKeccak256 {
    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
        Ok(HashKeccak256(Deserial::deserial(source)?))
    }
}

impl schema::SchemaType for HashKeccak256 {
    fn get_type() -> concordium_contracts_common::schema::Type { schema::Type::ByteArray(32) }
}

impl schema::SchemaType for MetadataUrl {
    fn get_type() -> schema::Type {
        schema::Type::Struct(schema::Fields::Named(crate::vec![
            (String::from("url"), schema::Type::String(schema::SizeLength::U16)),
            // Use the `HashSha2256` schema to represent `hash` as a hex string.
            (String::from("hash"), Option::<HashSha2256>::get_type()),
        ]))
    }
}

impl Serial for MetadataUrl {
    fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
        // Serialize url as a string with size_length = 2
        let bytes = self.url.as_bytes();
        let len = bytes.len() as u16;
        len.serial(out)?;
        serial_vector_no_length(bytes, out)?;
        self.hash.serial(out)
    }
}

impl Deserial for MetadataUrl {
    fn deserial<R: Read>(source: &mut R) -> ParseResult<Self> {
        // Deserialize url as a string with size_length = 2
        let len: u16 = source.get()?;
        let bytes = deserial_vector_no_length(source, len as usize)?;
        Ok(MetadataUrl {
            url:  String::from_utf8(bytes).map_err(|_| ParseError::default())?,
            hash: Deserial::deserial(source)?,
        })
    }
}

#[cfg(test)]
mod tests {

    /// Check that you cannot have multiple active entries from a statemap at
    /// the same time. See the test file for details.
    #[test]
    fn statemap_multiple_entries_not_allowed() {
        let t = trybuild::TestCases::new();
        t.compile_fail("tests/state/map-multiple-entries.rs");
    }

    #[test]
    fn statemap_multiple_state_ref_mut_not_allowed() {
        let t = trybuild::TestCases::new();
        t.compile_fail("tests/state/map-multiple-state-ref-mut.rs");
    }
}

/// This test module relies on the runtime providing host functions and can only
/// be run using `cargo concordium test`.
#[cfg(feature = "internal-wasm-test")]
mod wasm_test {
    use crate::{
        claim, claim_eq, concordium_test, to_bytes, Deletable, Deserial, DeserialWithState,
        EntryRaw, HasStateApi, HasStateEntry, ParseResult, Serial, StateApi, StateBuilder,
        StateError, StateMap, StateSet, INITIAL_NEXT_ITEM_PREFIX,
    };

    const GENERIC_MAP_PREFIX: u64 = 1;

    /// Some helper methods that are used for internal tests.
    impl<S> StateBuilder<S>
    where
        S: HasStateApi,
    {
        /// Get a value from the generic map.
        /// `Some(Err(_))` means that something exists in the state with that
        /// key, but it isn't of type `V`.
        pub(crate) fn get<K: Serial, V: DeserialWithState<S>>(
            &self,
            key: K,
        ) -> Option<ParseResult<V>> {
            let key_with_map_prefix = Self::prepend_generic_map_key(key);

            self.state_api
                .lookup_entry(&key_with_map_prefix)
                .map(|mut entry| V::deserial_with_state(&self.state_api, &mut entry))
        }

        /// Inserts a value in the generic map.
        /// The key and value are serialized before insert.
        pub(crate) fn insert<K: Serial, V: Serial>(
            &mut self,
            key: K,
            value: V,
        ) -> Result<(), StateError> {
            let key_with_map_prefix = Self::prepend_generic_map_key(key);
            match self.state_api.entry(key_with_map_prefix) {
                EntryRaw::Vacant(vac) => {
                    let _ = vac.insert(&value);
                }
                EntryRaw::Occupied(mut occ) => occ.insert(&value),
            }
            Ok(())
        }

        /// Serializes the key and prepends [GENERIC_MAP_PREFIX].
        /// This is similar to how [StateMap] works, where a unique prefix is
        /// prepended onto keys. Since there is only one generic map, the prefix
        /// is a constant.
        fn prepend_generic_map_key<K: Serial>(key: K) -> Vec<u8> {
            let mut key_with_map_prefix = to_bytes(&GENERIC_MAP_PREFIX);
            key_with_map_prefix.append(&mut to_bytes(&key));
            key_with_map_prefix
        }
    }

    #[concordium_test]
    fn high_level_insert_get() {
        let expected_value: u64 = 123123123;
        let mut state_builder = StateBuilder::open(StateApi::open());
        state_builder.insert(0, expected_value).expect("Insert failed");
        let actual_value: u64 = state_builder.get(0).expect("Not found").expect("Not a valid u64");
        claim_eq!(expected_value, actual_value);
    }

    #[concordium_test]
    fn low_level_entry() {
        let expected_value: u64 = 123123123;
        let key = to_bytes(&42u64);
        let mut state = StateApi::open();
        state
            .entry(&key[..])
            .or_insert_raw(&to_bytes(&expected_value))
            .expect("No iterators, so insertion should work.");

        match state.entry(key) {
            EntryRaw::Vacant(_) => panic!("Unexpected vacant entry."),
            EntryRaw::Occupied(occ) => {
                claim_eq!(u64::deserial(&mut occ.get()), Ok(expected_value))
            }
        }
    }

    #[concordium_test]
    fn high_level_statemap() {
        let my_map_key = "my_map";
        let mut state_builder = StateBuilder::open(StateApi::open());

        let map_to_insert = state_builder.new_map::<String, String>();
        state_builder.insert(my_map_key, map_to_insert).expect("Insert failed");

        let mut my_map: StateMap<String, String, _> = state_builder
            .get(my_map_key)
            .expect("Could not get statemap")
            .expect("Deserializing statemap failed");
        let _ = my_map.insert("abc".to_string(), "hello, world".to_string());
        let _ = my_map.insert("def".to_string(), "hallo, Weld".to_string());
        let _ = my_map.insert("ghi".to_string(), "hej, verden".to_string());
        claim_eq!(*my_map.get(&"abc".to_string()).unwrap(), "hello, world".to_string());

        let mut iter = my_map.iter();
        let (k1, v1) = iter.next().unwrap();
        claim_eq!(*k1, "abc".to_string());
        claim_eq!(*v1, "hello, world".to_string());
        let (k2, v2) = iter.next().unwrap();
        claim_eq!(*k2, "def".to_string());
        claim_eq!(*v2, "hallo, Weld".to_string());
        let (k3, v3) = iter.next().unwrap();
        claim_eq!(*k3, "ghi".to_string());
        claim_eq!(*v3, "hej, verden".to_string());
        claim!(iter.next().is_none());
    }

    #[concordium_test]
    fn statemap_insert_remove() {
        let mut state_builder = StateBuilder::open(StateApi::open());
        let mut map = state_builder.new_map();
        let value = String::from("hello");
        let _ = map.insert(42, value.clone());
        claim_eq!(*map.get(&42).unwrap(), value);
        map.remove(&42);
        claim!(map.get(&42).is_none());
    }

    #[concordium_test]
    fn statemap_clear() {
        let mut state_builder = StateBuilder::open(StateApi::open());
        let mut map = state_builder.new_map();
        let _ = map.insert(1, 2);
        let _ = map.insert(2, 3);
        let _ = map.insert(3, 4);
        map.clear();
        claim!(map.is_empty());
    }

    #[concordium_test]
    fn high_level_nested_statemaps() {
        let inner_map_key = 0u8;
        let key_to_value = 77u8;
        let value = 255u8;
        let mut state_builder = StateBuilder::open(StateApi::open());
        let mut outer_map = state_builder.new_map::<u8, StateMap<u8, u8, _>>();
        let mut inner_map = state_builder.new_map::<u8, u8>();

        let _ = inner_map.insert(key_to_value, value);
        let _ = outer_map.insert(inner_map_key, inner_map);

        claim_eq!(*outer_map.get(&inner_map_key).unwrap().get(&key_to_value).unwrap(), value);
    }

    #[concordium_test]
    fn statemap_iter_mut_works() {
        let mut state_builder = StateBuilder::open(StateApi::open());
        let mut map = state_builder.new_map();
        let _ = map.insert(0u8, 1u8);
        let _ = map.insert(1u8, 2u8);
        let _ = map.insert(2u8, 3u8);
        for (_, mut v) in map.iter_mut() {
            v.update(|old_value| *old_value += 10);
        }
        let mut iter = map.iter();
        let (k1, v1) = iter.next().unwrap();
        claim_eq!(*k1, 0);
        claim_eq!(*v1, 11);
        let (k2, v2) = iter.next().unwrap();
        claim_eq!(*k2, 1);
        claim_eq!(*v2, 12);
        let (k3, v3) = iter.next().unwrap();
        claim_eq!(*k3, 2);
        claim_eq!(*v3, 13);
        claim!(iter.next().is_none());
    }

    #[concordium_test]
    fn iter_mut_works_on_nested_statemaps() {
        let mut state_builder = StateBuilder::open(StateApi::open());
        let mut outer_map = state_builder.new_map();
        let mut inner_map = state_builder.new_map();
        let _ = inner_map.insert(0u8, 1u8);
        let _ = inner_map.insert(1u8, 2u8);
        let _ = outer_map.insert(99u8, inner_map);
        for (_, mut v_map) in outer_map.iter_mut() {
            v_map.update(|v_map| {
                for (_, mut inner_v) in v_map.iter_mut() {
                    inner_v.update(|inner_v| *inner_v += 10);
                }
            });
        }

        // Check the outer map.
        let mut outer_iter = outer_map.iter();
        let (inner_map_key, inner_map) = outer_iter.next().unwrap();
        claim_eq!(*inner_map_key, 99);
        claim!(outer_iter.next().is_none());

        // Check the inner map.
        let mut inner_iter = inner_map.iter();
        let (k1, v1) = inner_iter.next().unwrap();
        claim_eq!(*k1, 0);
        claim_eq!(*v1, 11);
        let (k2, v2) = inner_iter.next().unwrap();
        claim_eq!(*k2, 1);
        claim_eq!(*v2, 12);
        claim!(inner_iter.next().is_none());
    }

    #[concordium_test]
    fn statemap_iterator_unlocks_tree_once_dropped() {
        let mut state_builder = StateBuilder::open(StateApi::open());
        let mut map = state_builder.new_map();
        let _ = map.insert(0u8, 1u8);
        let _ = map.insert(1u8, 2u8);
        {
            let _iter = map.iter();
            // Uncommenting these two lines (and making iter mutable) should
            // give a compile error:
            //
            // map.insert(2u8, 3u8);
            // let n = iter.next();
        } // iter is dropped here, unlocking the subtree.
        let _ = map.insert(2u8, 3u8);
    }

    #[concordium_test]
    fn high_level_stateset() {
        let my_set_key = "my_set";
        let mut state_builder = StateBuilder::open(StateApi::open());

        let mut set = state_builder.new_set::<u8>();
        claim!(set.insert(0));
        claim!(set.insert(1));
        claim!(!set.insert(1));
        claim!(set.insert(2));
        claim!(set.remove(&2));
        state_builder.insert(my_set_key, set).expect("Insert failed");

        claim!(state_builder.get::<_, StateSet<u8, _>>(my_set_key).unwrap().unwrap().contains(&0),);
        claim!(!state_builder.get::<_, StateSet<u8, _>>(my_set_key).unwrap().unwrap().contains(&2),);

        let set = state_builder.get::<_, StateSet<u8, _>>(my_set_key).unwrap().unwrap();
        let mut iter = set.iter();
        claim_eq!(*iter.next().unwrap(), 0);
        claim_eq!(*iter.next().unwrap(), 1);
        claim!(iter.next().is_none());
    }

    #[concordium_test]
    fn high_level_nested_stateset() {
        let inner_set_key = 0u8;
        let value = 255u8;
        let mut state_builder = StateBuilder::open(StateApi::open());
        let mut outer_map = state_builder.new_map::<u8, StateSet<u8, _>>();
        let mut inner_set = state_builder.new_set::<u8>();

        inner_set.insert(value);
        let _ = outer_map.insert(inner_set_key, inner_set);

        claim!(outer_map.get(&inner_set_key).unwrap().contains(&value));
    }

    #[concordium_test]
    fn stateset_insert_remove() {
        let mut state_builder = StateBuilder::open(StateApi::open());
        let mut set = state_builder.new_set();
        let _ = set.insert(42);
        claim!(set.contains(&42));
        set.remove(&42);
        claim!(!set.contains(&42));
    }

    #[concordium_test]
    fn stateset_clear() {
        let mut state_builder = StateBuilder::open(StateApi::open());
        let mut set = state_builder.new_set();
        let _ = set.insert(1);
        let _ = set.insert(2);
        let _ = set.insert(3);
        set.clear();
        claim!(set.is_empty());
    }

    #[concordium_test]
    fn stateset_iterator_unlocks_tree_once_dropped() {
        let mut state_builder = StateBuilder::open(StateApi::open());
        let mut set = state_builder.new_set();
        set.insert(0u8);
        set.insert(1);
        {
            let _iter = set.iter();
            // Uncommenting these two lines (and making iter mutable) should
            // give a compile error:
            //
            // set.insert(2);
            // let n = iter.next();
        } // iter is dropped here, unlocking the subtree.
        set.insert(2);
    }

    #[concordium_test]
    fn allocate_and_get_statebox() {
        let mut state_builder = StateBuilder::open(StateApi::open());
        let boxed_value = String::from("I'm boxed");
        let statebox = state_builder.new_box(boxed_value.clone());
        claim_eq!(*statebox.get(), boxed_value);
    }

    #[concordium_test]
    fn a_new_entry_can_not_be_created_under_a_locked_subtree() {
        let expected_value: u64 = 123123123;
        let key = to_bytes(b"ab");
        let sub_key = to_bytes(b"abc");
        let mut state = StateApi::open();
        state
            .entry(&key[..])
            .or_insert_raw(&to_bytes(&expected_value))
            .expect("No iterators, so insertion should work.");
        claim!(state.iterator(&key).is_ok(), "Iterator should be present");
        let entry = state.create_entry(&sub_key);
        claim!(entry.is_err(), "Should not be able to create an entry under a locked subtree");
    }

    #[concordium_test]
    fn a_new_entry_can_be_created_under_a_different_subtree_in_same_super_tree() {
        let expected_value: u64 = 123123123;
        let key = to_bytes(b"abcd");
        let key2 = to_bytes(b"abe");
        let mut state = StateApi::open();
        state
            .entry(&key[..])
            .or_insert_raw(&to_bytes(&expected_value))
            .expect("No iterators, so insertion should work.");
        claim!(state.iterator(&key).is_ok(), "Iterator should be present");
        let entry = state.create_entry(&key2);
        claim!(entry.is_ok(), "Failed to create a new entry under a different subtree");
    }

    #[concordium_test]
    fn an_existing_entry_can_not_be_deleted_under_a_locked_subtree() {
        let expected_value: u64 = 123123123;
        let key = to_bytes(b"ab");
        let sub_key = to_bytes(b"abc");
        let mut state = StateApi::open();
        state
            .entry(&key[..])
            .or_insert_raw(&to_bytes(&expected_value))
            .expect("no iterators, so insertion should work.");
        let sub_entry = state
            .entry(sub_key)
            .or_insert_raw(&to_bytes(&expected_value))
            .expect("Should be possible to create the entry.");
        claim!(state.iterator(&key).is_ok(), "Iterator should be present");
        claim!(
            state.delete_entry(sub_entry).is_err(),
            "Should not be able to delete entry under a locked subtree"
        );
    }

    #[concordium_test]
    fn an_existing_entry_can_be_deleted_from_a_different_subtree_in_same_super_tree() {
        let expected_value: u64 = 123123123;
        let key = to_bytes(b"abcd");
        let key2 = to_bytes(b"abe");
        let mut state = StateApi::open();
        state
            .entry(&key[..])
            .or_insert_raw(&to_bytes(&expected_value))
            .expect("No iterators, so insertion should work.");
        let entry2 = state
            .entry(key2)
            .or_insert_raw(&to_bytes(&expected_value))
            .expect("Should be possible to create the entry.");
        claim!(state.iterator(&key).is_ok(), "Iterator should be present");
        claim!(
            state.delete_entry(entry2).is_ok(),
            "Should be able to delete entry under a different subtree"
        );
    }

    #[concordium_test]
    fn deleting_nested_stateboxes_works() {
        let mut state_builder = StateBuilder::open(StateApi::open());
        let inner_box = state_builder.new_box(99u8);
        let middle_box = state_builder.new_box(inner_box);
        let outer_box = state_builder.new_box(middle_box);
        outer_box.delete();
        let mut iter = state_builder.state_api.iterator(&[]).expect("Could not get iterator");
        // The only remaining node should be the state_builder's next_item_prefix node.
        claim!(iter.nth(1).is_none());
    }

    #[concordium_test]
    fn clearing_statemap_with_stateboxes_works() {
        let mut state_builder = StateBuilder::open(StateApi::open());
        let box1 = state_builder.new_box(1u8);
        let box2 = state_builder.new_box(2u8);
        let box3 = state_builder.new_box(3u8);
        let mut map = state_builder.new_map();
        let _ = map.insert(1u8, box1);
        let _ = map.insert(2u8, box2);
        let _ = map.insert(3u8, box3);
        map.clear();
        let mut iter = state_builder.state_api.iterator(&[]).expect("Could not get iterator");
        // The only remaining node should be the state_builder's next_item_prefix node.
        claim!(iter.nth(1).is_none());
    }

    #[concordium_test]
    fn clearing_nested_statemaps_works() {
        let mut state_builder = StateBuilder::open(StateApi::open());
        let mut inner_map_1 = state_builder.new_map();
        let _ = inner_map_1.insert(1u8, 2u8);
        let _ = inner_map_1.insert(2u8, 3u8);
        let _ = inner_map_1.insert(3u8, 4u8);
        let mut inner_map_2 = state_builder.new_map();
        let _ = inner_map_2.insert(11u8, 12u8);
        let _ = inner_map_2.insert(12u8, 13u8);
        let _ = inner_map_2.insert(13u8, 14u8);
        let mut outer_map = state_builder.new_map();
        let _ = outer_map.insert(0u8, inner_map_1);
        let _ = outer_map.insert(1u8, inner_map_2);
        outer_map.clear();
        let mut iter = state_builder.state_api.iterator(&[]).expect("Could not get iterator");
        // The only remaining node should be the state_builder's next_item_prefix node.
        claim!(iter.nth(1).is_none());
    }

    #[concordium_test]
    fn occupied_entry_truncates_leftover_data() {
        let mut state_builder = StateBuilder::open(StateApi::open());
        let mut map = state_builder.new_map();
        let _ = map.insert(99u8, "A longer string that should be truncated".into());
        let a_short_string = "A short string".to_string();
        let expected_size = a_short_string.len() + 4; // 4 bytes for the length of the string.
        map.entry(99u8).and_modify(|v| *v = a_short_string);
        let actual_size = state_builder
            .state_api
            .lookup_entry(&[INITIAL_NEXT_ITEM_PREFIX[0], 0, 0, 0, 0, 0, 0, 0, 99])
            .expect("Lookup failed")
            .size()
            .expect("Getting size failed");
        claim_eq!(expected_size as u32, actual_size);
    }

    #[concordium_test]
    fn occupied_entry_raw_truncates_leftover_data() {
        let mut state = StateApi::open();
        state
            .entry([])
            .or_insert_raw(&to_bytes(&"A longer string that should be truncated"))
            .expect("No iterators, so insertion should work.");

        let a_short_string = "A short string";
        let expected_size = a_short_string.len() + 4; // 4 bytes for the length of the string.

        match state.entry([]) {
            EntryRaw::Vacant(_) => panic!("Entry is vacant"),
            EntryRaw::Occupied(mut occ) => occ.insert_raw(&to_bytes(&a_short_string)),
        }
        let actual_size =
            state.lookup_entry(&[]).expect("Lookup failed").size().expect("Getting size failed");
        claim_eq!(expected_size as u32, actual_size);
    }
}