summaryrefslogtreecommitdiff
path: root/libphobos/src/std/typecons.d
blob: fb15001233ae9085a7220aaf1db8ed8807121489 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
// Written in the D programming language.

/**
This module implements a variety of type constructors, i.e., templates
that allow construction of new, useful general-purpose types.

$(SCRIPT inhibitQuickIndex = 1;)
$(DIVC quickindex,
$(BOOKTABLE,
$(TR $(TH Category) $(TH Symbols))
$(TR $(TD Tuple) $(TD
    $(LREF isTuple)
    $(LREF Tuple)
    $(LREF tuple)
    $(LREF reverse)
))
$(TR $(TD Flags) $(TD
    $(LREF BitFlags)
    $(LREF isBitFlagEnum)
    $(LREF Flag)
    $(LREF No)
    $(LREF Yes)
))
$(TR $(TD Memory allocation) $(TD
    $(LREF RefCounted)
    $(LREF refCounted)
    $(LREF RefCountedAutoInitialize)
    $(LREF scoped)
    $(LREF Unique)
))
$(TR $(TD Code generation) $(TD
    $(LREF AutoImplement)
    $(LREF BlackHole)
    $(LREF generateAssertTrap)
    $(LREF generateEmptyFunction)
    $(LREF WhiteHole)
))
$(TR $(TD Nullable) $(TD
    $(LREF Nullable)
    $(LREF nullable)
    $(LREF NullableRef)
    $(LREF nullableRef)
))
$(TR $(TD Proxies) $(TD
    $(LREF Proxy)
    $(LREF rebindable)
    $(LREF Rebindable)
    $(LREF ReplaceType)
    $(LREF unwrap)
    $(LREF wrap)
))
$(TR $(TD Types) $(TD
    $(LREF alignForSize)
    $(LREF Ternary)
    $(LREF Typedef)
    $(LREF TypedefType)
    $(LREF UnqualRef)
))
))

Copyright: Copyright the respective authors, 2008-
License:   $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
Source:    $(PHOBOSSRC std/typecons.d)
Authors:   $(HTTP erdani.org, Andrei Alexandrescu),
           $(HTTP bartoszmilewski.wordpress.com, Bartosz Milewski),
           Don Clugston,
           Shin Fujishiro,
           Kenji Hara
 */
module std.typecons;

import std.format.spec : singleSpec, FormatSpec;
import std.format.write : formatValue;
import std.meta : AliasSeq, allSatisfy;
import std.range.primitives : isOutputRange;
import std.traits;
import std.internal.attributes : betterC;

/// Value tuples
@safe unittest
{
    alias Coord = Tuple!(int, "x", int, "y", int, "z");
    Coord c;
    c[1] = 1;       // access by index
    c.z = 1;        // access by given name
    assert(c == Coord(0, 1, 1));

    // names can be omitted, types can be mixed
    alias DictEntry = Tuple!(string, int);
    auto dict = DictEntry("seven", 7);

    // element types can be inferred
    assert(tuple(2, 3, 4)[1] == 3);
    // type inference works with names too
    auto tup = tuple!("x", "y", "z")(2, 3, 4);
    assert(tup.y == 3);
}

/// Rebindable references to const and immutable objects
@safe unittest
{
    class Widget
    {
        void foo() const @safe {}
    }
    const w1 = new Widget, w2 = new Widget;
    w1.foo();
    // w1 = w2 would not work; can't rebind const object

    auto r = Rebindable!(const Widget)(w1);
    // invoke method as if r were a Widget object
    r.foo();
    // rebind r to refer to another object
    r = w2;
}

/**
Encapsulates unique ownership of a resource.

When a `Unique!T` goes out of scope it will call `destroy`
on the resource `T` that it manages, unless it is transferred.
One important consequence of `destroy` is that it will call the
destructor of the resource `T`.  GC-managed references are not
guaranteed to be valid during a destructor call, but other members of
`T`, such as file handles or pointers to `malloc` memory, will
still be valid during the destructor call.  This allows the resource
`T` to deallocate or clean up any non-GC resources.

If it is desirable to persist a `Unique!T` outside of its original
scope, then it can be transferred.  The transfer can be explicit, by
calling `release`, or implicit, when returning Unique from a
function. The resource `T` can be a polymorphic class object or
instance of an interface, in which case Unique behaves polymorphically
too.

If `T` is a value type, then `Unique!T` will be implemented
as a reference to a `T`.
*/
struct Unique(T)
{
/** Represents a reference to `T`. Resolves to `T*` if `T` is a value type. */
static if (is(T == class) || is(T == interface))
    alias RefT = T;
else
    alias RefT = T*;

public:
    // Deferred in case we get some language support for checking uniqueness.
    version (None)
    /**
    Allows safe construction of `Unique`. It creates the resource and
    guarantees unique ownership of it (unless `T` publishes aliases of
    `this`).
    Note: Nested structs/classes cannot be created.
    Params:
    args = Arguments to pass to `T`'s constructor.
    ---
    static class C {}
    auto u = Unique!(C).create();
    ---
    */
    static Unique!T create(A...)(auto ref A args)
    if (__traits(compiles, new T(args)))
    {
        Unique!T u;
        u._p = new T(args);
        return u;
    }

    /**
    Constructor that takes an rvalue.
    It will ensure uniqueness, as long as the rvalue
    isn't just a view on an lvalue (e.g., a cast).
    Typical usage:
    ----
    Unique!Foo f = new Foo;
    ----
    */
    this(RefT p)
    {
        _p = p;
    }
    /**
    Constructor that takes an lvalue. It nulls its source.
    The nulling will ensure uniqueness as long as there
    are no previous aliases to the source.
    */
    this(ref RefT p)
    {
        _p = p;
        p = null;
        assert(p is null);
    }
    /**
    Constructor that takes a `Unique` of a type that is convertible to our type.

    Typically used to transfer a `Unique` rvalue of derived type to
    a `Unique` of base type.
    Example:
    ---
    class C : Object {}

    Unique!C uc = new C;
    Unique!Object uo = uc.release;
    ---
    */
    this(U)(Unique!U u)
    if (is(u.RefT:RefT))
    {
        _p = u._p;
        u._p = null;
    }

    /// Transfer ownership from a `Unique` of a type that is convertible to our type.
    void opAssign(U)(Unique!U u)
    if (is(u.RefT:RefT))
    {
        // first delete any resource we own
        destroy(this);
        _p = u._p;
        u._p = null;
    }

    ~this()
    {
        if (_p !is null)
        {
            destroy(_p);
            _p = null;
        }
    }

    /** Returns whether the resource exists. */
    @property bool isEmpty() const
    {
        return _p is null;
    }
    /** Transfer ownership to a `Unique` rvalue. Nullifies the current contents.
    Same as calling std.algorithm.move on it.
    */
    Unique release()
    {
        import std.algorithm.mutation : move;
        return this.move;
    }

    /** Forwards member access to contents. */
    mixin Proxy!_p;

    /**
    Postblit operator is undefined to prevent the cloning of `Unique` objects.
    */
    @disable this(this);

private:
    RefT _p;
}

///
@safe unittest
{
    static struct S
    {
        int i;
        this(int i){this.i = i;}
    }
    Unique!S produce()
    {
        // Construct a unique instance of S on the heap
        Unique!S ut = new S(5);
        // Implicit transfer of ownership
        return ut;
    }
    // Borrow a unique resource by ref
    void increment(ref Unique!S ur)
    {
        ur.i++;
    }
    void consume(Unique!S u2)
    {
        assert(u2.i == 6);
        // Resource automatically deleted here
    }
    Unique!S u1;
    assert(u1.isEmpty);
    u1 = produce();
    increment(u1);
    assert(u1.i == 6);
    //consume(u1); // Error: u1 is not copyable
    // Transfer ownership of the resource
    consume(u1.release);
    assert(u1.isEmpty);
}

@system unittest
{
    // test conversion to base ref
    int deleted = 0;
    class C
    {
        ~this(){deleted++;}
    }
    // constructor conversion
    Unique!Object u = Unique!C(new C);
    static assert(!__traits(compiles, {u = new C;}));
    assert(!u.isEmpty);
    destroy(u);
    assert(deleted == 1);

    Unique!C uc = new C;
    static assert(!__traits(compiles, {Unique!Object uo = uc;}));
    Unique!Object uo = new C;
    // opAssign conversion, deleting uo resource first
    uo = uc.release;
    assert(uc.isEmpty);
    assert(!uo.isEmpty);
    assert(deleted == 2);
}

@system unittest
{
    class Bar
    {
        ~this() { debug(Unique) writeln("    Bar destructor"); }
        int val() const { return 4; }
    }
    alias UBar = Unique!(Bar);
    UBar g(UBar u)
    {
        debug(Unique) writeln("inside g");
        return u.release;
    }
    auto ub = UBar(new Bar);
    assert(!ub.isEmpty);
    assert(ub.val == 4);
    static assert(!__traits(compiles, {auto ub3 = g(ub);}));
    auto ub2 = g(ub.release);
    assert(ub.isEmpty);
    assert(!ub2.isEmpty);
}

@system unittest
{
    interface Bar
    {
        int val() const;
    }
    class BarImpl : Bar
    {
        static int count;
        this()
        {
            count++;
        }
        ~this()
        {
            count--;
        }
        int val() const { return 4; }
    }
    alias UBar = Unique!Bar;
    UBar g(UBar u)
    {
        debug(Unique) writeln("inside g");
        return u.release;
    }
    void consume(UBar u)
    {
        assert(u.val() == 4);
        // Resource automatically deleted here
    }
    auto ub = UBar(new BarImpl);
    assert(BarImpl.count == 1);
    assert(!ub.isEmpty);
    assert(ub.val == 4);
    static assert(!__traits(compiles, {auto ub3 = g(ub);}));
    auto ub2 = g(ub.release);
    assert(ub.isEmpty);
    assert(!ub2.isEmpty);
    consume(ub2.release);
    assert(BarImpl.count == 0);
}

@safe unittest
{
    struct Foo
    {
        ~this() { }
        int val() const { return 3; }
        @disable this(this);
    }
    alias UFoo = Unique!(Foo);

    UFoo f(UFoo u)
    {
        return u.release;
    }

    auto uf = UFoo(new Foo);
    assert(!uf.isEmpty);
    assert(uf.val == 3);
    static assert(!__traits(compiles, {auto uf3 = f(uf);}));
    auto uf2 = f(uf.release);
    assert(uf.isEmpty);
    assert(!uf2.isEmpty);
}

// ensure Unique behaves correctly through const access paths
@system unittest
{
    struct Bar {int val;}
    struct Foo
    {
        Unique!Bar bar = new Bar;
    }

    Foo foo;
    foo.bar.val = 6;
    const Foo* ptr = &foo;
    static assert(is(typeof(ptr) == const(Foo*)));
    static assert(is(typeof(ptr.bar) == const(Unique!Bar)));
    static assert(is(typeof(ptr.bar.val) == const(int)));
    assert(ptr.bar.val == 6);
    foo.bar.val = 7;
    assert(ptr.bar.val == 7);
}

// Used in Tuple.toString
private template sharedToString(alias field)
if (is(typeof(field) == shared))
{
    static immutable sharedToString = typeof(field).stringof;
}

private template sharedToString(alias field)
if (!is(typeof(field) == shared))
{
    alias sharedToString = field;
}

private enum bool distinctFieldNames(names...) = __traits(compiles,
{
    static foreach (__name; names)
        static if (is(typeof(__name) : string))
            mixin("enum int " ~ __name ~ " = 0;");
});

@safe unittest
{
    static assert(!distinctFieldNames!(string, "abc", string, "abc"));
    static assert(distinctFieldNames!(string, "abc", int, "abd"));
    static assert(!distinctFieldNames!(int, "abc", string, "abd", int, "abc"));
    // https://issues.dlang.org/show_bug.cgi?id=19240
    static assert(!distinctFieldNames!(int, "int"));
}


// Parse (type,name) pairs (FieldSpecs) out of the specified
// arguments. Some fields would have name, others not.
private template parseSpecs(Specs...)
{
    static if (Specs.length == 0)
    {
        alias parseSpecs = AliasSeq!();
    }
    else static if (is(Specs[0]))
    {
        static if (is(typeof(Specs[1]) : string))
        {
            alias parseSpecs =
                AliasSeq!(FieldSpec!(Specs[0 .. 2]),
                          parseSpecs!(Specs[2 .. $]));
        }
        else
        {
            alias parseSpecs =
                AliasSeq!(FieldSpec!(Specs[0]),
                          parseSpecs!(Specs[1 .. $]));
        }
    }
    else
    {
        static assert(0, "Attempted to instantiate Tuple with an "
                        ~"invalid argument: "~ Specs[0].stringof);
    }
}

private template FieldSpec(T, string s = "")
{
    alias Type = T;
    alias name = s;
}

// Used with staticMap.
private alias extractType(alias spec) = spec.Type;
private alias extractName(alias spec) = spec.name;
private template expandSpec(alias spec)
{
    static if (spec.name.length == 0)
        alias expandSpec = AliasSeq!(spec.Type);
    else
        alias expandSpec = AliasSeq!(spec.Type, spec.name);
}


private enum areCompatibleTuples(Tup1, Tup2, string op) =
    isTuple!(OriginalType!Tup2) && Tup1.Types.length == Tup2.Types.length && is(typeof(
    (ref Tup1 tup1, ref Tup2 tup2)
    {
        static foreach (i; 0 .. Tup1.Types.length)
        {{
            auto lhs = typeof(tup1.field[i]).init;
            auto rhs = typeof(tup2.field[i]).init;
            static if (op == "=")
                lhs = rhs;
            else
                auto result = mixin("lhs "~op~" rhs");
        }}
    }));

private enum areBuildCompatibleTuples(Tup1, Tup2) =
    isTuple!Tup2 && Tup1.Types.length == Tup2.Types.length && is(typeof(
    {
        static foreach (i; 0 .. Tup1.Types.length)
            static assert(isBuildable!(Tup1.Types[i], Tup2.Types[i]));
    }));

// Returns `true` iff a `T` can be initialized from a `U`.
private enum isBuildable(T, U) = is(typeof(
    {
        U u = U.init;
        T t = u;
    }));
// Helper for partial instantiation
private template isBuildableFrom(U)
{
    enum isBuildableFrom(T) = isBuildable!(T, U);
}


/**
_Tuple of values, for example $(D Tuple!(int, string)) is a record that
stores an `int` and a `string`. `Tuple` can be used to bundle
values together, notably when returning multiple values from a
function. If `obj` is a `Tuple`, the individual members are
accessible with the syntax `obj[0]` for the first field, `obj[1]`
for the second, and so on.

See_Also: $(LREF tuple).

Params:
    Specs = A list of types (and optionally, member names) that the `Tuple` contains.
*/
template Tuple(Specs...)
if (distinctFieldNames!(Specs))
{
    import std.meta : staticMap;

    alias fieldSpecs = parseSpecs!Specs;

    // Generates named fields as follows:
    //    alias name_0 = Identity!(field[0]);
    //    alias name_1 = Identity!(field[1]);
    //      :
    // NOTE: field[k] is an expression (which yields a symbol of a
    //       variable) and can't be aliased directly.
    enum injectNamedFields = ()
    {
        string decl = "";
        static foreach (i, val; fieldSpecs)
        {{
            immutable si = i.stringof;
            decl ~= "alias _" ~ si ~ " = Identity!(field[" ~ si ~ "]);";
            if (val.name.length != 0)
            {
                decl ~= "alias " ~ val.name ~ " = _" ~ si ~ ";";
            }
        }}
        return decl;
    };

    // Returns Specs for a subtuple this[from .. to] preserving field
    // names if any.
    alias sliceSpecs(size_t from, size_t to) =
        staticMap!(expandSpec, fieldSpecs[from .. to]);

    struct Tuple
    {
        /**
         * The types of the `Tuple`'s components.
         */
        alias Types = staticMap!(extractType, fieldSpecs);

        private alias _Fields = Specs;

        ///
        static if (Specs.length == 0) @safe unittest
        {
            import std.meta : AliasSeq;
            alias Fields = Tuple!(int, "id", string, float);
            static assert(is(Fields.Types == AliasSeq!(int, string, float)));
        }

        /**
         * The names of the `Tuple`'s components. Unnamed fields have empty names.
         */
        alias fieldNames = staticMap!(extractName, fieldSpecs);

        ///
        static if (Specs.length == 0) @safe unittest
        {
            import std.meta : AliasSeq;
            alias Fields = Tuple!(int, "id", string, float);
            static assert(Fields.fieldNames == AliasSeq!("id", "", ""));
        }

        /**
         * Use `t.expand` for a `Tuple` `t` to expand it into its
         * components. The result of `expand` acts as if the `Tuple`'s components
         * were listed as a list of values. (Ordinarily, a `Tuple` acts as a
         * single value.)
         */
        Types expand;
        mixin(injectNamedFields());

        ///
        static if (Specs.length == 0) @safe unittest
        {
            auto t1 = tuple(1, " hello ", 'a');
            assert(t1.toString() == `Tuple!(int, string, char)(1, " hello ", 'a')`);

            void takeSeveralTypes(int n, string s, bool b)
            {
                assert(n == 4 && s == "test" && b == false);
            }

            auto t2 = tuple(4, "test", false);
            //t.expand acting as a list of values
            takeSeveralTypes(t2.expand);
        }

        static if (is(Specs))
        {
            // This is mostly to make t[n] work.
            alias expand this;
        }
        else
        {
            @property
            ref inout(Tuple!Types) _Tuple_super() inout @trusted
            {
                static foreach (i; 0 .. Types.length)   // Rely on the field layout
                {
                    static assert(typeof(return).init.tupleof[i].offsetof ==
                                                       expand[i].offsetof);
                }
                return *cast(typeof(return)*) &(field[0]);
            }
            // This is mostly to make t[n] work.
            alias _Tuple_super this;
        }

        // backwards compatibility
        alias field = expand;

        /**
         * Constructor taking one value for each field.
         *
         * Params:
         *     values = A list of values that are either the same
         *              types as those given by the `Types` field
         *              of this `Tuple`, or can implicitly convert
         *              to those types. They must be in the same
         *              order as they appear in `Types`.
         */
        static if (Types.length > 0)
        {
            this(Types values)
            {
                field[] = values[];
            }
        }

        ///
        static if (Specs.length == 0) @safe unittest
        {
            alias ISD = Tuple!(int, string, double);
            auto tup = ISD(1, "test", 3.2);
            assert(tup.toString() == `Tuple!(int, string, double)(1, "test", 3.2)`);
        }

        /**
         * Constructor taking a compatible array.
         *
         * Params:
         *     values = A compatible static array to build the `Tuple` from.
         *              Array slices are not supported.
         */
        this(U, size_t n)(U[n] values)
        if (n == Types.length && allSatisfy!(isBuildableFrom!U, Types))
        {
            static foreach (i; 0 .. Types.length)
            {
                field[i] = values[i];
            }
        }

        ///
        static if (Specs.length == 0) @safe unittest
        {
            int[2] ints;
            Tuple!(int, int) t = ints;
        }

        /**
         * Constructor taking a compatible `Tuple`. Two `Tuple`s are compatible
         * $(B iff) they are both of the same length, and, for each type `T` on the
         * left-hand side, the corresponding type `U` on the right-hand side can
         * implicitly convert to `T`.
         *
         * Params:
         *     another = A compatible `Tuple` to build from. Its type must be
         *               compatible with the target `Tuple`'s type.
         */
        this(U)(U another)
        if (areBuildCompatibleTuples!(typeof(this), U))
        {
            field[] = another.field[];
        }

        ///
        static if (Specs.length == 0) @safe unittest
        {
            alias IntVec = Tuple!(int, int, int);
            alias DubVec = Tuple!(double, double, double);

            IntVec iv = tuple(1, 1, 1);

            //Ok, int can implicitly convert to double
            DubVec dv = iv;
            //Error: double cannot implicitly convert to int
            //IntVec iv2 = dv;
        }

        /**
         * Comparison for equality. Two `Tuple`s are considered equal
         * $(B iff) they fulfill the following criteria:
         *
         * $(UL
         *   $(LI Each `Tuple` is the same length.)
         *   $(LI For each type `T` on the left-hand side and each type
         *        `U` on the right-hand side, values of type `T` can be
         *        compared with values of type `U`.)
         *   $(LI For each value `v1` on the left-hand side and each value
         *        `v2` on the right-hand side, the expression `v1 == v2` is
         *        true.))
         *
         * Params:
         *     rhs = The `Tuple` to compare against. It must meeting the criteria
         *           for comparison between `Tuple`s.
         *
         * Returns:
         *     true if both `Tuple`s are equal, otherwise false.
         */
        bool opEquals(R)(R rhs)
        if (areCompatibleTuples!(typeof(this), R, "=="))
        {
            return field[] == rhs.field[];
        }

        /// ditto
        bool opEquals(R)(R rhs) const
        if (areCompatibleTuples!(typeof(this), R, "=="))
        {
            return field[] == rhs.field[];
        }

        /// ditto
        bool opEquals(R...)(auto ref R rhs)
        if (R.length > 1 && areCompatibleTuples!(typeof(this), Tuple!R, "=="))
        {
            static foreach (i; 0 .. Types.length)
                if (field[i] != rhs[i])
                    return false;

            return true;
        }

        ///
        static if (Specs.length == 0) @safe unittest
        {
            Tuple!(int, string) t1 = tuple(1, "test");
            Tuple!(double, string) t2 =  tuple(1.0, "test");
            //Ok, int can be compared with double and
            //both have a value of 1
            assert(t1 == t2);
        }

        /**
         * Comparison for ordering.
         *
         * Params:
         *     rhs = The `Tuple` to compare against. It must meet the criteria
         *           for comparison between `Tuple`s.
         *
         * Returns:
         * For any values `v1` contained by the left-hand side tuple and any
         * values `v2` contained by the right-hand side:
         *
         * 0 if `v1 == v2` for all members or the following value for the
         * first position were the mentioned criteria is not satisfied:
         *
         * $(UL
         *   $(LI NaN, in case one of the operands is a NaN.)
         *   $(LI A negative number if the expression `v1 < v2` is true.)
         *   $(LI A positive number if the expression `v1 > v2` is true.))
         */
        auto opCmp(R)(R rhs)
        if (areCompatibleTuples!(typeof(this), R, "<"))
        {
            static foreach (i; 0 .. Types.length)
            {
                if (field[i] != rhs.field[i])
                {
                    import std.math.traits : isNaN;
                    static if (isFloatingPoint!(Types[i]))
                    {
                        if (isNaN(field[i]))
                            return float.nan;
                    }
                    static if (isFloatingPoint!(typeof(rhs.field[i])))
                    {
                        if (isNaN(rhs.field[i]))
                            return float.nan;
                    }
                    static if (is(typeof(field[i].opCmp(rhs.field[i]))) &&
                               isFloatingPoint!(typeof(field[i].opCmp(rhs.field[i]))))
                    {
                        if (isNaN(field[i].opCmp(rhs.field[i])))
                            return float.nan;
                    }

                    return field[i] < rhs.field[i] ? -1 : 1;
                }
            }
            return 0;
        }

        /// ditto
        auto opCmp(R)(R rhs) const
        if (areCompatibleTuples!(typeof(this), R, "<"))
        {
            static foreach (i; 0 .. Types.length)
            {
                if (field[i] != rhs.field[i])
                {
                    import std.math.traits : isNaN;
                    static if (isFloatingPoint!(Types[i]))
                    {
                        if (isNaN(field[i]))
                            return float.nan;
                    }
                    static if (isFloatingPoint!(typeof(rhs.field[i])))
                    {
                        if (isNaN(rhs.field[i]))
                            return float.nan;
                    }
                    static if (is(typeof(field[i].opCmp(rhs.field[i]))) &&
                               isFloatingPoint!(typeof(field[i].opCmp(rhs.field[i]))))
                    {
                        if (isNaN(field[i].opCmp(rhs.field[i])))
                            return float.nan;
                    }

                    return field[i] < rhs.field[i] ? -1 : 1;
                }
            }
            return 0;
        }

        /**
            The first `v1` for which `v1 > v2` is true determines
            the result. This could lead to unexpected behaviour.
         */
        static if (Specs.length == 0) @safe unittest
        {
            auto tup1 = tuple(1, 1, 1);
            auto tup2 = tuple(1, 100, 100);
            assert(tup1 < tup2);

            //Only the first result matters for comparison
            tup1[0] = 2;
            assert(tup1 > tup2);
        }

        /**
         Concatenate Tuples.
         Tuple concatenation is only allowed if all named fields are distinct (no named field of this tuple occurs in `t`
         and no named field of `t` occurs in this tuple).

         Params:
             t = The `Tuple` to concatenate with

         Returns: A concatenation of this tuple and `t`
         */
        auto opBinary(string op, T)(auto ref T t)
        if (op == "~" && !(is(T : U[], U) && isTuple!U))
        {
            static if (isTuple!T)
            {
                static assert(distinctFieldNames!(_Fields, T._Fields),
                    "Cannot concatenate tuples with duplicate fields: " ~ fieldNames.stringof ~
                    " - " ~ T.fieldNames.stringof);
                return Tuple!(_Fields, T._Fields)(expand, t.expand);
            }
            else
            {
                return Tuple!(_Fields, T)(expand, t);
            }
        }

        /// ditto
        auto opBinaryRight(string op, T)(auto ref T t)
        if (op == "~" && !(is(T : U[], U) && isTuple!U))
        {
            static if (isTuple!T)
            {
                static assert(distinctFieldNames!(_Fields, T._Fields),
                    "Cannot concatenate tuples with duplicate fields: " ~ T.stringof ~
                    " - " ~ fieldNames.fieldNames.stringof);
                return Tuple!(T._Fields, _Fields)(t.expand, expand);
            }
            else
            {
                return Tuple!(T, _Fields)(t, expand);
            }
        }

        /**
         * Assignment from another `Tuple`.
         *
         * Params:
         *     rhs = The source `Tuple` to assign from. Each element of the
         *           source `Tuple` must be implicitly assignable to each
         *           respective element of the target `Tuple`.
         */
        ref Tuple opAssign(R)(auto ref R rhs)
        if (areCompatibleTuples!(typeof(this), R, "="))
        {
            import std.algorithm.mutation : swap;

            static if (is(R : Tuple!Types) && !__traits(isRef, rhs) && isTuple!R)
            {
                if (__ctfe)
                {
                    // Cannot use swap at compile time
                    field[] = rhs.field[];
                }
                else
                {
                    // Use swap-and-destroy to optimize rvalue assignment
                    swap!(Tuple!Types)(this, rhs);
                }
            }
            else
            {
                // Do not swap; opAssign should be called on the fields.
                field[] = rhs.field[];
            }
            return this;
        }

        /**
         * Renames the elements of a $(LREF Tuple).
         *
         * `rename` uses the passed `names` and returns a new
         * $(LREF Tuple) using these names, with the content
         * unchanged.
         * If fewer names are passed than there are members
         * of the $(LREF Tuple) then those trailing members are unchanged.
         * An empty string will remove the name for that member.
         * It is an compile-time error to pass more names than
         * there are members of the $(LREF Tuple).
         */
        ref rename(names...)() inout return
        if (names.length == 0 || allSatisfy!(isSomeString, typeof(names)))
        {
            import std.algorithm.comparison : equal;
            // to circumvent https://issues.dlang.org/show_bug.cgi?id=16418
            static if (names.length == 0 || equal([names], [fieldNames]))
                return this;
            else
            {
                enum nT = Types.length;
                enum nN = names.length;
                static assert(nN <= nT, "Cannot have more names than tuple members");
                alias allNames = AliasSeq!(names, fieldNames[nN .. $]);

                import std.meta : Alias, aliasSeqOf;

                template GetItem(size_t idx)
                {
                    import std.array : empty;
                    static if (idx < nT)
                        alias GetItem = Alias!(Types[idx]);
                    else static if (allNames[idx - nT].empty)
                        alias GetItem = AliasSeq!();
                    else
                        alias GetItem = Alias!(allNames[idx - nT]);
                }

                import std.range : roundRobin, iota;
                alias NewTupleT = Tuple!(staticMap!(GetItem, aliasSeqOf!(
                        roundRobin(iota(nT), iota(nT, 2*nT)))));
                return *(() @trusted => cast(NewTupleT*)&this)();
            }
        }

        ///
        static if (Specs.length == 0) @safe unittest
        {
            auto t0 = tuple(4, "hello");

            auto t0Named = t0.rename!("val", "tag");
            assert(t0Named.val == 4);
            assert(t0Named.tag == "hello");

            Tuple!(float, "dat", size_t[2], "pos") t1;
            t1.pos = [2, 1];
            auto t1Named = t1.rename!"height";
            t1Named.height = 3.4f;
            assert(t1Named.height == 3.4f);
            assert(t1Named.pos == [2, 1]);
            t1Named.rename!"altitude".altitude = 5;
            assert(t1Named.height == 5);

            Tuple!(int, "a", int, int, "c") t2;
            t2 = tuple(3,4,5);
            auto t2Named = t2.rename!("", "b");
            // "a" no longer has a name
            static assert(!__traits(hasMember, typeof(t2Named), "a"));
            assert(t2Named[0] == 3);
            assert(t2Named.b == 4);
            assert(t2Named.c == 5);

            // not allowed to specify more names than the tuple has members
            static assert(!__traits(compiles, t2.rename!("a","b","c","d")));

            // use it in a range pipeline
            import std.range : iota, zip;
            import std.algorithm.iteration : map, sum;
            auto res = zip(iota(1, 4), iota(10, 13))
                .map!(t => t.rename!("a", "b"))
                .map!(t => t.a * t.b)
                .sum;
            assert(res == 68);

            const tup = Tuple!(int, "a", int, "b")(2, 3);
            const renamed = tup.rename!("c", "d");
            assert(renamed.c + renamed.d == 5);
        }

        /**
         * Overload of $(LREF _rename) that takes an associative array
         * `translate` as a template parameter, where the keys are
         * either the names or indices of the members to be changed
         * and the new names are the corresponding values.
         * Every key in `translate` must be the name of a member of the
         * $(LREF tuple).
         * The same rules for empty strings apply as for the variadic
         * template overload of $(LREF _rename).
        */
        ref rename(alias translate)() inout
        if (is(typeof(translate) : V[K], V, K) && isSomeString!V &&
                (isSomeString!K || is(K : size_t)))
        {
            import std.meta : aliasSeqOf;
            import std.range : ElementType;
            static if (isSomeString!(ElementType!(typeof(translate.keys))))
            {
                {
                    import std.conv : to;
                    import std.algorithm.iteration : filter;
                    import std.algorithm.searching : canFind;
                    enum notFound = translate.keys
                        .filter!(k => fieldNames.canFind(k) == -1);
                    static assert(notFound.empty, "Cannot find members "
                        ~ notFound.to!string ~ " in type "
                        ~ typeof(this).stringof);
                }
                return this.rename!(aliasSeqOf!(
                    {
                        import std.array : empty;
                        auto names = [fieldNames];
                        foreach (ref n; names)
                            if (!n.empty)
                                if (auto p = n in translate)
                                    n = *p;
                        return names;
                    }()));
            }
            else
            {
                {
                    import std.algorithm.iteration : filter;
                    import std.conv : to;
                    enum invalid = translate.keys.
                        filter!(k => k < 0 || k >= this.length);
                    static assert(invalid.empty, "Indices " ~ invalid.to!string
                        ~ " are out of bounds for tuple with length "
                        ~ this.length.to!string);
                }
                return this.rename!(aliasSeqOf!(
                    {
                        auto names = [fieldNames];
                        foreach (k, v; translate)
                            names[k] = v;
                        return names;
                    }()));
            }
        }

        ///
        static if (Specs.length == 0) @safe unittest
        {
            //replacing names by their current name

            Tuple!(float, "dat", size_t[2], "pos") t1;
            t1.pos = [2, 1];
            auto t1Named = t1.rename!(["dat": "height"]);
            t1Named.height = 3.4;
            assert(t1Named.pos == [2, 1]);
            t1Named.rename!(["height": "altitude"]).altitude = 5;
            assert(t1Named.height == 5);

            Tuple!(int, "a", int, "b") t2;
            t2 = tuple(3, 4);
            auto t2Named = t2.rename!(["a": "b", "b": "c"]);
            assert(t2Named.b == 3);
            assert(t2Named.c == 4);

            const t3 = Tuple!(int, "a", int, "b")(3, 4);
            const t3Named = t3.rename!(["a": "b", "b": "c"]);
            assert(t3Named.b == 3);
            assert(t3Named.c == 4);
        }

        ///
        static if (Specs.length == 0) @safe unittest
        {
            //replace names by their position

            Tuple!(float, "dat", size_t[2], "pos") t1;
            t1.pos = [2, 1];
            auto t1Named = t1.rename!([0: "height"]);
            t1Named.height = 3.4;
            assert(t1Named.pos == [2, 1]);
            t1Named.rename!([0: "altitude"]).altitude = 5;
            assert(t1Named.height == 5);

            Tuple!(int, "a", int, "b", int, "c") t2;
            t2 = tuple(3, 4, 5);
            auto t2Named = t2.rename!([0: "c", 2: "a"]);
            assert(t2Named.a == 5);
            assert(t2Named.b == 4);
            assert(t2Named.c == 3);
        }

        static if (Specs.length == 0) @safe unittest
        {
            //check that empty translations work fine
            enum string[string] a0 = null;
            enum string[int] a1 = null;
            Tuple!(float, "a", float, "b") t0;

            auto t1 = t0.rename!a0;

            t1.a = 3;
            t1.b = 4;
            auto t2 = t0.rename!a1;
            t2.a = 3;
            t2.b = 4;
            auto t3 = t0.rename;
            t3.a = 3;
            t3.b = 4;
        }

        /**
         * Takes a slice by-reference of this `Tuple`.
         *
         * Params:
         *     from = A `size_t` designating the starting position of the slice.
         *     to = A `size_t` designating the ending position (exclusive) of the slice.
         *
         * Returns:
         *     A new `Tuple` that is a slice from `[from, to$(RPAREN)` of the original.
         *     It has the same types and values as the range `[from, to$(RPAREN)` in
         *     the original.
         */
        @property
        ref inout(Tuple!(sliceSpecs!(from, to))) slice(size_t from, size_t to)() inout @trusted
        if (from <= to && to <= Types.length)
        {
            static assert(
                (typeof(this).alignof % typeof(return).alignof == 0) &&
                (expand[from].offsetof % typeof(return).alignof == 0),
                "Slicing by reference is impossible because of an alignment mistmatch" ~
                " (See https://issues.dlang.org/show_bug.cgi?id=15645).");

            return *cast(typeof(return)*) &(field[from]);
        }

        ///
        static if (Specs.length == 0) @safe unittest
        {
            Tuple!(int, string, float, double) a;
            a[1] = "abc";
            a[2] = 4.5;
            auto s = a.slice!(1, 3);
            static assert(is(typeof(s) == Tuple!(string, float)));
            assert(s[0] == "abc" && s[1] == 4.5);

            // https://issues.dlang.org/show_bug.cgi?id=15645
            Tuple!(int, short, bool, double) b;
            static assert(!__traits(compiles, b.slice!(2, 4)));
        }

        /**
            Creates a hash of this `Tuple`.

            Returns:
                A `size_t` representing the hash of this `Tuple`.
         */
        size_t toHash() const nothrow @safe
        {
            size_t h = 0;
            static foreach (i, T; Types)
            {{
                static if (__traits(compiles, h = .hashOf(field[i])))
                    const k = .hashOf(field[i]);
                else
                {
                    // Workaround for when .hashOf is not both @safe and nothrow.
                    static if (is(T : shared U, U) && __traits(compiles, (U* a) nothrow @safe => .hashOf(*a))
                            && !__traits(hasMember, T, "toHash"))
                        // BUG: Improperly casts away `shared`!
                        const k = .hashOf(*(() @trusted => cast(U*) &field[i])());
                    else
                        // BUG: Improperly casts away `shared`!
                        const k = typeid(T).getHash((() @trusted => cast(const void*) &field[i])());
                }
                static if (i == 0)
                    h = k;
                else
                    // As in boost::hash_combine
                    // https://www.boost.org/doc/libs/1_55_0/doc/html/hash/reference.html#boost.hash_combine
                    h ^= k + 0x9e3779b9 + (h << 6) + (h >>> 2);
            }}
            return h;
        }

        /**
         * Converts to string.
         *
         * Returns:
         *     The string representation of this `Tuple`.
         */
        string toString()() const
        {
            import std.array : appender;
            auto app = appender!string();
            this.toString((const(char)[] chunk) => app ~= chunk);
            return app.data;
        }

        import std.format.spec : FormatSpec;

        /**
         * Formats `Tuple` with either `%s`, `%(inner%)` or `%(inner%|sep%)`.
         *
         * $(TABLE2 Formats supported by Tuple,
         * $(THEAD Format, Description)
         * $(TROW $(P `%s`), $(P Format like `Tuple!(types)(elements formatted with %s each)`.))
         * $(TROW $(P `%(inner%)`), $(P The format `inner` is applied the expanded `Tuple`$(COMMA) so
         *      it may contain as many formats as the `Tuple` has fields.))
         * $(TROW $(P `%(inner%|sep%)`), $(P The format `inner` is one format$(COMMA) that is applied
         *      on all fields of the `Tuple`. The inner format must be compatible to all
         *      of them.)))
         *
         * Params:
         *     sink = A `char` accepting delegate
         *     fmt = A $(REF FormatSpec, std,format)
         */
        void toString(DG)(scope DG sink) const
        {
            auto f = FormatSpec!char();
            toString(sink, f);
        }

        /// ditto
        void toString(DG, Char)(scope DG sink, scope const ref FormatSpec!Char fmt) const
        {
            import std.format : format, FormatException;
            import std.format.write : formattedWrite;
            import std.range : only;
            if (fmt.nested)
            {
                if (fmt.sep)
                {
                    foreach (i, Type; Types)
                    {
                        static if (i > 0)
                        {
                            sink(fmt.sep);
                        }
                        // TODO: Change this once formattedWrite() works for shared objects.
                        static if (is(Type == class) && is(Type == shared))
                        {
                            sink(Type.stringof);
                        }
                        else
                        {
                            formattedWrite(sink, fmt.nested, this.field[i]);
                        }
                    }
                }
                else
                {
                    formattedWrite(sink, fmt.nested, staticMap!(sharedToString, this.expand));
                }
            }
            else if (fmt.spec == 's')
            {
                enum header = Unqual!(typeof(this)).stringof ~ "(",
                     footer = ")",
                     separator = ", ";
                sink(header);
                foreach (i, Type; Types)
                {
                    static if (i > 0)
                    {
                        sink(separator);
                    }
                    // TODO: Change this once format() works for shared objects.
                    static if (is(Type == class) && is(Type == shared))
                    {
                        sink(Type.stringof);
                    }
                    else
                    {
                        sink(format!("%(%s%)")(only(field[i])));
                    }
                }
                sink(footer);
            }
            else
            {
                const spec = fmt.spec;
                throw new FormatException(
                    "Expected '%s' or '%(...%)' or '%(...%|...%)' format specifier for type '" ~
                        Unqual!(typeof(this)).stringof ~ "', not '%" ~ spec ~ "'.");
            }
        }

        ///
        static if (Specs.length == 0) @safe unittest
        {
            import std.format : format;

            Tuple!(int, double)[3] tupList = [ tuple(1, 1.0), tuple(2, 4.0), tuple(3, 9.0) ];

            // Default format
            assert(format("%s", tuple("a", 1)) == `Tuple!(string, int)("a", 1)`);

            // One Format for each individual component
            assert(format("%(%#x v %.4f w %#x%)", tuple(1, 1.0, 10))         == `0x1 v 1.0000 w 0xa`);
            assert(format(  "%#x v %.4f w %#x"  , tuple(1, 1.0, 10).expand)  == `0x1 v 1.0000 w 0xa`);

            // One Format for all components
            assert(format("%(>%s<%| & %)", tuple("abc", 1, 2.3, [4, 5])) == `>abc< & >1< & >2.3< & >[4, 5]<`);

            // Array of Tuples
            assert(format("%(%(f(%d) = %.1f%);  %)", tupList) == `f(1) = 1.0;  f(2) = 4.0;  f(3) = 9.0`);
        }

        ///
        static if (Specs.length == 0) @safe unittest
        {
            import std.exception : assertThrown;
            import std.format : format, FormatException;

            // Error: %( %) missing.
            assertThrown!FormatException(
                format("%d, %f", tuple(1, 2.0)) == `1, 2.0`
            );

            // Error: %( %| %) missing.
            assertThrown!FormatException(
                format("%d", tuple(1, 2)) == `1, 2`
            );

            // Error: %d inadequate for double
            assertThrown!FormatException(
                format("%(%d%|, %)", tuple(1, 2.0)) == `1, 2.0`
            );
        }
    }
}

///
@safe unittest
{
    Tuple!(int, int) point;
    // assign coordinates
    point[0] = 5;
    point[1] = 6;
    // read coordinates
    auto x = point[0];
    auto y = point[1];
}

/**
    `Tuple` members can be named. It is legal to mix named and unnamed
    members. The method above is still applicable to all fields.
 */
@safe unittest
{
    alias Entry = Tuple!(int, "index", string, "value");
    Entry e;
    e.index = 4;
    e.value = "Hello";
    assert(e[1] == "Hello");
    assert(e[0] == 4);
}

/**
    A `Tuple` with named fields is a distinct type from a `Tuple` with unnamed
    fields, i.e. each naming imparts a separate type for the `Tuple`. Two
    `Tuple`s differing in naming only are still distinct, even though they
    might have the same structure.
 */
@safe unittest
{
    Tuple!(int, "x", int, "y") point1;
    Tuple!(int, int) point2;
    assert(!is(typeof(point1) == typeof(point2)));
}

/// Use tuples as ranges
@safe unittest
{
    import std.algorithm.iteration : sum;
    import std.range : only;
    auto t = tuple(1, 2);
    assert(t.expand.only.sum == 3);
}

// https://issues.dlang.org/show_bug.cgi?id=4582
@safe unittest
{
    static assert(!__traits(compiles, Tuple!(string, "id", int, "id")));
    static assert(!__traits(compiles, Tuple!(string, "str", int, "i", string, "str", float)));
}

/// Concatenate tuples
@safe unittest
{
    import std.meta : AliasSeq;
    auto t = tuple(1, "2") ~ tuple(ushort(42), true);
    static assert(is(t.Types == AliasSeq!(int, string, ushort, bool)));
    assert(t[1] == "2");
    assert(t[2] == 42);
    assert(t[3] == true);
}

// https://issues.dlang.org/show_bug.cgi?id=14637
// tuple concat
@safe unittest
{
    auto t = tuple!"foo"(1.0) ~ tuple!"bar"("3");
    static assert(is(t.Types == AliasSeq!(double, string)));
    static assert(t.fieldNames == tuple("foo", "bar"));
    assert(t.foo == 1.0);
    assert(t.bar == "3");
}

// https://issues.dlang.org/show_bug.cgi?id=18824
// tuple concat
@safe unittest
{
    alias Type = Tuple!(int, string);
    Type[] arr;
    auto t = tuple(2, "s");
    // Test opBinaryRight
    arr = arr ~ t;
    // Test opBinary
    arr = t ~ arr;
    static assert(is(typeof(arr) == Type[]));
    immutable Type[] b;
    auto c = b ~ t;
    static assert(is(typeof(c) == immutable(Type)[]));
}

// tuple concat
@safe unittest
{
    auto t = tuple!"foo"(1.0) ~ "3";
    static assert(is(t.Types == AliasSeq!(double, string)));
    assert(t.foo == 1.0);
    assert(t[1]== "3");
}

// tuple concat
@safe unittest
{
    auto t = "2" ~ tuple!"foo"(1.0);
    static assert(is(t.Types == AliasSeq!(string, double)));
    assert(t.foo == 1.0);
    assert(t[0]== "2");
}

// tuple concat
@safe unittest
{
    auto t = "2" ~ tuple!"foo"(1.0) ~ tuple(42, 3.0f) ~ real(1) ~ "a";
    static assert(is(t.Types == AliasSeq!(string, double, int, float, real, string)));
    assert(t.foo == 1.0);
    assert(t[0] == "2");
    assert(t[1] == 1.0);
    assert(t[2] == 42);
    assert(t[3] == 3.0f);
    assert(t[4] == 1.0);
    assert(t[5] == "a");
}

// ensure that concatenation of tuples with non-distinct fields is forbidden
@safe unittest
{
    static assert(!__traits(compiles,
        tuple!("a")(0) ~ tuple!("a")("1")));
    static assert(!__traits(compiles,
        tuple!("a", "b")(0, 1) ~ tuple!("b", "a")("3", 1)));
    static assert(!__traits(compiles,
        tuple!("a")(0) ~ tuple!("b", "a")("3", 1)));
    static assert(!__traits(compiles,
        tuple!("a1", "a")(1.0, 0) ~ tuple!("a2", "a")("3", 0)));
}

// Ensure that Tuple comparison with non-const opEquals works
@safe unittest
{
    static struct Bad
    {
        int a;

        bool opEquals(Bad b)
        {
            return a == b.a;
        }
    }

    auto t = Tuple!(int, Bad, string)(1, Bad(1), "asdf");

    //Error: mutable method Bad.opEquals is not callable using a const object
    assert(t == AliasSeq!(1, Bad(1), "asdf"));
}

// Ensure Tuple.toHash works
@safe unittest
{
    Tuple!(int, int) point;
    assert(point.toHash == typeof(point).init.toHash);
    assert(tuple(1, 2) != point);
    assert(tuple(1, 2) == tuple(1, 2));
    point[0] = 1;
    assert(tuple(1, 2) != point);
    point[1] = 2;
    assert(tuple(1, 2) == point);
}

@safe @betterC unittest
{
    auto t = tuple(1, 2);
    assert(t == tuple(1, 2));
    auto t3 = tuple(1, 'd');
}

// https://issues.dlang.org/show_bug.cgi?id=20850
// Assignment to enum tuple
@safe unittest
{
    enum T : Tuple!(int*) { a = T(null) }
    T t;
    t = T.a;
}

// https://issues.dlang.org/show_bug.cgi?id=13663
@safe unittest
{
    auto t = tuple(real.nan);
    assert(!(t > t));
    assert(!(t < t));
    assert(!(t == t));
}

@safe unittest
{
    struct S
    {
        float opCmp(S s) { return float.nan; }
        bool opEquals(S s) { return false; }
    }

    auto t = tuple(S());
    assert(!(t > t));
    assert(!(t < t));
    assert(!(t == t));
}

// https://issues.dlang.org/show_bug.cgi?id=8015
@safe unittest
{
    struct MyStruct
    {
        string str;
        @property string toStr()
        {
            return str;
        }
        alias toStr this;
    }

    Tuple!(MyStruct) t;
}

/**
    Creates a copy of a $(LREF Tuple) with its fields in _reverse order.

    Params:
        t = The `Tuple` to copy.

    Returns:
        A new `Tuple`.
 */
auto reverse(T)(T t)
if (isTuple!T)
{
    import std.meta : Reverse;
    // @@@BUG@@@ Cannot be an internal function due to forward reference issues.

    // @@@BUG@@@ 9929 Need 'this' when calling template with expanded tuple
    // return tuple(Reverse!(t.expand));

    ReverseTupleType!T result;
    auto tup = t.expand;
    result.expand = Reverse!tup;
    return result;
}

///
@safe unittest
{
    auto tup = tuple(1, "2");
    assert(tup.reverse == tuple("2", 1));
}

/* Get a Tuple type with the reverse specification of Tuple T. */
private template ReverseTupleType(T)
if (isTuple!T)
{
    static if (is(T : Tuple!A, A...))
        alias ReverseTupleType = Tuple!(ReverseTupleSpecs!A);
}

/* Reverse the Specs of a Tuple. */
private template ReverseTupleSpecs(T...)
{
    static if (T.length > 1)
    {
        static if (is(typeof(T[$-1]) : string))
        {
            alias ReverseTupleSpecs = AliasSeq!(T[$-2], T[$-1], ReverseTupleSpecs!(T[0 .. $-2]));
        }
        else
        {
            alias ReverseTupleSpecs = AliasSeq!(T[$-1], ReverseTupleSpecs!(T[0 .. $-1]));
        }
    }
    else
    {
        alias ReverseTupleSpecs = T;
    }
}

// ensure that internal Tuple unittests are compiled
@safe unittest
{
    Tuple!() t;
}

@safe unittest
{
    import std.conv;
    {
        Tuple!(int, "a", int, "b") nosh;
        static assert(nosh.length == 2);
        nosh.a = 5;
        nosh.b = 6;
        assert(nosh.a == 5);
        assert(nosh.b == 6);
    }
    {
        Tuple!(short, double) b;
        static assert(b.length == 2);
        b[1] = 5;
        auto a = Tuple!(int, real)(b);
        assert(a[0] == 0 && a[1] == 5);
        a = Tuple!(int, real)(1, 2);
        assert(a[0] == 1 && a[1] == 2);
        auto c = Tuple!(int, "a", double, "b")(a);
        assert(c[0] == 1 && c[1] == 2);
    }
    {
        Tuple!(int, real) nosh;
        nosh[0] = 5;
        nosh[1] = 0;
        assert(nosh[0] == 5 && nosh[1] == 0);
        assert(nosh.to!string == "Tuple!(int, real)(5, 0)", nosh.to!string);
        Tuple!(int, int) yessh;
        nosh = yessh;
    }
    {
        class A {}
        Tuple!(int, shared A) nosh;
        nosh[0] = 5;
        assert(nosh[0] == 5 && nosh[1] is null);
        assert(nosh.to!string == "Tuple!(int, shared(A))(5, shared(A))");
    }
    {
        Tuple!(int, string) t;
        t[0] = 10;
        t[1] = "str";
        assert(t[0] == 10 && t[1] == "str");
        assert(t.to!string == `Tuple!(int, string)(10, "str")`, t.to!string);
    }
    {
        Tuple!(int, "a", double, "b") x;
        static assert(x.a.offsetof == x[0].offsetof);
        static assert(x.b.offsetof == x[1].offsetof);
        x.b = 4.5;
        x.a = 5;
        assert(x[0] == 5 && x[1] == 4.5);
        assert(x.a == 5 && x.b == 4.5);
    }
    // indexing
    {
        Tuple!(int, real) t;
        static assert(is(typeof(t[0]) == int));
        static assert(is(typeof(t[1]) == real));
        int* p0 = &t[0];
        real* p1 = &t[1];
        t[0] = 10;
        t[1] = -200.0L;
        assert(*p0 == t[0]);
        assert(*p1 == t[1]);
    }
    // slicing
    {
        Tuple!(int, "x", real, "y", double, "z", string) t;
        t[0] = 10;
        t[1] = 11;
        t[2] = 12;
        t[3] = "abc";
        auto a = t.slice!(0, 3);
        assert(a.length == 3);
        assert(a.x == t.x);
        assert(a.y == t.y);
        assert(a.z == t.z);
        auto b = t.slice!(2, 4);
        assert(b.length == 2);
        assert(b.z == t.z);
        assert(b[1] == t[3]);
    }
    // nesting
    {
        Tuple!(Tuple!(int, real), Tuple!(string, "s")) t;
        static assert(is(typeof(t[0]) == Tuple!(int, real)));
        static assert(is(typeof(t[1]) == Tuple!(string, "s")));
        static assert(is(typeof(t[0][0]) == int));
        static assert(is(typeof(t[0][1]) == real));
        static assert(is(typeof(t[1].s) == string));
        t[0] = tuple(10, 20.0L);
        t[1].s = "abc";
        assert(t[0][0] == 10);
        assert(t[0][1] == 20.0L);
        assert(t[1].s == "abc");
    }
    // non-POD
    {
        static struct S
        {
            int count;
            this(this) { ++count; }
            ~this() { --count; }
            void opAssign(S rhs) { count = rhs.count; }
        }
        Tuple!(S, S) ss;
        Tuple!(S, S) ssCopy = ss;
        assert(ssCopy[0].count == 1);
        assert(ssCopy[1].count == 1);
        ssCopy[1] = ssCopy[0];
        assert(ssCopy[1].count == 2);
    }
    // https://issues.dlang.org/show_bug.cgi?id=2800
    {
        static struct R
        {
            Tuple!(int, int) _front;
            @property ref Tuple!(int, int) front() return { return _front;  }
            @property bool empty() { return _front[0] >= 10; }
            void popFront() { ++_front[0]; }
        }
        foreach (a; R())
        {
            static assert(is(typeof(a) == Tuple!(int, int)));
            assert(0 <= a[0] && a[0] < 10);
            assert(a[1] == 0);
        }
    }
    // Construction with compatible elements
    {
        auto t1 = Tuple!(int, double)(1, 1);

        // https://issues.dlang.org/show_bug.cgi?id=8702
        auto t8702a = tuple(tuple(1));
        auto t8702b = Tuple!(Tuple!(int))(Tuple!(int)(1));
    }
    // Construction with compatible tuple
    {
        Tuple!(int, int) x;
        x[0] = 10;
        x[1] = 20;
        Tuple!(int, "a", double, "b") y = x;
        assert(y.a == 10);
        assert(y.b == 20);
        // incompatible
        static assert(!__traits(compiles, Tuple!(int, int)(y)));
    }
    // https://issues.dlang.org/show_bug.cgi?id=6275
    {
        const int x = 1;
        auto t1 = tuple(x);
        alias T = Tuple!(const(int));
        auto t2 = T(1);
    }
    // https://issues.dlang.org/show_bug.cgi?id=9431
    {
        alias T = Tuple!(int[1][]);
        auto t = T([[10]]);
    }
    // https://issues.dlang.org/show_bug.cgi?id=7666
    {
        auto tup = tuple(1, "2");
        assert(tup.reverse == tuple("2", 1));
    }
    {
        Tuple!(int, "x", string, "y") tup = tuple(1, "2");
        auto rev = tup.reverse;
        assert(rev == tuple("2", 1));
        assert(rev.x == 1 && rev.y == "2");
    }
    {
        Tuple!(wchar, dchar, int, "x", string, "y", char, byte, float) tup;
        tup = tuple('a', 'b', 3, "4", 'c', cast(byte) 0x0D, 0.00);
        auto rev = tup.reverse;
        assert(rev == tuple(0.00, cast(byte) 0x0D, 'c', "4", 3, 'b', 'a'));
        assert(rev.x == 3 && rev.y == "4");
    }
}
@safe unittest
{
    // opEquals
    {
        struct Equ1 { bool opEquals(Equ1) { return true; } }
        auto  tm1 = tuple(Equ1.init);
        const tc1 = tuple(Equ1.init);
        static assert( is(typeof(tm1 == tm1)));
        static assert(!is(typeof(tm1 == tc1)));
        static assert(!is(typeof(tc1 == tm1)));
        static assert(!is(typeof(tc1 == tc1)));

        struct Equ2 { bool opEquals(const Equ2) const { return true; } }
        auto  tm2 = tuple(Equ2.init);
        const tc2 = tuple(Equ2.init);
        static assert( is(typeof(tm2 == tm2)));
        static assert( is(typeof(tm2 == tc2)));
        static assert( is(typeof(tc2 == tm2)));
        static assert( is(typeof(tc2 == tc2)));

        // https://issues.dlang.org/show_bug.cgi?id=8686
        struct Equ3 { bool opEquals(T)(T) { return true; } }
        auto  tm3 = tuple(Equ3.init);
        const tc3 = tuple(Equ3.init);
        static assert( is(typeof(tm3 == tm3)));
        static assert( is(typeof(tm3 == tc3)));
        static assert(!is(typeof(tc3 == tm3)));
        static assert(!is(typeof(tc3 == tc3)));

        struct Equ4 { bool opEquals(T)(T) const { return true; } }
        auto  tm4 = tuple(Equ4.init);
        const tc4 = tuple(Equ4.init);
        static assert( is(typeof(tm4 == tm4)));
        static assert( is(typeof(tm4 == tc4)));
        static assert( is(typeof(tc4 == tm4)));
        static assert( is(typeof(tc4 == tc4)));
    }
    // opCmp
    {
        struct Cmp1 { int opCmp(Cmp1) { return 0; } }
        auto  tm1 = tuple(Cmp1.init);
        const tc1 = tuple(Cmp1.init);
        static assert( is(typeof(tm1 < tm1)));
        static assert(!is(typeof(tm1 < tc1)));
        static assert(!is(typeof(tc1 < tm1)));
        static assert(!is(typeof(tc1 < tc1)));

        struct Cmp2 { int opCmp(const Cmp2) const { return 0; } }
        auto  tm2 = tuple(Cmp2.init);
        const tc2 = tuple(Cmp2.init);
        static assert( is(typeof(tm2 < tm2)));
        static assert( is(typeof(tm2 < tc2)));
        static assert( is(typeof(tc2 < tm2)));
        static assert( is(typeof(tc2 < tc2)));

        struct Cmp3 { int opCmp(T)(T) { return 0; } }
        auto  tm3 = tuple(Cmp3.init);
        const tc3 = tuple(Cmp3.init);
        static assert( is(typeof(tm3 < tm3)));
        static assert( is(typeof(tm3 < tc3)));
        static assert(!is(typeof(tc3 < tm3)));
        static assert(!is(typeof(tc3 < tc3)));

        struct Cmp4 { int opCmp(T)(T) const { return 0; } }
        auto  tm4 = tuple(Cmp4.init);
        const tc4 = tuple(Cmp4.init);
        static assert( is(typeof(tm4 < tm4)));
        static assert( is(typeof(tm4 < tc4)));
        static assert( is(typeof(tc4 < tm4)));
        static assert( is(typeof(tc4 < tc4)));
    }
    // https://issues.dlang.org/show_bug.cgi?id=14890
    static void test14890(inout int[] dummy)
    {
        alias V = Tuple!(int, int);

                    V mv;
              const V cv;
          immutable V iv;
              inout V wv;   // OK <- NG
        inout const V wcv;  // OK <- NG

        static foreach (v1; AliasSeq!(mv, cv, iv, wv, wcv))
        static foreach (v2; AliasSeq!(mv, cv, iv, wv, wcv))
        {
            assert(!(v1 < v2));
        }
    }
    {
        int[2] ints = [ 1, 2 ];
        Tuple!(int, int) t = ints;
        assert(t[0] == 1 && t[1] == 2);
        Tuple!(long, uint) t2 = ints;
        assert(t2[0] == 1 && t2[1] == 2);
    }
}
@safe unittest
{
    auto t1 = Tuple!(int, "x", string, "y")(1, "a");
    assert(t1.x == 1);
    assert(t1.y == "a");
    void foo(Tuple!(int, string) t2) {}
    foo(t1);

    Tuple!(int, int)[] arr;
    arr ~= tuple(10, 20); // OK
    arr ~= Tuple!(int, "x", int, "y")(10, 20); // NG -> OK

    static assert(is(typeof(Tuple!(int, "x", string, "y").tupleof) ==
                     typeof(Tuple!(int,      string     ).tupleof)));
}
@safe unittest
{
    // https://issues.dlang.org/show_bug.cgi?id=10686
    immutable Tuple!(int) t1;
    auto r1 = t1[0]; // OK
    immutable Tuple!(int, "x") t2;
    auto r2 = t2[0]; // error
}
@safe unittest
{
    import std.exception : assertCTFEable;

    // https://issues.dlang.org/show_bug.cgi?id=10218
    assertCTFEable!(
    {
        auto t = tuple(1);
        t = tuple(2);   // assignment
    });
}
@safe unittest
{
    class Foo{}
    Tuple!(immutable(Foo)[]) a;
}

@safe unittest
{
    //Test non-assignable
    static struct S
    {
        int* p;
    }
    alias IS = immutable S;
    static assert(!isAssignable!IS);

    auto s = IS.init;

    alias TIS = Tuple!IS;
    TIS a = tuple(s);
    TIS b = a;

    alias TISIS = Tuple!(IS, IS);
    TISIS d = tuple(s, s);
    IS[2] ss;
    TISIS e = TISIS(ss);
}

// https://issues.dlang.org/show_bug.cgi?id=9819
@safe unittest
{
    alias T = Tuple!(int, "x", double, "foo");
    static assert(T.fieldNames[0] == "x");
    static assert(T.fieldNames[1] == "foo");

    alias Fields = Tuple!(int, "id", string, float);
    static assert(Fields.fieldNames == AliasSeq!("id", "", ""));
}

// https://issues.dlang.org/show_bug.cgi?id=13837
@safe unittest
{
    // New behaviour, named arguments.
    static assert(is(
        typeof(tuple!("x")(1)) == Tuple!(int, "x")));
    static assert(is(
        typeof(tuple!("x")(1.0)) == Tuple!(double, "x")));
    static assert(is(
        typeof(tuple!("x")("foo")) == Tuple!(string, "x")));
    static assert(is(
        typeof(tuple!("x", "y")(1, 2.0)) == Tuple!(int, "x", double, "y")));

    auto a = tuple!("a", "b", "c")("1", 2, 3.0f);
    static assert(is(typeof(a.a) == string));
    static assert(is(typeof(a.b) == int));
    static assert(is(typeof(a.c) == float));

    // Old behaviour, but with explicit type parameters.
    static assert(is(
        typeof(tuple!(int, double)(1, 2.0)) == Tuple!(int, double)));
    static assert(is(
        typeof(tuple!(const int)(1)) == Tuple!(const int)));
    static assert(is(
        typeof(tuple()) == Tuple!()));

    // Nonsensical behaviour
    static assert(!__traits(compiles, tuple!(1)(2)));
    static assert(!__traits(compiles, tuple!("x")(1, 2)));
    static assert(!__traits(compiles, tuple!("x", "y")(1)));
    static assert(!__traits(compiles, tuple!("x")()));
    static assert(!__traits(compiles, tuple!("x", int)(2)));
}

@safe unittest
{
    class C { override size_t toHash() const nothrow @safe { return 0; } }
    Tuple!(Rebindable!(const C)) a;
    Tuple!(const C) b;
    a = b;
}

@nogc @safe unittest
{
    alias T = Tuple!(string, "s");
    T x;
    x = T.init;
}

@safe unittest
{
    import std.format : format, FormatException;
    import std.exception : assertThrown;

    //enum tupStr = tuple(1, 1.0).toString; // toString is *impure*.
    //static assert(tupStr == `Tuple!(int, double)(1, 1)`);
}

// https://issues.dlang.org/show_bug.cgi?id=17803, parte uno
@safe unittest
{
    auto a = tuple(3, "foo");
    assert(__traits(compiles, { a = (a = a); }));
}
// Ditto
@safe unittest
{
    Tuple!(int[]) a, b, c;
    a = tuple([0, 1, 2]);
    c = b = a;
    assert(a[0].length == b[0].length && b[0].length == c[0].length);
    assert(a[0].ptr == b[0].ptr && b[0].ptr == c[0].ptr);
}

/**
    Constructs a $(LREF Tuple) object instantiated and initialized according to
    the given arguments.

    Params:
        Names = An optional list of strings naming each successive field of the `Tuple`
                or a list of types that the elements are being casted to.
                For a list of names,
                each name matches up with the corresponding field given by `Args`.
                A name does not have to be provided for every field, but as
                the names must proceed in order, it is not possible to skip
                one field and name the next after it.
                For a list of types,
                there must be exactly as many types as parameters.
*/
template tuple(Names...)
{
    /**
    Params:
        args = Values to initialize the `Tuple` with. The `Tuple`'s type will
               be inferred from the types of the values given.

    Returns:
        A new `Tuple` with its type inferred from the arguments given.
     */
    auto tuple(Args...)(Args args)
    {
        static if (Names.length == 0)
        {
            // No specified names, just infer types from Args...
            return Tuple!Args(args);
        }
        else static if (!is(typeof(Names[0]) : string))
        {
            // Names[0] isn't a string, must be explicit types.
            return Tuple!Names(args);
        }
        else
        {
            // Names[0] is a string, so must be specifying names.
            static assert(Names.length == Args.length,
                "Insufficient number of names given.");

            // Interleave(a, b).and(c, d) == (a, c, b, d)
            // This is to get the interleaving of types and names for Tuple
            // e.g. Tuple!(int, "x", string, "y")
            template Interleave(A...)
            {
                template and(B...) if (B.length == 1)
                {
                    alias and = AliasSeq!(A[0], B[0]);
                }

                template and(B...) if (B.length != 1)
                {
                    alias and = AliasSeq!(A[0], B[0],
                        Interleave!(A[1..$]).and!(B[1..$]));
                }
            }
            return Tuple!(Interleave!(Args).and!(Names))(args);
        }
    }
}

///
@safe unittest
{
    auto value = tuple(5, 6.7, "hello");
    assert(value[0] == 5);
    assert(value[1] == 6.7);
    assert(value[2] == "hello");

    // Field names can be provided.
    auto entry = tuple!("index", "value")(4, "Hello");
    assert(entry.index == 4);
    assert(entry.value == "Hello");
}

/**
    Returns `true` if and only if `T` is an instance of `std.typecons.Tuple`.

    Params:
        T = The type to check.

    Returns:
        true if `T` is a `Tuple` type, false otherwise.
 */
enum isTuple(T) = __traits(compiles,
                           {
                               void f(Specs...)(Tuple!Specs tup) {}
                               f(T.init);
                           } );

///
@safe unittest
{
    static assert(isTuple!(Tuple!()));
    static assert(isTuple!(Tuple!(int)));
    static assert(isTuple!(Tuple!(int, real, string)));
    static assert(isTuple!(Tuple!(int, "x", real, "y")));
    static assert(isTuple!(Tuple!(int, Tuple!(real), string)));
}

@safe unittest
{
    static assert(isTuple!(const Tuple!(int)));
    static assert(isTuple!(immutable Tuple!(int)));

    static assert(!isTuple!(int));
    static assert(!isTuple!(const int));

    struct S {}
    static assert(!isTuple!(S));
}

// used by both Rebindable and UnqualRef
private mixin template RebindableCommon(T, U, alias This)
if (is(T == class) || is(T == interface) || isAssociativeArray!T)
{
    private union
    {
        T original;
        U stripped;
    }

    void opAssign(return scope T another) pure nothrow @nogc
    {
        // If `T` defines `opCast` we must infer the safety
        static if (hasMember!(T, "opCast"))
        {
            // This will allow the compiler to infer the safety of `T.opCast!U`
            // without generating any runtime cost
            if (false) { stripped = cast(U) another; }
        }
        () @trusted { stripped = cast(U) another; }();
    }

    void opAssign(typeof(this) another) @trusted pure nothrow @nogc
    {
        stripped = another.stripped;
    }

    static if (is(T == const U) && is(T == const shared U))
    {
        // safely assign immutable to const / const shared
        void opAssign(This!(immutable U) another) @trusted pure nothrow @nogc
        {
            stripped = another.stripped;
        }
    }

    this(T initializer) pure nothrow @nogc
    {
        // Infer safety from opAssign
        opAssign(initializer);
    }

    @property inout(T) get() @trusted pure nothrow @nogc return scope inout
    {
        return original;
    }

    bool opEquals()(auto ref const(typeof(this)) rhs) const
    {
        // Must forward explicitly because 'stripped' is part of a union.
        // The necessary 'toHash' is forwarded to the class via alias this.
        return stripped == rhs.stripped;
    }

    bool opEquals(const(U) rhs) const
    {
        return stripped == rhs;
    }

    alias get this;
}

/**
`Rebindable!(T)` is a simple, efficient wrapper that behaves just
like an object of type `T`, except that you can reassign it to
refer to another object. For completeness, `Rebindable!(T)` aliases
itself away to `T` if `T` is a non-const object type.

You may want to use `Rebindable` when you want to have mutable
storage referring to `const` objects, for example an array of
references that must be sorted in place. `Rebindable` does not
break the soundness of D's type system and does not incur any of the
risks usually associated with `cast`.

Params:
    T = An object, interface, array slice type, or associative array type.
 */
template Rebindable(T)
if (is(T == class) || is(T == interface) || isDynamicArray!T || isAssociativeArray!T)
{
    static if (is(T == const U, U) || is(T == immutable U, U))
    {
        static if (isDynamicArray!T)
        {
            import std.range.primitives : ElementEncodingType;
            alias Rebindable = const(ElementEncodingType!T)[];
        }
        else
        {
            struct Rebindable
            {
                mixin RebindableCommon!(T, U, Rebindable);
            }
        }
    }
    else
    {
        alias Rebindable = T;
    }
}

///Regular `const` object references cannot be reassigned.
@safe unittest
{
    class Widget { int x; int y() @safe const { return x; } }
    const a = new Widget;
    // Fine
    a.y();
    // error! can't modify const a
    // a.x = 5;
    // error! can't modify const a
    // a = new Widget;
}

/**
    However, `Rebindable!(Widget)` does allow reassignment,
    while otherwise behaving exactly like a $(D const Widget).
 */
@safe unittest
{
    class Widget { int x; int y() const @safe { return x; } }
    auto a = Rebindable!(const Widget)(new Widget);
    // Fine
    a.y();
    // error! can't modify const a
    // a.x = 5;
    // Fine
    a = new Widget;
}

// https://issues.dlang.org/show_bug.cgi?id=16054
@safe unittest
{
    Rebindable!(immutable Object) r;
    static assert(__traits(compiles, r.get()));
    static assert(!__traits(compiles, &r.get()));
}

@safe unittest
{
    class CustomToHash
    {
        override size_t toHash() const nothrow @trusted { return 42; }
    }
    Rebindable!(immutable(CustomToHash)) a = new immutable CustomToHash();
    assert(a.toHash() == 42, "Rebindable!A should offer toHash()"
        ~ " by forwarding to A.toHash().");
}

// https://issues.dlang.org/show_bug.cgi?id=18615
// Rebindable!A should use A.opEqualsa
@system unittest
{
    class CustomOpEq
    {
        int x;
        override bool opEquals(Object rhsObj)
        {
            if (auto rhs = cast(const(CustomOpEq)) rhsObj)
                return this.x == rhs.x;
            else
                return false;
        }
    }
    CustomOpEq a = new CustomOpEq();
    CustomOpEq b = new CustomOpEq();
    assert(a !is b);
    assert(a == b, "a.x == b.x should be true (0 == 0).");

    Rebindable!(const(CustomOpEq)) ra = a;
    Rebindable!(const(CustomOpEq)) rb = b;
    assert(ra !is rb);
    assert(ra == rb, "Rebindable should use CustomOpEq's opEquals, not 'is'.");
    assert(ra == b, "Rebindable!(someQualifier(A)) should be comparable"
        ~ " against const(A) via A.opEquals.");
    assert(a == rb, "Rebindable!(someQualifier(A)) should be comparable"
        ~ " against const(A) via A.opEquals.");

    b.x = 1;
    assert(a != b);
    assert(ra != b, "Rebindable!(someQualifier(A)) should be comparable"
        ~ " against const(A) via A.opEquals.");
    assert(a != rb, "Rebindable!(someQualifier(A)) should be comparable"
        ~ " against const(A) via A.opEquals.");

    Rebindable!(const(Object)) o1 = new Object();
    Rebindable!(const(Object)) o2 = new Object();
    assert(o1 !is o2);
    assert(o1 == o1, "When the class doesn't provide its own opEquals,"
        ~ " Rebindable treats 'a == b' as 'a is b' like Object.opEquals.");
    assert(o1 != o2, "When the class doesn't provide its own opEquals,"
        ~ " Rebindable treats 'a == b' as 'a is b' like Object.opEquals.");
    assert(o1 != new Object(), "Rebindable!(const(Object)) should be"
        ~ " comparable against Object itself and use Object.opEquals.");
}

// https://issues.dlang.org/show_bug.cgi?id=18755
@safe unittest
{
    static class Foo
    {
        auto opCast(T)() @system immutable pure nothrow
        {
            *(cast(uint*) 0xdeadbeef) = 0xcafebabe;
            return T.init;
        }
    }

    static assert(!__traits(compiles, () @safe {
        auto r = Rebindable!(immutable Foo)(new Foo);
    }));
    static assert(__traits(compiles, () @system {
        auto r = Rebindable!(immutable Foo)(new Foo);
    }));
}

/**
Convenience function for creating a `Rebindable` using automatic type
inference.

Params:
    obj = A reference to an object, interface, associative array, or an array slice
          to initialize the `Rebindable` with.

Returns:
    A newly constructed `Rebindable` initialized with the given reference.
*/
Rebindable!T rebindable(T)(T obj)
if (is(T == class) || is(T == interface) || isDynamicArray!T || isAssociativeArray!T)
{
    typeof(return) ret;
    ret = obj;
    return ret;
}

///
@system unittest
{
    class C
    {
        int payload;
        this(int p) { payload = p; }
    }
    const c = new C(1);

    auto c2 = c.rebindable;
    assert(c2.payload == 1);
    // passing Rebindable to rebindable
    c2 = c2.rebindable;

    c2 = new C(2);
    assert(c2.payload == 2);

    const c3 = c2.get;
    assert(c3.payload == 2);
}

/**
This function simply returns the `Rebindable` object passed in.  It's useful
in generic programming cases when a given object may be either a regular
`class` or a `Rebindable`.

Params:
    obj = An instance of Rebindable!T.

Returns:
    `obj` without any modification.
*/
Rebindable!T rebindable(T)(Rebindable!T obj)
{
    return obj;
}

// TODO: remove me once the rebindable overloads have been joined
///
@system unittest
{
    class C
    {
        int payload;
        this(int p) { payload = p; }
    }
    const c = new C(1);

    auto c2 = c.rebindable;
    assert(c2.payload == 1);
    // passing Rebindable to rebindable
    c2 = c2.rebindable;
    assert(c2.payload == 1);
}

@system unittest
{
    interface CI { int foo() const; }
    class C : CI {
      int foo() const { return 42; }
      @property int bar() const { return 23; }
    }
    Rebindable!(C) obj0;
    static assert(is(typeof(obj0) == C));

    Rebindable!(const(C)) obj1;
    static assert(is(typeof(obj1.get) == const(C)), typeof(obj1.get).stringof);
    static assert(is(typeof(obj1.stripped) == C));
    obj1 = new C;
    assert(obj1.get !is null);
    obj1 = new const(C);
    assert(obj1.get !is null);

    Rebindable!(immutable(C)) obj2;
    static assert(is(typeof(obj2.get) == immutable(C)));
    static assert(is(typeof(obj2.stripped) == C));
    obj2 = new immutable(C);
    assert(obj1.get !is null);

    // test opDot
    assert(obj2.foo() == 42);
    assert(obj2.bar == 23);

    interface I { final int foo() const { return 42; } }
    Rebindable!(I) obj3;
    static assert(is(typeof(obj3) == I));

    Rebindable!(const I) obj4;
    static assert(is(typeof(obj4.get) == const I));
    static assert(is(typeof(obj4.stripped) == I));
    static assert(is(typeof(obj4.foo()) == int));
    obj4 = new class I {};

    Rebindable!(immutable C) obj5i;
    Rebindable!(const C) obj5c;
    obj5c = obj5c;
    obj5c = obj5i;
    obj5i = obj5i;
    static assert(!__traits(compiles, obj5i = obj5c));

    // Test the convenience functions.
    auto obj5convenience = rebindable(obj5i);
    assert(obj5convenience is obj5i);

    auto obj6 = rebindable(new immutable(C));
    static assert(is(typeof(obj6) == Rebindable!(immutable C)));
    assert(obj6.foo() == 42);

    auto obj7 = rebindable(new C);
    CI interface1 = obj7;
    auto interfaceRebind1 = rebindable(interface1);
    assert(interfaceRebind1.foo() == 42);

    const interface2 = interface1;
    auto interfaceRebind2 = rebindable(interface2);
    assert(interfaceRebind2.foo() == 42);

    auto arr = [1,2,3,4,5];
    const arrConst = arr;
    assert(rebindable(arr) == arr);
    assert(rebindable(arrConst) == arr);

    // https://issues.dlang.org/show_bug.cgi?id=7654
    immutable(char[]) s7654;
    Rebindable!(typeof(s7654)) r7654 = s7654;

    static foreach (T; AliasSeq!(char, wchar, char, int))
    {
        static assert(is(Rebindable!(immutable(T[])) == immutable(T)[]));
        static assert(is(Rebindable!(const(T[])) == const(T)[]));
        static assert(is(Rebindable!(T[]) == T[]));
    }

    // https://issues.dlang.org/show_bug.cgi?id=12046
    static assert(!__traits(compiles, Rebindable!(int[1])));
    static assert(!__traits(compiles, Rebindable!(const int[1])));

    // Pull request 3341
    Rebindable!(immutable int[int]) pr3341 = [123:345];
    assert(pr3341[123] == 345);
    immutable int[int] pr3341_aa = [321:543];
    pr3341 = pr3341_aa;
    assert(pr3341[321] == 543);
    assert(rebindable(pr3341_aa)[321] == 543);
}

/**
    Similar to `Rebindable!(T)` but strips all qualifiers from the reference as
    opposed to just constness / immutability. Primary intended use case is with
    shared (having thread-local reference to shared class data)

    Params:
        T = A class or interface type.
 */
template UnqualRef(T)
if (is(T == class) || is(T == interface))
{
    static if (is(T == immutable U, U)
        || is(T == const shared U, U)
        || is(T == const U, U)
        || is(T == shared U, U))
    {
        struct UnqualRef
        {
            mixin RebindableCommon!(T, U, UnqualRef);
        }
    }
    else
    {
        alias UnqualRef = T;
    }
}

///
@system unittest
{
    class Data {}

    static shared(Data) a;
    static UnqualRef!(shared Data) b;

    import core.thread;

    auto thread = new core.thread.Thread({
        a = new shared Data();
        b = new shared Data();
    });

    thread.start();
    thread.join();

    assert(a !is null);
    assert(b is null);
}

@safe unittest
{
    class C { }
    alias T = UnqualRef!(const shared C);
    static assert(is(typeof(T.stripped) == C));
}



/**
  Order the provided members to minimize size while preserving alignment.
  Alignment is not always optimal for 80-bit reals, nor for structs declared
  as align(1).

  Params:
      E = A list of the types to be aligned, representing fields
          of an aggregate such as a `struct` or `class`.

      names = The names of the fields that are to be aligned.

  Returns:
      A string to be mixed in to an aggregate, such as a `struct` or `class`.
*/
string alignForSize(E...)(const char[][] names...)
{
    // Sort all of the members by .alignof.
    // BUG: Alignment is not always optimal for align(1) structs
    // or 80-bit reals or 64-bit primitives on x86.
    // TRICK: Use the fact that .alignof is always a power of 2,
    // and maximum 16 on extant systems. Thus, we can perform
    // a very limited radix sort.
    // Contains the members with .alignof = 64,32,16,8,4,2,1

    assert(E.length == names.length,
        "alignForSize: There should be as many member names as the types");

    string[7] declaration = ["", "", "", "", "", "", ""];

    foreach (i, T; E)
    {
        auto a = T.alignof;
        auto k = a >= 64? 0 : a >= 32? 1 : a >= 16? 2 : a >= 8? 3 : a >= 4? 4 : a >= 2? 5 : 6;
        declaration[k] ~= T.stringof ~ " " ~ names[i] ~ ";\n";
    }

    auto s = "";
    foreach (decl; declaration)
        s ~= decl;
    return s;
}

///
@safe unittest
{
    struct Banner {
        mixin(alignForSize!(byte[6], double)(["name", "height"]));
    }
}

@safe unittest
{
    enum x = alignForSize!(int[], char[3], short, double[5])("x", "y","z", "w");
    struct Foo { int x; }
    enum y = alignForSize!(ubyte, Foo, double)("x", "y", "z");

    enum passNormalX = x == "double[5] w;\nint[] x;\nshort z;\nchar[3] y;\n";
    enum passNormalY = y == "double z;\nFoo y;\nubyte x;\n";

    enum passAbnormalX = x == "int[] x;\ndouble[5] w;\nshort z;\nchar[3] y;\n";
    enum passAbnormalY = y == "Foo y;\ndouble z;\nubyte x;\n";
    // ^ blame https://issues.dlang.org/show_bug.cgi?id=231

    static assert(passNormalX || passAbnormalX && double.alignof <= (int[]).alignof);
    static assert(passNormalY || passAbnormalY && double.alignof <= int.alignof);
}

// https://issues.dlang.org/show_bug.cgi?id=12914
@safe unittest
{
    immutable string[] fieldNames = ["x", "y"];
    struct S
    {
        mixin(alignForSize!(byte, int)(fieldNames));
    }
}

/**
Defines a value paired with a distinctive "null" state that denotes
the absence of a value. If default constructed, a $(D
Nullable!T) object starts in the null state. Assigning it renders it
non-null. Calling `nullify` can nullify it again.

Practically `Nullable!T` stores a `T` and a `bool`.
 */
struct Nullable(T)
{
    private union DontCallDestructorT
    {
        import std.traits : hasIndirections;
        static if (hasIndirections!T)
            T payload;
        else
            T payload = void;
    }

    private DontCallDestructorT _value = DontCallDestructorT.init;

    private bool _isNull = true;

    /**
     * Constructor initializing `this` with `value`.
     *
     * Params:
     *     value = The value to initialize this `Nullable` with.
     */
    this(inout T value) inout
    {
        _value.payload = value;
        _isNull = false;
    }

    static if (hasElaborateDestructor!T)
    {
        ~this()
        {
            if (!_isNull)
            {
                destroy(_value.payload);
            }
        }
    }

    static if (__traits(hasPostblit, T))
    {
        this(this)
        {
            if (!_isNull)
                _value.payload.__xpostblit();
        }
    }
    else static if (__traits(hasCopyConstructor, T))
    {
        this(ref return scope inout Nullable!T rhs) inout
        {
            _isNull = rhs._isNull;
            if (!_isNull)
                _value.payload = rhs._value.payload;
            else
                _value = DontCallDestructorT.init;
        }
    }

    /**
     * If they are both null, then they are equal. If one is null and the other
     * is not, then they are not equal. If they are both non-null, then they are
     * equal if their values are equal.
     */
    bool opEquals(this This, Rhs)(auto ref Rhs rhs)
    if (!is(CommonType!(This, Rhs) == void))
    {
        static if (is(This == Rhs))
        {
            if (_isNull)
                return rhs._isNull;
            if (rhs._isNull)
                return false;
            return _value.payload == rhs._value.payload;
        }
        else
        {
            alias Common = CommonType!(This, Rhs);
            return cast(Common) this == cast(Common) rhs;
        }
    }

    /// Ditto
    bool opEquals(this This, Rhs)(auto ref Rhs rhs)
    if (is(CommonType!(This, Rhs) == void) && is(typeof(this.get == rhs)))
    {
        return _isNull ? false : rhs == _value.payload;
    }

    ///
    @safe unittest
    {
        Nullable!int empty;
        Nullable!int a = 42;
        Nullable!int b = 42;
        Nullable!int c = 27;

        assert(empty == empty);
        assert(empty == Nullable!int.init);
        assert(empty != a);
        assert(empty != b);
        assert(empty != c);

        assert(a == b);
        assert(a != c);

        assert(empty != 42);
        assert(a == 42);
        assert(c != 42);
    }

    @safe unittest
    {
        // Test constness
        immutable Nullable!int a = 42;
        Nullable!int b = 42;
        immutable Nullable!int c = 29;
        Nullable!int d = 29;
        immutable e = 42;
        int f = 29;
        assert(a == a);
        assert(a == b);
        assert(a != c);
        assert(a != d);
        assert(a == e);
        assert(a != f);

        // Test rvalue
        assert(a == const Nullable!int(42));
        assert(a != Nullable!int(29));
    }

    // https://issues.dlang.org/show_bug.cgi?id=17482
    @system unittest
    {
        import std.variant : Variant;
        Nullable!Variant a = Variant(12);
        assert(a == 12);
        Nullable!Variant e;
        assert(e != 12);
    }

    size_t toHash() const @safe nothrow
    {
        static if (__traits(compiles, .hashOf(_value.payload)))
            return _isNull ? 0 : .hashOf(_value.payload);
        else
            // Workaround for when .hashOf is not both @safe and nothrow.
            return _isNull ? 0 : typeid(T).getHash(&_value.payload);
    }

    /**
     * Gives the string `"Nullable.null"` if `isNull` is `true`. Otherwise, the
     * result is equivalent to calling $(REF formattedWrite, std,format) on the
     * underlying value.
     *
     * Params:
     *     writer = A `char` accepting
     *     $(REF_ALTTEXT output range, isOutputRange, std, range, primitives)
     *     fmt = A $(REF FormatSpec, std,format) which is used to represent
     *     the value if this Nullable is not null
     * Returns:
     *     A `string` if `writer` and `fmt` are not set; `void` otherwise.
     */
    string toString()
    {
        import std.array : appender;
        auto app = appender!string();
        auto spec = singleSpec("%s");
        toString(app, spec);
        return app.data;
    }

    /// ditto
    string toString() const
    {
        import std.array : appender;
        auto app = appender!string();
        auto spec = singleSpec("%s");
        toString(app, spec);
        return app.data;
    }

    /// ditto
    void toString(W)(ref W writer, scope const ref FormatSpec!char fmt)
    if (isOutputRange!(W, char))
    {
        import std.range.primitives : put;
        if (isNull)
            put(writer, "Nullable.null");
        else
            formatValue(writer, _value.payload, fmt);
    }

    /// ditto
    void toString(W)(ref W writer, scope const ref FormatSpec!char fmt) const
    if (isOutputRange!(W, char))
    {
        import std.range.primitives : put;
        if (isNull)
            put(writer, "Nullable.null");
        else
            formatValue(writer, _value.payload, fmt);
    }

    /**
     * Check if `this` is in the null state.
     *
     * Returns:
     *     true $(B iff) `this` is in the null state, otherwise false.
     */
    @property bool isNull() const @safe pure nothrow
    {
        return _isNull;
    }

    ///
    @safe unittest
    {
        Nullable!int ni;
        assert(ni.isNull);

        ni = 0;
        assert(!ni.isNull);
    }

    // https://issues.dlang.org/show_bug.cgi?id=14940
    @safe unittest
    {
        import std.array : appender;
        import std.format.write : formattedWrite;

        auto app = appender!string();
        Nullable!int a = 1;
        formattedWrite(app, "%s", a);
        assert(app.data == "1");
    }

    // https://issues.dlang.org/show_bug.cgi?id=19799
    @safe unittest
    {
        import std.format : format;

        const Nullable!string a = const(Nullable!string)();

        format!"%s"(a);
    }

    /**
     * Forces `this` to the null state.
     */
    void nullify()()
    {
        static if (is(T == class) || is(T == interface))
            _value.payload = null;
        else
            .destroy(_value.payload);
        _isNull = true;
    }

    ///
    @safe unittest
    {
        Nullable!int ni = 0;
        assert(!ni.isNull);

        ni.nullify();
        assert(ni.isNull);
    }

    /**
     * Assigns `value` to the internally-held state. If the assignment
     * succeeds, `this` becomes non-null.
     *
     * Params:
     *     value = A value of type `T` to assign to this `Nullable`.
     */
    Nullable opAssign()(T value)
    {
        import std.algorithm.mutation : moveEmplace, move;

        // the lifetime of the value in copy shall be managed by
        // this Nullable, so we must avoid calling its destructor.
        auto copy = DontCallDestructorT(value);

        if (_isNull)
        {
            // trusted since payload is known to be uninitialized.
            () @trusted { moveEmplace(copy.payload, _value.payload); }();
        }
        else
        {
            move(copy.payload, _value.payload);
        }
        _isNull = false;
        return this;
    }

    /**
     * If this `Nullable` wraps a type that already has a null value
     * (such as a pointer), then assigning the null value to this
     * `Nullable` is no different than assigning any other value of
     * type `T`, and the resulting code will look very strange. It
     * is strongly recommended that this be avoided by instead using
     * the version of `Nullable` that takes an additional `nullValue`
     * template argument.
     */
    @safe unittest
    {
        //Passes
        Nullable!(int*) npi;
        assert(npi.isNull);

        //Passes?!
        npi = null;
        assert(!npi.isNull);
    }

    /**
     * Gets the value if not null. If `this` is in the null state, and the optional
     * parameter `fallback` was provided, it will be returned. Without `fallback`,
     * calling `get` with a null state is invalid.
     *
     * When the fallback type is different from the Nullable type, `get(T)` returns
     * the common type.
     *
     * Params:
     *     fallback = the value to return in case the `Nullable` is null.
     *
     * Returns:
     *     The value held internally by this `Nullable`.
     */
    @property ref inout(T) get() inout @safe pure nothrow
    {
        enum message = "Called `get' on null Nullable!" ~ T.stringof ~ ".";
        assert(!isNull, message);
        return _value.payload;
    }

    /// ditto
    @property inout(T) get()(inout(T) fallback) inout
    {
        return isNull ? fallback : _value.payload;
    }

    /// ditto
    @property auto get(U)(inout(U) fallback) inout
    {
        return isNull ? fallback : _value.payload;
    }

    /// $(MREF_ALTTEXT Range interface, std, range, primitives) functions.
    alias empty = isNull;

    /// ditto
    alias popFront = nullify;

    /// ditto
    alias popBack = nullify;

    /// ditto
    @property ref inout(T) front() inout @safe pure nothrow
    {
        return get();
    }

    /// ditto
    alias back = front;

    /// ditto
    @property inout(typeof(this)) save() inout
    {
        return this;
    }

    /// ditto
    inout(typeof(this)) opIndex() inout
    {
        return this;
    }

    /// ditto
    inout(typeof(this)) opIndex(size_t[2] dim) inout
    in (dim[0] <= length && dim[1] <= length && dim[1] >= dim[0])
    {
        return (dim[0] == 0 && dim[1] == 1) ? this : this.init;
    }
    /// ditto
    size_t[2] opSlice(size_t dim : 0)(size_t from, size_t to) const
    {
        return [from, to];
    }

    /// ditto
    @property size_t length() const @safe pure nothrow
    {
        return !empty;
    }

    /// ditto
    alias opDollar(size_t dim : 0) = length;

    /// ditto
    ref inout(T) opIndex(size_t index) inout @safe pure nothrow
    in (index < length)
    {
        return get();
    }
}

/// ditto
auto nullable(T)(T t)
{
    return Nullable!T(t);
}

///
@safe unittest
{
    struct CustomerRecord
    {
        string name;
        string address;
        int customerNum;
    }

    Nullable!CustomerRecord getByName(string name)
    {
        //A bunch of hairy stuff

        return Nullable!CustomerRecord.init;
    }

    auto queryResult = getByName("Doe, John");
    if (!queryResult.isNull)
    {
        //Process Mr. Doe's customer record
        auto address = queryResult.get.address;
        auto customerNum = queryResult.get.customerNum;

        //Do some things with this customer's info
    }
    else
    {
        //Add the customer to the database
    }
}

///
@system unittest
{
    import std.exception : assertThrown;

    auto a = 42.nullable;
    assert(!a.isNull);
    assert(a.get == 42);

    a.nullify();
    assert(a.isNull);
    assertThrown!Throwable(a.get);
}
///
@safe unittest
{
    import std.algorithm.iteration : each, joiner;
    Nullable!int a = 42;
    Nullable!int b;
    // Add each value to an array
    int[] arr;
    a.each!((n) => arr ~= n);
    assert(arr == [42]);
    b.each!((n) => arr ~= n);
    assert(arr == [42]);
    // Take first value from an array of Nullables
    Nullable!int[] c = new Nullable!int[](10);
    c[7] = Nullable!int(42);
    assert(c.joiner.front == 42);
}
@safe unittest
{
    auto k = Nullable!int(74);
    assert(k == 74);
    k.nullify();
    assert(k.isNull);
}
@safe unittest
{
    static int f(scope const Nullable!int x) {
        return x.isNull ? 42 : x.get;
    }
    Nullable!int a;
    assert(f(a) == 42);
    a = 8;
    assert(f(a) == 8);
    a.nullify();
    assert(f(a) == 42);
}
@system unittest
{
    import std.exception : assertThrown;

    static struct S { int x; }
    Nullable!S s;
    assert(s.isNull);
    s = S(6);
    assert(s == S(6));
    assert(s != S(0));
    assert(s.get != S(0));
    s.get.x = 9190;
    assert(s.get.x == 9190);
    s.nullify();
    assertThrown!Throwable(s.get.x = 9441);
}
@safe unittest
{
    // Ensure Nullable can be used in pure/nothrow/@safe environment.
    function() @safe pure nothrow
    {
        Nullable!int n;
        assert(n.isNull);
        n = 4;
        assert(!n.isNull);
        assert(n == 4);
        n.nullify();
        assert(n.isNull);
    }();
}
@system unittest
{
    // Ensure Nullable can be used when the value is not pure/nothrow/@safe
    static struct S
    {
        int x;
        this(this) @system {}
    }

    Nullable!S s;
    assert(s.isNull);
    s = S(5);
    assert(!s.isNull);
    assert(s.get.x == 5);
    s.nullify();
    assert(s.isNull);
}

// https://issues.dlang.org/show_bug.cgi?id=9404
@safe unittest
{
    alias N = Nullable!int;

    void foo(N a)
    {
        N b;
        b = a; // `N b = a;` works fine
    }
    N n;
    foo(n);
}
@safe unittest
{
    //Check nullable immutable is constructable
    {
        auto a1 = Nullable!(immutable int)();
        auto a2 = Nullable!(immutable int)(1);
        auto i = a2.get;
    }
    //Check immutable nullable is constructable
    {
        auto a1 = immutable (Nullable!int)();
        auto a2 = immutable (Nullable!int)(1);
        auto i = a2.get;
    }
}
@safe unittest
{
    alias NInt   = Nullable!int;

    //Construct tests
    {
        //from other Nullable null
        NInt a1;
        NInt b1 = a1;
        assert(b1.isNull);

        //from other Nullable non-null
        NInt a2 = NInt(1);
        NInt b2 = a2;
        assert(b2 == 1);

        //Construct from similar nullable
        auto a3 = immutable(NInt)();
        NInt b3 = a3;
        assert(b3.isNull);
    }

    //Assign tests
    {
        //from other Nullable null
        NInt a1;
        NInt b1;
        b1 = a1;
        assert(b1.isNull);

        //from other Nullable non-null
        NInt a2 = NInt(1);
        NInt b2;
        b2 = a2;
        assert(b2 == 1);

        //Construct from similar nullable
        auto a3 = immutable(NInt)();
        NInt b3 = a3;
        b3 = a3;
        assert(b3.isNull);
    }
}
@safe unittest
{
    //Check nullable is nicelly embedable in a struct
    static struct S1
    {
        Nullable!int ni;
    }
    static struct S2 //inspired from 9404
    {
        Nullable!int ni;
        this(ref S2 other)
        {
            ni = other.ni;
        }
        void opAssign(ref S2 other)
        {
            ni = other.ni;
        }
    }
    static foreach (S; AliasSeq!(S1, S2))
    {{
        S a;
        S b = a;
        S c;
        c = a;
    }}
}

// https://issues.dlang.org/show_bug.cgi?id=10268
@system unittest
{
    import std.json;
    JSONValue value = null;
    auto na = Nullable!JSONValue(value);

    struct S1 { int val; }
    struct S2 { int* val; }
    struct S3 { immutable int* val; }

    {
        auto sm = S1(1);
        immutable si = immutable S1(1);
        auto x1 =           Nullable!S1(sm);
        auto x2 = immutable Nullable!S1(sm);
        auto x3 =           Nullable!S1(si);
        auto x4 = immutable Nullable!S1(si);
        assert(x1.get.val == 1);
        assert(x2.get.val == 1);
        assert(x3.get.val == 1);
        assert(x4.get.val == 1);
    }

    auto nm = 10;
    immutable ni = 10;

    {
        auto sm = S2(&nm);
        immutable si = immutable S2(&ni);
        auto x1 =           Nullable!S2(sm);
        static assert(!__traits(compiles, { auto x2 = immutable Nullable!S2(sm); }));
        static assert(!__traits(compiles, { auto x3 =           Nullable!S2(si); }));
        auto x4 = immutable Nullable!S2(si);
        assert(*x1.get.val == 10);
        assert(*x4.get.val == 10);
    }

    {
        auto sm = S3(&ni);
        immutable si = immutable S3(&ni);
        auto x1 =           Nullable!S3(sm);
        auto x2 = immutable Nullable!S3(sm);
        auto x3 =           Nullable!S3(si);
        auto x4 = immutable Nullable!S3(si);
        assert(*x1.get.val == 10);
        assert(*x2.get.val == 10);
        assert(*x3.get.val == 10);
        assert(*x4.get.val == 10);
    }
}

// https://issues.dlang.org/show_bug.cgi?id=10357
@safe unittest
{
    import std.datetime;
    Nullable!SysTime time = SysTime(0);
}

// https://issues.dlang.org/show_bug.cgi?id=10915
@system unittest
{
    import std.conv : to;
    import std.array;

    Appender!string buffer;

    Nullable!int ni;
    assert(ni.to!string() == "Nullable.null");
    assert((cast(const) ni).to!string() == "Nullable.null");

    struct Test { string s; }
    alias NullableTest = Nullable!Test;

    NullableTest nt = Test("test");
    // test output range version
    assert(nt.to!string() == `Test("test")`);
    // test appender version
    assert(nt.toString() == `Test("test")`);
    // test const version
    assert((cast(const) nt).toString() == `const(Test)("test")`);

    NullableTest ntn = Test("null");
    assert(ntn.to!string() == `Test("null")`);

    class TestToString
    {
        double d;

        this (double d)
        {
            this.d = d;
        }

        override string toString()
        {
            return d.to!string();
        }
    }
    Nullable!TestToString ntts = new TestToString(2.5);
    assert(ntts.to!string() == "2.5");
}

// https://issues.dlang.org/show_bug.cgi?id=14477
@safe unittest
{
    static struct DisabledDefaultConstructor
    {
        @disable this();
        this(int i) { }
    }
    Nullable!DisabledDefaultConstructor var;
    var = DisabledDefaultConstructor(5);
    var.nullify;
}

// https://issues.dlang.org/show_bug.cgi?id=17440
@system unittest
{
    static interface I { }

    static class C : I
    {
        int canary;
        ~this()
        {
            canary = 0x5050DEAD;
        }
    }
    auto c = new C;
    c.canary = 0xA71FE;
    auto nc = nullable(c);
    nc.nullify;
    assert(c.canary == 0xA71FE);

    I i = c;
    auto ni = nullable(i);
    ni.nullify;
    assert(c.canary == 0xA71FE);
}

// https://issues.dlang.org/show_bug.cgi?id=19037
@safe unittest
{
    import std.datetime : SysTime;

    struct Test
    {
        bool b;

        nothrow invariant { assert(b == true); }

        SysTime _st;

        static bool destroyed;

        @disable this();
        this(bool b) { this.b = b; }
        ~this() @safe { destroyed = true; }

        // mustn't call opAssign on Test.init in Nullable!Test, because the invariant
        // will be called before opAssign on the Test.init that is in Nullable
        // and Test.init violates its invariant.
        void opAssign(Test rhs) @safe { assert(false); }
    }

    {
        Nullable!Test nt;

        nt = Test(true);

        // destroy value
        Test.destroyed = false;

        nt.nullify;

        assert(Test.destroyed);

        Test.destroyed = false;
    }
    // don't run destructor on T.init in Nullable on scope exit!
    assert(!Test.destroyed);
}
// check that the contained type's destructor is called on assignment
@system unittest
{
    struct S
    {
        // can't be static, since we need a specific value's pointer
        bool* destroyedRef;

        ~this()
        {
            if (this.destroyedRef)
            {
                *this.destroyedRef = true;
            }
        }
    }

    Nullable!S ns;

    bool destroyed;

    ns = S(&destroyed);

    // reset from rvalue destruction in Nullable's opAssign
    destroyed = false;

    // overwrite Nullable
    ns = S(null);

    // the original S should be destroyed.
    assert(destroyed == true);
}
// check that the contained type's destructor is still called when required
@system unittest
{
    bool destructorCalled = false;

    struct S
    {
        bool* destroyed;
        ~this() { *this.destroyed = true; }
    }

    {
        Nullable!S ns;
    }
    assert(!destructorCalled);
    {
        Nullable!S ns = Nullable!S(S(&destructorCalled));

        destructorCalled = false; // reset after S was destroyed in the NS constructor
    }
    assert(destructorCalled);
}

// check that toHash on Nullable is forwarded to the contained type
@system unittest
{
    struct S
    {
        size_t toHash() const @safe pure nothrow { return 5; }
    }

    Nullable!S s1 = S();
    Nullable!S s2 = Nullable!S();

    assert(typeid(Nullable!S).getHash(&s1) == 5);
    assert(typeid(Nullable!S).getHash(&s2) == 0);
}

// https://issues.dlang.org/show_bug.cgi?id=21704
@safe unittest
{
    import std.array : staticArray;

    bool destroyed;

    struct Probe
    {
        ~this() { destroyed = true; }
    }

    {
        Nullable!(Probe[1]) test = [Probe()].staticArray;
        destroyed = false;
    }
    assert(destroyed);
}

// https://issues.dlang.org/show_bug.cgi?id=21705
@safe unittest
{
    static struct S
    {
        int n;
        bool opEquals(S rhs) { return n == rhs.n; }
    }

    Nullable!S test1 = S(1), test2 = S(1);
    S s = S(1);

    assert(test1 == s);
    assert(test1 == test2);
}

// https://issues.dlang.org/show_bug.cgi?id=22101
@safe unittest
{
    static int impure;

    struct S
    {
        ~this() { impure++; }
    }

    Nullable!S s;
    s.get(S());
}

// https://issues.dlang.org/show_bug.cgi?id=22100
@safe unittest
{
    Nullable!int a, b, c;
    a = b = c = 5;
    a = b = c = nullable(5);
}

// https://issues.dlang.org/show_bug.cgi?id=18374
@safe pure nothrow unittest
{
    import std.algorithm.comparison : equal;
    import std.range : only, takeNone;
    import std.range.primitives : hasAssignableElements, hasLength,
        hasLvalueElements, hasSlicing, hasSwappableElements,
        isRandomAccessRange;
    Nullable!int a = 42;
    assert(!a.empty);
    assert(a.front == 42);
    assert(a.back == 42);
    assert(a[0] == 42);
    assert(a.equal(only(42)));
    assert(a[0 .. $].equal(only(42)));
    a[0] = 43;
    assert(a.equal(only(43)));
    --a[0];
    assert(a.equal(only(42)));
    Nullable!int b;
    assert(b.empty);
    assert(b.equal(takeNone(b)));
    Nullable!int c = a.save();
    assert(!c.empty);
    c.popFront();
    assert(!a.empty);
    assert(c.empty);

    assert(isRandomAccessRange!(Nullable!int));
    assert(hasLength!(Nullable!int));
    assert(hasSlicing!(Nullable!int));
    assert(hasAssignableElements!(Nullable!int));
    assert(hasSwappableElements!(Nullable!int));
    assert(hasLvalueElements!(Nullable!int));
}

/**
Just like `Nullable!T`, except that the null state is defined as a
particular value. For example, $(D Nullable!(uint, uint.max)) is an
`uint` that sets aside the value `uint.max` to denote a null
state. $(D Nullable!(T, nullValue)) is more storage-efficient than $(D
Nullable!T) because it does not need to store an extra `bool`.

Params:
    T = The wrapped type for which Nullable provides a null value.

    nullValue = The null value which denotes the null state of this
                `Nullable`. Must be of type `T`.
 */
struct Nullable(T, T nullValue)
{
    private T _value = nullValue;

/**
Constructor initializing `this` with `value`.

Params:
    value = The value to initialize this `Nullable` with.
 */
    this(T value)
    {
        _value = value;
    }

    template toString()
    {
        import std.format.spec : FormatSpec;
        import std.format.write : formatValue;
        // Needs to be a template because of https://issues.dlang.org/show_bug.cgi?id=13737.
        void toString()(scope void delegate(const(char)[]) sink, scope const ref FormatSpec!char fmt)
        {
            if (isNull)
            {
                sink.formatValue("Nullable.null", fmt);
            }
            else
            {
                sink.formatValue(_value, fmt);
            }
        }
    }

/**
Check if `this` is in the null state.

Returns:
    true $(B iff) `this` is in the null state, otherwise false.
 */
    @property bool isNull() const
    {
        //Need to use 'is' if T is a nullable type and
        //nullValue is null, or it's a compiler error
        static if (is(CommonType!(T, typeof(null)) == T) && nullValue is null)
        {
            return _value is nullValue;
        }
        //Need to use 'is' if T is a float type
        //because NaN != NaN
        else static if (__traits(isFloating, T) || __traits(compiles, { static assert(!(nullValue == nullValue)); }))
        {
            return _value is nullValue;
        }
        else
        {
            return _value == nullValue;
        }
    }

///
@safe unittest
{
    Nullable!(int, -1) ni;
    //Initialized to "null" state
    assert(ni.isNull);

    ni = 0;
    assert(!ni.isNull);
}

@system unittest
{
    assert(typeof(this).init.isNull, typeof(this).stringof ~
        ".isNull does not work correctly because " ~ T.stringof ~
        " has an == operator that is non-reflexive and could not be" ~
        " determined before runtime to be non-reflexive!");
}

// https://issues.dlang.org/show_bug.cgi?id=11135
// disable test until https://issues.dlang.org/show_bug.cgi?id=15316 gets fixed
version (none) @system unittest
{
    static foreach (T; AliasSeq!(float, double, real))
    {{
        Nullable!(T, T.init) nf;
        //Initialized to "null" state
        assert(nf.isNull);
        assert(nf is typeof(nf).init);

        nf = 0;
        assert(!nf.isNull);

        nf.nullify();
        assert(nf.isNull);
    }}
}

/**
Forces `this` to the null state.
 */
    void nullify()()
    {
        _value = nullValue;
    }

///
@safe unittest
{
    Nullable!(int, -1) ni = 0;
    assert(!ni.isNull);

    ni = -1;
    assert(ni.isNull);
}

/**
Assigns `value` to the internally-held state. If the assignment
succeeds, `this` becomes non-null. No null checks are made. Note
that the assignment may leave `this` in the null state.

Params:
    value = A value of type `T` to assign to this `Nullable`.
            If it is `nullvalue`, then the internal state of
            this `Nullable` will be set to null.
 */
    void opAssign()(T value)
    {
        import std.algorithm.mutation : swap;

        swap(value, _value);
    }

/**
    If this `Nullable` wraps a type that already has a null value
    (such as a pointer), and that null value is not given for
    `nullValue`, then assigning the null value to this `Nullable`
    is no different than assigning any other value of type `T`,
    and the resulting code will look very strange. It is strongly
    recommended that this be avoided by using `T`'s "built in"
    null value for `nullValue`.
 */
@system unittest
{
    //Passes
    enum nullVal = cast(int*) 0xCAFEBABE;
    Nullable!(int*, nullVal) npi;
    assert(npi.isNull);

    //Passes?!
    npi = null;
    assert(!npi.isNull);
}

/**
Gets the value. `this` must not be in the null state.
This function is also called for the implicit conversion to `T`.

Preconditions: `isNull` must be `false`.
Returns:
    The value held internally by this `Nullable`.
 */
    @property ref inout(T) get() inout
    {
        //@@@6169@@@: We avoid any call that might evaluate nullValue's %s,
        //Because it might messup get's purity and safety inference.
        enum message = "Called `get' on null Nullable!(" ~ T.stringof ~ ",nullValue).";
        assert(!isNull, message);
        return _value;
    }

///
@system unittest
{
    import std.exception : assertThrown, assertNotThrown;

    Nullable!(int, -1) ni;
    //`get` is implicitly called. Will throw
    //an error in non-release mode
    assertThrown!Throwable(ni == 0);

    ni = 0;
    assertNotThrown!Throwable(ni == 0);
}

/**
Implicitly converts to `T`.
`this` must not be in the null state.
 */
    alias get this;
}

/// ditto
auto nullable(alias nullValue, T)(T t)
if (is (typeof(nullValue) == T))
{
    return Nullable!(T, nullValue)(t);
}

///
@safe unittest
{
    Nullable!(size_t, size_t.max) indexOf(string[] haystack, string needle)
    {
        //Find the needle, returning -1 if not found

        return Nullable!(size_t, size_t.max).init;
    }

    void sendLunchInvite(string name)
    {
    }

    //It's safer than C...
    auto coworkers = ["Jane", "Jim", "Marry", "Fred"];
    auto pos = indexOf(coworkers, "Bob");
    if (!pos.isNull)
    {
        //Send Bob an invitation to lunch
        sendLunchInvite(coworkers[pos]);
    }
    else
    {
        //Bob not found; report the error
    }

    //And there's no overhead
    static assert(Nullable!(size_t, size_t.max).sizeof == size_t.sizeof);
}

///
@system unittest
{
    import std.exception : assertThrown;

    Nullable!(int, int.min) a;
    assert(a.isNull);
    assertThrown!Throwable(a.get);
    a = 5;
    assert(!a.isNull);
    assert(a == 5);
    static assert(a.sizeof == int.sizeof);
}

///
@safe unittest
{
    auto a = nullable!(int.min)(8);
    assert(a == 8);
    a.nullify();
    assert(a.isNull);
}

@nogc nothrow pure @safe unittest
{
    // https://issues.dlang.org/show_bug.cgi?id=19226
    // fully handle non-self-equal nullValue
    static struct Fraction
    {
        int denominator;
        bool isNaN() const
        {
            return denominator == 0;
        }
        bool opEquals(const Fraction rhs) const
        {
            return !isNaN && denominator == rhs.denominator;
        }
    }
    alias N = Nullable!(Fraction, Fraction.init);
    assert(N.init.isNull);
}

@safe unittest
{
    static int f(scope const Nullable!(int, int.min) x) {
        return x.isNull ? 42 : x.get;
    }
    Nullable!(int, int.min) a;
    assert(f(a) == 42);
    a = 8;
    assert(f(a) == 8);
    a.nullify();
    assert(f(a) == 42);
}
@safe unittest
{
    // Ensure Nullable can be used in pure/nothrow/@safe environment.
    function() @safe pure nothrow
    {
        Nullable!(int, int.min) n;
        assert(n.isNull);
        n = 4;
        assert(!n.isNull);
        assert(n == 4);
        n.nullify();
        assert(n.isNull);
    }();
}
@system unittest
{
    // Ensure Nullable can be used when the value is not pure/nothrow/@system
    static struct S
    {
        int x;
        bool opEquals(const S s) const @system { return s.x == x; }
    }

    Nullable!(S, S(711)) s;
    assert(s.isNull);
    s = S(5);
    assert(!s.isNull);
    assert(s.x == 5);
    s.nullify();
    assert(s.isNull);
}
@safe unittest
{
    //Check nullable is nicelly embedable in a struct
    static struct S1
    {
        Nullable!(int, 0) ni;
    }
    static struct S2 //inspired from 9404
    {
        Nullable!(int, 0) ni;
        this(S2 other)
        {
            ni = other.ni;
        }
        void opAssign(S2 other)
        {
            ni = other.ni;
        }
    }
    static foreach (S; AliasSeq!(S1, S2))
    {{
        S a;
        S b = a;
        S c;
        c = a;
    }}
}
@system unittest
{
    import std.conv : to;

    // https://issues.dlang.org/show_bug.cgi?id=10915
    Nullable!(int, 1) ni = 1;
    assert(ni.to!string() == "Nullable.null");

    struct Test { string s; }
    alias NullableTest = Nullable!(Test, Test("null"));

    NullableTest nt = Test("test");
    assert(nt.to!string() == `Test("test")`);

    NullableTest ntn = Test("null");
    assert(ntn.to!string() == "Nullable.null");

    class TestToString
    {
        double d;

        this(double d)
        {
            this.d = d;
        }

        override string toString()
        {
            return d.to!string();
        }
    }
    alias NullableTestToString = Nullable!(TestToString, null);

    NullableTestToString ntts = new TestToString(2.5);
    assert(ntts.to!string() == "2.5");
}

// apply
/**
Unpacks the content of a `Nullable`, performs an operation and packs it again. Does nothing if isNull.

When called on a `Nullable`, `apply` will unpack the value contained in the `Nullable`,
pass it to the function you provide and wrap the result in another `Nullable` (if necessary).
If the `Nullable` is null, `apply` will return null itself.

Params:
    t = a `Nullable`
    fun = a function operating on the content of the nullable

Returns:
    `fun(t.get).nullable` if `!t.isNull`, else `Nullable.init`.

See also:
    $(HTTPS en.wikipedia.org/wiki/Monad_(functional_programming)#The_Maybe_monad, The `Maybe` monad)
 */
template apply(alias fun)
{
    import std.functional : unaryFun;

    auto apply(T)(auto ref T t)
    if (isInstanceOf!(Nullable, T))
    {
        alias FunType = typeof(unaryFun!fun(T.init.get));

        enum MustWrapReturn = !isInstanceOf!(Nullable, FunType);

        static if (MustWrapReturn)
        {
            alias ReturnType = Nullable!FunType;
        }
        else
        {
            alias ReturnType = FunType;
        }

        if (!t.isNull)
        {
            static if (MustWrapReturn)
            {
                return unaryFun!fun(t.get).nullable;
            }
            else
            {
                return unaryFun!fun(t.get);
            }
        }
        else
        {
            return ReturnType.init;
        }
    }
}

///
nothrow pure @nogc @safe unittest
{
    alias toFloat = i => cast(float) i;

    Nullable!int sample;

    // apply(null) results in a null `Nullable` of the function's return type.
    Nullable!float f = sample.apply!toFloat;
    assert(sample.isNull && f.isNull);

    sample = 3;

    // apply(non-null) calls the function and wraps the result in a `Nullable`.
    f = sample.apply!toFloat;
    assert(!sample.isNull && !f.isNull);
    assert(f.get == 3.0f);
}

///
nothrow pure @nogc @safe unittest
{
    alias greaterThree = i => (i > 3) ? i.nullable : Nullable!(typeof(i)).init;

    Nullable!int sample;

    // when the function already returns a `Nullable`, that `Nullable` is not wrapped.
    auto result = sample.apply!greaterThree;
    assert(sample.isNull && result.isNull);

    // The function may decide to return a null `Nullable`.
    sample = 3;
    result = sample.apply!greaterThree;
    assert(!sample.isNull && result.isNull);

    // Or it may return a value already wrapped in a `Nullable`.
    sample = 4;
    result = sample.apply!greaterThree;
    assert(!sample.isNull && !result.isNull);
    assert(result.get == 4);
}

// test that Nullable.get(default) can merge types
@safe @nogc nothrow pure
unittest
{
    Nullable!ubyte sample = Nullable!ubyte();

    // Test that get(U) returns the common type of the Nullable type and the parameter type.
    assert(sample.get(1000) == 1000);
}

// Workaround for https://issues.dlang.org/show_bug.cgi?id=20670
@safe @nogc nothrow pure
unittest
{
    immutable struct S { }

    S[] array = Nullable!(S[])().get(S[].init);
}

// regression test for https://issues.dlang.org/show_bug.cgi?id=21199
@safe @nogc nothrow pure
unittest
{
    struct S { int i; }
    assert(S(5).nullable.apply!"a.i" == 5);
}

// regression test for https://issues.dlang.org/show_bug.cgi?id=22176
@safe @nogc nothrow pure
unittest
{
    struct S
    {
        int i;
        invariant(i != 0);

        // Nullable shouldn't cause S to generate an
        // opAssign that would check the invariant.
        Nullable!int j;
    }
    S s;
    s = S(5);
}

/**
Just like `Nullable!T`, except that the object refers to a value
sitting elsewhere in memory. This makes assignments overwrite the
initially assigned value. Internally `NullableRef!T` only stores a
pointer to `T` (i.e., $(D Nullable!T.sizeof == (T*).sizeof)).
 */
struct NullableRef(T)
{
    private T* _value;

/**
Constructor binding `this` to `value`.

Params:
    value = The value to bind to.
 */
    this(T* value) @safe pure nothrow
    {
        _value = value;
    }

    template toString()
    {
        import std.format.spec : FormatSpec;
        import std.format.write : formatValue;
        // Needs to be a template because of https://issues.dlang.org/show_bug.cgi?id=13737.
        void toString()(scope void delegate(const(char)[]) sink, scope const ref FormatSpec!char fmt)
        {
            if (isNull)
            {
                sink.formatValue("Nullable.null", fmt);
            }
            else
            {
                sink.formatValue(*_value, fmt);
            }
        }
    }

/**
Binds the internal state to `value`.

Params:
    value = A pointer to a value of type `T` to bind this `NullableRef` to.
 */
    void bind(T* value) @safe pure nothrow
    {
        _value = value;
    }

    ///
    @safe unittest
    {
        NullableRef!int nr = new int(42);
        assert(nr == 42);

        int* n = new int(1);
        nr.bind(n);
        assert(nr == 1);
    }

/**
Returns `true` if and only if `this` is in the null state.

Returns:
    true if `this` is in the null state, otherwise false.
 */
    @property bool isNull() const @safe pure nothrow
    {
        return _value is null;
    }

    ///
    @safe unittest
    {
        NullableRef!int nr;
        assert(nr.isNull);

        int* n = new int(42);
        nr.bind(n);
        assert(!nr.isNull && nr == 42);
    }

/**
Forces `this` to the null state.
 */
    void nullify() @safe pure nothrow
    {
        _value = null;
    }

    ///
    @safe unittest
    {
        NullableRef!int nr = new int(42);
        assert(!nr.isNull);

        nr.nullify();
        assert(nr.isNull);
    }

/**
Assigns `value` to the internally-held state.

Params:
    value = A value of type `T` to assign to this `NullableRef`.
            If the internal state of this `NullableRef` has not
            been initialized, an error will be thrown in
            non-release mode.
 */
    void opAssign()(T value)
        if (isAssignable!T) //@@@9416@@@
    {
        enum message = "Called `opAssign' on null NullableRef!" ~ T.stringof ~ ".";
        assert(!isNull, message);
        *_value = value;
    }

    ///
    @system unittest
    {
        import std.exception : assertThrown, assertNotThrown;

        NullableRef!int nr;
        assert(nr.isNull);
        assertThrown!Throwable(nr = 42);

        nr.bind(new int(0));
        assert(!nr.isNull);
        assertNotThrown!Throwable(nr = 42);
        assert(nr == 42);
    }

/**
Gets the value. `this` must not be in the null state.
This function is also called for the implicit conversion to `T`.
 */
    @property ref inout(T) get() inout @safe pure nothrow
    {
        enum message = "Called `get' on null NullableRef!" ~ T.stringof ~ ".";
        assert(!isNull, message);
        return *_value;
    }

    ///
    @system unittest
    {
        import std.exception : assertThrown, assertNotThrown;

        NullableRef!int nr;
        //`get` is implicitly called. Will throw
        //an error in non-release mode
        assertThrown!Throwable(nr == 0);

        nr.bind(new int(0));
        assertNotThrown!Throwable(nr == 0);
    }

/**
Implicitly converts to `T`.
`this` must not be in the null state.
 */
    alias get this;
}

/// ditto
auto nullableRef(T)(T* t)
{
    return NullableRef!T(t);
}

///
@system unittest
{
    import std.exception : assertThrown;

    int x = 5, y = 7;
    auto a = nullableRef(&x);
    assert(!a.isNull);
    assert(a == 5);
    assert(x == 5);
    a = 42;
    assert(x == 42);
    assert(!a.isNull);
    assert(a == 42);
    a.nullify();
    assert(x == 42);
    assert(a.isNull);
    assertThrown!Throwable(a.get);
    assertThrown!Throwable(a = 71);
    a.bind(&y);
    assert(a == 7);
    y = 135;
    assert(a == 135);
}
@system unittest
{
    static int f(scope const NullableRef!int x) {
        return x.isNull ? 42 : x.get;
    }
    int x = 5;
    auto a = nullableRef(&x);
    assert(f(a) == 5);
    a.nullify();
    assert(f(a) == 42);
}
@safe unittest
{
    // Ensure NullableRef can be used in pure/nothrow/@safe environment.
    function() @safe pure nothrow
    {
        auto storage = new int;
        *storage = 19902;
        NullableRef!int n;
        assert(n.isNull);
        n.bind(storage);
        assert(!n.isNull);
        assert(n == 19902);
        n = 2294;
        assert(n == 2294);
        assert(*storage == 2294);
        n.nullify();
        assert(n.isNull);
    }();
}
@system unittest
{
    // Ensure NullableRef can be used when the value is not pure/nothrow/@safe
    static struct S
    {
        int x;
        this(this) @system {}
        bool opEquals(const S s) const @system { return s.x == x; }
    }

    auto storage = S(5);

    NullableRef!S s;
    assert(s.isNull);
    s.bind(&storage);
    assert(!s.isNull);
    assert(s.x == 5);
    s.nullify();
    assert(s.isNull);
}
@safe unittest
{
    //Check nullable is nicelly embedable in a struct
    static struct S1
    {
        NullableRef!int ni;
    }
    static struct S2 //inspired from 9404
    {
        NullableRef!int ni;
        this(S2 other)
        {
            ni = other.ni;
        }
        void opAssign(S2 other)
        {
            ni = other.ni;
        }
    }
    static foreach (S; AliasSeq!(S1, S2))
    {{
        S a;
        S b = a;
        S c;
        c = a;
    }}
}

// https://issues.dlang.org/show_bug.cgi?id=10915
@system unittest
{
    import std.conv : to;

    NullableRef!int nri;
    assert(nri.to!string() == "Nullable.null");

    struct Test
    {
        string s;
    }
    NullableRef!Test nt = new Test("test");
    assert(nt.to!string() == `Test("test")`);

    class TestToString
    {
        double d;

        this(double d)
        {
            this.d = d;
        }

        override string toString()
        {
            return d.to!string();
        }
    }
    TestToString tts = new TestToString(2.5);
    NullableRef!TestToString ntts = &tts;
    assert(ntts.to!string() == "2.5");
}


/**
`BlackHole!Base` is a subclass of `Base` which automatically implements
all abstract member functions in `Base` as do-nothing functions.  Each
auto-implemented function just returns the default value of the return type
without doing anything.

The name came from
$(HTTP search.cpan.org/~sburke/Class-_BlackHole-0.04/lib/Class/_BlackHole.pm, Class::_BlackHole)
Perl module by Sean M. Burke.

Params:
    Base = A non-final class for `BlackHole` to inherit from.

See_Also:
  $(LREF AutoImplement), $(LREF generateEmptyFunction)
 */
alias BlackHole(Base) = AutoImplement!(Base, generateEmptyFunction, isAbstractFunction);

///
@system unittest
{
    import std.math.traits : isNaN;

    static abstract class C
    {
        int m_value;
        this(int v) { m_value = v; }
        int value() @property { return m_value; }

        abstract real realValue() @property;
        abstract void doSomething();
    }

    auto c = new BlackHole!C(42);
    assert(c.value == 42);

    // Returns real.init which is NaN
    assert(c.realValue.isNaN);
    // Abstract functions are implemented as do-nothing
    c.doSomething();
}

@system unittest
{
    import std.math.traits : isNaN;

    // return default
    {
        interface I_1 { real test(); }
        auto o = new BlackHole!I_1;
        assert(o.test().isNaN()); // NaN
    }
    // doc example
    {
        static class C
        {
            int m_value;
            this(int v) { m_value = v; }
            int value() @property { return m_value; }

            abstract real realValue() @property;
            abstract void doSomething();
        }

        auto c = new BlackHole!C(42);
        assert(c.value == 42);

        assert(c.realValue.isNaN); // NaN
        c.doSomething();
    }

    // https://issues.dlang.org/show_bug.cgi?id=12058
    interface Foo
    {
        inout(Object) foo() inout;
    }
    BlackHole!Foo o;
}

nothrow pure @nogc @safe unittest
{
    static interface I
    {
        I foo() nothrow pure @nogc @safe return scope;
    }

    scope cb = new BlackHole!I();
    cb.foo();
}


/**
`WhiteHole!Base` is a subclass of `Base` which automatically implements
all abstract member functions as functions that always fail. These functions
simply throw an `Error` and never return. `Whitehole` is useful for
trapping the use of class member functions that haven't been implemented.

The name came from
$(HTTP search.cpan.org/~mschwern/Class-_WhiteHole-0.04/lib/Class/_WhiteHole.pm, Class::_WhiteHole)
Perl module by Michael G Schwern.

Params:
    Base = A non-final class for `WhiteHole` to inherit from.

See_Also:
  $(LREF AutoImplement), $(LREF generateAssertTrap)
 */
alias WhiteHole(Base) = AutoImplement!(Base, generateAssertTrap, isAbstractFunction);

///
@system unittest
{
    import std.exception : assertThrown;

    static class C
    {
        abstract void notYetImplemented();
    }

    auto c = new WhiteHole!C;
    assertThrown!NotImplementedError(c.notYetImplemented()); // throws an Error
}

// https://issues.dlang.org/show_bug.cgi?id=20232
nothrow pure @safe unittest
{
    static interface I
    {
        I foo() nothrow pure @safe return scope;
    }

    if (0) // Just checking attribute interference
    {
        scope cw = new WhiteHole!I();
        cw.foo();
    }
}

// / ditto
class NotImplementedError : Error
{
    this(string method) nothrow pure @safe
    {
        super(method ~ " is not implemented");
    }
}

@system unittest
{
    import std.exception : assertThrown;
    // nothrow
    {
        interface I_1
        {
            void foo();
            void bar() nothrow;
        }
        auto o = new WhiteHole!I_1;
        assertThrown!NotImplementedError(o.foo());
        assertThrown!NotImplementedError(o.bar());
    }
    // doc example
    {
        static class C
        {
            abstract void notYetImplemented();
        }

        auto c = new WhiteHole!C;
        try
        {
            c.notYetImplemented();
            assert(0);
        }
        catch (Error e) {}
    }
}


/**
`AutoImplement` automatically implements (by default) all abstract member
functions in the class or interface `Base` in specified way.

The second version of `AutoImplement` automatically implements
`Interface`, while deriving from `BaseClass`.

Params:
  how  = template which specifies _how functions will be implemented/overridden.

         Two arguments are passed to `how`: the type `Base` and an alias
         to an implemented function.  Then `how` must return an implemented
         function body as a string.

         The generated function body can use these keywords:
         $(UL
            $(LI `a0`, `a1`, &hellip;: arguments passed to the function;)
            $(LI `args`: a tuple of the arguments;)
            $(LI `self`: an alias to the function itself;)
            $(LI `parent`: an alias to the overridden function (if any).)
         )

        You may want to use templated property functions (instead of Implicit
        Template Properties) to generate complex functions:
--------------------
// Prints log messages for each call to overridden functions.
string generateLogger(C, alias fun)() @property
{
    import std.traits;
    enum qname = C.stringof ~ "." ~ __traits(identifier, fun);
    string stmt;

    stmt ~= q{ struct Importer { import std.stdio; } };
    stmt ~= `Importer.writeln("Log: ` ~ qname ~ `(", args, ")");`;
    static if (!__traits(isAbstractFunction, fun))
    {
        static if (is(ReturnType!fun == void))
            stmt ~= q{ parent(args); };
        else
            stmt ~= q{
                auto r = parent(args);
                Importer.writeln("--> ", r);
                return r;
            };
    }
    return stmt;
}
--------------------

  what = template which determines _what functions should be
         implemented/overridden.

         An argument is passed to `what`: an alias to a non-final member
         function in `Base`.  Then `what` must return a boolean value.
         Return `true` to indicate that the passed function should be
         implemented/overridden.

--------------------
// Sees if fun returns something.
enum bool hasValue(alias fun) = !is(ReturnType!(fun) == void);
--------------------


Note:

Generated code is inserted in the scope of `std.typecons` module.  Thus,
any useful functions outside `std.typecons` cannot be used in the generated
code.  To workaround this problem, you may `import` necessary things in a
local struct, as done in the `generateLogger()` template in the above
example.


BUGS:

$(UL
 $(LI Variadic arguments to constructors are not forwarded to super.)
 $(LI Deep interface inheritance causes compile error with messages like
      "Error: function std.typecons._AutoImplement!(Foo)._AutoImplement.bar
      does not override any function".  [$(BUGZILLA 2525)] )
 $(LI The `parent` keyword is actually a delegate to the super class'
      corresponding member function.  [$(BUGZILLA 2540)] )
 $(LI Using alias template parameter in `how` and/or `what` may cause
     strange compile error.  Use template tuple parameter instead to workaround
     this problem.  [$(BUGZILLA 4217)] )
)
 */
class AutoImplement(Base, alias how, alias what = isAbstractFunction) : Base
if (!is(how == class))
{
    private alias autoImplement_helper_ =
        AutoImplement_Helper!("autoImplement_helper_", "Base", Base, typeof(this), how, what);
    mixin(autoImplement_helper_.code);
}

/// ditto
class AutoImplement(
    Interface, BaseClass, alias how,
    alias what = isAbstractFunction) : BaseClass, Interface
if (is(Interface == interface) && is(BaseClass == class))
{
    private alias autoImplement_helper_ = AutoImplement_Helper!(
            "autoImplement_helper_", "Interface", Interface, typeof(this), how, what);
    mixin(autoImplement_helper_.code);
}

///
@system unittest
{
    interface PackageSupplier
    {
        int foo();
        int bar();
    }

    static abstract class AbstractFallbackPackageSupplier : PackageSupplier
    {
        protected PackageSupplier default_, fallback;

        this(PackageSupplier default_, PackageSupplier fallback)
        {
            this.default_ = default_;
            this.fallback = fallback;
        }

        abstract int foo();
        abstract int bar();
    }

    template fallback(T, alias func)
    {
        import std.format : format;
        // for all implemented methods:
        // - try default first
        // - only on a failure run & return fallback
        enum fallback = q{
            try
            {
                return default_.%1$s(args);
            }
            catch (Exception)
            {
                return fallback.%1$s(args);
            }
        }.format(__traits(identifier, func));
    }

    // combines two classes and use the second one as fallback
    alias FallbackPackageSupplier = AutoImplement!(AbstractFallbackPackageSupplier, fallback);

    class FailingPackageSupplier : PackageSupplier
    {
        int foo(){ throw new Exception("failure"); }
        int bar(){ return 2;}
    }

    class BackupPackageSupplier : PackageSupplier
    {
        int foo(){ return -1; }
        int bar(){ return -1;}
    }

    auto registry = new FallbackPackageSupplier(new FailingPackageSupplier(), new BackupPackageSupplier());

    assert(registry.foo() == -1);
    assert(registry.bar() == 2);
}

/*
 * Code-generating stuffs are encupsulated in this helper template so that
 * namespace pollution, which can cause name confliction with Base's public
 * members, should be minimized.
 */
private template AutoImplement_Helper(string myName, string baseName,
        Base, Self, alias generateMethodBody, alias cherrypickMethod)
{
private static:
    //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
    // Internal stuffs
    //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://

    // Returns function overload sets in the class C, filtered with pred.
    template enumerateOverloads(C, alias pred)
    {
        template Impl(names...)
        {
            import std.meta : Filter;
            static if (names.length > 0)
            {
                alias methods = Filter!(pred, MemberFunctionsTuple!(C, names[0]));
                alias next = Impl!(names[1 .. $]);

                static if (methods.length > 0)
                    alias Impl = AliasSeq!(OverloadSet!(names[0], methods), next);
                else
                    alias Impl = next;
            }
            else
                alias Impl = AliasSeq!();
        }

        alias enumerateOverloads = Impl!(__traits(allMembers, C));
    }

    //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
    // Target functions
    //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://

    // Add a non-final check to the cherrypickMethod.
    enum bool canonicalPicker(fun.../+[https://issues.dlang.org/show_bug.cgi?id=4217]+/) =
        !__traits(isFinalFunction, fun[0]) && cherrypickMethod!(fun);

    /*
     * A tuple of overload sets, each item of which consists of functions to be
     * implemented by the generated code.
     */
    alias targetOverloadSets = enumerateOverloads!(Base, canonicalPicker);

    /*
     * Super class of this AutoImplement instance
     */
    alias Super = BaseTypeTuple!(Self)[0];
    static assert(is(Super == class));
    static assert(is(Base == interface) || is(Super == Base));

    /*
     * A tuple of the super class' constructors.  Used for forwarding
     * constructor calls.
     */
    static if (__traits(hasMember, Super, "__ctor"))
        alias ctorOverloadSet = OverloadSet!("__ctor", __traits(getOverloads, Super, "__ctor"));
    else
        alias ctorOverloadSet = OverloadSet!("__ctor"); // empty


    //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
    // Type information
    //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://

    /*
     * The generated code will be mixed into AutoImplement, which will be
     * instantiated in this module's scope.  Thus, any user-defined types are
     * out of scope and cannot be used directly (i.e. by their names).
     *
     * We will use FuncInfo instances for accessing return types and parameter
     * types of the implemented functions.  The instances will be populated to
     * the AutoImplement's scope in a certain way; see the populate() below.
     */

    // Returns the preferred identifier for the FuncInfo instance for the i-th
    // overloaded function with the name.
    template INTERNAL_FUNCINFO_ID(string name, size_t i)
    {
        import std.format : format;

        enum string INTERNAL_FUNCINFO_ID = format("F_%s_%s", name, i);
    }

    /*
     * Insert FuncInfo instances about all the target functions here.  This
     * enables the generated code to access type information via, for example,
     * "autoImplement_helper_.F_foo_1".
     */
    template populate(overloads...)
    {
        static if (overloads.length > 0)
        {
            mixin populate!(overloads[0].name, overloads[0].contents);
            mixin populate!(overloads[1 .. $]);
        }
    }
    template populate(string name, methods...)
    {
        static if (methods.length > 0)
        {
            mixin populate!(name, methods[0 .. $ - 1]);
            //
            alias target = methods[$ - 1];
            enum ith = methods.length - 1;
            mixin("alias " ~ INTERNAL_FUNCINFO_ID!(name, ith) ~ " = FuncInfo!target;");
        }
    }

    public mixin populate!(targetOverloadSets);
    public mixin populate!(  ctorOverloadSet );


    //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
    // Code-generating policies
    //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://

    /* Common policy configurations for generating constructors and methods. */
    template CommonGeneratingPolicy()
    {
        // base class identifier which generated code should use
        enum string BASE_CLASS_ID = baseName;

        // FuncInfo instance identifier which generated code should use
        template FUNCINFO_ID(string name, size_t i)
        {
            enum string FUNCINFO_ID =
                myName ~ "." ~ INTERNAL_FUNCINFO_ID!(name, i);
        }
    }

    /* Policy configurations for generating constructors. */
    template ConstructorGeneratingPolicy()
    {
        mixin CommonGeneratingPolicy;

        /* Generates constructor body.  Just forward to the base class' one. */
        string generateFunctionBody(ctor.../+[https://issues.dlang.org/show_bug.cgi?id=4217]+/)() @property
        {
            enum varstyle = variadicFunctionStyle!(typeof(&ctor[0]));

            static if (varstyle & (Variadic.c | Variadic.d))
            {
                // the argptr-forwarding problem
                //pragma(msg, "Warning: AutoImplement!(", Base, ") ",
                //        "ignored variadic arguments to the constructor ",
                //        FunctionTypeOf!(typeof(&ctor[0])) );
            }
            return "super(args);";
        }
    }

    /* Policy configurations for genearting target methods. */
    template MethodGeneratingPolicy()
    {
        mixin CommonGeneratingPolicy;

        /* Geneartes method body. */
        string generateFunctionBody(func.../+[https://issues.dlang.org/show_bug.cgi?id=4217]+/)() @property
        {
            return generateMethodBody!(Base, func); // given
        }
    }


    //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
    // Generated code
    //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://

    alias ConstructorGenerator = MemberFunctionGenerator!(ConstructorGeneratingPolicy!());
    alias MethodGenerator      = MemberFunctionGenerator!(MethodGeneratingPolicy!());

    public enum string code =
        ConstructorGenerator.generateCode!(  ctorOverloadSet ) ~ "\n" ~
             MethodGenerator.generateCode!(targetOverloadSets);

    debug (SHOW_GENERATED_CODE)
    {
        pragma(msg, "-------------------- < ", Base, " >");
        pragma(msg, code);
        pragma(msg, "--------------------");
    }
}

//debug = SHOW_GENERATED_CODE;
@system unittest
{
    import core.vararg;
    // no function to implement
    {
        interface I_1 {}
        auto o = new BlackHole!I_1;
    }
    // parameters
    {
        interface I_3 { void test(int, in int, out int, ref int, lazy int); }
        auto o = new BlackHole!I_3;
    }
    // use of user-defined type
    {
        struct S {}
        interface I_4 { S test(); }
        auto o = new BlackHole!I_4;
    }
    // overloads
    {
        interface I_5
        {
            void test(string);
            real test(real);
            int  test();
        }
        auto o = new BlackHole!I_5;
    }
    // constructor forwarding
    {
        static class C_6
        {
            this(int n) { assert(n == 42); }
            this(string s) { assert(s == "Deeee"); }
            this(...) {}
        }
        auto o1 = new BlackHole!C_6(42);
        auto o2 = new BlackHole!C_6("Deeee");
        auto o3 = new BlackHole!C_6(1, 2, 3, 4);
    }
    // attributes
    {
        interface I_7
        {
            ref int test_ref();
            int test_pure() pure;
            int test_nothrow() nothrow;
            int test_property() @property;
            int test_safe() @safe;
            int test_trusted() @trusted;
            int test_system() @system;
            int test_pure_nothrow() pure nothrow;
        }
        auto o = new BlackHole!I_7;
    }
    // storage classes
    {
        interface I_8
        {
            void test_const() const;
            void test_immutable() immutable;
            void test_shared() shared;
            void test_shared_const() shared const;
        }
        auto o = new BlackHole!I_8;
    }
    // use baseclass
    {
        static class C_9
        {
            private string foo_;

            this(string s) {
                foo_ = s;
            }

            protected string boilerplate() @property
            {
                return "Boilerplate stuff.";
            }

            public string foo() @property
            {
                return foo_;
            }
        }

        interface I_10
        {
            string testMethod(size_t);
        }

        static string generateTestMethod(C, alias fun)() @property
        {
            return "return this.boilerplate[0 .. a0];";
        }

        auto o = new AutoImplement!(I_10, C_9, generateTestMethod)("Testing");
        assert(o.testMethod(11) == "Boilerplate");
        assert(o.foo == "Testing");
    }
    /+ // deep inheritance
    {
    // https://issues.dlang.org/show_bug.cgi?id=2525
    // https://issues.dlang.org/show_bug.cgi?id=3525
    // NOTE: [r494] func.c(504-571) FuncDeclaration::semantic()
        interface I { void foo(); }
        interface J : I {}
        interface K : J {}
        static abstract class C_9 : K {}
        auto o = new BlackHole!C_9;
    }+/
    // test `parent` alias
    {
        interface I_11
        {
            void simple(int) @safe;
            int anotherSimple(string);
            int overloaded(int);
            /+ XXX [BUG 19715]
            void overloaded(string) @safe;
            +/
        }

        static class C_11
        {
            import std.traits : Parameters, ReturnType;
            import std.meta : Alias;

            protected ReturnType!fn _impl(alias fn)(Parameters!fn)
            if (is(Alias!(__traits(parent, fn)) == interface))
            {
                static if (!is(typeof(return) == void))
                    return typeof(return).init;
            }
        }

        template tpl(I, alias fn)
        if (is(I == interface) && __traits(isSame, __traits(parent, fn), I))
        {
            enum string tpl = q{
                enum bool haveReturn = !is(typeof(return) == void);

                static if (is(typeof(return) == void))
                    _impl!parent(args);
                else
                    return _impl!parent(args);
            };
        }

        auto o = new AutoImplement!(I_11, C_11, tpl);
    }
}

// https://issues.dlang.org/show_bug.cgi?id=17177
// AutoImplement fails on function overload sets with
// "cannot infer type from overloaded function symbol"
@system unittest
{
    static class Issue17177
    {
        private string n_;

        public {
            Issue17177 overloaded(string n)
            {
                this.n_ = n;

                return this;
            }

            string overloaded()
            {
                return this.n_;
            }
        }
    }

    static string how(C, alias fun)()
    {
        static if (!is(ReturnType!fun == void))
        {
            return q{
                return parent(args);
            };
        }
        else
        {
            return q{
                parent(args);
            };
        }
    }

    import std.meta : templateNot;
    alias Implementation = AutoImplement!(Issue17177, how, templateNot!isFinalFunction);
}

version (StdUnittest)
{
    // https://issues.dlang.org/show_bug.cgi?id=10647
    // Add prefix "issue10647_" as a workaround for
    // https://issues.dlang.org/show_bug.cgi?id=1238
    private string issue10647_generateDoNothing(C, alias fun)() @property
    {
        string stmt;

        static if (is(ReturnType!fun == void))
            stmt ~= "";
        else
        {
            string returnType = ReturnType!fun.stringof;
            stmt ~= "return "~returnType~".init;";
        }
        return stmt;
    }

    private template issue10647_isAlwaysTrue(alias fun)
    {
        enum issue10647_isAlwaysTrue = true;
    }

    // Do nothing template
    private template issue10647_DoNothing(Base)
    {
        alias issue10647_DoNothing = AutoImplement!(Base, issue10647_generateDoNothing, issue10647_isAlwaysTrue);
    }

    // A class to be overridden
    private class issue10647_Foo{
        void bar(int a) { }
    }
}

@system unittest
{
    auto foo = new issue10647_DoNothing!issue10647_Foo();
    foo.bar(13);
}

/*
Used by MemberFunctionGenerator.
 */
package template OverloadSet(string nam, T...)
{
    enum string name = nam;
    alias contents = T;
}

/*
Used by MemberFunctionGenerator.
 */
package template FuncInfo(alias func)
if (is(typeof(&func)))
{
    alias RT = ReturnType!(typeof(&func));
    alias PT = Parameters!(typeof(&func));
}
package template FuncInfo(Func)
{
    alias RT = ReturnType!Func;
    alias PT = Parameters!Func;
}

/*
General-purpose member function generator.
--------------------
template GeneratingPolicy()
{
    // [optional] the name of the class where functions are derived
    enum string BASE_CLASS_ID;

    // [optional] define this if you have only function types
    enum bool WITHOUT_SYMBOL;

    // [optional] Returns preferred identifier for i-th parameter.
    template PARAMETER_VARIABLE_ID(size_t i);

    // Returns the identifier of the FuncInfo instance for the i-th overload
    // of the specified name.  The identifier must be accessible in the scope
    // where generated code is mixed.
    template FUNCINFO_ID(string name, size_t i);

    // Returns implemented function body as a string.  When WITHOUT_SYMBOL is
    // defined, the latter is used.
    template generateFunctionBody(alias func);
    template generateFunctionBody(string name, FuncType);
}
--------------------
 */
package template MemberFunctionGenerator(alias Policy)
{
private static:
    //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
    // Internal stuffs
    //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
    import std.format;
    alias format = std.format.format;

    enum CONSTRUCTOR_NAME = "__ctor";

    // true if functions are derived from a base class
    enum WITH_BASE_CLASS = __traits(hasMember, Policy, "BASE_CLASS_ID");

    // true if functions are specified as types, not symbols
    enum WITHOUT_SYMBOL = __traits(hasMember, Policy, "WITHOUT_SYMBOL");

    // preferred identifier for i-th parameter variable
    static if (__traits(hasMember, Policy, "PARAMETER_VARIABLE_ID"))
    {
        alias PARAMETER_VARIABLE_ID = Policy.PARAMETER_VARIABLE_ID;
    }
    else
    {
        enum string PARAMETER_VARIABLE_ID(size_t i) = format("a%s", i);
            // default: a0, a1, ...
    }

    // Returns a tuple consisting of 0,1,2,...,n-1.  For static foreach.
    template CountUp(size_t n)
    {
        static if (n > 0)
            alias CountUp = AliasSeq!(CountUp!(n - 1), n - 1);
        else
            alias CountUp = AliasSeq!();
    }


    //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
    // Code generator
    //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://

    /*
     * Runs through all the target overload sets and generates D code which
     * implements all the functions in the overload sets.
     */
    public string generateCode(overloads...)() @property
    {
        string code = "";

        // run through all the overload sets
        foreach (i_; CountUp!(0 + overloads.length)) // workaround
        {
            enum i = 0 + i_; // workaround
            alias oset = overloads[i];

            code ~= generateCodeForOverloadSet!(oset);

            static if (WITH_BASE_CLASS && oset.name != CONSTRUCTOR_NAME)
            {
                // The generated function declarations may hide existing ones
                // in the base class (cf. HiddenFuncError), so we put an alias
                // declaration here to reveal possible hidden functions.
                code ~= format("alias %s = %s.%s;\n",
                            oset.name,
                            // super: https://issues.dlang.org/show_bug.cgi?id=2540
                            Policy.BASE_CLASS_ID,
                            oset.name);
            }
        }
        return code;
    }

    // handle each overload set
    private string generateCodeForOverloadSet(alias oset)() @property
    {
        string code = "";

        foreach (i_; CountUp!(0 + oset.contents.length)) // workaround
        {
            enum i = 0 + i_; // workaround
            code ~= generateFunction!(
                    Policy.FUNCINFO_ID!(oset.name, i), oset.name,
                    oset.contents[i]) ~ "\n";
        }
        return code;
    }

    /*
     * Returns D code which implements the function func.  This function
     * actually generates only the declarator part; the function body part is
     * generated by the functionGenerator() policy.
     */
    public string generateFunction(
            string myFuncInfo, string name, func... )() @property
    {
        import std.format : format;

        enum isCtor = (name == CONSTRUCTOR_NAME);

        string code; // the result

        auto paramsRes = generateParameters!(myFuncInfo, func)();
        code ~= paramsRes.imports;

        /*** Function Declarator ***/
        {
            alias Func = FunctionTypeOf!(func);
            alias FA = FunctionAttribute;
            enum atts     = functionAttributes!(func);
            enum realName = isCtor ? "this" : name;

            // FIXME?? Make it so that these aren't CTFE funcs any more, since
            // Format is deprecated, and format works at compile time?
            /* Made them CTFE funcs just for the sake of Format!(...) */

            // return type with optional "ref"
            static string make_returnType()
            {
                string rtype = "";

                if (!isCtor)
                {
                    if (atts & FA.ref_) rtype ~= "ref ";
                    rtype ~= myFuncInfo ~ ".RT";
                }
                return rtype;
            }
            enum returnType = make_returnType();

            // function attributes attached after declaration
            static string make_postAtts()
            {
                string poatts = "";
                if (atts & FA.pure_   ) poatts ~= " pure";
                if (atts & FA.nothrow_) poatts ~= " nothrow";
                if (atts & FA.property) poatts ~= " @property";
                if (atts & FA.safe    ) poatts ~= " @safe";
                if (atts & FA.trusted ) poatts ~= " @trusted";
                if (atts & FA.scope_ )  poatts ~= " scope";
                if (atts & FA.return_ ) poatts ~= " return";
                return poatts;
            }
            enum postAtts = make_postAtts();

            // function storage class
            static string make_storageClass()
            {
                string postc = "";
                if (is(Func ==    shared)) postc ~= " shared";
                if (is(Func ==     const)) postc ~= " const";
                if (is(Func ==     inout)) postc ~= " inout";
                if (is(Func == immutable)) postc ~= " immutable";
                return postc;
            }
            enum storageClass = make_storageClass();

            //
            if (__traits(isVirtualMethod, func))
                code ~= "override ";
            code ~= format("extern(%s) %s %s(%s) %s %s\n",
                    functionLinkage!(func),
                    returnType,
                    realName,
                    paramsRes.params,
                    postAtts, storageClass );
        }

        /*** Function Body ***/
        code ~= "{\n";
        {
            enum nparams = Parameters!(func).length;

            /* Declare keywords: args, self and parent. */
            string preamble;

            preamble ~= "alias args = AliasSeq!(" ~ enumerateParameters!(nparams) ~ ");\n";
            if (!isCtor)
            {
                preamble ~= "alias self = " ~ name ~ ";\n";
                static if (WITH_BASE_CLASS)
                    preamble ~= `alias parent = __traits(getMember, ` ~ Policy.BASE_CLASS_ID ~ `, "` ~ name ~ `");`;
            }

            // Function body
            static if (WITHOUT_SYMBOL)
                enum fbody = Policy.generateFunctionBody!(name, func);
            else
                enum fbody = Policy.generateFunctionBody!(func);

            code ~= preamble;
            code ~= fbody;
        }
        code ~= "}";

        return code;
    }

    /*
     * Returns D code which declares function parameters,
     * and optionally any imports (e.g. core.vararg)
     * "ref int a0, real a1, ..."
     */
    static struct GenParams { string imports, params; }
    private GenParams generateParameters(string myFuncInfo, func...)()
    {
        alias STC = ParameterStorageClass;
        alias stcs = ParameterStorageClassTuple!(func);
        enum nparams = stcs.length;

        string imports = ""; // any imports required
        string params = ""; // parameters

        foreach (i, stc; stcs)
        {
            if (i > 0) params ~= ", ";

            // Parameter storage classes.
            if (stc & STC.scope_) params ~= "scope ";
            if (stc & STC.in_)    params ~= "in ";
            if (stc & STC.out_  ) params ~= "out ";
            if (stc & STC.ref_  ) params ~= "ref ";
            if (stc & STC.lazy_ ) params ~= "lazy ";

            // Take parameter type from the FuncInfo.
            params ~= format("%s.PT[%s]", myFuncInfo, i);

            // Declare a parameter variable.
            params ~= " " ~ PARAMETER_VARIABLE_ID!(i);
        }

        // Add some ellipsis part if needed.
        auto style = variadicFunctionStyle!(func);
        final switch (style)
        {
            case Variadic.no:
                break;

            case Variadic.c, Variadic.d:
                imports ~= "import core.vararg;\n";
                // (...) or (a, b, ...)
                params ~= (nparams == 0) ? "..." : ", ...";
                break;

            case Variadic.typesafe:
                params ~= " ...";
                break;
        }

        return typeof(return)(imports, params);
    }

    // Returns D code which enumerates n parameter variables using comma as the
    // separator.  "a0, a1, a2, a3"
    private string enumerateParameters(size_t n)() @property
    {
        string params = "";

        foreach (i_; CountUp!(n))
        {
            enum i = 0 + i_; // workaround
            if (i > 0) params ~= ", ";
            params ~= PARAMETER_VARIABLE_ID!(i);
        }
        return params;
    }
}


/**
Predefined how-policies for `AutoImplement`.  These templates are also used by
`BlackHole` and `WhiteHole`, respectively.
 */
template generateEmptyFunction(C, func.../+[https://issues.dlang.org/show_bug.cgi?id=4217]+/)
{
    static if (is(ReturnType!(func) == void))
        enum string generateEmptyFunction = q{
        };
    else static if (functionAttributes!(func) & FunctionAttribute.ref_)
        enum string generateEmptyFunction = q{
            static typeof(return) dummy;
            return dummy;
        };
    else
        enum string generateEmptyFunction = q{
            return typeof(return).init;
        };
}

///
@system unittest
{
    alias BlackHole(Base) = AutoImplement!(Base, generateEmptyFunction);

    interface I
    {
        int foo();
        string bar();
    }

    auto i = new BlackHole!I();
    // generateEmptyFunction returns the default value of the return type without doing anything
    assert(i.foo == 0);
    assert(i.bar is null);
}

/// ditto
template generateAssertTrap(C, func...)
{
    enum string generateAssertTrap =
        `throw new NotImplementedError("` ~ C.stringof ~ "."
                ~ __traits(identifier, func) ~ `");`;
}

///
@system unittest
{
    import std.exception : assertThrown;

    alias WhiteHole(Base) = AutoImplement!(Base, generateAssertTrap);

    interface I
    {
        int foo();
        string bar();
    }

    auto i = new WhiteHole!I();
    // generateAssertTrap throws an exception for every unimplemented function of the interface
    assertThrown!NotImplementedError(i.foo);
    assertThrown!NotImplementedError(i.bar);
}

private
{
    pragma(mangle, "_d_toObject")
    extern(C) pure nothrow Object typecons_d_toObject(void* p);
}

/*
 * Avoids opCast operator overloading.
 */
private template dynamicCast(T)
if (is(T == class) || is(T == interface))
{
    @trusted
    T dynamicCast(S)(inout S source)
    if (is(S == class) || is(S == interface))
    {
        static if (is(Unqual!S : Unqual!T))
        {
            import std.traits : QualifierOf;
            alias Qual = QualifierOf!S; // SharedOf or MutableOf
            alias TmpT = Qual!(Unqual!T);
            inout(TmpT) tmp = source;   // bypass opCast by implicit conversion
            return *cast(T*)(&tmp);     // + variable pointer cast + dereference
        }
        else
        {
            return cast(T) typecons_d_toObject(*cast(void**)(&source));
        }
    }
}

@system unittest
{
    class C { @disable void opCast(T)(); }
    auto c = new C;
    static assert(!__traits(compiles, cast(Object) c));
    auto o = dynamicCast!Object(c);
    assert(c is o);

    interface I { @disable void opCast(T)(); Object instance(); }
    interface J { @disable void opCast(T)(); Object instance(); }
    class D : I, J { Object instance() { return this; } }
    I i = new D();
    static assert(!__traits(compiles, cast(J) i));
    J j = dynamicCast!J(i);
    assert(i.instance() is j.instance());
}

/**
Supports structural based typesafe conversion.

If `Source` has structural conformance with the `interface` `Targets`,
wrap creates an internal wrapper class which inherits `Targets` and
wraps the `src` object, then returns it.

`unwrap` can be used to extract objects which have been wrapped by `wrap`.
*/
template wrap(Targets...)
if (Targets.length >= 1 && allSatisfy!(isMutable, Targets))
{
    import std.meta : staticMap;

    // strict upcast
    auto wrap(Source)(inout Source src) @trusted pure nothrow
    if (Targets.length == 1 && is(Source : Targets[0]))
    {
        alias T = Select!(is(Source == shared), shared Targets[0], Targets[0]);
        return dynamicCast!(inout T)(src);
    }
    // structural upcast
    template wrap(Source)
    if (!allSatisfy!(Bind!(isImplicitlyConvertible, Source), Targets))
    {
        auto wrap(inout Source src)
        {
            static assert(hasRequireMethods!(),
                          "Source "~Source.stringof~
                          " does not have structural conformance to "~
                          Targets.stringof);

            alias T = Select!(is(Source == shared), shared Impl, Impl);
            return new inout T(src);
        }

        template FuncInfo(string s, F)
        {
            enum name = s;
            alias type = F;
        }

        // https://issues.dlang.org/show_bug.cgi?id=12064: Remove NVI members
        template OnlyVirtual(members...)
        {
            enum notFinal(alias T) = !__traits(isFinalFunction, T);
            import std.meta : Filter;
            alias OnlyVirtual = Filter!(notFinal, members);
        }

        // Concat all Targets function members into one tuple
        template Concat(size_t i = 0)
        {
            static if (i >= Targets.length)
                alias Concat = AliasSeq!();
            else
            {
                alias Concat = AliasSeq!(OnlyVirtual!(GetOverloadedMethods!(Targets[i]), Concat!(i + 1)));
            }
        }

        // Remove duplicated functions based on the identifier name and function type covariance
        template Uniq(members...)
        {
            static if (members.length == 0)
                alias Uniq = AliasSeq!();
            else
            {
                alias func = members[0];
                enum  name = __traits(identifier, func);
                alias type = FunctionTypeOf!func;
                template check(size_t i, mem...)
                {
                    static if (i >= mem.length)
                        enum ptrdiff_t check = -1;
                    else
                    {
                        enum ptrdiff_t check =
                            __traits(identifier, func) == __traits(identifier, mem[i]) &&
                            !is(DerivedFunctionType!(type, FunctionTypeOf!(mem[i])) == void)
                          ? i : check!(i + 1, mem);
                    }
                }
                enum ptrdiff_t x = 1 + check!(0, members[1 .. $]);
                static if (x >= 1)
                {
                    alias typex = DerivedFunctionType!(type, FunctionTypeOf!(members[x]));
                    alias remain = Uniq!(members[1 .. x], members[x + 1 .. $]);

                    static if (remain.length >= 1 && remain[0].name == name &&
                               !is(DerivedFunctionType!(typex, remain[0].type) == void))
                    {
                        alias F = DerivedFunctionType!(typex, remain[0].type);
                        alias Uniq = AliasSeq!(FuncInfo!(name, F), remain[1 .. $]);
                    }
                    else
                        alias Uniq = AliasSeq!(FuncInfo!(name, typex), remain);
                }
                else
                {
                    alias Uniq = AliasSeq!(FuncInfo!(name, type), Uniq!(members[1 .. $]));
                }
            }
        }
        alias TargetMembers = Uniq!(Concat!());             // list of FuncInfo
        alias SourceMembers = GetOverloadedMethods!Source;  // list of function symbols

        // Check whether all of SourceMembers satisfy covariance target in TargetMembers
        template hasRequireMethods(size_t i = 0)
        {
            static if (i >= TargetMembers.length)
                enum hasRequireMethods = true;
            else
            {
                enum hasRequireMethods =
                    findCovariantFunction!(TargetMembers[i], Source, SourceMembers) != -1 &&
                    hasRequireMethods!(i + 1);
            }
        }

        // Internal wrapper class
        final class Impl : Structural, Targets
        {
        private:
            Source _wrap_source;

            this(       inout Source s)        inout @safe pure nothrow { _wrap_source = s; }
            this(shared inout Source s) shared inout @safe pure nothrow { _wrap_source = s; }

            // BUG: making private should work with NVI.
            protected final inout(Object) _wrap_getSource() inout @trusted
            {
                return dynamicCast!(inout Object)(_wrap_source);
            }

            import std.conv : to;
            import core.lifetime : forward;
            template generateFun(size_t i)
            {
                enum name = TargetMembers[i].name;
                enum fa = functionAttributes!(TargetMembers[i].type);
                static @property stc()
                {
                    string r;
                    if (fa & FunctionAttribute.property)    r ~= "@property ";
                    if (fa & FunctionAttribute.ref_)        r ~= "ref ";
                    if (fa & FunctionAttribute.pure_)       r ~= "pure ";
                    if (fa & FunctionAttribute.nothrow_)    r ~= "nothrow ";
                    if (fa & FunctionAttribute.trusted)     r ~= "@trusted ";
                    if (fa & FunctionAttribute.safe)        r ~= "@safe ";
                    return r;
                }
                static @property mod()
                {
                    alias type = AliasSeq!(TargetMembers[i].type)[0];
                    string r;
                    static if (is(type == immutable))       r ~= " immutable";
                    else
                    {
                        static if (is(type == shared))      r ~= " shared";
                        static if (is(type == const))       r ~= " const";
                        else static if (is(type == inout))  r ~= " inout";
                        //else  --> mutable
                    }
                    return r;
                }
                enum n = to!string(i);
                static if (fa & FunctionAttribute.property)
                {
                    static if (Parameters!(TargetMembers[i].type).length == 0)
                        enum fbody = "_wrap_source."~name;
                    else
                        enum fbody = "_wrap_source."~name~" = forward!args";
                }
                else
                {
                        enum fbody = "_wrap_source."~name~"(forward!args)";
                }
                enum generateFun =
                    "override "~stc~"ReturnType!(TargetMembers["~n~"].type) "
                    ~ name~"(Parameters!(TargetMembers["~n~"].type) args) "~mod~
                    "{ return "~fbody~"; }";
            }

        public:
            static foreach (i; 0 .. TargetMembers.length)
                mixin(generateFun!i);
        }
    }
}
/// ditto
template wrap(Targets...)
if (Targets.length >= 1 && !allSatisfy!(isMutable, Targets))
{
    import std.meta : staticMap;

    alias wrap = .wrap!(staticMap!(Unqual, Targets));
}

/// ditto
template unwrap(Target)
if (isMutable!Target)
{
    // strict downcast
    auto unwrap(Source)(inout Source src) @trusted pure nothrow
    if (is(Target : Source))
    {
        alias T = Select!(is(Source == shared), shared Target, Target);
        return dynamicCast!(inout T)(src);
    }
    // structural downcast
    auto unwrap(Source)(inout Source src) @trusted pure nothrow
    if (!is(Target : Source))
    {
        alias T = Select!(is(Source == shared), shared Target, Target);
        Object o = dynamicCast!(Object)(src);   // remove qualifier
        do
        {
            if (auto a = dynamicCast!(Structural)(o))
            {
                if (auto d = dynamicCast!(inout T)(o = a._wrap_getSource()))
                    return d;
            }
            else if (auto d = dynamicCast!(inout T)(o))
                return d;
            else
                break;
        } while (o);
        return null;
    }
}

/// ditto
template unwrap(Target)
if (!isMutable!Target)
{
    alias unwrap = .unwrap!(Unqual!Target);
}

///
@system unittest
{
    interface Quack
    {
        int quack();
        @property int height();
    }
    interface Flyer
    {
        @property int height();
    }
    class Duck : Quack
    {
        int quack() { return 1; }
        @property int height() { return 10; }
    }
    class Human
    {
        int quack() { return 2; }
        @property int height() { return 20; }
    }

    Duck d1 = new Duck();
    Human h1 = new Human();

    interface Refleshable
    {
        int reflesh();
    }

    // does not have structural conformance
    static assert(!__traits(compiles, d1.wrap!Refleshable));
    static assert(!__traits(compiles, h1.wrap!Refleshable));

    // strict upcast
    Quack qd = d1.wrap!Quack;
    assert(qd is d1);
    assert(qd.quack() == 1);    // calls Duck.quack
    // strict downcast
    Duck d2 = qd.unwrap!Duck;
    assert(d2 is d1);

    // structural upcast
    Quack qh = h1.wrap!Quack;
    assert(qh.quack() == 2);    // calls Human.quack
    // structural downcast
    Human h2 = qh.unwrap!Human;
    assert(h2 is h1);

    // structural upcast (two steps)
    Quack qx = h1.wrap!Quack;   // Human -> Quack
    Flyer fx = qx.wrap!Flyer;   // Quack -> Flyer
    assert(fx.height == 20);    // calls Human.height
    // structural downcast (two steps)
    Quack qy = fx.unwrap!Quack; // Flyer -> Quack
    Human hy = qy.unwrap!Human; // Quack -> Human
    assert(hy is h1);
    // structural downcast (one step)
    Human hz = fx.unwrap!Human; // Flyer -> Human
    assert(hz is h1);
}

///
@system unittest
{
    import std.traits : FunctionAttribute, functionAttributes;
    interface A { int run(); }
    interface B { int stop(); @property int status(); }
    class X
    {
        int run() { return 1; }
        int stop() { return 2; }
        @property int status() { return 3; }
    }

    auto x = new X();
    auto ab = x.wrap!(A, B);
    A a = ab;
    B b = ab;
    assert(a.run() == 1);
    assert(b.stop() == 2);
    assert(b.status == 3);
    static assert(functionAttributes!(typeof(ab).status) & FunctionAttribute.property);
}

// Internal class to support dynamic cross-casting
private interface Structural
{
    inout(Object) _wrap_getSource() inout @safe pure nothrow;
}

@system unittest
{
    class A
    {
        int draw()              { return 1; }
        int draw(int v)         { return v; }

        int draw() const        { return 2; }
        int draw() shared       { return 3; }
        int draw() shared const { return 4; }
        int draw() immutable    { return 5; }
    }
    interface Drawable
    {
        int draw();
        int draw() const;
        int draw() shared;
        int draw() shared const;
        int draw() immutable;
    }
    interface Drawable2
    {
        int draw(int v);
    }

    auto ma = new A();
    auto sa = new shared A();
    auto ia = new immutable A();
    {
                     Drawable  md = ma.wrap!Drawable;
               const Drawable  cd = ma.wrap!Drawable;
              shared Drawable  sd = sa.wrap!Drawable;
        shared const Drawable scd = sa.wrap!Drawable;
           immutable Drawable  id = ia.wrap!Drawable;
        assert( md.draw() == 1);
        assert( cd.draw() == 2);
        assert( sd.draw() == 3);
        assert(scd.draw() == 4);
        assert( id.draw() == 5);
    }
    {
        Drawable2 d = ma.wrap!Drawable2;
        static assert(!__traits(compiles, d.draw()));
        assert(d.draw(10) == 10);
    }
}

// https://issues.dlang.org/show_bug.cgi?id=10377
@system unittest
{
    import std.range, std.algorithm;

    interface MyInputRange(T)
    {
        @property T front();
        void popFront();
        @property bool empty();
    }

    //auto o = iota(0,10,1).inputRangeObject();
    //pragma(msg, __traits(allMembers, typeof(o)));
    auto r = iota(0,10,1).inputRangeObject().wrap!(MyInputRange!int)();
    assert(equal(r, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
}

// https://issues.dlang.org/show_bug.cgi?id=10536
@system unittest
{
    interface Interface
    {
        int foo();
    }
    class Pluggable
    {
        int foo() { return 1; }
        @disable void opCast(T, this X)();  // !
    }

    Interface i = new Pluggable().wrap!Interface;
    assert(i.foo() == 1);
}
@system unittest
{
    // Enhancement 10538
    interface Interface
    {
        int foo();
        int bar(int);
    }
    class Pluggable
    {
        int opDispatch(string name, A...)(A args) { return 100; }
    }

    Interface i = wrap!Interface(new Pluggable());
    assert(i.foo() == 100);
    assert(i.bar(10) == 100);
}

// https://issues.dlang.org/show_bug.cgi?id=12064
@system unittest
{
    interface I
    {
        int foo();
        final int nvi1(){return foo();}
    }

    interface J
    {
        int bar();
        final int nvi2(){return bar();}
    }

    class Baz
    {
        int foo() { return 42;}
        int bar() { return 12064;}
    }

    auto baz = new Baz();
    auto foobar = baz.wrap!(I, J)();
    assert(foobar.nvi1 == 42);
    assert(foobar.nvi2 == 12064);
}

// Make a tuple of non-static function symbols
package template GetOverloadedMethods(T)
{
    import std.meta : Filter;

    alias allMembers = __traits(allMembers, T);
    template follows(size_t i = 0)
    {
        static if (i >= allMembers.length)
        {
            alias follows = AliasSeq!();
        }
        else static if (!__traits(compiles, mixin("T."~allMembers[i])))
        {
            alias follows = follows!(i + 1);
        }
        else
        {
            enum name = allMembers[i];

            template isMethod(alias f)
            {
                static if (is(typeof(&f) F == F*) && is(F == function))
                    enum isMethod = !__traits(isStaticFunction, f);
                else
                    enum isMethod = false;
            }
            alias follows = AliasSeq!(
                Filter!(isMethod, __traits(getOverloads, T, name)),
                follows!(i + 1));
        }
    }
    alias GetOverloadedMethods = follows!();
}
// find a function from Fs that has same identifier and covariant type with f
private template findCovariantFunction(alias finfo, Source, Fs...)
{
    template check(size_t i = 0)
    {
        static if (i >= Fs.length)
            enum ptrdiff_t check = -1;
        else
        {
            enum ptrdiff_t check =
                (finfo.name == __traits(identifier, Fs[i])) &&
                isCovariantWith!(FunctionTypeOf!(Fs[i]), finfo.type)
              ? i : check!(i + 1);
        }
    }
    enum x = check!();
    static if (x == -1 && is(typeof(Source.opDispatch)))
    {
        alias Params = Parameters!(finfo.type);
        enum ptrdiff_t findCovariantFunction =
            is(typeof((             Source).init.opDispatch!(finfo.name)(Params.init))) ||
            is(typeof((       const Source).init.opDispatch!(finfo.name)(Params.init))) ||
            is(typeof((   immutable Source).init.opDispatch!(finfo.name)(Params.init))) ||
            is(typeof((      shared Source).init.opDispatch!(finfo.name)(Params.init))) ||
            is(typeof((shared const Source).init.opDispatch!(finfo.name)(Params.init)))
          ? ptrdiff_t.max : -1;
    }
    else
        enum ptrdiff_t findCovariantFunction = x;
}

private enum TypeModifier
{
    mutable     = 0,    // type is mutable
    const_      = 1,    // type is const
    immutable_  = 2,    // type is immutable
    shared_     = 4,    // type is shared
    inout_      = 8,    // type is wild
}
private template TypeMod(T)
{
    static if (is(T == immutable))
    {
        enum mod1 = TypeModifier.immutable_;
        enum mod2 = 0;
    }
    else
    {
        enum mod1 = is(T == shared) ? TypeModifier.shared_ : 0;
        static if (is(T == const))
            enum mod2 = TypeModifier.const_;
        else static if (is(T == inout))
            enum mod2 = TypeModifier.inout_;
        else
            enum mod2 = TypeModifier.mutable;
    }
    enum TypeMod = cast(TypeModifier)(mod1 | mod2);
}

@system unittest
{
    template UnittestFuncInfo(alias f)
    {
        enum name = __traits(identifier, f);
        alias type = FunctionTypeOf!f;
    }

    class A
    {
        int draw() { return 1; }
        @property int value() { return 2; }
        final int run() { return 3; }
    }
    alias methods = GetOverloadedMethods!A;

    alias int F1();
    alias @property int F2();
    alias string F3();
    alias nothrow @trusted uint F4();
    alias int F5(Object);
    alias bool F6(Object);
    static assert(methods.length == 3 + 4);
    static assert(__traits(identifier, methods[0]) == "draw"     && is(typeof(&methods[0]) == F1*));
    static assert(__traits(identifier, methods[1]) == "value"    && is(typeof(&methods[1]) == F2*));
    static assert(__traits(identifier, methods[2]) == "run"      && is(typeof(&methods[2]) == F1*));

    int draw();
    @property int value();
    void opEquals();
    int nomatch();
    static assert(findCovariantFunction!(UnittestFuncInfo!draw,     A, methods) == 0);
    static assert(findCovariantFunction!(UnittestFuncInfo!value,    A, methods) == 1);
    static assert(findCovariantFunction!(UnittestFuncInfo!opEquals, A, methods) == -1);
    static assert(findCovariantFunction!(UnittestFuncInfo!nomatch,  A, methods) == -1);

    // considering opDispatch
    class B
    {
        void opDispatch(string name, A...)(A) {}
    }
    alias methodsB = GetOverloadedMethods!B;
    static assert(findCovariantFunction!(UnittestFuncInfo!draw,     B, methodsB) == ptrdiff_t.max);
    static assert(findCovariantFunction!(UnittestFuncInfo!value,    B, methodsB) == ptrdiff_t.max);
    static assert(findCovariantFunction!(UnittestFuncInfo!opEquals, B, methodsB) == ptrdiff_t.max);
    static assert(findCovariantFunction!(UnittestFuncInfo!nomatch,  B, methodsB) == ptrdiff_t.max);
}

package template DerivedFunctionType(T...)
{
    static if (!T.length)
    {
        alias DerivedFunctionType = void;
    }
    else static if (T.length == 1)
    {
        static if (is(T[0] == function))
        {
            alias DerivedFunctionType = T[0];
        }
        else
        {
            alias DerivedFunctionType = void;
        }
    }
    else static if (is(T[0] P0 == function) && is(T[1] P1 == function))
    {
        alias FA = FunctionAttribute;

        alias F0 = T[0], R0 = ReturnType!F0, PSTC0 = ParameterStorageClassTuple!F0;
        alias F1 = T[1], R1 = ReturnType!F1, PSTC1 = ParameterStorageClassTuple!F1;
        enum FA0 = functionAttributes!F0;
        enum FA1 = functionAttributes!F1;

        template CheckParams(size_t i = 0)
        {
            static if (i >= P0.length)
                enum CheckParams = true;
            else
            {
                enum CheckParams = (is(P0[i] == P1[i]) && PSTC0[i] == PSTC1[i]) &&
                                   CheckParams!(i + 1);
            }
        }
        static if (R0.sizeof == R1.sizeof && !is(CommonType!(R0, R1) == void) &&
                   P0.length == P1.length && CheckParams!() && TypeMod!F0 == TypeMod!F1 &&
                   variadicFunctionStyle!F0 == variadicFunctionStyle!F1 &&
                   functionLinkage!F0 == functionLinkage!F1 &&
                   ((FA0 ^ FA1) & (FA.ref_ | FA.property)) == 0)
        {
            alias R = Select!(is(R0 : R1), R0, R1);
            alias FX = FunctionTypeOf!(R function(P0));
            // @system is default
            alias FY = SetFunctionAttributes!(FX, functionLinkage!F0, (FA0 | FA1) & ~FA.system);
            alias DerivedFunctionType = DerivedFunctionType!(FY, T[2 .. $]);
        }
        else
            alias DerivedFunctionType = void;
    }
    else
        alias DerivedFunctionType = void;
}
@safe unittest
{
    // attribute covariance
    alias int F1();
    static assert(is(DerivedFunctionType!(F1, F1) == F1));
    alias int F2() pure nothrow;
    static assert(is(DerivedFunctionType!(F1, F2) == F2));
    alias int F3() @safe;
    alias int F23() @safe pure nothrow;
    static assert(is(DerivedFunctionType!(F2, F3) == F23));

    // return type covariance
    alias long F4();
    static assert(is(DerivedFunctionType!(F1, F4) == void));
    class C {}
    class D : C {}
    alias C F5();
    alias D F6();
    static assert(is(DerivedFunctionType!(F5, F6) == F6));
    alias typeof(null) F7();
    alias int[] F8();
    alias int* F9();
    static assert(is(DerivedFunctionType!(F5, F7) == F7));
    static assert(is(DerivedFunctionType!(F7, F8) == void));
    static assert(is(DerivedFunctionType!(F7, F9) == F7));

    // variadic type equality
    alias int F10(int);
    alias int F11(int...);
    alias int F12(int, ...);
    static assert(is(DerivedFunctionType!(F10, F11) == void));
    static assert(is(DerivedFunctionType!(F10, F12) == void));
    static assert(is(DerivedFunctionType!(F11, F12) == void));

    // linkage equality
    alias extern(C) int F13(int);
    alias extern(D) int F14(int);
    alias extern(Windows) int F15(int);
    static assert(is(DerivedFunctionType!(F13, F14) == void));
    static assert(is(DerivedFunctionType!(F13, F15) == void));
    static assert(is(DerivedFunctionType!(F14, F15) == void));

    // ref & @property equality
    alias int F16(int);
    alias ref int F17(int);
    alias @property int F18(int);
    static assert(is(DerivedFunctionType!(F16, F17) == void));
    static assert(is(DerivedFunctionType!(F16, F18) == void));
    static assert(is(DerivedFunctionType!(F17, F18) == void));
}

package template Bind(alias Template, args1...)
{
    alias Bind(args2...) = Template!(args1, args2);
}


/**
Options regarding auto-initialization of a `RefCounted` object (see
the definition of `RefCounted` below).
 */
enum RefCountedAutoInitialize
{
    /// Do not auto-initialize the object
    no,
    /// Auto-initialize the object
    yes,
}

///
@system unittest
{
    import core.exception : AssertError;
    import std.exception : assertThrown;

    struct Foo
    {
        int a = 42;
    }

    RefCounted!(Foo, RefCountedAutoInitialize.yes) rcAuto;
    RefCounted!(Foo, RefCountedAutoInitialize.no) rcNoAuto;

    assert(rcAuto.refCountedPayload.a == 42);

    assertThrown!AssertError(rcNoAuto.refCountedPayload);
    rcNoAuto.refCountedStore.ensureInitialized;
    assert(rcNoAuto.refCountedPayload.a == 42);
}

/**
Defines a reference-counted object containing a `T` value as
payload.

An instance of `RefCounted` is a reference to a structure,
which is referred to as the $(I store), or $(I storage implementation
struct) in this documentation.  The store contains a reference count
and the `T` payload.  `RefCounted` uses `malloc` to allocate
the store.  As instances of `RefCounted` are copied or go out of
scope, they will automatically increment or decrement the reference
count.  When the reference count goes down to zero, `RefCounted`
will call `destroy` against the payload and call `free` to
deallocate the store.  If the `T` payload contains any references
to GC-allocated memory, then `RefCounted` will add it to the GC memory
that is scanned for pointers, and remove it from GC scanning before
`free` is called on the store.

One important consequence of `destroy` is that it will call the
destructor of the `T` payload.  GC-managed references are not
guaranteed to be valid during a destructor call, but other members of
`T`, such as file handles or pointers to `malloc` memory, will
still be valid during the destructor call.  This allows the `T` to
deallocate or clean up any non-GC resources immediately after the
reference count has reached zero.

`RefCounted` is unsafe and should be used with care. No references
to the payload should be escaped outside the `RefCounted` object.

The `autoInit` option makes the object ensure the store is
automatically initialized. Leaving $(D autoInit ==
RefCountedAutoInitialize.yes) (the default option) is convenient but
has the cost of a test whenever the payload is accessed. If $(D
autoInit == RefCountedAutoInitialize.no), user code must call either
`refCountedStore.isInitialized` or `refCountedStore.ensureInitialized`
before attempting to access the payload. Not doing so results in null
pointer dereference.

If `T.this()` is annotated with `@disable` then `autoInit` must be
`RefCountedAutoInitialize.no` in order to compile.
 */
struct RefCounted(T, RefCountedAutoInitialize autoInit =
        RefCountedAutoInitialize.yes)
if (!is(T == class) && !(is(T == interface)))
{
    version (D_BetterC)
    {
        private enum enableGCScan = false;
    }
    else
    {
        private enum enableGCScan = hasIndirections!T;
    }

    // TODO remove pure when https://issues.dlang.org/show_bug.cgi?id=15862 has been fixed
    extern(C) private pure nothrow @nogc static
    {
        pragma(mangle, "free") void pureFree( void *ptr );
        static if (enableGCScan)
        {
            pragma(mangle, "gc_addRange") void pureGcAddRange( in void* p, size_t sz, const TypeInfo ti = null );
            pragma(mangle, "gc_removeRange") void pureGcRemoveRange( in void* p );
        }
    }

    /// `RefCounted` storage implementation.
    struct RefCountedStore
    {
        private struct Impl
        {
            T _payload;
            size_t _count;
        }

        private Impl* _store;

        private void initialize(A...)(auto ref A args)
        {
            import core.lifetime : emplace, forward;

            allocateStore();
            version (D_Exceptions) scope(failure) deallocateStore();
            emplace(&_store._payload, forward!args);
            _store._count = 1;
        }

        private void move(ref T source) nothrow pure
        {
            import std.algorithm.mutation : moveEmplace;

            allocateStore();
            moveEmplace(source, _store._payload);
            _store._count = 1;
        }

        // 'nothrow': can only generate an Error
        private void allocateStore() nothrow pure
        {
            static if (enableGCScan)
            {
                import std.internal.memory : enforceCalloc;
                _store = cast(Impl*) enforceCalloc(1, Impl.sizeof);
                pureGcAddRange(&_store._payload, T.sizeof);
            }
            else
            {
                import std.internal.memory : enforceMalloc;
                _store = cast(Impl*) enforceMalloc(Impl.sizeof);
            }
        }

        private void deallocateStore() nothrow pure
        {
            static if (enableGCScan)
            {
                pureGcRemoveRange(&this._store._payload);
            }
            pureFree(_store);
            _store = null;
        }

        /**
           Returns `true` if and only if the underlying store has been
           allocated and initialized.
        */
        @property nothrow @safe pure @nogc
        bool isInitialized() const
        {
            return _store !is null;
        }

        /**
           Returns underlying reference count if it is allocated and initialized
           (a positive integer), and `0` otherwise.
        */
        @property nothrow @safe pure @nogc
        size_t refCount() const
        {
            return isInitialized ? _store._count : 0;
        }

        /**
           Makes sure the payload was properly initialized. Such a
           call is typically inserted before using the payload.

           This function is unavailable if `T.this()` is annotated with
           `@disable`.
        */
        void ensureInitialized()()
        {
            // By checking for `@disable this()` and failing early we can
            // produce a clearer error message.
            static assert(__traits(compiles, { static T t; }),
                "Cannot automatically initialize `" ~ fullyQualifiedName!T ~
                "` because `" ~ fullyQualifiedName!T ~
                ".this()` is annotated with `@disable`.");
            if (!isInitialized) initialize();
        }

    }
    RefCountedStore _refCounted;

    /// Returns storage implementation struct.
    @property nothrow @safe
    ref inout(RefCountedStore) refCountedStore() inout
    {
        return _refCounted;
    }

/**
Constructor that initializes the payload.

Postcondition: `refCountedStore.isInitialized`
 */
    this(A...)(auto ref A args) if (A.length > 0)
    out
    {
        assert(refCountedStore.isInitialized);
    }
    do
    {
        import core.lifetime : forward;
        _refCounted.initialize(forward!args);
    }

    /// Ditto
    this(T val)
    {
        _refCounted.move(val);
    }

/**
Constructor that tracks the reference count appropriately. If $(D
!refCountedStore.isInitialized), does nothing.
 */
    this(this) @safe pure nothrow @nogc
    {
        if (!_refCounted.isInitialized) return;
        ++_refCounted._store._count;
    }

/**
Destructor that tracks the reference count appropriately. If $(D
!refCountedStore.isInitialized), does nothing. When the reference count goes
down to zero, calls `destroy` agaist the payload and calls `free`
to deallocate the corresponding resource.
 */
    ~this()
    {
        if (!_refCounted.isInitialized) return;
        assert(_refCounted._store._count > 0);
        if (--_refCounted._store._count)
            return;
        // Done, destroy and deallocate
        .destroy(_refCounted._store._payload);
        _refCounted.deallocateStore();
    }

/**
Assignment operators
 */
    void opAssign(typeof(this) rhs)
    {
        import std.algorithm.mutation : swap;

        swap(_refCounted._store, rhs._refCounted._store);
    }

/// Ditto
    void opAssign(T rhs)
    {
        import std.algorithm.mutation : move;

        static if (autoInit == RefCountedAutoInitialize.yes)
        {
            _refCounted.ensureInitialized();
        }
        else
        {
            assert(_refCounted.isInitialized);
        }
        move(rhs, _refCounted._store._payload);
    }

    //version to have a single properly ddoc'ed function (w/ correct sig)
    version (StdDdoc)
    {
        /**
        Returns a reference to the payload. If (autoInit ==
        RefCountedAutoInitialize.yes), calls $(D
        refCountedStore.ensureInitialized). Otherwise, just issues $(D
        assert(refCountedStore.isInitialized)). Used with $(D alias
        refCountedPayload this;), so callers can just use the `RefCounted`
        object as a `T`.

        $(BLUE The first overload exists only if $(D autoInit == RefCountedAutoInitialize.yes).)
        So if $(D autoInit == RefCountedAutoInitialize.no)
        or called for a constant or immutable object, then
        `refCountedPayload` will also be qualified as safe and nothrow
        (but will still assert if not initialized).
         */
        @property @trusted
        ref T refCountedPayload() return;

        /// ditto
        @property nothrow @safe pure @nogc
        ref inout(T) refCountedPayload() inout return;
    }
    else
    {
        static if (autoInit == RefCountedAutoInitialize.yes)
        {
            //Can't use inout here because of potential mutation
            @property
            ref T refCountedPayload() return
            {
                _refCounted.ensureInitialized();
                return _refCounted._store._payload;
            }
        }

        @property nothrow @safe pure @nogc
        ref inout(T) refCountedPayload() inout return
        {
            assert(_refCounted.isInitialized, "Attempted to access an uninitialized payload.");
            return _refCounted._store._payload;
        }
    }

/**
Returns a reference to the payload. If (autoInit ==
RefCountedAutoInitialize.yes), calls $(D
refCountedStore.ensureInitialized). Otherwise, just issues $(D
assert(refCountedStore.isInitialized)).
 */
    alias refCountedPayload this;

    static if (is(T == struct) && !is(typeof((ref T t) => t.toString())))
    {
        string toString(this This)()
        {
            import std.conv : to;

            static if (autoInit)
                return to!string(refCountedPayload);
            else
            {
                if (!_refCounted.isInitialized)
                    return This.stringof ~ "(RefCountedStore(null))";
                else
                    return to!string(_refCounted._store._payload);
            }
        }
    }
}

///
@betterC pure @system nothrow @nogc unittest
{
    // A pair of an `int` and a `size_t` - the latter being the
    // reference count - will be dynamically allocated
    auto rc1 = RefCounted!int(5);
    assert(rc1 == 5);
    // No more allocation, add just one extra reference count
    auto rc2 = rc1;
    // Reference semantics
    rc2 = 42;
    assert(rc1 == 42);
    // the pair will be freed when rc1 and rc2 go out of scope
}

pure @system unittest
{
    RefCounted!int* p;
    {
        auto rc1 = RefCounted!int(5);
        p = &rc1;
        assert(rc1 == 5);
        assert(rc1._refCounted._store._count == 1);
        auto rc2 = rc1;
        assert(rc1._refCounted._store._count == 2);
        // Reference semantics
        rc2 = 42;
        assert(rc1 == 42);
        rc2 = rc2;
        assert(rc2._refCounted._store._count == 2);
        rc1 = rc2;
        assert(rc1._refCounted._store._count == 2);
    }
    assert(p._refCounted._store == null);

    // RefCounted as a member
    struct A
    {
        RefCounted!int x;
        this(int y)
        {
            x._refCounted.initialize(y);
        }
        A copy()
        {
            auto another = this;
            return another;
        }
    }
    auto a = A(4);
    auto b = a.copy();
    assert(a.x._refCounted._store._count == 2,
           "https://issues.dlang.org/show_bug.cgi?id=4356 still unfixed");
}

@betterC pure @system nothrow @nogc unittest
{
    import std.algorithm.mutation : swap;

    RefCounted!int p1, p2;
    swap(p1, p2);
}

// https://issues.dlang.org/show_bug.cgi?id=6606
@betterC @safe pure nothrow @nogc unittest
{
    union U {
       size_t i;
       void* p;
    }

    struct S {
       U u;
    }

    alias SRC = RefCounted!S;
}

// https://issues.dlang.org/show_bug.cgi?id=6436
@betterC @system pure unittest
{
    struct S
    {
        this(int rval) { assert(rval == 1); }
        this(ref int lval) { assert(lval == 3); ++lval; }
    }

    auto s1 = RefCounted!S(1);
    int lval = 3;
    auto s2 = RefCounted!S(lval);
    assert(lval == 4);
}

// gc_addRange coverage
@betterC @system pure unittest
{
    struct S { int* p; }

    auto s = RefCounted!S(null);
}

@betterC @system pure nothrow @nogc unittest
{
    RefCounted!int a;
    a = 5; //This should not assert
    assert(a == 5);

    RefCounted!int b;
    b = a; //This should not assert either
    assert(b == 5);

    RefCounted!(int*) c;
}

// https://issues.dlang.org/show_bug.cgi?id=21638
@betterC @system pure nothrow @nogc unittest
{
    static struct NoDefaultCtor
    {
        @disable this();
        this(int x) @nogc nothrow pure { this.x = x; }
        int x;
    }
    auto rc = RefCounted!(NoDefaultCtor, RefCountedAutoInitialize.no)(5);
    assert(rc.x == 5);
}

// https://issues.dlang.org/show_bug.cgi?id=20502
@system unittest
{
    import std.conv : to;
    // Check that string conversion is transparent for refcounted
    // structs that do not have either toString or alias this.
    static struct A { Object a; }
    auto a  = A(new Object());
    auto r = refCounted(a);
    assert(to!string(r) == to!string(a));
    assert(to!string(cast(const) r) == to!string(cast(const) a));
    // Check that string conversion is still transparent for refcounted
    // structs that have alias this.
    static struct B { int b; alias b this; }
    static struct C { B b; alias b this; }
    assert(to!string(refCounted(C(B(123)))) == to!string(C(B(123))));
    // https://issues.dlang.org/show_bug.cgi?id=22093
    // Check that uninitialized refcounted structs that previously could be
    // converted to strings still can be.
    alias R = typeof(r);
    R r2;
    cast(void) (((const ref R a) => to!string(a))(r2));
    cast(void) to!string(RefCounted!(A, RefCountedAutoInitialize.no).init);
}

/**
 * Initializes a `RefCounted` with `val`. The template parameter
 * `T` of `RefCounted` is inferred from `val`.
 * This function can be used to move non-copyable values to the heap.
 * It also disables the `autoInit` option of `RefCounted`.
 *
 * Params:
 *   val = The value to be reference counted
 * Returns:
 *   An initialized `RefCounted` containing `val`.
 * See_Also:
 *   $(HTTP en.cppreference.com/w/cpp/memory/shared_ptr/make_shared, C++'s make_shared)
 */
RefCounted!(T, RefCountedAutoInitialize.no) refCounted(T)(T val)
{
    typeof(return) res;
    res._refCounted.move(val);
    return res;
}

///
@system unittest
{
    static struct File
    {
        static size_t nDestroyed;
        string name;
        @disable this(this); // not copyable
        ~this() { name = null; ++nDestroyed; }
    }

    auto file = File("name");
    assert(file.name == "name");
    // file cannot be copied and has unique ownership
    static assert(!__traits(compiles, {auto file2 = file;}));

    assert(File.nDestroyed == 0);

    // make the file refcounted to share ownership
    // Note:
    //   We write a compound statement (brace-delimited scope) in which all `RefCounted!File` handles are created and deleted.
    //   This allows us to see (after the scope) what happens after all handles have been destroyed.
    {
        // We move the content of `file` to a separate (and heap-allocated) `File` object,
        // managed-and-accessed via one-or-multiple (initially: one) `RefCounted!File` objects ("handles").
        // This "moving":
        //   (1) invokes `file`'s destructor (=> `File.nDestroyed` is incremented from 0 to 1 and `file.name` becomes `null`);
        //   (2) overwrites `file` with `File.init` (=> `file.name` becomes `null`).
        // It appears that writing `name = null;` in the destructor is redundant,
        // but please note that (2) is only performed if `File` defines a destructor (or post-blit operator),
        // and in the absence of the `nDestroyed` instrumentation there would have been no reason to define a destructor.
        import std.algorithm.mutation : move;
        auto rcFile = refCounted(move(file));
        assert(rcFile.name == "name");
        assert(File.nDestroyed == 1);
        assert(file.name == null);

        // We create another `RefCounted!File` handle to the same separate `File` object.
        // While any of the handles is still alive, the `File` object is kept alive (=> `File.nDestroyed` is not modified).
        auto rcFile2 = rcFile;
        assert(rcFile.refCountedStore.refCount == 2);
        assert(File.nDestroyed == 1);
    }
    // The separate `File` object is deleted when the last `RefCounted!File` handle is destroyed
    // (i.e. at the closing brace of the compound statement above, which destroys both handles: `rcFile` and `rcFile2`)
    // (=> `File.nDestroyed` is incremented again, from 1 to 2):
    assert(File.nDestroyed == 2);
}

/**
    Creates a proxy for the value `a` that will forward all operations
    while disabling implicit conversions. The aliased item `a` must be
    an $(B lvalue). This is useful for creating a new type from the
    "base" type (though this is $(B not) a subtype-supertype
    relationship; the new type is not related to the old type in any way,
    by design).

    The new type supports all operations that the underlying type does,
    including all operators such as `+`, `--`, `<`, `[]`, etc.

    Params:
        a = The value to act as a proxy for all operations. It must
            be an lvalue.
 */
mixin template Proxy(alias a)
{
    private alias ValueType = typeof({ return a; }());

    /* Determine if 'T.a' can referenced via a const(T).
     * Use T* as the parameter because 'scope' inference needs a fully
     * analyzed T, which doesn't work when accessibleFrom() is used in a
     * 'static if' in the definition of Proxy or T.
     */
    private enum bool accessibleFrom(T) =
        is(typeof((T* self){ cast(void) mixin("(*self)."~__traits(identifier, a)); }));

    static if (is(typeof(this) == class))
    {
        override bool opEquals(Object o)
        {
            if (auto b = cast(typeof(this))o)
            {
                return a == mixin("b."~__traits(identifier, a));
            }
            return false;
        }

        bool opEquals(T)(T b)
            if (is(ValueType : T) || is(typeof(a.opEquals(b))) || is(typeof(b.opEquals(a))))
        {
            static if (is(typeof(a.opEquals(b))))
                return a.opEquals(b);
            else static if (is(typeof(b.opEquals(a))))
                return b.opEquals(a);
            else
                return a == b;
        }

        override int opCmp(Object o)
        {
            if (auto b = cast(typeof(this))o)
            {
                return a < mixin("b."~__traits(identifier, a)) ? -1
                     : a > mixin("b."~__traits(identifier, a)) ? +1 : 0;
            }
            static if (is(ValueType == class))
                return a.opCmp(o);
            else
                throw new Exception("Attempt to compare a "~typeid(this).toString~" and a "~typeid(o).toString);
        }

        int opCmp(T)(auto ref const T b)
            if (is(ValueType : T) || is(typeof(a.opCmp(b))) || is(typeof(b.opCmp(a))))
        {
            static if (is(typeof(a.opCmp(b))))
                return a.opCmp(b);
            else static if (is(typeof(b.opCmp(a))))
                return -b.opCmp(a);
            else
                return a < b ? -1 : a > b ? +1 : 0;
        }

        static if (accessibleFrom!(const typeof(this)))
        {
            override size_t toHash() const nothrow @safe
            {
                static if (__traits(compiles, .hashOf(a)))
                    return .hashOf(a);
                else
                // Workaround for when .hashOf is not both @safe and nothrow.
                {
                    static if (is(typeof(&a) == ValueType*))
                        alias v = a;
                    else
                        auto v = a; // if a is (property) function
                    // BUG: Improperly casts away `shared`!
                    return typeid(ValueType).getHash((() @trusted => cast(const void*) &v)());
                }
            }
        }
    }
    else
    {
        auto ref opEquals(this X, B)(auto ref B b)
        {
            static if (is(immutable B == immutable typeof(this)))
            {
                return a == mixin("b."~__traits(identifier, a));
            }
            else
                return a == b;
        }

        auto ref opCmp(this X, B)(auto ref B b)
        {
            static if (is(typeof(a.opCmp(b))))
                return a.opCmp(b);
            else static if (is(typeof(b.opCmp(a))))
                return -b.opCmp(a);
            else static if (isFloatingPoint!ValueType || isFloatingPoint!B)
                return a < b ? -1 : a > b ? +1 : a == b ? 0 : float.nan;
            else
                return a < b ? -1 : (a > b);
        }

        static if (accessibleFrom!(const typeof(this)))
        {
            size_t toHash() const nothrow @safe
            {
                static if (__traits(compiles, .hashOf(a)))
                    return .hashOf(a);
                else
                // Workaround for when .hashOf is not both @safe and nothrow.
                {
                    static if (is(typeof(&a) == ValueType*))
                        alias v = a;
                    else
                        auto v = a; // if a is (property) function
                    // BUG: Improperly casts away `shared`!
                    return typeid(ValueType).getHash((() @trusted => cast(const void*) &v)());
                }
            }
        }
    }

    auto ref opCall(this X, Args...)(auto ref Args args) { return a(args); }

    auto ref opCast(T, this X)() { return cast(T) a; }

    auto ref opIndex(this X, D...)(auto ref D i)               { return a[i]; }
    auto ref opSlice(this X      )()                           { return a[]; }
    auto ref opSlice(this X, B, E)(auto ref B b, auto ref E e) { return a[b .. e]; }

    auto ref opUnary     (string op, this X      )()                           { return mixin(op~"a"); }
    auto ref opIndexUnary(string op, this X, D...)(auto ref D i)               { return mixin(op~"a[i]"); }
    auto ref opSliceUnary(string op, this X      )()                           { return mixin(op~"a[]"); }
    auto ref opSliceUnary(string op, this X, B, E)(auto ref B b, auto ref E e) { return mixin(op~"a[b .. e]"); }

    auto ref opBinary(string op, this X, B)(auto ref B b)
    if (op == "in" && is(typeof(a in b)) || op != "in")
    {
        return mixin("a "~op~" b");
    }
    auto ref opBinaryRight(string op, this X, B)(auto ref B b) { return mixin("b "~op~" a"); }

    static if (!is(typeof(this) == class))
    {
        import std.traits;
        static if (isAssignable!ValueType)
        {
            auto ref opAssign(this X)(auto ref typeof(this) v)
            {
                a = mixin("v."~__traits(identifier, a));
                return this;
            }
        }
        else
        {
            @disable void opAssign(this X)(auto ref typeof(this) v);
        }
    }

    auto ref opAssign     (this X, V      )(auto ref V v) if (!is(V == typeof(this))) { return a       = v; }
    auto ref opIndexAssign(this X, V, D...)(auto ref V v, auto ref D i)               { return a[i]    = v; }
    auto ref opSliceAssign(this X, V      )(auto ref V v)                             { return a[]     = v; }
    auto ref opSliceAssign(this X, V, B, E)(auto ref V v, auto ref B b, auto ref E e) { return a[b .. e] = v; }

    auto ref opOpAssign     (string op, this X, V      )(auto ref V v)
    {
        return mixin("a = a "~op~" v");
    }
    auto ref opIndexOpAssign(string op, this X, V, D...)(auto ref V v, auto ref D i)
    {
        return mixin("a[i] "   ~op~"= v");
    }
    auto ref opSliceOpAssign(string op, this X, V      )(auto ref V v)
    {
        return mixin("a[] "    ~op~"= v");
    }
    auto ref opSliceOpAssign(string op, this X, V, B, E)(auto ref V v, auto ref B b, auto ref E e)
    {
        return mixin("a[b .. e] "~op~"= v");
    }

    template opDispatch(string name)
    {
        static if (is(typeof(__traits(getMember, a, name)) == function))
        {
            // non template function
            auto ref opDispatch(this X, Args...)(auto ref Args args) { return mixin("a."~name~"(args)"); }
        }
        else static if (is(typeof({ enum x = mixin("a."~name); })))
        {
            // built-in type field, manifest constant, and static non-mutable field
            enum opDispatch = mixin("a."~name);
        }
        else static if (__traits(isTemplate, mixin("a."~name)))
        {
            // member template
            template opDispatch(T...)
            {
                enum targs = T.length ? "!T" : "";
                auto ref opDispatch(this X, Args...)(auto ref Args args){ return mixin("a."~name~targs~"(args)"); }
            }
        }
        else
        {
            // field or property function
            @property auto ref opDispatch(this X)()                { return mixin("a."~name);        }
            @property auto ref opDispatch(this X, V)(auto ref V v) { return mixin("a."~name~" = v"); }
        }

    }

    import std.traits : isArray;

    static if (isArray!ValueType)
    {
        auto opDollar() const { return a.length; }
    }
    else static if (is(typeof(a.opDollar!0)))
    {
        auto ref opDollar(size_t pos)() { return a.opDollar!pos(); }
    }
    else static if (is(typeof(a.opDollar) == function))
    {
        auto ref opDollar() { return a.opDollar(); }
    }
    else static if (is(typeof(a.opDollar)))
    {
        alias opDollar = a.opDollar;
    }
}

///
@safe unittest
{
    struct MyInt
    {
        private int value;
        mixin Proxy!value;

        this(int n){ value = n; }
    }

    MyInt n = 10;

    // Enable operations that original type has.
    ++n;
    assert(n == 11);
    assert(n * 2 == 22);

    void func(int n) { }

    // Disable implicit conversions to original type.
    //int x = n;
    //func(n);
}

///The proxied value must be an $(B lvalue).
@safe unittest
{
    struct NewIntType
    {
        //Won't work; the literal '1'
        //is an rvalue, not an lvalue
        //mixin Proxy!1;

        //Okay, n is an lvalue
        int n;
        mixin Proxy!n;

        this(int n) { this.n = n; }
    }

    NewIntType nit = 0;
    nit++;
    assert(nit == 1);


    struct NewObjectType
    {
        Object obj;
        //Ok, obj is an lvalue
        mixin Proxy!obj;

        this (Object o) { obj = o; }
    }

    NewObjectType not = new Object();
    assert(__traits(compiles, not.toHash()));
}

/**
    There is one exception to the fact that the new type is not related to the
    old type. $(DDSUBLINK spec/function,pseudo-member, Pseudo-member)
    functions are usable with the new type; they will be forwarded on to the
    proxied value.
 */
@safe unittest
{
    import std.math.traits : isInfinity;

    float f = 1.0;
    assert(!f.isInfinity);

    struct NewFloat
    {
        float _;
        mixin Proxy!_;

        this(float f) { _ = f; }
    }

    NewFloat nf = 1.0f;
    assert(!nf.isInfinity);
}

@safe unittest
{
    static struct MyInt
    {
        private int value;
        mixin Proxy!value;
        this(int n) inout { value = n; }

        enum str = "str";
        static immutable arr = [1,2,3];
    }

    static foreach (T; AliasSeq!(MyInt, const MyInt, immutable MyInt))
    {{
        T m = 10;
        static assert(!__traits(compiles, { int x = m; }));
        static assert(!__traits(compiles, { void func(int n){} func(m); }));
        assert(m == 10);
        assert(m != 20);
        assert(m < 20);
        assert(+m == 10);
        assert(-m == -10);
        assert(cast(double) m == 10.0);
        assert(m + 10 == 20);
        assert(m - 5 == 5);
        assert(m * 20 == 200);
        assert(m / 2 == 5);
        assert(10 + m == 20);
        assert(15 - m == 5);
        assert(20 * m == 200);
        assert(50 / m == 5);
        static if (is(T == MyInt))  // mutable
        {
            assert(++m == 11);
            assert(m++ == 11); assert(m == 12);
            assert(--m == 11);
            assert(m-- == 11); assert(m == 10);
            m = m;
            m = 20; assert(m == 20);
        }
        static assert(T.max == int.max);
        static assert(T.min == int.min);
        static assert(T.init == int.init);
        static assert(T.str == "str");
        static assert(T.arr == [1,2,3]);
    }}
}
@system unittest
{
    static struct MyArray
    {
        private int[] value;
        mixin Proxy!value;
        this(int[] arr) { value = arr; }
        this(immutable int[] arr) immutable { value = arr; }
    }

    static foreach (T; AliasSeq!(MyArray, const MyArray, immutable MyArray))
    {{
      static if (is(T == immutable) && !is(typeof({ T a = [1,2,3,4]; })))
        T a = [1,2,3,4].idup;   // workaround until qualified ctor is properly supported
      else
        T a = [1,2,3,4];
        assert(a == [1,2,3,4]);
        assert(a != [5,6,7,8]);
        assert(+a[0]    == 1);
        version (LittleEndian)
            assert(cast(ulong[]) a == [0x0000_0002_0000_0001, 0x0000_0004_0000_0003]);
        else
            assert(cast(ulong[]) a == [0x0000_0001_0000_0002, 0x0000_0003_0000_0004]);
        assert(a ~ [10,11] == [1,2,3,4,10,11]);
        assert(a[0]    == 1);
        assert(a[]     == [1,2,3,4]);
        assert(a[2 .. 4] == [3,4]);
        static if (is(T == MyArray))    // mutable
        {
            a = a;
            a = [5,6,7,8];  assert(a == [5,6,7,8]);
            a[0]     = 0;   assert(a == [0,6,7,8]);
            a[]      = 1;   assert(a == [1,1,1,1]);
            a[0 .. 3]  = 2;   assert(a == [2,2,2,1]);
            a[0]    += 2;   assert(a == [4,2,2,1]);
            a[]     *= 2;   assert(a == [8,4,4,2]);
            a[0 .. 2] /= 2;   assert(a == [4,2,4,2]);
        }
    }}
}
@system unittest
{
    class Foo
    {
        int field;

        @property int val1() const { return field; }
        @property void val1(int n) { field = n; }

        @property ref int val2() { return field; }

        int func(int x, int y) const { return x; }
        void func1(ref int a) { a = 9; }

        T ifti1(T)(T t) { return t; }
        void ifti2(Args...)(Args args) { }
        void ifti3(T, Args...)(Args args) { }

        T opCast(T)(){ return T.init; }

        T tempfunc(T)() { return T.init; }
    }
    class Hoge
    {
        Foo foo;
        mixin Proxy!foo;
        this(Foo f) { foo = f; }
    }

    auto h = new Hoge(new Foo());
    int n;

    static assert(!__traits(compiles, { Foo f = h; }));

    // field
    h.field = 1;            // lhs of assign
    n = h.field;            // rhs of assign
    assert(h.field == 1);   // lhs of BinExp
    assert(1 == h.field);   // rhs of BinExp
    assert(n == 1);

    // getter/setter property function
    h.val1 = 4;
    n = h.val1;
    assert(h.val1 == 4);
    assert(4 == h.val1);
    assert(n == 4);

    // ref getter property function
    h.val2 = 8;
    n = h.val2;
    assert(h.val2 == 8);
    assert(8 == h.val2);
    assert(n == 8);

    // member function
    assert(h.func(2,4) == 2);
    h.func1(n);
    assert(n == 9);

    // IFTI
    assert(h.ifti1(4) == 4);
    h.ifti2(4);
    h.ifti3!int(4, 3);

    // https://issues.dlang.org/show_bug.cgi?id=5896 test
    assert(h.opCast!int() == 0);
    assert(cast(int) h == 0);
    const ih = new const Hoge(new Foo());
    static assert(!__traits(compiles, ih.opCast!int()));
    static assert(!__traits(compiles, cast(int) ih));

    // template member function
    assert(h.tempfunc!int() == 0);
}

@system unittest // about Proxy inside a class
{
    class MyClass
    {
        int payload;
        mixin Proxy!payload;
        this(int i){ payload = i; }
        string opCall(string msg){ return msg; }
        int pow(int i){ return payload ^^ i; }
    }

    class MyClass2
    {
        MyClass payload;
        mixin Proxy!payload;
        this(int i){ payload = new MyClass(i); }
    }

    class MyClass3
    {
        int payload;
        mixin Proxy!payload;
        this(int i){ payload = i; }
    }

    // opEquals
    Object a = new MyClass(5);
    Object b = new MyClass(5);
    Object c = new MyClass2(5);
    Object d = new MyClass3(5);
    assert(a == b);
    assert((cast(MyClass) a) == 5);
    assert(5 == (cast(MyClass) b));
    assert(5 == cast(MyClass2) c);
    assert(a != d);

    assert(c != a);
    // oops! above line is unexpected, isn't it?
    // the reason is below.
    // MyClass2.opEquals knows MyClass but,
    // MyClass.opEquals doesn't know MyClass2.
    // so, c.opEquals(a) is true, but a.opEquals(c) is false.
    // furthermore, opEquals(T) couldn't be invoked.
    assert((cast(MyClass2) c) != (cast(MyClass) a));

    // opCmp
    Object e = new MyClass2(7);
    assert(a < cast(MyClass2) e); // OK. and
    assert(e > a); // OK, but...
    // assert(a < e); // RUNTIME ERROR!
    // assert((cast(MyClass) a) < e); // RUNTIME ERROR!
    assert(3 < cast(MyClass) a);
    assert((cast(MyClass2) e) < 11);

    // opCall
    assert((cast(MyClass2) e)("hello") == "hello");

    // opCast
    assert((cast(MyClass)(cast(MyClass2) c)) == a);
    assert((cast(int)(cast(MyClass2) c)) == 5);

    // opIndex
    class MyClass4
    {
        string payload;
        mixin Proxy!payload;
        this(string s){ payload = s; }
    }
    class MyClass5
    {
        MyClass4 payload;
        mixin Proxy!payload;
        this(string s){ payload = new MyClass4(s); }
    }
    auto f = new MyClass4("hello");
    assert(f[1] == 'e');
    auto g = new MyClass5("hello");
    assert(f[1] == 'e');

    // opSlice
    assert(f[2 .. 4] == "ll");

    // opUnary
    assert(-(cast(MyClass2) c) == -5);

    // opBinary
    assert((cast(MyClass) a) + (cast(MyClass2) c) == 10);
    assert(5 + cast(MyClass) a == 10);

    // opAssign
    (cast(MyClass2) c) = 11;
    assert((cast(MyClass2) c) == 11);
    (cast(MyClass2) c) = new MyClass(13);
    assert((cast(MyClass2) c) == 13);

    // opOpAssign
    assert((cast(MyClass2) c) += 4);
    assert((cast(MyClass2) c) == 17);

    // opDispatch
    assert((cast(MyClass2) c).pow(2) == 289);

    // opDollar
    assert(f[2..$-1] == "ll");

    // toHash
    int[Object] hash;
    hash[a] = 19;
    hash[c] = 21;
    assert(hash[b] == 19);
    assert(hash[c] == 21);
}

@safe unittest
{
    struct MyInt
    {
        int payload;

        mixin Proxy!payload;
    }

    MyInt v;
    v = v;

    struct Foo
    {
        @disable void opAssign(typeof(this));
    }
    struct MyFoo
    {
        Foo payload;

        mixin Proxy!payload;
    }
    MyFoo f;
    static assert(!__traits(compiles, f = f));

    struct MyFoo2
    {
        Foo payload;

        mixin Proxy!payload;

        // override default Proxy behavior
        void opAssign(typeof(this) rhs){}
    }
    MyFoo2 f2;
    f2 = f2;
}

// https://issues.dlang.org/show_bug.cgi?id=8613
@safe unittest
{
    static struct Name
    {
        mixin Proxy!val;
        private string val;
        this(string s) { val = s; }
    }

    bool[Name] names;
    names[Name("a")] = true;
    bool* b = Name("a") in names;
}

// workaround for https://issues.dlang.org/show_bug.cgi?id=19669
private enum isDIP1000 = __traits(compiles, () @safe {
     int x;
     int* p;
     p = &x;
});
// excludes struct S; it's 'mixin Proxy!foo' doesn't compile with -dip1000
static if (isDIP1000) {} else
@system unittest
{
    // https://issues.dlang.org/show_bug.cgi?id=14213
    // using function for the payload
    static struct S
    {
        int foo() { return 12; }
        mixin Proxy!foo;
    }
    S s;
    assert(s + 1 == 13);
    assert(s * 2 == 24);
}

@system unittest
{
    static class C
    {
        int foo() { return 12; }
        mixin Proxy!foo;
    }
    C c = new C();
}

// Check all floating point comparisons for both Proxy and Typedef,
// also against int and a Typedef!int, to be as regression-proof
// as possible. https://issues.dlang.org/show_bug.cgi?id=15561
@safe unittest
{
    static struct MyFloatImpl
    {
        float value;
        mixin Proxy!value;
    }
    static void allFail(T0, T1)(T0 a, T1 b)
    {
        assert(!(a == b));
        assert(!(a<b));
        assert(!(a <= b));
        assert(!(a>b));
        assert(!(a >= b));
    }
    static foreach (T1; AliasSeq!(MyFloatImpl, Typedef!float, Typedef!double,
        float, real, Typedef!int, int))
    {
        static foreach (T2; AliasSeq!(MyFloatImpl, Typedef!float))
        {{
            T1 a;
            T2 b;

            static if (isFloatingPoint!T1 || isFloatingPoint!(TypedefType!T1))
                allFail(a, b);
            a = 3;
            allFail(a, b);

            b = 4;
            assert(a != b);
            assert(a<b);
            assert(a <= b);
            assert(!(a>b));
            assert(!(a >= b));

            a = 4;
            assert(a == b);
            assert(!(a<b));
            assert(a <= b);
            assert(!(a>b));
            assert(a >= b);
        }}
    }
}

/**
$(B Typedef) allows the creation of a unique type which is
based on an existing type. Unlike the `alias` feature,
$(B Typedef) ensures the two types are not considered as equals.

Params:

    init = Optional initial value for the new type.
    cookie = Optional, used to create multiple unique types which are
             based on the same origin type `T`

Note: If a library routine cannot handle the Typedef type,
you can use the `TypedefType` template to extract the
type which the Typedef wraps.
 */
struct Typedef(T, T init = T.init, string cookie=null)
{
    private T Typedef_payload = init;

    // https://issues.dlang.org/show_bug.cgi?id=18415
    // prevent default construction if original type does too.
    static if ((is(T == struct) || is(T == union)) && !is(typeof({T t;})))
    {
        @disable this();
    }

    this(T init)
    {
        Typedef_payload = init;
    }

    this(Typedef tdef)
    {
        this(tdef.Typedef_payload);
    }

    // We need to add special overload for cast(Typedef!X) exp,
    // thus we can't simply inherit Proxy!Typedef_payload
    T2 opCast(T2 : Typedef!(T, Unused), this X, T, Unused...)()
    {
        return T2(cast(T) Typedef_payload);
    }

    auto ref opCast(T2, this X)()
    {
        return cast(T2) Typedef_payload;
    }

    mixin Proxy!Typedef_payload;

    pure nothrow @nogc @safe @property
    {
        alias TD = typeof(this);
        static if (isIntegral!T)
        {
            static TD min() {return TD(T.min);}
            static TD max() {return TD(T.max);}
        }
        else static if (isFloatingPoint!T)
        {
            static TD infinity() {return TD(T.infinity);}
            static TD nan() {return TD(T.nan);}
            static TD dig() {return TD(T.dig);}
            static TD epsilon() {return TD(T.epsilon);}
            static TD mant_dig() {return TD(T.mant_dig);}
            static TD max_10_exp() {return TD(T.max_10_exp);}
            static TD max_exp()  {return TD(T.max_exp);}
            static TD min_10_exp() {return TD(T.min_10_exp);}
            static TD min_exp() {return TD(T.min_exp);}
            static TD max() {return TD(T.max);}
            static TD min_normal() {return TD(T.min_normal);}
            TD re() {return TD(Typedef_payload.re);}
            TD im() {return TD(Typedef_payload.im);}
        }
    }

    /**
     * Convert wrapped value to a human readable string
     */
    string toString(this T)()
    {
        import std.array : appender;
        auto app = appender!string();
        auto spec = singleSpec("%s");
        toString(app, spec);
        return app.data;
    }

    /// ditto
    void toString(this T, W)(ref W writer, scope const ref FormatSpec!char fmt)
    if (isOutputRange!(W, char))
    {
        formatValue(writer, Typedef_payload, fmt);
    }

    ///
    @safe unittest
    {
        import std.conv : to;

        int i = 123;
        auto td = Typedef!int(i);
        assert(i.to!string == td.to!string);
    }
}

///
@safe unittest
{
    alias MyInt = Typedef!int;
    MyInt foo = 10;
    foo++;
    assert(foo == 11);
}

/// custom initialization values
@safe unittest
{
    alias MyIntInit = Typedef!(int, 42);
    static assert(is(TypedefType!MyIntInit == int));
    static assert(MyIntInit() == 42);
}

/// Typedef creates a new type
@safe unittest
{
    alias MyInt = Typedef!int;
    static void takeInt(int) {}
    static void takeMyInt(MyInt) {}

    int i;
    takeInt(i);    // ok
    static assert(!__traits(compiles, takeMyInt(i)));

    MyInt myInt;
    static assert(!__traits(compiles, takeInt(myInt)));
    takeMyInt(myInt);  // ok
}

/// Use the optional `cookie` argument to create different types of the same base type
@safe unittest
{
    alias TypeInt1 = Typedef!int;
    alias TypeInt2 = Typedef!int;

    // The two Typedefs are the same type.
    static assert(is(TypeInt1 == TypeInt2));

    alias MoneyEuros = Typedef!(float, float.init, "euros");
    alias MoneyDollars = Typedef!(float, float.init, "dollars");

    // The two Typedefs are _not_ the same type.
    static assert(!is(MoneyEuros == MoneyDollars));
}

// https://issues.dlang.org/show_bug.cgi?id=12461
@safe unittest
{
    alias Int = Typedef!int;

    Int a, b;
    a += b;
    assert(a == 0);
}

/**
Get the underlying type which a `Typedef` wraps.
If `T` is not a `Typedef` it will alias itself to `T`.
*/
template TypedefType(T)
{
    static if (is(T : Typedef!Arg, Arg))
        alias TypedefType = Arg;
    else
        alias TypedefType = T;
}

///
@safe unittest
{
    import std.conv : to;

    alias MyInt = Typedef!int;
    static assert(is(TypedefType!MyInt == int));

    /// Instantiating with a non-Typedef will return that type
    static assert(is(TypedefType!int == int));

    string num = "5";

    // extract the needed type
    MyInt myInt = MyInt( num.to!(TypedefType!MyInt) );
    assert(myInt == 5);

    // cast to the underlying type to get the value that's being wrapped
    int x = cast(TypedefType!MyInt) myInt;

    alias MyIntInit = Typedef!(int, 42);
    static assert(is(TypedefType!MyIntInit == int));
    static assert(MyIntInit() == 42);
}

@safe unittest
{
    Typedef!int x = 10;
    static assert(!__traits(compiles, { int y = x; }));
    static assert(!__traits(compiles, { long z = x; }));

    Typedef!int y = 10;
    assert(x == y);

    static assert(Typedef!int.init == int.init);

    Typedef!(float, 1.0) z; // specifies the init
    assert(z == 1.0);

    static assert(typeof(z).init == 1.0);

    alias Dollar = Typedef!(int, 0, "dollar");
    alias Yen    = Typedef!(int, 0, "yen");
    static assert(!is(Dollar == Yen));

    Typedef!(int[3]) sa;
    static assert(sa.length == 3);
    static assert(typeof(sa).length == 3);

    Typedef!(int[3]) dollar1;
    assert(dollar1[0..$] is dollar1[0 .. 3]);

    Typedef!(int[]) dollar2;
    dollar2.length = 3;
    assert(dollar2[0..$] is dollar2[0 .. 3]);

    static struct Dollar1
    {
        static struct DollarToken {}
        enum opDollar = DollarToken.init;
        auto opSlice(size_t, DollarToken) { return 1; }
        auto opSlice(size_t, size_t) { return 2; }
    }

    Typedef!Dollar1 drange1;
    assert(drange1[0..$] == 1);
    assert(drange1[0 .. 1] == 2);

    static struct Dollar2
    {
        size_t opDollar(size_t pos)() { return pos == 0 ? 1 : 100; }
        size_t opIndex(size_t i, size_t j) { return i + j; }
    }

    Typedef!Dollar2 drange2;
    assert(drange2[$, $] == 101);

    static struct Dollar3
    {
        size_t opDollar() { return 123; }
        size_t opIndex(size_t i) { return i; }
    }

    Typedef!Dollar3 drange3;
    assert(drange3[$] == 123);
}

// https://issues.dlang.org/show_bug.cgi?id=18415
@safe @nogc pure nothrow unittest
{
    struct NoDefCtorS{@disable this();}
    union NoDefCtorU{@disable this();}
    static assert(!is(typeof({Typedef!NoDefCtorS s;})));
    static assert(!is(typeof({Typedef!NoDefCtorU u;})));
}

// https://issues.dlang.org/show_bug.cgi?id=11703
@safe @nogc pure nothrow unittest
{
    alias I = Typedef!int;
    static assert(is(typeof(I.min) == I));
    static assert(is(typeof(I.max) == I));

    alias F = Typedef!double;
    static assert(is(typeof(F.infinity) == F));
    static assert(is(typeof(F.epsilon) == F));

    F f;
    assert(!is(typeof(F.re).stringof == double));
    assert(!is(typeof(F.im).stringof == double));
}

@safe unittest
{
    // https://issues.dlang.org/show_bug.cgi?id=8655
    import std.typecons;
    import std.bitmanip;
    static import core.stdc.config;

    alias c_ulong = Typedef!(core.stdc.config.c_ulong);

    static struct Foo
    {
        mixin(bitfields!(
            c_ulong, "NameOffset", 31,
            c_ulong, "NameIsString", 1
        ));
    }
}

// https://issues.dlang.org/show_bug.cgi?id=12596
@safe unittest
{
    import std.typecons;
    alias TD = Typedef!int;
    TD x = TD(1);
    TD y = TD(x);
    assert(x == y);
}

@safe unittest // about toHash
{
    import std.typecons;
    {
        alias TD = Typedef!int;
        int[TD] td;
        td[TD(1)] = 1;
        assert(td[TD(1)] == 1);
    }

    {
        alias TD = Typedef!(int[]);
        int[TD] td;
        td[TD([1,2,3,4])] = 2;
        assert(td[TD([1,2,3,4])] == 2);
    }

    {
        alias TD = Typedef!(int[][]);
        int[TD] td;
        td[TD([[1,0,0,0], [0,1,0,0], [0,0,1,0], [0,0,0,1]])] = 3;
        assert(td[TD([[1,0,0,0], [0,1,0,0], [0,0,1,0], [0,0,0,1]])] == 3);
    }

    {
        struct MyStruct{ int x; }
        alias TD = Typedef!MyStruct;
        int[TD] td;
        td[TD(MyStruct(10))] = 4;
        assert(TD(MyStruct(20)) !in td);
        assert(td[TD(MyStruct(10))] == 4);
    }

    {
        static struct MyStruct2
        {
            int x;
            size_t toHash() const nothrow @safe { return x; }
            bool opEquals(ref const MyStruct2 r) const { return r.x == x; }
        }

        alias TD = Typedef!MyStruct2;
        int[TD] td;
        td[TD(MyStruct2(50))] = 5;
        assert(td[TD(MyStruct2(50))] == 5);
    }

    {
        class MyClass{}
        alias TD = Typedef!MyClass;
        int[TD] td;
        auto c = new MyClass;
        td[TD(c)] = 6;
        assert(TD(new MyClass) !in td);
        assert(td[TD(c)] == 6);
    }
}

@system unittest
{
    alias String = Typedef!(char[]);
    alias CString = Typedef!(const(char)[]);
    CString cs = "fubar";
    String s = cast(String) cs;
    assert(cs == s);
    char[] s2 = cast(char[]) cs;
    const(char)[] cs2 = cast(const(char)[])s;
    assert(s2 == cs2);
}

@system unittest // toString
{
    import std.meta : AliasSeq;
    import std.conv : to;

    struct TestS {}
    class TestC {}

    static foreach (T; AliasSeq!(int, bool, float, double, real,
                                 char, dchar, wchar,
                                 TestS, TestC,
                                 int*, int[], int[2], int[int]))
    {{
        T t;

        Typedef!T td;
        Typedef!(const T) ctd;
        Typedef!(immutable T) itd;

        assert(t.to!string() == td.to!string());

        static if (!(is(T == TestS) || is(T == TestC)))
        {
            assert(t.to!string() == ctd.to!string());
            assert(t.to!string() == itd.to!string());
        }
    }}
}

@safe @nogc unittest // typedef'ed type with custom operators
{
    static struct MyInt
    {
        int value;
        int opCmp(MyInt other)
        {
            if (value < other.value)
                return -1;
            return !(value == other.value);
        }
    }

    auto m1 = Typedef!MyInt(MyInt(1));
    auto m2 = Typedef!MyInt(MyInt(2));
    assert(m1 < m2);
}

/**
Allocates a `class` object right inside the current scope,
therefore avoiding the overhead of `new`. This facility is unsafe;
it is the responsibility of the user to not escape a reference to the
object outside the scope.

The class destructor will be called when the result of `scoped()` is
itself destroyed.

Scoped class instances can be embedded in a parent `class` or `struct`,
just like a child struct instance. Scoped member variables must have
type `typeof(scoped!Class(args))`, and be initialized with a call to
scoped. See below for an example.

Note:
It's illegal to move a class instance even if you are sure there
are no pointers to it. As such, it is illegal to move a scoped object.
 */
template scoped(T)
if (is(T == class))
{
    // _d_newclass now use default GC alignment (looks like (void*).sizeof * 2 for
    // small objects). We will just use the maximum of filed alignments.
    alias alignment = classInstanceAlignment!T;
    alias aligned = _alignUp!alignment;

    static struct Scoped
    {
        // Addition of `alignment` is required as `Scoped_store` can be misaligned in memory.
        private void[aligned(__traits(classInstanceSize, T) + size_t.sizeof) + alignment] Scoped_store = void;

        @property inout(T) Scoped_payload() inout
        {
            void* alignedStore = cast(void*) aligned(cast(size_t) Scoped_store.ptr);
            // As `Scoped` can be unaligned moved in memory class instance should be moved accordingly.
            immutable size_t d = alignedStore - Scoped_store.ptr;
            size_t* currD = cast(size_t*) &Scoped_store[$ - size_t.sizeof];
            if (d != *currD)
            {
                import core.stdc.string : memmove;
                memmove(alignedStore, Scoped_store.ptr + *currD, __traits(classInstanceSize, T));
                *currD = d;
            }
            return cast(inout(T)) alignedStore;
        }
        alias Scoped_payload this;

        @disable this();
        @disable this(this);

        ~this()
        {
            // `destroy` will also write .init but we have no functions in druntime
            // for deterministic finalization and memory releasing for now.
            .destroy(Scoped_payload);
        }
    }

    /** Returns the _scoped object.
    Params: args = Arguments to pass to `T`'s constructor.
    */
    @system auto scoped(Args...)(auto ref Args args)
    {
        import core.lifetime : emplace, forward;

        Scoped result = void;
        void* alignedStore = cast(void*) aligned(cast(size_t) result.Scoped_store.ptr);
        immutable size_t d = alignedStore - result.Scoped_store.ptr;
        *cast(size_t*) &result.Scoped_store[$ - size_t.sizeof] = d;
        emplace!(Unqual!T)(result.Scoped_store[d .. $ - size_t.sizeof], forward!args);
        return result;
    }
}

///
@system unittest
{
    class A
    {
        int x;
        this()     {x = 0;}
        this(int i){x = i;}
        ~this()    {}
    }

    // Standard usage, constructing A on the stack
    auto a1 = scoped!A();
    a1.x = 42;

    // Result of `scoped` call implicitly converts to a class reference
    A aRef = a1;
    assert(aRef.x == 42);

    // Scoped destruction
    {
        auto a2 = scoped!A(1);
        assert(a2.x == 1);
        aRef = a2;
        // a2 is destroyed here, calling A's destructor
    }
    // aRef is now an invalid reference

    // Here the temporary scoped A is immediately destroyed.
    // This means the reference is then invalid.
    version (Bug)
    {
        // Wrong, should use `auto`
        A invalid = scoped!A();
    }

    // Restrictions
    version (Bug)
    {
        import std.algorithm.mutation : move;
        auto invalid = a1.move; // illegal, scoped objects can't be moved
    }
    static assert(!is(typeof({
        auto e1 = a1; // illegal, scoped objects can't be copied
        assert([a1][0].x == 42); // ditto
    })));
    static assert(!is(typeof({
        alias ScopedObject = typeof(a1);
        auto e2 = ScopedObject();  // illegal, must be built via scoped!A
        auto e3 = ScopedObject(1); // ditto
    })));

    // Use with alias
    alias makeScopedA = scoped!A;
    auto a3 = makeScopedA();
    auto a4 = makeScopedA(1);

    // Use as member variable
    struct B
    {
        typeof(scoped!A()) a; // note the trailing parentheses

        this(int i)
        {
            // construct member
            a = scoped!A(i);
        }
    }

    // Stack-allocate
    auto b1 = B(5);
    aRef = b1.a;
    assert(aRef.x == 5);
    destroy(b1); // calls A's destructor for b1.a
    // aRef is now an invalid reference

    // Heap-allocate
    auto b2 = new B(6);
    assert(b2.a.x == 6);
    destroy(*b2); // calls A's destructor for b2.a
}

private size_t _alignUp(size_t alignment)(size_t n)
if (alignment > 0 && !((alignment - 1) & alignment))
{
    enum badEnd = alignment - 1; // 0b11, 0b111, ...
    return (n + badEnd) & ~badEnd;
}

// https://issues.dlang.org/show_bug.cgi?id=6580 testcase
@system unittest
{
    enum alignment = (void*).alignof;

    static class C0 { }
    static class C1 { byte b; }
    static class C2 { byte[2] b; }
    static class C3 { byte[3] b; }
    static class C7 { byte[7] b; }
    static assert(scoped!C0().sizeof % alignment == 0);
    static assert(scoped!C1().sizeof % alignment == 0);
    static assert(scoped!C2().sizeof % alignment == 0);
    static assert(scoped!C3().sizeof % alignment == 0);
    static assert(scoped!C7().sizeof % alignment == 0);

    enum longAlignment = long.alignof;
    static class C1long
    {
        long long_; byte byte_ = 4;
        this() { }
        this(long _long, ref int i) { long_ = _long; ++i; }
    }
    static class C2long { byte[2] byte_ = [5, 6]; long long_ = 7; }
    static assert(scoped!C1long().sizeof % longAlignment == 0);
    static assert(scoped!C2long().sizeof % longAlignment == 0);

    void alignmentTest()
    {
        int var = 5;
        auto c1long = scoped!C1long(3, var);
        assert(var == 6);
        auto c2long = scoped!C2long();
        assert(cast(uint)&c1long.long_ % longAlignment == 0);
        assert(cast(uint)&c2long.long_ % longAlignment == 0);
        assert(c1long.long_ == 3 && c1long.byte_ == 4);
        assert(c2long.byte_ == [5, 6] && c2long.long_ == 7);
    }

    alignmentTest();

    version (DigitalMars)
    {
        void test(size_t size)
        {
            import core.stdc.stdlib;
            cast(void) alloca(size);
            alignmentTest();
        }
        foreach (i; 0 .. 10)
            test(i);
    }
    else
    {
        void test(size_t size)()
        {
            byte[size] arr;
            alignmentTest();
        }
        static foreach (i; 0 .. 11)
            test!i();
    }
}

// Original https://issues.dlang.org/show_bug.cgi?id=6580 testcase
@system unittest
{
    class C { int i; byte b; }

    auto sa = [scoped!C(), scoped!C()];
    assert(cast(uint)&sa[0].i % int.alignof == 0);
    assert(cast(uint)&sa[1].i % int.alignof == 0); // fails
}

@system unittest
{
    class A { int x = 1; }
    auto a1 = scoped!A();
    assert(a1.x == 1);
    auto a2 = scoped!A();
    a1.x = 42;
    a2.x = 53;
    assert(a1.x == 42);
}

@system unittest
{
    class A { int x = 1; this() { x = 2; } }
    auto a1 = scoped!A();
    assert(a1.x == 2);
    auto a2 = scoped!A();
    a1.x = 42;
    a2.x = 53;
    assert(a1.x == 42);
}

@system unittest
{
    class A { int x = 1; this(int y) { x = y; } ~this() {} }
    auto a1 = scoped!A(5);
    assert(a1.x == 5);
    auto a2 = scoped!A(42);
    a1.x = 42;
    a2.x = 53;
    assert(a1.x == 42);
}

@system unittest
{
    class A { static bool dead; ~this() { dead = true; } }
    class B : A { static bool dead; ~this() { dead = true; } }
    {
        auto b = scoped!B();
    }
    assert(B.dead, "asdasd");
    assert(A.dead, "asdasd");
}

// https://issues.dlang.org/show_bug.cgi?id=8039 testcase
@system unittest
{
    static int dels;
    static struct S { ~this(){ ++dels; } }

    static class A { S s; }
    dels = 0; { scoped!A(); }
    assert(dels == 1);

    static class B { S[2] s; }
    dels = 0; { scoped!B(); }
    assert(dels == 2);

    static struct S2 { S[3] s; }
    static class C { S2[2] s; }
    dels = 0; { scoped!C(); }
    assert(dels == 6);

    static class D: A { S2[2] s; }
    dels = 0; { scoped!D(); }
    assert(dels == 1+6);
}

@system unittest
{
    // https://issues.dlang.org/show_bug.cgi?id=4500
    class A
    {
        this() { a = this; }
        this(int i) { a = this; }
        A a;
        bool check() { return this is a; }
    }

    auto a1 = scoped!A();
    assert(a1.check());

    auto a2 = scoped!A(1);
    assert(a2.check());

    a1.a = a1;
    assert(a1.check());
}

@system unittest
{
    static class A
    {
        static int sdtor;

        this() { ++sdtor; assert(sdtor == 1); }
        ~this() { assert(sdtor == 1); --sdtor; }
    }

    interface Bob {}

    static class ABob : A, Bob
    {
        this() { ++sdtor; assert(sdtor == 2); }
        ~this() { assert(sdtor == 2); --sdtor; }
    }

    A.sdtor = 0;
    scope(exit) assert(A.sdtor == 0);
    auto abob = scoped!ABob();
}

@safe unittest
{
    static class A { this(int) {} }
    static assert(!__traits(compiles, scoped!A()));
}

@system unittest
{
    static class A { @property inout(int) foo() inout { return 1; } }

    auto a1 = scoped!A();
    assert(a1.foo == 1);
    static assert(is(typeof(a1.foo) == int));

    auto a2 = scoped!(const(A))();
    assert(a2.foo == 1);
    static assert(is(typeof(a2.foo) == const(int)));

    auto a3 = scoped!(immutable(A))();
    assert(a3.foo == 1);
    static assert(is(typeof(a3.foo) == immutable(int)));

    const c1 = scoped!A();
    assert(c1.foo == 1);
    static assert(is(typeof(c1.foo) == const(int)));

    const c2 = scoped!(const(A))();
    assert(c2.foo == 1);
    static assert(is(typeof(c2.foo) == const(int)));

    const c3 = scoped!(immutable(A))();
    assert(c3.foo == 1);
    static assert(is(typeof(c3.foo) == immutable(int)));
}

@system unittest
{
    class C
    {
        this(int rval) { assert(rval == 1); }
        this(ref int lval) { assert(lval == 3); ++lval; }
    }

    auto c1 = scoped!C(1);
    int lval = 3;
    auto c2 = scoped!C(lval);
    assert(lval == 4);
}

@system unittest
{
    class C
    {
        this(){}
        this(int){}
        this(int, int){}
    }
    alias makeScopedC = scoped!C;

    auto a = makeScopedC();
    auto b = makeScopedC(1);
    auto c = makeScopedC(1, 1);

    static assert(is(typeof(a) == typeof(b)));
    static assert(is(typeof(b) == typeof(c)));
}

/**
Defines a simple, self-documenting yes/no flag. This makes it easy for
APIs to define functions accepting flags without resorting to $(D
bool), which is opaque in calls, and without needing to define an
enumerated type separately. Using `Flag!"Name"` instead of $(D
bool) makes the flag's meaning visible in calls. Each yes/no flag has
its own type, which makes confusions and mix-ups impossible.

Example:

Code calling `getLine` (usually far away from its definition) can't be
understood without looking at the documentation, even by users familiar with
the API:
----
string getLine(bool keepTerminator)
{
    ...
    if (keepTerminator) ...
    ...
}
...
auto line = getLine(false);
----

Assuming the reverse meaning (i.e. "ignoreTerminator") and inserting the wrong
code compiles and runs with erroneous results.

After replacing the boolean parameter with an instantiation of `Flag`, code
calling `getLine` can be easily read and understood even by people not
fluent with the API:

----
string getLine(Flag!"keepTerminator" keepTerminator)
{
    ...
    if (keepTerminator) ...
    ...
}
...
auto line = getLine(Yes.keepTerminator);
----

The structs `Yes` and `No` are provided as shorthand for
`Flag!"Name".yes` and `Flag!"Name".no` and are preferred for brevity and
readability. These convenience structs mean it is usually unnecessary and
counterproductive to create an alias of a `Flag` as a way of avoiding typing
out the full type while specifying the affirmative or negative options.

Passing categorical data by means of unstructured `bool`
parameters is classified under "simple-data coupling" by Steve
McConnell in the $(LUCKY Code Complete) book, along with three other
kinds of coupling. The author argues citing several studies that
coupling has a negative effect on code quality. `Flag` offers a
simple structuring method for passing yes/no flags to APIs.
 */
template Flag(string name) {
    ///
    enum Flag : bool
    {
        /**
         When creating a value of type `Flag!"Name"`, use $(D
         Flag!"Name".no) for the negative option. When using a value
         of type `Flag!"Name"`, compare it against $(D
         Flag!"Name".no) or just `false` or `0`.  */
        no = false,

        /** When creating a value of type `Flag!"Name"`, use $(D
         Flag!"Name".yes) for the affirmative option. When using a
         value of type `Flag!"Name"`, compare it against $(D
         Flag!"Name".yes).
        */
        yes = true
    }
}

///
@safe unittest
{
    Flag!"abc" flag;

    assert(flag == Flag!"abc".no);
    assert(flag == No.abc);
    assert(!flag);
    if (flag) assert(0);
}

///
@safe unittest
{
    auto flag = Yes.abc;

    assert(flag);
    assert(flag == Yes.abc);
    if (!flag) assert(0);
    if (flag) {} else assert(0);
}

/**
Convenience names that allow using e.g. `Yes.encryption` instead of
`Flag!"encryption".yes` and `No.encryption` instead of $(D
Flag!"encryption".no).
*/
struct Yes
{
    template opDispatch(string name)
    {
        enum opDispatch = Flag!name.yes;
    }
}
//template yes(string name) { enum Flag!name yes = Flag!name.yes; }

/// Ditto
struct No
{
    template opDispatch(string name)
    {
        enum opDispatch = Flag!name.no;
    }
}

///
@safe unittest
{
    Flag!"abc" flag;

    assert(flag == Flag!"abc".no);
    assert(flag == No.abc);
    assert(!flag);
    if (flag) assert(0);
}

///
@safe unittest
{
    auto flag = Yes.abc;

    assert(flag);
    assert(flag == Yes.abc);
    if (!flag) assert(0);
    if (flag) {} else assert(0);
}

/**
Detect whether an enum is of integral type and has only "flag" values
(i.e. values with a bit count of exactly 1).
Additionally, a zero value is allowed for compatibility with enums including
a "None" value.
*/
template isBitFlagEnum(E)
{
    static if (is(E Base == enum) && isIntegral!Base)
    {
        enum isBitFlagEnum = (E.min >= 0) &&
        {
            static foreach (immutable flag; EnumMembers!E)
            {{
                Base value = flag;
                value &= value - 1;
                if (value != 0) return false;
            }}
            return true;
        }();
    }
    else
    {
        enum isBitFlagEnum = false;
    }
}

///
@safe pure nothrow unittest
{
    enum A
    {
        None,
        A = 1 << 0,
        B = 1 << 1,
        C = 1 << 2,
        D = 1 << 3,
    }

    static assert(isBitFlagEnum!A);
}

/// Test an enum with default (consecutive) values
@safe pure nothrow unittest
{
    enum B
    {
        A,
        B,
        C,
        D // D == 3
    }

    static assert(!isBitFlagEnum!B);
}

/// Test an enum with non-integral values
@safe pure nothrow unittest
{
    enum C: double
    {
        A = 1 << 0,
        B = 1 << 1
    }

    static assert(!isBitFlagEnum!C);
}

/**
A typesafe structure for storing combinations of enum values.

This template defines a simple struct to represent bitwise OR combinations of
enum values. It can be used if all the enum values are integral constants with
a bit count of at most 1, or if the `unsafe` parameter is explicitly set to
Yes.
This is much safer than using the enum itself to store
the OR combination, which can produce surprising effects like this:
----
enum E
{
    A = 1 << 0,
    B = 1 << 1
}
E e = E.A | E.B;
// will throw SwitchError
final switch (e)
{
    case E.A:
        return;
    case E.B:
        return;
}
----
*/
struct BitFlags(E, Flag!"unsafe" unsafe = No.unsafe)
if (unsafe || isBitFlagEnum!(E))
{
@safe @nogc pure nothrow:
private:
    enum isBaseEnumType(T) = is(E == T);
    alias Base = OriginalType!E;
    Base mValue;

public:
    this(E flag)
    {
        this = flag;
    }

    this(T...)(T flags)
        if (allSatisfy!(isBaseEnumType, T))
    {
        this = flags;
    }

    bool opCast(B: bool)() const
    {
        return mValue != 0;
    }

    Base opCast(B)() const
        if (isImplicitlyConvertible!(Base, B))
    {
        return mValue;
    }

    auto opUnary(string op)() const
        if (op == "~")
    {
        return BitFlags(cast(E) cast(Base) ~mValue);
    }

    auto ref opAssign(T...)(T flags)
        if (allSatisfy!(isBaseEnumType, T))
    {
        mValue = 0;
        foreach (E flag; flags)
        {
            mValue |= flag;
        }
        return this;
    }

    auto ref opAssign(E flag)
    {
        mValue = flag;
        return this;
    }

    auto ref opOpAssign(string op: "|")(BitFlags flags)
    {
        mValue |= flags.mValue;
        return this;
    }

    auto ref opOpAssign(string op: "&")(BitFlags  flags)
    {
        mValue &= flags.mValue;
        return this;
    }

    auto ref opOpAssign(string op: "|")(E flag)
    {
        mValue |= flag;
        return this;
    }

    auto ref opOpAssign(string op: "&")(E flag)
    {
        mValue &= flag;
        return this;
    }

    auto opBinary(string op)(BitFlags flags) const
        if (op == "|" || op == "&")
    {
        BitFlags result = this;
        result.opOpAssign!op(flags);
        return result;
    }

    auto opBinary(string op)(E flag) const
        if (op == "|" || op == "&")
    {
        BitFlags result = this;
        result.opOpAssign!op(flag);
        return result;
    }

    auto opBinaryRight(string op)(E flag) const
        if (op == "|" || op == "&")
    {
        return opBinary!op(flag);
    }

    bool opDispatch(string name)() const
    if (__traits(hasMember, E, name))
    {
        enum e = __traits(getMember, E, name);
        return (mValue & e) == e;
    }

    void opDispatch(string name)(bool set)
    if (__traits(hasMember, E, name))
    {
        enum e = __traits(getMember, E, name);
        if (set)
            mValue |= e;
        else
            mValue &= ~e;
    }
}

/// Set values with the | operator and test with &
@safe @nogc pure nothrow unittest
{
    enum Enum
    {
        A = 1 << 0,
    }

    // A default constructed BitFlags has no value set
    immutable BitFlags!Enum flags_empty;
    assert(!flags_empty.A);

    // Value can be set with the | operator
    immutable flags_A = flags_empty | Enum.A;

    // and tested using property access
    assert(flags_A.A);

    // or the & operator
    assert(flags_A & Enum.A);
    // which commutes.
    assert(Enum.A & flags_A);
}

/// A default constructed BitFlags has no value set
@safe @nogc pure nothrow unittest
{
    enum Enum
    {
        None,
        A = 1 << 0,
        B = 1 << 1,
        C = 1 << 2
    }

    immutable BitFlags!Enum flags_empty;
    assert(!(flags_empty & (Enum.A | Enum.B | Enum.C)));
    assert(!(flags_empty & Enum.A) && !(flags_empty & Enum.B) && !(flags_empty & Enum.C));
}

// BitFlags can be variadically initialized
@safe @nogc pure nothrow unittest
{
    import std.traits : EnumMembers;

    enum Enum
    {
        A = 1 << 0,
        B = 1 << 1,
        C = 1 << 2
    }

    // Values can also be set using property access
    BitFlags!Enum flags;
    flags.A = true;
    assert(flags & Enum.A);
    flags.A = false;
    assert(!(flags & Enum.A));

    // BitFlags can be variadically initialized
    immutable BitFlags!Enum flags_AB = BitFlags!Enum(Enum.A, Enum.B);
    assert(flags_AB.A && flags_AB.B && !flags_AB.C);

    // You can use the EnumMembers template to set all flags
    immutable BitFlags!Enum flags_all = EnumMembers!Enum;
    assert(flags_all.A && flags_all.B && flags_all.C);
}

/// Binary operations: subtracting and intersecting flags
@safe @nogc pure nothrow unittest
{
    enum Enum
    {
        A = 1 << 0,
        B = 1 << 1,
        C = 1 << 2,
    }
    immutable BitFlags!Enum flags_AB = BitFlags!Enum(Enum.A, Enum.B);
    immutable BitFlags!Enum flags_BC = BitFlags!Enum(Enum.B, Enum.C);

    // Use the ~ operator for subtracting flags
    immutable BitFlags!Enum flags_B = flags_AB & ~BitFlags!Enum(Enum.A);
    assert(!flags_B.A && flags_B.B && !flags_B.C);

    // use & between BitFlags for intersection
    assert(flags_B == (flags_BC & flags_AB));
}

/// All the binary operators work in their assignment version
@safe @nogc pure nothrow unittest
{
    enum Enum
    {
        A = 1 << 0,
        B = 1 << 1,
    }

    BitFlags!Enum flags_empty, temp, flags_AB;
    flags_AB = Enum.A | Enum.B;

    temp |= flags_AB;
    assert(temp == (flags_empty | flags_AB));

    temp = flags_empty;
    temp |= Enum.B;
    assert(temp == (flags_empty | Enum.B));

    temp = flags_empty;
    temp &= flags_AB;
    assert(temp == (flags_empty & flags_AB));

    temp = flags_empty;
    temp &= Enum.A;
    assert(temp == (flags_empty & Enum.A));
}

/// Conversion to bool and int
@safe @nogc pure nothrow unittest
{
    enum Enum
    {
        A = 1 << 0,
        B = 1 << 1,
    }

    BitFlags!Enum flags;

    // BitFlags with no value set evaluate to false
    assert(!flags);

    // BitFlags with at least one value set evaluate to true
    flags |= Enum.A;
    assert(flags);

    // This can be useful to check intersection between BitFlags
    BitFlags!Enum flags_AB = Enum.A | Enum.B;
    assert(flags & flags_AB);
    assert(flags & Enum.A);

    // You can of course get you raw value out of flags
    auto value = cast(int) flags;
    assert(value == Enum.A);
}

/// You need to specify the `unsafe` parameter for enums with custom values
@safe @nogc pure nothrow unittest
{
    enum UnsafeEnum
    {
        A = 1,
        B = 2,
        C = 4,
        BC = B|C
    }
    static assert(!__traits(compiles, { BitFlags!UnsafeEnum flags; }));
    BitFlags!(UnsafeEnum, Yes.unsafe) flags;

    // property access tests for exact match of unsafe enums
    flags.B = true;
    assert(!flags.BC); // only B
    flags.C = true;
    assert(flags.BC); // both B and C
    flags.B = false;
    assert(!flags.BC); // only C

    // property access sets all bits of unsafe enum group
    flags = flags.init;
    flags.BC = true;
    assert(!flags.A && flags.B && flags.C);
    flags.A = true;
    flags.BC = false;
    assert(flags.A && !flags.B && !flags.C);
}

// Negation of BitFlags should work with any base type.
// Double-negation of BitFlags should work.
@safe @nogc pure nothrow unittest
{
    static foreach (alias Base; AliasSeq!(
        byte,
        ubyte,
        short,
        ushort,
        int,
        uint,
        long,
        ulong,
    ))
    {{
        enum Enum : Base
        {
            A = 1 << 0,
            B = 1 << 1,
            C = 1 << 2,
        }

        auto flags = BitFlags!Enum(Enum.A);

        assert(flags == ~~flags);
    }}
}

private enum false_(T) = false;

// ReplaceType
/**
Replaces all occurrences of `From` into `To`, in one or more types `T`. For
example, `ReplaceType!(int, uint, Tuple!(int, float)[string])` yields
`Tuple!(uint, float)[string]`. The types in which replacement is performed
may be arbitrarily complex, including qualifiers, built-in type constructors
(pointers, arrays, associative arrays, functions, and delegates), and template
instantiations; replacement proceeds transitively through the type definition.
However, member types in `struct`s or `class`es are not replaced because there
are no ways to express the types resulting after replacement.

This is an advanced type manipulation necessary e.g. for replacing the
placeholder type `This` in $(REF Algebraic, std,variant).

Returns: `ReplaceType` aliases itself to the type(s) that result after
replacement.
*/
alias ReplaceType(From, To, T...) = ReplaceTypeUnless!(false_, From, To, T);

///
@safe unittest
{
    static assert(
        is(ReplaceType!(int, string, int[]) == string[]) &&
        is(ReplaceType!(int, string, int[int]) == string[string]) &&
        is(ReplaceType!(int, string, const(int)[]) == const(string)[]) &&
        is(ReplaceType!(int, string, Tuple!(int[], float))
            == Tuple!(string[], float))
    );
}

/**
Like $(LREF ReplaceType), but does not perform replacement in types for which
`pred` evaluates to `true`.
*/
template ReplaceTypeUnless(alias pred, From, To, T...)
{
    import std.meta;

    static if (T.length == 1)
    {
        static if (pred!(T[0]))
            alias ReplaceTypeUnless = T[0];
        else static if (is(T[0] == From))
            alias ReplaceTypeUnless = To;
        else static if (is(T[0] == const(U), U))
            alias ReplaceTypeUnless = const(ReplaceTypeUnless!(pred, From, To, U));
        else static if (is(T[0] == immutable(U), U))
            alias ReplaceTypeUnless = immutable(ReplaceTypeUnless!(pred, From, To, U));
        else static if (is(T[0] == shared(U), U))
            alias ReplaceTypeUnless = shared(ReplaceTypeUnless!(pred, From, To, U));
        else static if (is(T[0] == U*, U))
        {
            static if (is(U == function))
                alias ReplaceTypeUnless = replaceTypeInFunctionTypeUnless!(pred, From, To, T[0]);
            else
                alias ReplaceTypeUnless = ReplaceTypeUnless!(pred, From, To, U)*;
        }
        else static if (is(T[0] == delegate))
        {
            alias ReplaceTypeUnless = replaceTypeInFunctionTypeUnless!(pred, From, To, T[0]);
        }
        else static if (is(T[0] == function))
        {
            static assert(0, "Function types not supported," ~
                " use a function pointer type instead of " ~ T[0].stringof);
        }
        else static if (is(T[0] == U!V, alias U, V...))
        {
            template replaceTemplateArgs(T...)
            {
                static if (is(typeof(T[0]))) {   // template argument is value or symbol
                    static if (__traits(compiles, { alias _ = T[0]; }))
                        // it's a symbol
                        alias replaceTemplateArgs = T[0];
                    else
                        // it's a value
                        enum replaceTemplateArgs = T[0];
                } else
                    alias replaceTemplateArgs = ReplaceTypeUnless!(pred, From, To, T[0]);
            }
            alias ReplaceTypeUnless = U!(staticMap!(replaceTemplateArgs, V));
        }
        else static if (is(T[0] == struct))
            // don't match with alias this struct below
            // https://issues.dlang.org/show_bug.cgi?id=15168
            alias ReplaceTypeUnless = T[0];
        else static if (is(T[0] == U[], U))
            alias ReplaceTypeUnless = ReplaceTypeUnless!(pred, From, To, U)[];
        else static if (is(T[0] == U[n], U, size_t n))
            alias ReplaceTypeUnless = ReplaceTypeUnless!(pred, From, To, U)[n];
        else static if (is(T[0] == U[V], U, V))
            alias ReplaceTypeUnless =
                ReplaceTypeUnless!(pred, From, To, U)[ReplaceTypeUnless!(pred, From, To, V)];
        else
            alias ReplaceTypeUnless = T[0];
    }
    else static if (T.length > 1)
    {
        alias ReplaceTypeUnless = AliasSeq!(ReplaceTypeUnless!(pred, From, To, T[0]),
            ReplaceTypeUnless!(pred, From, To, T[1 .. $]));
    }
    else
    {
        alias ReplaceTypeUnless = AliasSeq!();
    }
}

///
@safe unittest
{
    import std.traits : isArray;

    static assert(
        is(ReplaceTypeUnless!(isArray, int, string, int*) == string*) &&
        is(ReplaceTypeUnless!(isArray, int, string, int[]) == int[]) &&
        is(ReplaceTypeUnless!(isArray, int, string, Tuple!(int, int[]))
            == Tuple!(string, int[]))
   );
}

private template replaceTypeInFunctionTypeUnless(alias pred, From, To, fun)
{
    alias RX = ReplaceTypeUnless!(pred, From, To, ReturnType!fun);
    alias PX = AliasSeq!(ReplaceTypeUnless!(pred, From, To, Parameters!fun));
    // Wrapping with AliasSeq is neccesary because ReplaceType doesn't return
    // tuple if Parameters!fun.length == 1

    string gen()
    {
        enum  linkage = functionLinkage!fun;
        alias attributes = functionAttributes!fun;
        enum  variadicStyle = variadicFunctionStyle!fun;
        alias storageClasses = ParameterStorageClassTuple!fun;

        string result;

        result ~= "extern(" ~ linkage ~ ") ";
        static if (attributes & FunctionAttribute.ref_)
        {
            result ~= "ref ";
        }

        result ~= "RX";
        static if (is(fun == delegate))
            result ~= " delegate";
        else
            result ~= " function";

        result ~= "(";
        static foreach (i; 0 .. PX.length)
        {
            if (i)
                result ~= ", ";
            if (storageClasses[i] & ParameterStorageClass.scope_)
                result ~= "scope ";
            if (storageClasses[i] & ParameterStorageClass.in_)
                result ~= "in ";
            if (storageClasses[i] & ParameterStorageClass.out_)
                result ~= "out ";
            if (storageClasses[i] & ParameterStorageClass.ref_)
                result ~= "ref ";
            if (storageClasses[i] & ParameterStorageClass.lazy_)
                result ~= "lazy ";
            if (storageClasses[i] & ParameterStorageClass.return_)
                result ~= "return ";

            result ~= "PX[" ~ i.stringof ~ "]";
        }
        static if (variadicStyle == Variadic.typesafe)
            result ~= " ...";
        else static if (variadicStyle != Variadic.no)
            result ~= ", ...";
        result ~= ")";

        static if (attributes & FunctionAttribute.pure_)
            result ~= " pure";
        static if (attributes & FunctionAttribute.nothrow_)
            result ~= " nothrow";
        static if (attributes & FunctionAttribute.property)
            result ~= " @property";
        static if (attributes & FunctionAttribute.trusted)
            result ~= " @trusted";
        static if (attributes & FunctionAttribute.safe)
            result ~= " @safe";
        static if (attributes & FunctionAttribute.nogc)
            result ~= " @nogc";
        static if (attributes & FunctionAttribute.system)
            result ~= " @system";
        static if (attributes & FunctionAttribute.const_)
            result ~= " const";
        static if (attributes & FunctionAttribute.immutable_)
            result ~= " immutable";
        static if (attributes & FunctionAttribute.inout_)
            result ~= " inout";
        static if (attributes & FunctionAttribute.shared_)
            result ~= " shared";
        static if (attributes & FunctionAttribute.return_)
            result ~= " return";

        return result;
    }

    mixin("alias replaceTypeInFunctionTypeUnless = " ~ gen() ~ ";");
}

@safe unittest
{
    template Test(Ts...)
    {
        static if (Ts.length)
        {
            //pragma(msg, "Testing: ReplaceType!("~Ts[0].stringof~", "
            //    ~Ts[1].stringof~", "~Ts[2].stringof~")");
            static assert(is(ReplaceType!(Ts[0], Ts[1], Ts[2]) == Ts[3]),
                "ReplaceType!("~Ts[0].stringof~", "~Ts[1].stringof~", "
                    ~Ts[2].stringof~") == "
                    ~ReplaceType!(Ts[0], Ts[1], Ts[2]).stringof);
            alias Test = Test!(Ts[4 .. $]);
        }
        else alias Test = void;
    }

    //import core.stdc.stdio;
    alias RefFun1 = ref int function(float, long);
    alias RefFun2 = ref float function(float, long);
    extern(C) int printf(const char*, ...) nothrow @nogc @system;
    extern(C) float floatPrintf(const char*, ...) nothrow @nogc @system;
    int func(float);

    int x;
    struct S1 { void foo() { x = 1; } }
    struct S2 { void bar() { x = 2; } }

    alias Pass = Test!(
        int, float, typeof(&func), float delegate(float),
        int, float, typeof(&printf), typeof(&floatPrintf),
        int, float, int function(out long, ...),
            float function(out long, ...),
        int, float, int function(ref float, long),
            float function(ref float, long),
        int, float, int function(ref int, long),
            float function(ref float, long),
        int, float, int function(out int, long),
            float function(out float, long),
        int, float, int function(lazy int, long),
            float function(lazy float, long),
        int, float, int function(out long, ref const int),
            float function(out long, ref const float),
        int, float, int function(in long, ref const int),
            float function(in long, ref const float),
        int, float, int function(long, in int),
            float function(long, in float),
        int, int, int, int,
        int, float, int, float,
        int, float, const int, const float,
        int, float, immutable int, immutable float,
        int, float, shared int, shared float,
        int, float, int*, float*,
        int, float, const(int)*, const(float)*,
        int, float, const(int*), const(float*),
        const(int)*, float, const(int*), const(float),
        int*, float, const(int)*, const(int)*,
        int, float, int[], float[],
        int, float, int[42], float[42],
        int, float, const(int)[42], const(float)[42],
        int, float, const(int[42]), const(float[42]),
        int, float, int[int], float[float],
        int, float, int[double], float[double],
        int, float, double[int], double[float],
        int, float, int function(float, long), float function(float, long),
        int, float, int function(float), float function(float),
        int, float, int function(float, int), float function(float, float),
        int, float, int delegate(float, long), float delegate(float, long),
        int, float, int delegate(float), float delegate(float),
        int, float, int delegate(float, int), float delegate(float, float),
        int, float, Unique!int, Unique!float,
        int, float, Tuple!(float, int), Tuple!(float, float),
        int, float, RefFun1, RefFun2,
        S1, S2,
            S1[1][][S1]* function(),
            S2[1][][S2]* function(),
        int, string,
               int[3] function(   int[] arr,    int[2] ...) pure @trusted,
            string[3] function(string[] arr, string[2] ...) pure @trusted,
    );

    // https://issues.dlang.org/show_bug.cgi?id=15168
    static struct T1 { string s; alias s this; }
    static struct T2 { char[10] s; alias s this; }
    static struct T3 { string[string] s; alias s this; }
    alias Pass2 = Test!(
        ubyte, ubyte, T1, T1,
        ubyte, ubyte, T2, T2,
        ubyte, ubyte, T3, T3,
    );
}

// https://issues.dlang.org/show_bug.cgi?id=17116
@safe unittest
{
    alias ConstDg = void delegate(float) const;
    alias B = void delegate(int) const;
    alias A = ReplaceType!(float, int, ConstDg);
    static assert(is(B == A));
}

 // https://issues.dlang.org/show_bug.cgi?id=19696
@safe unittest
{
    static struct T(U) {}
    static struct S { T!int t; alias t this; }
    static assert(is(ReplaceType!(float, float, S) == S));
}

 // https://issues.dlang.org/show_bug.cgi?id=19697
@safe unittest
{
    class D(T) {}
    class C : D!C {}
    static assert(is(ReplaceType!(float, float, C)));
}

// https://issues.dlang.org/show_bug.cgi?id=16132
@safe unittest
{
    interface I(T) {}
    class C : I!int {}
    static assert(is(ReplaceType!(int, string, C) == C));
}

// https://issues.dlang.org/show_bug.cgi?id=22325
@safe unittest
{
    static struct Foo(alias f) {}
    static void bar() {}
    alias _ = ReplaceType!(int, int, Foo!bar);
}

/**
Ternary type with three truth values:

$(UL
    $(LI `Ternary.yes` for `true`)
    $(LI `Ternary.no` for `false`)
    $(LI `Ternary.unknown` as an unknown state)
)

Also known as trinary, trivalent, or trilean.

See_Also:
    $(HTTP en.wikipedia.org/wiki/Three-valued_logic,
        Three Valued Logic on Wikipedia)
*/
struct Ternary
{
    @safe @nogc nothrow pure:

    private ubyte value = 6;
    private static Ternary make(ubyte b)
    {
        Ternary r = void;
        r.value = b;
        return r;
    }

    /**
        The possible states of the `Ternary`
    */
    enum no = make(0);
    /// ditto
    enum yes = make(2);
    /// ditto
    enum unknown = make(6);

    /**
     Construct and assign from a `bool`, receiving `no` for `false` and `yes`
     for `true`.
    */
    this(bool b) { value = b << 1; }

    /// ditto
    void opAssign(bool b) { value = b << 1; }

    /**
    Construct a ternary value from another ternary value
    */
    this(const Ternary b) { value = b.value; }

    /**
    $(TABLE Truth table for logical operations,
      $(TR $(TH `a`) $(TH `b`) $(TH `$(TILDE)a`) $(TH `a | b`) $(TH `a & b`) $(TH `a ^ b`))
      $(TR $(TD `no`) $(TD `no`) $(TD `yes`) $(TD `no`) $(TD `no`) $(TD `no`))
      $(TR $(TD `no`) $(TD `yes`) $(TD) $(TD `yes`) $(TD `no`) $(TD `yes`))
      $(TR $(TD `no`) $(TD `unknown`) $(TD) $(TD `unknown`) $(TD `no`) $(TD `unknown`))
      $(TR $(TD `yes`) $(TD `no`) $(TD `no`) $(TD `yes`) $(TD `no`) $(TD `yes`))
      $(TR $(TD `yes`) $(TD `yes`) $(TD) $(TD `yes`) $(TD `yes`) $(TD `no`))
      $(TR $(TD `yes`) $(TD `unknown`) $(TD) $(TD `yes`) $(TD `unknown`) $(TD `unknown`))
      $(TR $(TD `unknown`) $(TD `no`) $(TD `unknown`) $(TD `unknown`) $(TD `no`) $(TD `unknown`))
      $(TR $(TD `unknown`) $(TD `yes`) $(TD) $(TD `yes`) $(TD `unknown`) $(TD `unknown`))
      $(TR $(TD `unknown`) $(TD `unknown`) $(TD) $(TD `unknown`) $(TD `unknown`) $(TD `unknown`))
    )
    */
    Ternary opUnary(string s)() if (s == "~")
    {
        return make((386 >> value) & 6);
    }

    /// ditto
    Ternary opBinary(string s)(Ternary rhs) if (s == "|")
    {
        return make((25_512 >> (value + rhs.value)) & 6);
    }

    /// ditto
    Ternary opBinary(string s)(Ternary rhs) if (s == "&")
    {
        return make((26_144 >> (value + rhs.value)) & 6);
    }

    /// ditto
    Ternary opBinary(string s)(Ternary rhs) if (s == "^")
    {
        return make((26_504 >> (value + rhs.value)) & 6);
    }

    /// ditto
    Ternary opBinary(string s)(bool rhs)
    if (s == "|" || s == "&" || s == "^")
    {
        return this.opBinary!s(Ternary(rhs));
    }
}

///
@safe @nogc nothrow pure
unittest
{
    Ternary a;
    assert(a == Ternary.unknown);

    assert(~Ternary.yes == Ternary.no);
    assert(~Ternary.no == Ternary.yes);
    assert(~Ternary.unknown == Ternary.unknown);
}

@safe @nogc nothrow pure
unittest
{
    alias f = Ternary.no, t = Ternary.yes, u = Ternary.unknown;
    Ternary[27] truthTableAnd =
    [
        t, t, t,
        t, u, u,
        t, f, f,
        u, t, u,
        u, u, u,
        u, f, f,
        f, t, f,
        f, u, f,
        f, f, f,
    ];

    Ternary[27] truthTableOr =
    [
        t, t, t,
        t, u, t,
        t, f, t,
        u, t, t,
        u, u, u,
        u, f, u,
        f, t, t,
        f, u, u,
        f, f, f,
    ];

    Ternary[27] truthTableXor =
    [
        t, t, f,
        t, u, u,
        t, f, t,
        u, t, u,
        u, u, u,
        u, f, u,
        f, t, t,
        f, u, u,
        f, f, f,
    ];

    for (auto i = 0; i != truthTableAnd.length; i += 3)
    {
        assert((truthTableAnd[i] & truthTableAnd[i + 1])
            == truthTableAnd[i + 2]);
        assert((truthTableOr[i] | truthTableOr[i + 1])
            == truthTableOr[i + 2]);
        assert((truthTableXor[i] ^ truthTableXor[i + 1])
            == truthTableXor[i + 2]);
    }

    Ternary a;
    assert(a == Ternary.unknown);
    static assert(!is(typeof({ if (a) {} })));
    assert(!is(typeof({ auto b = Ternary(3); })));
    a = true;
    assert(a == Ternary.yes);
    a = false;
    assert(a == Ternary.no);
    a = Ternary.unknown;
    assert(a == Ternary.unknown);
    Ternary b;
    b = a;
    assert(b == a);
    assert(~Ternary.yes == Ternary.no);
    assert(~Ternary.no == Ternary.yes);
    assert(~Ternary.unknown == Ternary.unknown);
}

@safe @nogc nothrow pure
unittest
{
    Ternary a = Ternary(true);
    assert(a == Ternary.yes);
    assert((a & false) == Ternary.no);
    assert((a | false) == Ternary.yes);
    assert((a ^ true) == Ternary.no);
    assert((a ^ false) == Ternary.yes);
}

// https://issues.dlang.org/show_bug.cgi?id=22511
@safe unittest
{
    static struct S
    {
        int b;
        @disable this(this);
        this(ref return scope inout S rhs) inout
        {
            this.b = rhs.b + 1;
        }
    }

    Nullable!S s1 = S(1);
    assert(s1.get().b == 2);
    Nullable!S s2 = s1;
    assert(s2.get().b == 3);
}

@safe unittest
{
    static struct S
    {
        int b;
        this(this) { ++b; }
    }

    Nullable!S s1 = S(1);
    assert(s1.get().b == 2);
    Nullable!S s2 = s1;
    assert(s2.get().b == 3);
}