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
//! A double-ended queue that `Deref`s into a slice.
//!
//! The double-ended queue in the standard library ([`VecDeque`]) is
//! implemented using a growable ring buffer (`0` represents uninitialized
//! memory, and `T` represents one element in the queue):
//!
//! ```rust
//! // [ 0 | 0 | 0 | T | T | T | 0 ]
//! //               ^:head  ^:tail
//! ```
//!
//! When the queue grows beyond the end of the allocated buffer, its tail wraps
//! around:
//!
//! ```rust
//! // [ T | T | 0 | T | T | T | T ]
//! //       ^:tail  ^:head
//! ```
//!
//! As a consequence, [`VecDeque`] cannot `Deref` into a slice, since its
//! elements do not, in general, occupy a contiguous memory region. This
//! complicates the implementation and its interface (for example, there is no
//! `as_slice` method, but [`as_slices`] returns a pair of slices) and has
//! negative performance consequences (e.g. need to account for wrap around
//! while iterating over the elements).
//!
//! This crates provides [`SliceDeque`], a double-ended queue implemented with
//! a growable *virtual* ring-buffer.
//!
//! A virtual ring-buffer implementation is very similar to the one used in
//! `VecDeque`. The main difference is that a virtual ring-buffer maps two
//! adjacent regions of virtual memory to the same region of physical memory:
//!
//! ```rust
//! // Virtual memory:
//! //
//! //  __________region_0_________ __________region_1_________
//! // [ 0 | 0 | 0 | T | T | T | 0 | 0 | 0 | 0 | T | T | T | 0 ]
//! //               ^:head  ^:tail
//! //
//! // Physical memory:
//! //
//! // [ 0 | 0 | 0 | T | T | T | 0 ]
//! //               ^:head  ^:tail
//! ```
//!
//! That is, both the virtual memory regions `0` and `1` above (top) map to
//! the same physical memory (bottom). Just like `VecDeque`, when the queue
//! grows beyond the end of the allocated physical memory region, the queue
//! wraps around, and new elements continue to be appended at the beginning of
//! the queue. However, because `SliceDeque` maps the physical memory to two
//! adjacent memory regions, in virtual memory space the queue maintais the
//! ilusion of a contiguous memory layout:
//!
//! ```rust
//! // Virtual memory:
//! //
//! //  __________region_0_________ __________region_1_________
//! // [ T | T | 0 | T | T | T | T | T | T | 0 | T | T | T | T ]
//! //               ^:head              ^:tail
//! //
//! // Physical memory:
//! //
//! // [ T | T | 0 | T | T | T | T ]
//! //       ^:tail  ^:head
//! ```
//!
//! Since processes in many Operating Systems only deal with virtual memory
//! addresses, leaving the mapping to physical memory to the CPU Memory
//! Management Unit (MMU), [`SliceDeque`] is able to `Deref`s into a slice in
//! those systems.
//!
//! This simplifies [`SliceDeque`]'s API and implementation, giving it a
//! performance advantage over [`VecDeque`] in some situations.
//!
//! In general, you can think of [`SliceDeque`] as a `Vec` with `O(1)`
//! `pop_front` and amortized `O(1)` `push_front` methods.
//!
//! The main drawbacks of [`SliceDeque`] are:
//!
//! * constrained platform support: by necessity [`SliceDeque`] must use the
//! platform-specific virtual memory facilities of the underlying operating
//! system. While [`SliceDeque`] can work on all major operating systems,
//! currently only `MacOS X` is supported.
//!
//! * no global allocator support: since the `Alloc`ator API does not support
//! virtual memory, to use platform-specific virtual memory support
//! [`SliceDeque`] must bypass the global allocator and talk directly to the
//! operating system. This can have negative performance consequences since
//! growing [`SliceDeque`] is always going to incur the cost of some system
//! calls.
//!
//! * capacity constrained by virtual memory facilities: [`SliceDeque`] must
//! allocate two adjacent memory regions that map to the same region of
//! physical memory. Most operating systems allow this operation to be
//! performed exclusively on memory pages (or memory allocations that are
//! multiples of a memory page). As a consequence, the smalles [`SliceDeque`]
//! that can be created has typically a capacity of 2 memory pages, and it can
//! grow only to capacities that are a multiple of a memory page.
//!
//! The main advantages of [`SliceDeque`] are:
//!
//! * nicer API: since it `Deref`s to a slice, all operations that work on
//! slices are available for `SliceDeque`.
//!
//! * efficient iteration: as efficient as for slices.
//!
//! * simpler serialization: since one can just serialize/deserialize a single
//! slice.
//!
//! All in all, if your double-ended queues are small (smaller than a memory
//! page) or they get resized very often, `VecDeque` can perform better than
//! [`SliceDeque`]. Otherwise, [`SliceDeque`] typically performs better (see
//! the benchmarks), but platform support and global allocator bypass are two
//! reasons to weight in against its usage.
//!
//! [`VecDeque`]: https://doc.rust-lang.org/std/collections/struct.VecDeque.html
//! [`as_slices`]: https://doc.rust-lang.org/std/collections/struct.VecDeque.html#method.as_slices
//! [`SliceDeque`]: struct.SliceDeque.html

#![cfg_attr(
    feature = "unstable",
    feature(
        core_intrinsics,
        exact_size_is_empty,
        dropck_eyepatch,
        trusted_len,
        ptr_wrapping_offset_from,
        specialization,
    )
)]
#![cfg_attr(all(test, feature = "unstable"), feature(box_syntax))]
#![allow(
    clippy::len_without_is_empty,
    clippy::shadow_reuse,
    clippy::cast_possible_wrap,
    clippy::cast_sign_loss,
    clippy::cast_possible_truncation,
    clippy::inline_always,
    clippy::indexing_slicing
)]
#![cfg_attr(not(any(feature = "use_std", test)), no_std)]

#[macro_use]
mod macros;

#[cfg(any(feature = "use_std", test))]
extern crate core;

#[cfg(all(
    any(target_os = "macos", target_os = "ios"),
    not(feature = "unix_sysv")
))]
extern crate mach;

#[cfg(unix)]
extern crate libc;

#[cfg(target_os = "windows")]
extern crate winapi;

#[cfg(all(feature = "bytes_buf", feature = "use_std"))]
extern crate bytes;

mod mirrored;
pub use mirrored::{AllocError, Buffer};

#[cfg(all(feature = "bytes_buf", feature = "use_std"))]
use std::io;

use core::{cmp, convert, fmt, hash, iter, mem, ops, ptr, slice, str};

use core::ptr::NonNull;

#[cfg(feature = "unstable")]
use core::intrinsics;

/// A stable version of the `core::intrinsics` module.
#[cfg(not(feature = "unstable"))]
mod intrinsics {
    /// Like `core::intrinsics::unlikely` but does nothing.
    #[inline(always)]
    pub unsafe fn unlikely<T>(x: T) -> T {
        x
    }

    /// Like `core::intrinsics::assume` but does nothing.
    #[inline(always)]
    pub unsafe fn assume<T>(x: T) -> T {
        x
    }

    /// Like `core::intrinsics::arith_offset` but doing pointer to integer
    /// conversions.
    #[inline(always)]
    pub unsafe fn arith_offset<T>(dst: *const T, offset: isize) -> *const T {
        let r = if offset >= 0 {
            (dst as usize).wrapping_add(offset as usize)
        } else {
            (dst as usize).wrapping_sub((-offset) as usize)
        };
        r as *const T
    }
}

/// Stable implementation of `.wrapping_offset_from` for pointers.
trait WrappingOffsetFrom {
    /// Stable implementation of `.wrapping_offset_from` for pointers.
    fn wrapping_offset_from_(self, other: Self) -> Option<isize>;
}

#[cfg(not(feature = "unstable"))]
impl<T: Sized> WrappingOffsetFrom for *const T {
    #[inline(always)]
    fn wrapping_offset_from_(self, other: Self) -> Option<isize>
    where
        T: Sized,
    {
        let size = mem::size_of::<T>();
        if size == 0 {
            None
        } else {
            let diff = (other as isize).wrapping_sub(self as isize);
            Some(diff / size as isize)
        }
    }
}

#[cfg(feature = "unstable")]
impl<T: Sized> WrappingOffsetFrom for *const T {
    #[inline(always)]
    fn wrapping_offset_from_(self, other: Self) -> Option<isize>
    where
        T: Sized,
    {
        let size = mem::size_of::<T>();
        if size == 0 {
            None
        } else {
            Some(other.wrapping_offset_from(self))
        }
    }
}

/// Is `p` in bounds of `s` ?
///
/// Does it point to an element of `s` ? That is, one past the end of `s` is
/// not in bounds.
fn in_bounds<T>(s: &[T], p: *mut T) -> bool {
    let p = p as usize;
    let s_begin = s.as_ptr() as usize;
    let s_end = s_begin + mem::size_of::<T>() * s.len();
    s_begin <= p && p < s_end
}

unsafe fn nonnull_raw_slice<T>(ptr: *mut T, len: usize) -> NonNull<[T]> {
    NonNull::new_unchecked(slice::from_raw_parts_mut(ptr, len))
}

/// A double-ended queue that derefs into a slice.
///
/// It is implemented with a growable virtual ring buffer.
pub struct SliceDeque<T> {
    /// Elements in the queue.
    elems_: NonNull<[T]>,
    /// Mirrored memory buffer.
    buf: Buffer<T>,
}

// Safe because it is possible to free this from a different thread
unsafe impl<T> Send for SliceDeque<T> where T: Send {}
// Safe because this doesn't use any kind of interior mutability.
unsafe impl<T> Sync for SliceDeque<T> where T: Sync {}

/// Implementation detail of the sdeq! macro.
#[doc(hidden)]
pub use mem::forget as __mem_forget;

/// Creates a [`SliceDeque`] containing the arguments.
///
/// `sdeq!` allows `SliceDeque`s to be defined with the same syntax as array
/// expressions. There are two forms of this macro:
///
/// - Create a [`SliceDeque`] containing a given list of elements:
///
/// ```
/// # #[macro_use] extern crate slice_deque;
/// # use slice_deque::SliceDeque;
/// # fn main() {
/// let v: SliceDeque<i32> = sdeq![1, 2, 3];
/// assert_eq!(v[0], 1);
/// assert_eq!(v[1], 2);
/// assert_eq!(v[2], 3);
/// # }
/// ```
///
/// - Create a [`SliceDeque`] from a given element and size:
///
/// ```
/// # #[macro_use] extern crate slice_deque;
/// # use slice_deque::SliceDeque;
/// # fn main() {
/// let v = sdeq![7; 3];
/// assert_eq!(v, [7, 7, 7]);
/// # }
/// ```
///
/// Note that unlike array expressions this syntax supports all elements
/// which implement `Clone` and the number of elements doesn't have to be
/// a constant.
///
/// This will use `clone` to duplicate an expression, so one should be careful
/// using this with types having a nonstandard `Clone` implementation. For
/// example, `sdeq![Rc::new(1); 5]` will create a deque of five references
/// to the same boxed integer value, not five references pointing to
/// independently boxed integers.
///
/// ```
/// # #[macro_use] extern crate slice_deque;
/// # use slice_deque::SliceDeque;
/// # use std::rc::Rc;
/// # fn main() {
/// let v = sdeq![Rc::new(1_i32); 5];
/// let ptr: *const i32 = &*v[0] as *const i32;
/// for i in v.iter() {
///     assert_eq!(Rc::into_raw(i.clone()), ptr);
/// }
/// # }
/// ```
///
/// [`SliceDeque`]: struct.SliceDeque.html
#[macro_export]
macro_rules! sdeq {
    ($elem:expr; $n:expr) => (
        {
            let mut deq = $crate::SliceDeque::with_capacity($n);
            deq.resize($n, $elem);
            deq
        }
    );
    () => ( $crate::SliceDeque::new() );
    ($($x:expr),*) => (
        {
            unsafe {
                let array = [$($x),*];
                let deq = $crate::SliceDeque::steal_from_slice(&array);
                #[allow(clippy::forget_copy)]
                $crate::__mem_forget(array);
                deq
            }
        }
    );
    ($($x:expr,)*) => (sdeq![$($x),*])
}

impl<T> SliceDeque<T> {
    /// Creates a new empty deque.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use slice_deque::SliceDeque;
    /// let deq = SliceDeque::new();
    /// # let o: SliceDeque<u32> = deq;
    /// ```
    #[inline]
    pub fn new() -> Self {
        unsafe {
            let buf = Buffer::new();
            Self {
                elems_: nonnull_raw_slice(buf.ptr(), 0),
                buf,
            }
        }
    }

    /// Creates a SliceDeque from its raw components.
    ///
    /// The `ptr` must be a pointer to the beginning of the memory buffer from
    /// another `SliceDeque`, `capacity` the capacity of this `SliceDeque`, and
    /// `elems` the elements of this `SliceDeque`.
    #[inline]
    pub unsafe fn from_raw_parts(
        ptr: *mut T, capacity: usize, elems: &mut [T],
    ) -> Self {
        let begin = elems.as_mut_ptr();
        debug_assert!(in_bounds(slice::from_raw_parts(ptr, capacity), begin));
        debug_assert!(elems.len() < capacity);

        Self {
            elems_: NonNull::new_unchecked(elems),
            buf: Buffer::from_raw_parts(ptr, capacity * 2),
        }
    }

    /// Create an empty deque with capacity to hold `n` elements.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use slice_deque::SliceDeque;
    /// let deq = SliceDeque::with_capacity(10);
    /// # let o: SliceDeque<u32> = deq;
    /// ```
    #[inline]
    pub fn with_capacity(n: usize) -> Self {
        unsafe {
            let buf = Buffer::uninitialized(2 * n).unwrap_or_else(|e| {
                let s = tiny_str!(
                    "failed to allocate a buffer with capacity \"{}\" due to \"{:?}\"",
                    n, e
                );
                panic!("{}", s.as_str())
            });
            Self {
                elems_: nonnull_raw_slice(buf.ptr(), 0),
                buf,
            }
        }
    }

    /// Returns the number of elements that the deque can hold without
    /// reallocating.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use slice_deque::SliceDeque;
    /// let deq = SliceDeque::with_capacity(10);
    /// assert!(deq.capacity() >= 10);
    /// # let o: SliceDeque<u32> = deq;
    /// ```
    #[inline]
    pub fn capacity(&self) -> usize {
        // Note: the buffer length is not necessarily a power of two
        // debug_assert!(self.buf.len() % 2 == 0);
        self.buf.len() / 2
    }

    /// Number of elements in the ring buffer.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use slice_deque::SliceDeque;
    /// let mut deq = SliceDeque::with_capacity(10);
    /// assert!(deq.len() == 0);
    /// deq.push_back(3);
    /// assert!(deq.len() == 1);
    /// ```
    #[inline]
    pub fn len(&self) -> usize {
        let l = self.as_slice().len();
        debug_assert!(l <= self.capacity());
        l
    }

    /// Is the ring buffer full ?
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use slice_deque::SliceDeque;
    /// let mut deq = SliceDeque::with_capacity(10);
    /// assert!(!deq.is_full());
    /// # let o: SliceDeque<u32> = deq;
    /// ```
    #[inline]
    pub fn is_full(&self) -> bool {
        self.len() == self.capacity()
    }

    /// Extracts a slice containing the entire deque.
    #[inline]
    pub fn as_slice(&self) -> &[T] {
        unsafe { self.elems_.as_ref() }
    }

    /// Extracts a mutable slice containing the entire deque.
    #[inline]
    pub fn as_mut_slice(&mut self) -> &mut [T] {
        unsafe { self.elems_.as_mut() }
    }

    /// Returns a pair of slices, where the first slice contains the contents
    /// of the deque and the second one is empty.
    #[inline]
    pub fn as_slices(&self) -> (&[T], &[T]) {
        unsafe {
            let left = self.as_slice();
            let right =
                slice::from_raw_parts(usize::max_value() as *const _, 0);
            (left, right)
        }
    }

    /// Returns a pair of slices, where the first slice contains the contents
    /// of the deque and the second one is empty.
    #[inline]
    pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
        unsafe {
            let left = self.as_mut_slice();
            let right =
                slice::from_raw_parts_mut(usize::max_value() as *mut _, 0);
            (left, right)
        }
    }

    /// Returns the slice of uninitialized memory between the `tail` and the
    /// `begin`.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[macro_use] extern crate slice_deque;
    /// # fn main() {
    /// let mut d = sdeq![1, 2, 3];
    /// let cap = d.capacity();
    /// let len = d.len();
    /// unsafe {
    ///     {
    ///         // This slice contains the uninitialized elements in
    ///         // the deque:
    ///         let mut s = d.tail_head_slice();
    ///         assert_eq!(s.len(), cap - len);
    ///         // We can write to them and for example bump the tail of
    ///         // the deque:
    ///         s[0] = 4;
    ///         s[1] = 5;
    ///     }
    ///     d.move_tail(2);
    /// }
    /// assert_eq!(d, sdeq![1, 2, 3, 4, 5]);
    /// # }
    /// ```
    pub unsafe fn tail_head_slice(&mut self) -> &mut [T] {
        let ptr = self.as_mut_slice().as_mut_ptr().add(self.len());
        slice::from_raw_parts_mut(ptr, self.capacity() - self.len())
    }

    /// Attempts to reserve capacity for inserting at least `additional`
    /// elements without reallocating. Does nothing if the capacity is already
    /// sufficient.
    ///
    /// The collection always reserves memory in multiples of the page size.
    ///
    /// # Panics
    ///
    /// Panics if the new capacity overflows `usize`.
    #[inline]
    pub fn try_reserve(
        &mut self, additional: usize,
    ) -> Result<(), AllocError> {
        let old_len = self.len();
        let new_cap = self.grow_policy(additional);
        self.reserve_capacity(new_cap)?;
        debug_assert!(self.capacity() >= old_len + additional);
        Ok(())
    }

    /// Reserves capacity for inserting at least `additional` elements without
    /// reallocating. Does nothing if the capacity is already sufficient.
    ///
    /// The collection always reserves memory in multiples of the page size.
    ///
    /// # Panics
    ///
    /// Panics if the new capacity overflows `usize` or on OOM.
    #[inline]
    pub fn reserve(&mut self, additional: usize) {
        self.try_reserve(additional).unwrap();
    }

    /// Attempts to reserve capacity for `new_capacity` elements. Does nothing
    /// if the capacity is already sufficient.
    #[inline]
    fn reserve_capacity(
        &mut self, new_capacity: usize,
    ) -> Result<(), AllocError> {
        unsafe {
            if new_capacity <= self.capacity() {
                return Ok(());
            }

            let mut new_buffer = Buffer::uninitialized(2 * new_capacity)?;
            debug_assert!(new_buffer.len() >= 2 * new_capacity);

            let len = self.len();
            // Move the elements from the current buffer
            // to the beginning of the new buffer:
            {
                let from_ptr = self.as_mut_ptr();
                let to_ptr = new_buffer.as_mut_slice().as_mut_ptr();
                crate::ptr::copy_nonoverlapping(from_ptr, to_ptr, len);
            }

            // Exchange buffers
            crate::mem::swap(&mut self.buf, &mut new_buffer);

            // Correct the slice - we copied to the
            // beginning of the of the new buffer:
            self.elems_ = nonnull_raw_slice(self.buf.ptr(), len);
            Ok(())
        }
    }

    /// Reserves the minimum capacity for exactly `additional` more elements to
    /// be inserted in the given `SliceDeq<T>`. After calling `reserve_exact`,
    /// capacity will be greater than or equal to `self.len() + additional`.
    /// Does nothing if the capacity is already sufficient.
    ///
    /// Note that the allocator may give the collection more space than it
    /// requests. Therefore capacity can not be relied upon to be precisely
    /// minimal. Prefer `reserve` if future insertions are expected.
    ///
    /// # Panics
    ///
    /// Panics if the new capacity overflows `usize`.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[macro_use] extern crate slice_deque;
    /// # fn main() {
    /// let mut deq = sdeq![1];
    /// deq.reserve_exact(10);
    /// assert!(deq.capacity() >= 11);
    /// # }
    /// ```
    #[inline]
    pub fn reserve_exact(&mut self, additional: usize) {
        let old_len = self.len();
        let new_cap = old_len.checked_add(additional).expect("overflow");
        self.reserve_capacity(new_cap).unwrap();
        debug_assert!(self.capacity() >= old_len + additional);
    }

    /// Growth policy of the deque. The capacity is going to be a multiple of
    /// the page-size anyways, so we just double capacity when needed.
    #[inline]
    fn grow_policy(&self, additional: usize) -> usize {
        let cur_cap = self.capacity();
        let old_len = self.len();
        let req_cap = old_len.checked_add(additional).expect("overflow");
        if req_cap > cur_cap {
            let dbl_cap = cur_cap.saturating_mul(2);
            cmp::max(req_cap, dbl_cap)
        } else {
            req_cap
        }
    }

    /// Moves the deque head by `x`.
    ///
    /// # Panics
    ///
    /// If the head wraps over the tail the behavior is undefined, that is,
    /// if `x` is out-of-range `[-(capacity() - len()), len()]`.
    ///
    /// If `-C debug-assertions=1` violating this pre-condition `panic!`s.
    ///
    /// # Unsafe
    ///
    /// It does not `drop` nor initialize elements, it just moves where the
    /// tail of the deque points to within the allocated buffer.
    #[inline]
    pub unsafe fn move_head_unchecked(&mut self, x: isize) {
        let cap = self.capacity();
        let len = self.len();
        // Make sure that the begin does not wrap over the end:
        debug_assert!(x >= -((cap - len) as isize));
        debug_assert!(x <= len as isize);

        // Obtain the begin of the slice and offset it by x:
        let mut new_begin = self.as_mut_ptr().offset(x) as usize;

        // Compute the boundaries of the first and second memory regions:
        let first_region_begin = self.buf.ptr() as usize;
        let region_size = Buffer::<T>::size_in_bytes(self.buf.len()) / 2;
        debug_assert!(cap * mem::size_of::<T>() <= region_size);
        let second_region_begin = first_region_begin + region_size;

        // If the new begin is not inside the first memory region, we shift it
        // by the region size into it:
        if new_begin < first_region_begin {
            new_begin += region_size;
        } else if new_begin >= second_region_begin {
            // Should be within the second region:
            debug_assert!(new_begin < second_region_begin + region_size);
            new_begin -= region_size;
        }
        debug_assert!(new_begin >= first_region_begin);
        debug_assert!(new_begin < second_region_begin);

        // The new begin is now in the first memory region:
        let new_begin = new_begin as *mut T;
        debug_assert!(in_bounds(
            slice::from_raw_parts(self.buf.ptr() as *mut u8, region_size),
            new_begin as *mut u8
        ));

        let new_len = len as isize - x;
        debug_assert!(
            new_len >= 0,
            "len = {}, x = {}, new_len = {}",
            len,
            x,
            new_len
        );
        debug_assert!(new_len <= cap as isize);
        self.elems_ = nonnull_raw_slice(new_begin, new_len as usize);
    }

    /// Moves the deque head by `x`.
    ///
    /// # Panics
    ///
    /// If the `head` wraps over the `tail`, that is, if `x` is out-of-range
    /// `[-(capacity() - len()), len()]`.
    ///
    /// # Unsafe
    ///
    /// It does not `drop` nor initialize elements, it just moves where the
    /// tail of the deque points to within the allocated buffer.
    #[inline]
    pub unsafe fn move_head(&mut self, x: isize) {
        assert!(
            x >= -((self.capacity() - self.len()) as isize)
                && x <= self.len() as isize
        );
        self.move_head_unchecked(x)
    }

    /// Moves the deque tail by `x`.
    ///
    /// # Panics
    ///
    /// If the `tail` wraps over the `head` the behavior is undefined, that is,
    /// if `x` is out-of-range `[-len(), capacity() - len()]`.
    ///
    /// If `-C debug-assertions=1` violating this pre-condition `panic!`s.
    ///
    /// # Unsafe
    ///
    /// It does not `drop` nor initialize elements, it just moves where the
    /// tail of the deque points to within the allocated buffer.
    #[inline]
    pub unsafe fn move_tail_unchecked(&mut self, x: isize) {
        // Make sure that the end does not wrap over the begin:
        let len = self.len();
        let cap = self.capacity();
        debug_assert!(x >= -(len as isize));
        debug_assert!(x <= (cap - len) as isize);

        let new_len = len as isize + x;
        debug_assert!(new_len >= 0);
        debug_assert!(new_len <= cap as isize);

        self.elems_ = nonnull_raw_slice(self.as_mut_ptr(), new_len as usize);
    }

    /// Moves the deque tail by `x`.
    ///
    /// # Panics
    ///
    /// If the `tail` wraps over the `head`, that is, if `x` is out-of-range
    /// `[-len(), capacity() - len()]`.
    ///
    /// # Unsafe
    ///
    /// It does not `drop` nor initialize elements, it just moves where the
    /// tail of the deque points to within the allocated buffer.
    #[inline]
    pub unsafe fn move_tail(&mut self, x: isize) {
        assert!(
            x >= -(self.len() as isize)
                && x <= (self.capacity() - self.len()) as isize
        );
        self.move_tail_unchecked(x);
    }

    /// Appends elements to `self` from `other`.
    #[inline]
    unsafe fn append_elements(&mut self, other: *const [T]) {
        let count = (*other).len();
        self.reserve(count);
        let len = self.len();
        ptr::copy_nonoverlapping(
            other as *const T,
            self.get_unchecked_mut(len),
            count,
        );
        self.move_tail_unchecked(count as isize);
    }

    /// Steal the elements from the slice `s`. You should `mem::forget` the
    /// slice afterwards.
    pub unsafe fn steal_from_slice(s: &[T]) -> Self {
        let mut deq = Self::new();
        deq.append_elements(s as *const _);
        deq
    }

    /// Moves all the elements of `other` into `Self`, leaving `other` empty.
    ///
    /// # Panics
    ///
    /// Panics if the number of elements in the deque overflows a `isize`.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[macro_use] extern crate slice_deque;
    /// # use slice_deque::SliceDeque;
    /// # fn main() {
    /// let mut deq = sdeq![1, 2, 3];
    /// let mut deq2 = sdeq![4, 5, 6];
    /// deq.append(&mut deq2);
    /// assert_eq!(deq, [1, 2, 3, 4, 5, 6]);
    /// assert_eq!(deq2, []);
    /// # }
    /// ```
    #[inline]
    pub fn append(&mut self, other: &mut Self) {
        unsafe {
            self.append_elements(other.as_slice() as _);
            other.elems_ = nonnull_raw_slice(other.buf.ptr(), 0);
        }
    }

    /// Provides a reference to the first element, or `None` if the deque is
    /// empty.
    ///
    /// # Examples
    ///
    /// ```
    /// # use slice_deque::SliceDeque;
    /// let mut deq = SliceDeque::new();
    /// assert_eq!(deq.front(), None);
    ///
    /// deq.push_back(1);
    /// deq.push_back(2);
    /// assert_eq!(deq.front(), Some(&1));
    /// deq.push_front(3);
    /// assert_eq!(deq.front(), Some(&3));
    /// ```
    #[inline]
    pub fn front(&self) -> Option<&T> {
        self.get(0)
    }

    /// Provides a mutable reference to the first element, or `None` if the
    /// deque is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// # use slice_deque::SliceDeque;
    /// let mut deq = SliceDeque::new();
    /// assert_eq!(deq.front(), None);
    ///
    /// deq.push_back(1);
    /// deq.push_back(2);
    /// assert_eq!(deq.front(), Some(&1));
    /// (*deq.front_mut().unwrap()) = 3;
    /// assert_eq!(deq.front(), Some(&3));
    /// ```
    #[inline]
    pub fn front_mut(&mut self) -> Option<&mut T> {
        self.get_mut(0)
    }

    /// Provides a reference to the last element, or `None` if the deque is
    /// empty.
    ///
    /// # Examples
    ///
    /// ```
    /// # use slice_deque::SliceDeque;
    /// let mut deq = SliceDeque::new();
    /// assert_eq!(deq.back(), None);
    ///
    /// deq.push_back(1);
    /// deq.push_back(2);
    /// assert_eq!(deq.back(), Some(&2));
    /// deq.push_front(3);
    /// assert_eq!(deq.back(), Some(&2));
    /// ```
    #[inline]
    pub fn back(&self) -> Option<&T> {
        let last_idx = self.len().wrapping_sub(1);
        self.get(last_idx)
    }

    /// Provides a mutable reference to the last element, or `None` if the
    /// deque is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// # use slice_deque::SliceDeque;
    /// let mut deq = SliceDeque::new();
    /// assert_eq!(deq.front(), None);
    ///
    /// deq.push_back(1);
    /// deq.push_back(2);
    /// assert_eq!(deq.back(), Some(&2));
    /// (*deq.back_mut().unwrap()) = 3;
    /// assert_eq!(deq.back(), Some(&3));
    /// ```
    #[inline]
    pub fn back_mut(&mut self) -> Option<&mut T> {
        let last_idx = self.len().wrapping_sub(1);
        self.get_mut(last_idx)
    }

    /// Attempts to prepend `value` to the deque.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use slice_deque::SliceDeque;
    /// let mut deq = SliceDeque::new();
    /// deq.try_push_front(1).unwrap();
    /// deq.try_push_front(2).unwrap();
    /// assert_eq!(deq.front(), Some(&2));
    /// ```
    #[inline]
    pub fn try_push_front(&mut self, value: T) -> Result<(), (T, AllocError)> {
        unsafe {
            if intrinsics::unlikely(self.is_full()) {
                if let Err(e) = self.try_reserve(1) {
                    return Err((value, e));
                }
            }

            self.move_head_unchecked(-1);
            ptr::write(self.get_mut(0).unwrap(), value);
            Ok(())
        }
    }

    /// Prepends `value` to the deque.
    ///
    /// # Panics
    ///
    /// On OOM.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use slice_deque::SliceDeque;
    /// let mut deq = SliceDeque::new();
    /// deq.push_front(1);
    /// deq.push_front(2);
    /// assert_eq!(deq.front(), Some(&2));
    /// ```
    #[inline]
    pub fn push_front(&mut self, value: T) {
        if let Err(e) = self.try_push_front(value) {
            panic!("{:?}", e.1);
        }
    }

    /// Attempts to appends `value` to the deque.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use slice_deque::SliceDeque;
    /// let mut deq = SliceDeque::new();
    /// deq.try_push_back(1).unwrap();
    /// deq.try_push_back(3).unwrap();
    /// assert_eq!(deq.back(), Some(&3));
    /// ```
    #[inline]
    pub fn try_push_back(&mut self, value: T) -> Result<(), (T, AllocError)> {
        unsafe {
            if intrinsics::unlikely(self.is_full()) {
                if let Err(e) = self.try_reserve(1) {
                    return Err((value, e));
                }
            }
            self.move_tail_unchecked(1);
            let len = self.len();
            ptr::write(self.get_mut(len - 1).unwrap(), value);
            Ok(())
        }
    }

    /// Appends `value` to the deque.
    ///
    /// # Panics
    ///
    /// On OOM.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use slice_deque::SliceDeque;
    /// let mut deq = SliceDeque::new();
    /// deq.push_back(1);
    /// deq.push_back(3);
    /// assert_eq!(deq.back(), Some(&3));
    /// ```
    #[inline]
    pub fn push_back(&mut self, value: T) {
        if let Err(e) = self.try_push_back(value) {
            panic!("{:?}", e.1);
        }
    }

    /// Removes the first element and returns it, or `None` if the deque is
    /// empty.
    ///
    /// # Examples
    ///
    /// ```
    /// # use slice_deque::SliceDeque;
    /// let mut deq = SliceDeque::new();
    /// assert_eq!(deq.pop_front(), None);
    ///
    /// deq.push_back(1);
    /// deq.push_back(2);
    ///
    /// assert_eq!(deq.pop_front(), Some(1));
    /// assert_eq!(deq.pop_front(), Some(2));
    /// assert_eq!(deq.pop_front(), None);
    /// ```
    #[inline]
    pub fn pop_front(&mut self) -> Option<T> {
        unsafe {
            let v = match self.get_mut(0) {
                None => return None,
                Some(v) => ptr::read(v),
            };
            self.move_head_unchecked(1);
            Some(v)
        }
    }

    /// Removes the last element from the deque and returns it, or `None` if it
    /// is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// # use slice_deque::SliceDeque;
    /// let mut deq = SliceDeque::new();
    /// assert_eq!(deq.pop_back(), None);
    ///
    /// deq.push_back(1);
    /// deq.push_back(3);
    ///
    /// assert_eq!(deq.pop_back(), Some(3));
    /// assert_eq!(deq.pop_back(), Some(1));
    /// assert_eq!(deq.pop_back(), None);
    /// ```
    #[inline]
    pub fn pop_back(&mut self) -> Option<T> {
        unsafe {
            let len = self.len();
            let v = match self.get_mut(len.wrapping_sub(1)) {
                None => return None,
                Some(v) => ptr::read(v),
            };
            self.move_tail_unchecked(-1);
            Some(v)
        }
    }

    /// Shrinks the capacity of the deque as much as possible.
    ///
    /// It will drop down as close as possible to the length, but because
    /// `SliceDeque` allocates memory in multiples of the page size the deque
    /// might still have capacity for inserting new elements without
    /// reallocating.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use slice_deque::SliceDeque;
    /// let mut deq = SliceDeque::with_capacity(15);
    /// deq.extend(0..4);
    /// assert!(deq.capacity() >= 15);
    /// deq.shrink_to_fit();
    /// assert!(deq.capacity() >= 4);
    /// # let o: SliceDeque<u32> = deq;
    /// ```
    #[inline]
    pub fn shrink_to_fit(&mut self) {
        if unsafe { intrinsics::unlikely(self.is_empty()) } {
            return;
        }

        // FIXME: we should compute the capacity and only allocate a shrunk
        // deque if that's worth it.
        let mut new_sdeq = Self::with_capacity(self.len());
        if new_sdeq.capacity() < self.capacity() {
            unsafe {
                crate::ptr::copy_nonoverlapping(
                    self.as_mut_ptr(),
                    new_sdeq.as_mut_ptr(),
                    self.len(),
                );
                new_sdeq.elems_ =
                    nonnull_raw_slice(new_sdeq.buf.ptr(), self.len());
                mem::swap(self, &mut new_sdeq);
            }
        }
    }

    /// Shortens the deque by removing excess elements from the back.
    ///
    /// If `len` is greater than the SliceDeque's current length, this has no
    /// effect.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # #[macro_use] extern crate slice_deque;
    /// # use slice_deque::SliceDeque;
    /// # fn main() {
    /// let mut deq = sdeq![5, 10, 15];
    /// assert_eq!(deq, [5, 10, 15]);
    /// deq.truncate_back(1);
    /// assert_eq!(deq, [5]);
    /// # }
    /// ```
    #[inline]
    pub fn truncate_back(&mut self, len: usize) {
        unsafe {
            if len >= self.len() {
                return;
            }

            let diff = self.len() - len;
            let s = &mut self[len..] as *mut [_];
            // decrement tail before the drop_in_place(), so a panic on
            // Drop doesn't re-drop the just-failed value.
            self.move_tail(-(diff as isize));
            ptr::drop_in_place(&mut *s);
            debug_assert_eq!(self.len(), len);
        }
    }

    /// Shortens the deque by removing excess elements from the back.
    ///
    /// If `len` is greater than the SliceDeque's current length, this has no
    /// effect. See `truncate_back` for examples.
    #[inline]
    pub fn truncate(&mut self, len: usize) {
        self.truncate_back(len);
    }

    /// Shortens the deque by removing excess elements from the front.
    ///
    /// If `len` is greater than the SliceDeque's current length, this has no
    /// effect.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # #[macro_use] extern crate slice_deque;
    /// # use slice_deque::SliceDeque;
    /// # fn main() {
    /// let mut deq = sdeq![5, 10, 15];
    /// assert_eq!(deq, [5, 10, 15]);
    /// deq.truncate_front(1);
    /// assert_eq!(deq, [15]);
    /// # }
    /// ```
    #[inline]
    pub fn truncate_front(&mut self, len: usize) {
        unsafe {
            if len >= self.len() {
                return;
            }

            let diff = self.len() - len;
            let s = &mut self[..diff] as *mut [_];
            // increment head before the drop_in_place(), so a panic on
            // Drop doesn't re-drop the just-failed value.
            self.move_head(diff as isize);
            ptr::drop_in_place(&mut *s);
            debug_assert_eq!(self.len(), len);
        }
    }

    /// Creates a draining iterator that removes the specified range in the
    /// deque and yields the removed items.
    ///
    /// Note 1: The element range is removed even if the iterator is only
    /// partially consumed or not consumed at all.
    ///
    /// Note 2: It is unspecified how many elements are removed from the deque
    /// if the `Drain` value is leaked.
    ///
    /// # Panics
    ///
    /// Panics if the starting point is greater than the end point or if
    /// the end point is greater than the length of the deque.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[macro_use] extern crate slice_deque;
    /// # use slice_deque::SliceDeque;
    /// # fn main() {
    /// let mut deq = sdeq![1, 2, 3];
    /// let u: Vec<_> = deq.drain(1..).collect();
    /// assert_eq!(deq, &[1]);
    /// assert_eq!(u, &[2, 3]);
    ///
    /// // A full range clears the deque
    /// deq.drain(..);
    /// assert_eq!(deq, &[]);
    /// # }
    /// ```
    #[inline]
    #[allow(clippy::needless_pass_by_value)]
    pub fn drain<R>(&mut self, range: R) -> Drain<T>
    where
        R: ops::RangeBounds<usize>,
    {
        use ops::Bound::{Excluded, Included, Unbounded};
        // Memory safety
        //
        // When the Drain is first created, it shortens the length of
        // the source deque to make sure no uninitalized or moved-from
        // elements are accessible at all if the Drain's destructor
        // never gets to run.
        //
        // Drain will ptr::read out the values to remove.
        // When finished, remaining tail of the deque is copied back to cover
        // the hole, and the deque length is restored to the new length.
        //
        let len = self.len();
        let start = match range.start_bound() {
            Included(&n) => n,
            Excluded(&n) => n + 1,
            Unbounded => 0,
        };
        let end = match range.end_bound() {
            Included(&n) => n + 1,
            Excluded(&n) => n,
            Unbounded => len,
        };
        assert!(start <= end);
        assert!(end <= len);

        unsafe {
            // set self.deq length's to start, to be safe in case Drain is
            // leaked
            self.elems_ = nonnull_raw_slice(self.as_mut_ptr(), start);
            // Use the borrow in the IterMut to indicate borrowing behavior of
            // the whole Drain iterator (like &mut T).
            let range_slice = slice::from_raw_parts_mut(
                if mem::size_of::<T>() == 0 {
                    intrinsics::arith_offset(
                        self.as_mut_ptr() as *mut i8,
                        start as _,
                    ) as *mut _
                } else {
                    self.as_mut_ptr().add(start)
                },
                end - start,
            );
            Drain {
                tail_start: end,
                tail_len: len - end,
                iter: range_slice.iter(),
                deq: NonNull::from(self),
            }
        }
    }

    /// Removes all values from the deque.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # #[macro_use] extern crate slice_deque;
    /// # use slice_deque::SliceDeque;
    /// # fn main() {
    /// let mut deq = sdeq![1];
    /// assert!(!deq.is_empty());
    /// deq.clear();
    /// assert!(deq.is_empty());
    /// # }
    /// ```
    #[inline]
    pub fn clear(&mut self) {
        self.truncate(0);
    }

    /// Removes the element at `index` and return it in `O(1)` by swapping the
    /// last element into its place.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use slice_deque::SliceDeque;
    /// let mut deq = SliceDeque::new();
    /// assert_eq!(deq.swap_remove_back(0), None);
    /// deq.extend(1..4);
    /// assert_eq!(deq, [1, 2, 3]);
    ///
    /// assert_eq!(deq.swap_remove_back(0), Some(1));
    /// assert_eq!(deq, [3, 2]);
    /// ```
    #[inline]
    pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
        let len = self.len();
        if self.is_empty() {
            None
        } else {
            self.swap(index, len - 1);
            self.pop_back()
        }
    }

    /// Removes the element at `index` and returns it in `O(1)` by swapping the
    /// first element into its place.
    ///
    /// # Examples
    ///
    /// ```
    /// # use slice_deque::SliceDeque;
    /// let mut deq = SliceDeque::new();
    /// assert_eq!(deq.swap_remove_front(0), None);
    /// deq.extend(1..4);
    /// assert_eq!(deq, [1, 2, 3]);
    ///
    /// assert_eq!(deq.swap_remove_front(2), Some(3));
    /// assert_eq!(deq, [2, 1]);
    /// ```
    #[inline]
    pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
        if self.is_empty() {
            None
        } else {
            self.swap(index, 0);
            self.pop_front()
        }
    }

    /// Inserts an `element` at `index` within the deque, shifting all elements
    /// with indices greater than or equal to `index` towards the back.
    ///
    /// Element at index 0 is the front of the queue.
    ///
    /// # Panics
    ///
    /// Panics if `index` is greater than deque's length
    ///
    /// # Examples
    ///
    /// ```
    /// # #[macro_use] extern crate slice_deque;
    /// # use slice_deque::SliceDeque;
    /// # fn main() {
    /// let mut deq = sdeq!['a', 'b', 'c'];
    /// assert_eq!(deq, &['a', 'b', 'c']);
    ///
    /// deq.insert(1, 'd');
    /// assert_eq!(deq, &['a', 'd', 'b', 'c']);
    /// # }
    /// ```
    #[inline]
    pub fn insert(&mut self, index: usize, element: T) {
        unsafe {
            let len = self.len();
            assert!(index <= len);

            if intrinsics::unlikely(self.is_full()) {
                self.reserve(1);
                // TODO: when the deque needs to grow, reserve should
                // copy the memory to the new storage leaving a whole
                // at the index where the new elements are to be inserted
                // to avoid having to copy the memory again
            }

            let p = if index > self.len() / 2 {
                let p = self.as_mut_ptr().add(index);
                // Shift elements towards the back
                ptr::copy(p, p.add(1), len - index);
                self.move_tail_unchecked(1);
                p
            } else {
                // Shift elements towards the front
                self.move_head_unchecked(-1);
                let p = self.as_mut_ptr().add(index);
                ptr::copy(p, p.sub(1), index);
                p
            };
            ptr::write(p, element); // Overwritte
        }
    }

    /// Removes and returns the element at position `index` within the deque.
    ///
    /// # Panics
    ///
    /// Panics if `index` is out of bounds.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[macro_use] extern crate slice_deque;
    /// # use slice_deque::SliceDeque;
    /// # fn main() {
    /// let mut deq = sdeq![1, 2, 3, 4, 5];
    /// assert_eq!(deq.remove(1), 2);
    /// assert_eq!(deq, [1, 3, 4, 5]);
    /// # }
    /// ```
    #[inline]
    #[allow(clippy::shadow_unrelated)] // FIXME: bug in clippy due to ptr
    pub fn remove(&mut self, index: usize) -> T {
        let len = self.len();
        assert!(index < len);
        unsafe {
            // copy element at pointer:
            let ptr = self.as_mut_ptr().add(index);
            let ret = ptr::read(ptr);
            if index > self.len() / 2 {
                // If the index is close to the back, shift elements from the
                // back towards the front
                ptr::copy(ptr.add(1), ptr, len - index - 1);
                self.move_tail_unchecked(-1);
            } else {
                // If the index is close to the front, shift elements from the
                // front towards the back
                let ptr = self.as_mut_ptr();
                ptr::copy(ptr, ptr.add(1), index);
                self.move_head_unchecked(1);
            }

            ret
        }
    }

    /// Splits the collection into two at the given index.
    ///
    /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
    /// and the returned `Self` contains elements `[at, len)`.
    ///
    /// Note that the capacity of `self` does not change.
    ///
    /// # Panics
    ///
    /// Panics if `at > len`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # #[macro_use] extern crate slice_deque;
    /// # use slice_deque::SliceDeque;
    /// # fn main() {
    /// let mut deq = sdeq![1, 2, 3];
    /// let deq2 = deq.split_off(1);
    /// assert_eq!(deq, [1]);
    /// assert_eq!(deq2, [2, 3]);
    /// # }
    /// ```
    #[inline]
    pub fn split_off(&mut self, at: usize) -> Self {
        assert!(at <= self.len(), "`at` out of bounds");

        let other_len = self.len() - at;
        let mut other = Self::with_capacity(other_len);

        unsafe {
            self.move_tail_unchecked(-(other_len as isize));
            other.move_tail_unchecked(other_len as isize);

            ptr::copy_nonoverlapping(
                self.as_ptr().add(at),
                other.as_mut_ptr(),
                other.len(),
            );
        }
        other
    }

    /// Retains only the elements specified by the predicate.
    ///
    /// That is, remove all elements `e` such that `f(&e)` returns `false`.
    /// This method operates in place and preserves the order of the
    /// retained elements.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[macro_use] extern crate slice_deque;
    /// # use slice_deque::SliceDeque;
    /// # fn main() {
    /// let mut deq = sdeq![1, 2, 3, 4];
    /// deq.retain(|&x| x % 2 == 0);
    /// assert_eq!(deq, [2, 4]);
    /// # }
    /// ```
    #[inline]
    pub fn retain<F>(&mut self, mut f: F)
    where
        F: FnMut(&T) -> bool,
    {
        let len = self.len();
        let mut del = 0;
        {
            let v = &mut **self;

            for i in 0..len {
                if !f(&v[i]) {
                    del += 1;
                } else if del > 0 {
                    v.swap(i - del, i);
                }
            }
        }
        if del > 0 {
            self.truncate(len - del);
        }
    }

    /// Removes all but the first of consecutive elements in the deque that
    /// resolve to the same key.
    ///
    /// If the deque is sorted, this removes all duplicates.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[macro_use] extern crate slice_deque;
    /// # use slice_deque::SliceDeque;
    /// # fn main() {
    /// let mut deq = sdeq![10, 20, 21, 30, 20];
    ///
    /// deq.dedup_by_key(|i| *i / 10);
    /// assert_eq!(deq, [10, 20, 30, 20]);
    /// # }
    /// ```
    #[inline]
    pub fn dedup_by_key<F, K>(&mut self, mut key: F)
    where
        F: FnMut(&mut T) -> K,
        K: PartialEq,
    {
        self.dedup_by(|a, b| key(a) == key(b))
    }

    /// Removes all but the first of consecutive elements in the deque
    /// satisfying a given equality relation.
    ///
    /// The `same_bucket` function is passed references to two elements from
    /// the deque, and returns `true` if the elements compare equal, or
    /// `false` if they do not. The elements are passed in opposite order
    /// from their order in the deque, so if `same_bucket(a, b)` returns
    /// `true`, `a` is removed.
    ///
    /// If the deque is sorted, this removes all duplicates.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[macro_use] extern crate slice_deque;
    /// # use slice_deque::SliceDeque;
    /// # fn main() {
    /// let mut deq = sdeq!["foo", "bar", "Bar", "baz", "bar"];
    ///
    /// deq.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
    ///
    /// assert_eq!(deq, ["foo", "bar", "baz", "bar"]);
    /// # }
    /// ```
    #[inline]
    pub fn dedup_by<F>(&mut self, mut same_bucket: F)
    where
        F: FnMut(&mut T, &mut T) -> bool,
    {
        unsafe {
            // Although we have a mutable reference to `self`, we cannot make
            // *arbitrary* changes. The `same_bucket` calls could panic, so we
            // must ensure that the deque is in a valid state at all time.
            //
            // The way that we handle this is by using swaps; we iterate
            // over all the elements, swapping as we go so that at the end
            // the elements we wish to keep are in the front, and those we
            // wish to reject are at the back. We can then truncate the
            // deque. This operation is still O(n).
            //
            // Example: We start in this state, where `r` represents "next
            // read" and `w` represents "next_write`.
            //
            //           r
            //     +---+---+---+---+---+---+
            //     | 0 | 1 | 1 | 2 | 3 | 3 |
            //     +---+---+---+---+---+---+
            //           w
            //
            // Comparing self[r] against self[w-1], this is not a duplicate, so
            // we swap self[r] and self[w] (no effect as r==w) and then
            // increment both r and w, leaving us with:
            //
            //               r
            //     +---+---+---+---+---+---+
            //     | 0 | 1 | 1 | 2 | 3 | 3 |
            //     +---+---+---+---+---+---+
            //               w
            //
            // Comparing self[r] against self[w-1], this value is a duplicate,
            // so we increment `r` but leave everything else unchanged:
            //
            //                   r
            //     +---+---+---+---+---+---+
            //     | 0 | 1 | 1 | 2 | 3 | 3 |
            //     +---+---+---+---+---+---+
            //               w
            //
            // Comparing self[r] against self[w-1], this is not a duplicate,
            // so swap self[r] and self[w] and advance r and w:
            //
            //                       r
            //     +---+---+---+---+---+---+
            //     | 0 | 1 | 2 | 1 | 3 | 3 |
            //     +---+---+---+---+---+---+
            //                   w
            //
            // Not a duplicate, repeat:
            //
            //                           r
            //     +---+---+---+---+---+---+
            //     | 0 | 1 | 2 | 3 | 1 | 3 |
            //     +---+---+---+---+---+---+
            //                       w
            //
            // Duplicate, advance r. End of deque. Truncate to w.

            let ln = self.len();
            if intrinsics::unlikely(ln <= 1) {
                return;
            }

            // Avoid bounds checks by using raw pointers.
            let p = self.as_mut_ptr();
            let mut r: usize = 1;
            let mut w: usize = 1;

            while r < ln {
                let p_r = p.add(r);
                let p_wm1 = p.add(w - 1);
                if !same_bucket(&mut *p_r, &mut *p_wm1) {
                    if r != w {
                        let p_w = p_wm1.add(1);
                        mem::swap(&mut *p_r, &mut *p_w);
                    }
                    w += 1;
                }
                r += 1;
            }

            self.truncate(w);
        }
    }

    /// Extend the `SliceDeque` by `n` values, using the given generator.
    #[inline]
    fn extend_with<E: ExtendWith<T>>(&mut self, n: usize, value: E) {
        self.reserve(n);

        unsafe {
            let mut ptr = self.as_mut_ptr().add(self.len());

            // Write all elements except the last one
            for _ in 1..n {
                ptr::write(ptr, value.next());
                ptr = ptr.add(1);
                // Increment the length in every step in case next() panics
                self.move_tail_unchecked(1);
            }

            if n > 0 {
                // We can write the last element directly without cloning
                // needlessly
                ptr::write(ptr, value.last());
                self.move_tail_unchecked(1);
            }

            // len set by scope guard
        }
    }

    /// Extend for a general iterator.
    ///
    /// This function should be the moral equivalent of:
    ///
    /// >  for item in iterator {
    /// >      self.push_back(item);
    /// >  }
    #[inline]
    fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
        #[allow(clippy::while_let_on_iterator)]
        while let Some(element) = iterator.next() {
            let len = self.len();
            let cap = self.capacity();
            if len == cap {
                let (lower, upper) = iterator.size_hint();
                let additional_cap = if let Some(upper) = upper {
                    upper
                } else {
                    lower
                }
                .checked_add(1)
                .expect("overflow");
                self.reserve(additional_cap);
            }
            debug_assert!(self.len() < self.capacity());
            unsafe {
                ptr::write(self.get_unchecked_mut(len), element);
                // NB can't overflow since we would have had to alloc the
                // address space
                self.move_tail_unchecked(1);
            }
        }
    }

    /// Creates a splicing iterator that replaces the specified range in the
    /// deque with the given `replace_with` iterator and yields the
    /// removed items. `replace_with` does not need to be the same length
    /// as `range`.
    ///
    /// Note 1: The element range is removed even if the iterator is not
    /// consumed until the end.
    ///
    /// Note 2: It is unspecified how many elements are removed from the deque,
    /// if the `Splice` value is leaked.
    ///
    /// Note 3: The input iterator `replace_with` is only consumed
    /// when the `Splice` value is dropped.
    ///
    /// Note 4: This is optimal if:
    ///
    /// * The tail (elements in the deque after `range`) is empty,
    /// * or `replace_with` yields fewer elements than `range`’s length
    /// * or the lower bound of its `size_hint()` is exact.
    ///
    /// Otherwise, a temporary deque is allocated and the tail is moved twice.
    ///
    /// # Panics
    ///
    /// Panics if the starting point is greater than the end point or if
    /// the end point is greater than the length of the deque.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[macro_use] extern crate slice_deque;
    /// # use slice_deque::SliceDeque;
    /// # fn main() {
    /// let mut deq = sdeq![1, 2, 3];
    /// let new = [7, 8];
    /// let u: SliceDeque<_> = deq.splice(..2, new.iter().cloned()).collect();
    /// assert_eq!(deq, &[7, 8, 3]);
    /// assert_eq!(u, &[1, 2]);
    /// # }
    /// ```
    #[inline]
    pub fn splice<R, I>(
        &mut self, range: R, replace_with: I,
    ) -> Splice<I::IntoIter>
    where
        R: ops::RangeBounds<usize>,
        I: IntoIterator<Item = T>,
    {
        Splice {
            drain: self.drain(range),
            replace_with: replace_with.into_iter(),
        }
    }

    /// Creates an iterator which uses a closure to determine if an element
    /// should be removed.
    ///
    /// If the closure returns `true`, then the element is removed and yielded.
    /// If the closure returns `false`, it will try again, and call the closure
    /// on the next element, seeing if it passes the test.
    ///
    /// Using this method is equivalent to the following code:
    ///
    /// ```
    /// # #[macro_use] extern crate slice_deque;
    /// # use slice_deque::SliceDeque;
    /// # fn main() {
    /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6
    /// # };
    /// let mut deq = SliceDeque::new();
    /// deq.extend(1..7);
    /// let mut i = 0;
    /// while i != deq.len() {
    ///     if some_predicate(&mut deq[i]) {
    ///         let val = deq.remove(i);
    ///     // your code here
    ///     } else {
    ///         i += 1;
    ///     }
    /// }
    /// # let mut expected = sdeq![1, 4, 5];
    /// # assert_eq!(deq, expected);
    /// # }
    /// ```
    ///
    /// But `drain_filter` is easier to use. `drain_filter` is also more
    /// efficient, because it can backshift the elements of the deque in
    /// bulk.
    ///
    /// Note that `drain_filter` also lets you mutate every element in the
    /// filter closure, regardless of whether you choose to keep or remove
    /// it.
    ///
    ///
    /// # Examples
    ///
    /// Splitting a deque into evens and odds, reusing the original allocation:
    ///
    /// ```
    /// # #[macro_use] extern crate slice_deque;
    /// # use slice_deque::SliceDeque;
    /// # fn main() {
    /// let mut numbers = sdeq![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
    ///
    /// let evens = numbers
    ///     .drain_filter(|x| *x % 2 == 0)
    ///     .collect::<SliceDeque<_>>();
    /// let odds = numbers;
    ///
    /// assert_eq!(sdeq![2, 4, 6, 8, 14], evens);
    /// assert_eq!(odds, sdeq![1, 3, 5, 9, 11, 13, 15]);
    /// # }
    /// ```
    #[inline]
    pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<T, F>
    where
        F: FnMut(&mut T) -> bool,
    {
        let old_len = self.len();

        // Guard against us getting leaked (leak amplification)
        unsafe {
            self.move_tail_unchecked(-(old_len as isize));
        }

        DrainFilter {
            deq: self,
            idx: 0,
            del: 0,
            old_len,
            pred: filter,
        }
    }
}

impl<T> SliceDeque<T>
where
    T: Clone,
{
    /// Clones and appends all elements in a slice to the `SliceDeque`.
    ///
    /// Iterates over the slice `other`, clones each element, and then appends
    /// it to this `SliceDeque`. The `other` slice is traversed in-order.
    ///
    /// Note that this function is same as `extend` except that it is
    /// specialized to work with slices instead. If and when Rust gets
    /// specialization this function will likely be deprecated (but still
    /// available).
    ///
    /// # Examples
    ///
    /// ```
    /// # use slice_deque::SliceDeque;
    /// let mut deq = SliceDeque::new();
    /// deq.push_back(1);
    /// deq.extend_from_slice(&[2, 3, 4]);
    /// assert_eq!(deq, [1, 2, 3, 4]);
    /// ```
    #[inline]
    pub fn extend_from_slice(&mut self, other: &[T]) {
        #[cfg(feature = "unstable")]
        {
            self.spec_extend(other.iter())
        }
        #[cfg(not(feature = "unstable"))]
        {
            self.reserve(other.len());
            unsafe {
                let len = self.len();
                self.move_tail_unchecked(other.len() as isize);
                self.get_unchecked_mut(len..).clone_from_slice(other);
            }
        }
    }

    /// Modifies the `SliceDeque` in-place so that `len()` is equal to
    /// `new_len`, either by removing excess elements or by appending clones of
    /// `value` to the back.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[macro_use] extern crate slice_deque;
    /// # use slice_deque::SliceDeque;
    /// # fn main() {
    /// let mut deq = sdeq![5, 10, 15];
    /// assert_eq!(deq, [5, 10, 15]);
    ///
    /// deq.resize(2, 0);
    /// assert_eq!(deq, [5, 10]);
    ///
    /// deq.resize(5, 20);
    /// assert_eq!(deq, [5, 10, 20, 20, 20]);
    /// # }
    /// ```
    #[inline]
    pub fn resize(&mut self, new_len: usize, value: T) {
        let len = self.len();

        if new_len > len {
            self.reserve(new_len - len);
            while self.len() < new_len {
                self.push_back(value.clone());
            }
        } else {
            self.truncate(new_len);
        }
        debug_assert!(self.len() == new_len);
    }
}

impl<T: Default> SliceDeque<T> {
    /// Resizes the `SliceDeque` in-place so that `len` is equal to `new_len`.
    ///
    /// If `new_len` is greater than `len`, the `SliceDeque` is extended by the
    /// difference, with each additional slot filled with `Default::default()`.
    /// If `new_len` is less than `len`, the `SliceDeque` is simply truncated.
    ///
    /// This method uses `Default` to create new values on every push. If
    /// you'd rather `Clone` a given value, use [`resize`].
    ///
    ///
    /// # Examples
    ///
    /// ```
    /// # #[macro_use] extern crate slice_deque;
    /// # use slice_deque::SliceDeque;
    /// # fn main() {
    /// let mut deq = sdeq![1, 2, 3];
    /// deq.resize_default(5);
    /// assert_eq!(deq, [1, 2, 3, 0, 0]);
    ///
    /// deq.resize_default(2);
    /// assert_eq!(deq, [1, 2]);
    /// # }
    /// ```
    ///
    /// [`resize`]: #method.resize
    #[inline]
    pub fn resize_default(&mut self, new_len: usize) {
        let len = self.len();

        if new_len > len {
            self.extend_with(new_len - len, ExtendDefault);
        } else {
            self.truncate(new_len);
        }
    }
}

impl<T: PartialEq> SliceDeque<T> {
    /// Removes consecutive repeated elements in the deque.
    ///
    /// If the deque is sorted, this removes all duplicates.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[macro_use] extern crate slice_deque;
    /// # use slice_deque::SliceDeque;
    /// # fn main() {
    /// let mut deq = sdeq![1, 2, 2, 3, 2];
    ///
    /// deq.dedup();
    /// assert_eq!(deq, [1, 2, 3, 2]);
    ///
    /// deq.sort();
    /// assert_eq!(deq, [1, 2, 2, 3]);
    ///
    /// deq.dedup();
    /// assert_eq!(deq, [1, 2, 3]);
    /// # }
    /// ```
    #[inline]
    pub fn dedup(&mut self) {
        self.dedup_by(|a, b| a == b)
    }

    /// Removes the first instance of `item` from the deque if the item exists.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[macro_use] extern crate slice_deque;
    /// # use slice_deque::SliceDeque;
    /// # fn main() {
    /// let mut deq = sdeq![1, 2, 3, 1];
    ///
    /// deq.remove_item(&1);
    /// assert_eq!(deq, &[2, 3, 1]);
    /// deq.remove_item(&1);
    /// assert_eq!(deq, &[2, 3]);
    /// # }
    /// ```
    #[inline]
    pub fn remove_item(&mut self, item: &T) -> Option<T> {
        let pos = match self.iter().position(|x| *x == *item) {
            Some(x) => x,
            None => return None,
        };
        Some(self.remove(pos))
    }
}

impl<T: fmt::Debug> fmt::Debug for SliceDeque<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        write!(f, "{:?}", self.as_slice())
        /*
         write!(
             f,
             // TODO: "SliceDeque({:?})",
             "SliceDeque(len: {}, cap: {}, head: {}, tail: {}, elems: {:?})",
             self.len(),
             self.capacity(),
             self.head(),
             self.tail(),
             self.as_slice()
         )
        */
    }
}

impl<T> Drop for SliceDeque<T> {
    #[inline]
    fn drop(&mut self) {
        // In Rust, if Drop::drop panics, the value must be leaked,
        // therefore we don't need to make sure that we handle that case
        // here:
        unsafe {
            // use drop for [T]
            ptr::drop_in_place(&mut self[..]);
        }
        // Buffer handles deallocation
    }
}

impl<T> ops::Deref for SliceDeque<T> {
    type Target = [T];
    #[inline]
    fn deref(&self) -> &Self::Target {
        self.as_slice()
    }
}

impl<T> ops::DerefMut for SliceDeque<T> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.as_mut_slice()
    }
}

impl<T> Default for SliceDeque<T> {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl<T: Clone> Clone for SliceDeque<T> {
    #[inline]
    fn clone(&self) -> Self {
        let mut new = Self::with_capacity(self.len());
        for i in self.iter() {
            new.push_back(i.clone());
        }
        new
    }
    #[inline]
    fn clone_from(&mut self, other: &Self) {
        self.clear();
        for i in other.iter() {
            self.push_back(i.clone());
        }
    }
}

impl<'a, T: Clone> From<&'a [T]> for SliceDeque<T> {
    #[inline]
    fn from(s: &'a [T]) -> Self {
        let mut new = Self::with_capacity(s.len());
        for i in s {
            new.push_back(i.clone());
        }
        new
    }
}

impl<'a, T: Clone> From<&'a mut [T]> for SliceDeque<T> {
    #[inline]
    fn from(s: &'a mut [T]) -> Self {
        let mut new = Self::with_capacity(s.len());
        for i in s {
            new.push_back(i.clone());
        }
        new
    }
}

impl<T: hash::Hash> hash::Hash for SliceDeque<T> {
    #[inline]
    fn hash<H: hash::Hasher>(&self, state: &mut H) {
        hash::Hash::hash(&**self, state)
    }
}

///////////////////////////////////////////////////////////////////////////////
// PartialEq implementations:

macro_rules! __impl_slice_eq1 {
    ($Lhs:ty, $Rhs:ty) => {
        __impl_slice_eq1! { $Lhs, $Rhs, Sized }
    };
    ($Lhs:ty, $Rhs:ty, $Bound:ident) => {
        impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs
        where
            A: PartialEq<B>,
        {
            #[inline]
            fn eq(&self, other: &$Rhs) -> bool {
                self[..] == other[..]
            }
        }
    };
}

__impl_slice_eq1! { SliceDeque<A>, SliceDeque<B> }
__impl_slice_eq1! { SliceDeque<A>, &'b [B] }
__impl_slice_eq1! { SliceDeque<A>, &'b mut [B] }

#[cfg(feature = "use_std")]
__impl_slice_eq1! { SliceDeque<A>, Vec<B> }

macro_rules! array_impls {
    ($($N: expr)+) => {
        $(
            // NOTE: some less important impls are omitted to reduce code bloat
            __impl_slice_eq1! { SliceDeque<A>, [B; $N] }
            __impl_slice_eq1! { SliceDeque<A>, &'b [B; $N] }
        )+
    }
}

array_impls! {
    0  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
}

///////////////////////////////////////////////////////////////////////////////

impl<T: Eq> Eq for SliceDeque<T> {}

impl<T: PartialOrd> PartialOrd for SliceDeque<T> {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
        PartialOrd::partial_cmp(&**self, &**other)
    }
}

impl<'a, T: PartialOrd> PartialOrd<&'a [T]> for SliceDeque<T> {
    #[inline]
    fn partial_cmp(&self, other: &&'a [T]) -> Option<cmp::Ordering> {
        PartialOrd::partial_cmp(&**self, other)
    }
}

/// A draining iterator for `SliceDeque<T>`.
///
/// This `struct` is created by the [`drain`] method on [`SliceDeque`].
///
/// [`drain`]: struct.SliceDeque.html#method.drain
/// [`SliceDeque`]: struct.SliceDeque.html
pub struct Drain<'a, T: 'a> {
    /// Index of tail to preserve
    tail_start: usize,
    /// Length of tail
    tail_len: usize,
    /// Current remaining range to remove
    iter: slice::Iter<'a, T>,
    /// A shared mutable pointer to the deque (with shared ownership).
    deq: NonNull<SliceDeque<T>>,
}

impl<'a, T: 'a + fmt::Debug> fmt::Debug for Drain<'a, T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
    }
}

unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
unsafe impl<'a, T: Send> Send for Drain<'a, T> {}

impl<'a, T> Iterator for Drain<'a, T> {
    type Item = T;

    #[inline]
    fn next(&mut self) -> Option<T> {
        self.iter
            .next()
            .map(|elt| unsafe { ptr::read(elt as *const _) })
    }
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}

impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
    #[inline]
    fn next_back(&mut self) -> Option<T> {
        self.iter
            .next_back()
            .map(|elt| unsafe { ptr::read(elt as *const _) })
    }
}

impl<'a, T> Drop for Drain<'a, T> {
    #[inline]
    fn drop(&mut self) {
        // exhaust self first
        self.for_each(|_| {});

        if self.tail_len > 0 {
            unsafe {
                let source_deq = self.deq.as_mut();
                // memmove back untouched tail, update to new length
                let start = source_deq.len();
                let tail = self.tail_start;
                let src = source_deq.as_ptr().add(tail);
                let dst = source_deq.as_mut_ptr().add(start);
                ptr::copy(src, dst, self.tail_len);
                source_deq.move_tail_unchecked(self.tail_len as isize);
            }
        }
    }
}

#[cfg(feature = "unstable")]
impl<'a, T> ExactSizeIterator for Drain<'a, T> {
    #[inline]
    fn is_empty(&self) -> bool {
        self.iter.is_empty()
    }
}

#[cfg(feature = "unstable")]
impl<'a, T> iter::FusedIterator for Drain<'a, T> {}

/// An iterator that moves out of a deque.
///
/// This `struct` is created by the `into_iter` method on
/// [`SliceDeque`][`SliceDeque`] (provided by the [`IntoIterator`] trait).
///
/// [`SliceDeque`]: struct.SliceDeque.html
/// [`IntoIterator`]: ../../std/iter/trait.IntoIterator.html
pub struct IntoIter<T> {
    /// NonNull pointer to the buffer
    buf: NonNull<T>,
    /// Capacity of the buffer.
    cap: usize,
    /// Pointer to the first element.
    ptr: *const T,
    /// Pointer to one-past-the-end.
    end: *const T,
}

impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
    }
}

impl<T> IntoIter<T> {
    /// Returns the element slice
    #[cfg(feature = "unstable")]
    #[allow(clippy::option_unwrap_used)]
    #[inline]
    fn elems(&mut self) -> &mut [T] {
        unsafe {
            slice::from_raw_parts_mut(
                self.ptr as *mut _,
                (self.end as usize - self.ptr as usize) / mem::size_of::<T>(),
            )
        }
    }

    /// Returns the remaining items of this iterator as a slice.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[macro_use] extern crate slice_deque;
    /// # use slice_deque::SliceDeque;
    /// # fn main() {
    /// let mut deq = sdeq!['a', 'b', 'c'];
    /// let mut into_iter = deq.into_iter();
    /// assert_eq!(into_iter.as_slice(), ['a', 'b', 'c']);
    /// let _ = into_iter.next().unwrap();
    /// assert_eq!(into_iter.as_slice(), ['b', 'c']);
    /// # }
    /// ```
    #[inline]
    pub fn as_slice(&self) -> &[T] {
        unsafe { slice::from_raw_parts(self.ptr, self.size_hint().0) }
    }

    /// Returns the remaining items of this iterator as a mutable slice.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[macro_use] extern crate slice_deque;
    /// # use slice_deque::SliceDeque;
    /// # fn main() {
    /// let mut deq = sdeq!['a', 'b', 'c'];
    /// let mut into_iter = deq.into_iter();
    /// assert_eq!(into_iter.as_slice(), ['a', 'b', 'c']);
    /// into_iter.as_mut_slice()[2] = 'z';
    /// assert_eq!(into_iter.next().unwrap(), 'a');
    /// assert_eq!(into_iter.next().unwrap(), 'b');
    /// assert_eq!(into_iter.next().unwrap(), 'z');
    /// # }
    /// ```
    #[inline]
    pub fn as_mut_slice(&mut self) -> &mut [T] {
        unsafe {
            slice::from_raw_parts_mut(self.ptr as *mut T, self.size_hint().0)
        }
    }
}

unsafe impl<T: Send> Send for IntoIter<T> {}
unsafe impl<T: Sync> Sync for IntoIter<T> {}

impl<T> Iterator for IntoIter<T> {
    type Item = T;

    #[inline]
    fn next(&mut self) -> Option<T> {
        unsafe {
            if self.ptr as *const _ == self.end {
                None
            } else if mem::size_of::<T>() == 0 {
                // purposefully don't use 'ptr.offset' because for
                // deques with 0-size elements this would return the
                // same pointer.
                self.ptr = intrinsics::arith_offset(self.ptr as *const i8, 1)
                    as *mut T;

                // Use a non-null pointer value
                // (self.ptr might be null because of wrapping)
                Some(ptr::read(1 as *mut T))
            } else {
                let old = self.ptr;
                self.ptr = self.ptr.add(1);

                Some(ptr::read(old))
            }
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let exact = match self.ptr.wrapping_offset_from_(self.end) {
            Some(x) => x as usize,
            None => (self.end as usize).wrapping_sub(self.ptr as usize),
        };
        (exact, Some(exact))
    }

    #[inline]
    fn count(self) -> usize {
        self.size_hint().0
    }
}

impl<T> DoubleEndedIterator for IntoIter<T> {
    #[inline]
    fn next_back(&mut self) -> Option<T> {
        unsafe {
            if self.end == self.ptr {
                None
            } else if mem::size_of::<T>() == 0 {
                // See above for why 'ptr.offset' isn't used
                self.end = intrinsics::arith_offset(self.end as *const i8, -1)
                    as *mut T;

                // Use a non-null pointer value
                // (self.end might be null because of wrapping)
                Some(ptr::read(1 as *mut T))
            } else {
                self.end = self.end.offset(-1);

                Some(ptr::read(self.end))
            }
        }
    }
}

#[cfg(feature = "unstable")]
impl<T> ExactSizeIterator for IntoIter<T> {
    #[inline]
    fn is_empty(&self) -> bool {
        self.ptr == self.end
    }
}

#[cfg(feature = "unstable")]
impl<T> iter::FusedIterator for IntoIter<T> {}

#[cfg(feature = "unstable")]
unsafe impl<T> iter::TrustedLen for IntoIter<T> {}

impl<T: Clone> Clone for IntoIter<T> {
    #[inline]
    fn clone(&self) -> Self {
        let mut deq = SliceDeque::<T>::with_capacity(self.size_hint().0);
        unsafe {
            deq.append_elements(self.as_slice());
        }
        deq.into_iter()
    }
}

#[cfg(feature = "unstable")]
unsafe impl<#[may_dangle] T> Drop for IntoIter<T> {
    #[inline]
    fn drop(&mut self) {
        // destroy the remaining elements
        for _x in self.by_ref() {}

        // Buffer handles deallocation
        let _ =
            unsafe { Buffer::from_raw_parts(self.buf.as_ptr(), 2 * self.cap) };
    }
}

#[cfg(not(feature = "unstable"))]
impl<T> Drop for IntoIter<T> {
    #[inline]
    fn drop(&mut self) {
        // destroy the remaining elements
        for _x in self.by_ref() {}

        // Buffer handles deallocation
        let _ =
            unsafe { Buffer::from_raw_parts(self.buf.as_ptr(), 2 * self.cap) };
    }
}

impl<T> IntoIterator for SliceDeque<T> {
    type Item = T;
    type IntoIter = IntoIter<T>;

    /// Creates a consuming iterator, that is, one that moves each value out of
    /// the deque (from start to end). The deque cannot be used after calling
    /// this.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[macro_use] extern crate slice_deque;
    /// # use slice_deque::SliceDeque;
    /// # fn main() {
    /// let mut deq = sdeq!["a".to_string(), "b".to_string()];
    /// let expected = ["a".to_string(), "b".to_string()];
    /// for (i, s) in deq.into_iter().enumerate() {
    ///     // s has type String, not &String
    ///     println!("{}", s);
    ///     assert_eq!(s, expected[i]);
    /// }
    /// # }
    /// ```
    #[inline]
    fn into_iter(self) -> IntoIter<T> {
        unsafe {
            let buf_ptr = self.buf.ptr();
            intrinsics::assume(!buf_ptr.is_null());
            let begin = self.as_ptr();
            let end = if mem::size_of::<T>() == 0 {
                intrinsics::arith_offset(begin as *const i8, self.len() as _)
                    as *const _
            } else {
                begin.add(self.len())
            };
            assert!(begin as usize <= end as usize);
            let it = IntoIter {
                buf: NonNull::new_unchecked(buf_ptr),
                cap: self.capacity(),
                ptr: begin,
                end,
            };
            debug_assert_eq!(self.len(), it.size_hint().0);
            #[allow(clippy::mem_forget)]
            mem::forget(self);
            it
        }
    }
}

impl<'a, T> IntoIterator for &'a SliceDeque<T> {
    type Item = &'a T;
    type IntoIter = slice::Iter<'a, T>;
    #[inline]
    fn into_iter(self) -> slice::Iter<'a, T> {
        self.iter()
    }
}

impl<'a, T> IntoIterator for &'a mut SliceDeque<T> {
    type Item = &'a mut T;
    type IntoIter = slice::IterMut<'a, T>;
    #[inline]
    fn into_iter(self) -> slice::IterMut<'a, T> {
        self.iter_mut()
    }
}

impl<T> Extend<T> for SliceDeque<T> {
    #[inline]
    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
        <Self as SpecExtend<T, I::IntoIter>>::spec_extend(
            self,
            iter.into_iter(),
        )
    }
}

/// Specialization trait used for `SliceDeque::from_iter` and
/// `SliceDeque::extend`.
trait SpecExtend<T, I> {
    /// Specialization for `SliceDeque::from_iter`.
    fn from_iter(iter: I) -> Self;
    /// Specialization for `SliceDeque::extend`.
    fn spec_extend(&mut self, iter: I);
}

/// Default implementation of `SpecExtend::from_iter`.
#[inline(always)]
fn from_iter_default<T, I: Iterator<Item = T>>(
    mut iterator: I,
) -> SliceDeque<T> {
    // Unroll the first iteration, as the deque is going to be
    // expanded on this iteration in every case when the iterable is not
    // empty, but the loop in extend_desugared() is not going to see the
    // deque being full in the few subsequent loop iterations.
    // So we get better branch prediction.
    let mut deque = match iterator.next() {
        None => return SliceDeque::<T>::new(),
        Some(element) => {
            let (lower, _) = iterator.size_hint();
            let mut deque =
                SliceDeque::<T>::with_capacity(lower.saturating_add(1));
            unsafe {
                ptr::write(deque.get_unchecked_mut(0), element);
                deque.move_tail_unchecked(1);
            }
            deque
        }
    };
    <SliceDeque<T> as SpecExtend<T, I>>::spec_extend(&mut deque, iterator);
    deque
}

impl<T, I> SpecExtend<T, I> for SliceDeque<T>
where
    I: Iterator<Item = T>,
{
    #[cfg(feature = "unstable")]
    default fn from_iter(iterator: I) -> Self {
        from_iter_default(iterator)
    }

    #[cfg(feature = "unstable")]
    default fn spec_extend(&mut self, iter: I) {
        self.extend_desugared(iter)
    }

    #[cfg(not(feature = "unstable"))]
    fn from_iter(iterator: I) -> Self {
        from_iter_default(iterator)
    }

    #[cfg(not(feature = "unstable"))]
    fn spec_extend(&mut self, iter: I) {
        self.extend_desugared(iter)
    }
}

#[cfg(feature = "unstable")]
impl<T, I> SpecExtend<T, I> for SliceDeque<T>
where
    I: iter::TrustedLen<Item = T>,
{
    default fn from_iter(iterator: I) -> Self {
        let mut deque = Self::new();
        <Self as SpecExtend<T, I>>::spec_extend(&mut deque, iterator);
        deque
    }

    #[allow(clippy::use_debug)]
    default fn spec_extend(&mut self, iterator: I) {
        // This is the case for a TrustedLen iterator.
        let (low, high) = iterator.size_hint();
        if let Some(high_value) = high {
            debug_assert_eq!(
                low,
                high_value,
                "TrustedLen iterator's size hint is not exact: {:?}",
                (low, high)
            );
        }
        if let Some(additional) = high {
            self.reserve(additional);
            unsafe {
                let mut ptr = self.as_mut_ptr().add(self.len());
                for element in iterator {
                    ptr::write(ptr, element);
                    ptr = ptr.add(1);
                    // NB can't overflow since we would have had to alloc the
                    // address space
                    self.move_tail_unchecked(1);
                }
            }
        } else {
            self.extend_desugared(iterator)
        }
    }
}

#[cfg(feature = "unstable")]
impl<T> SpecExtend<T, IntoIter<T>> for SliceDeque<T> {
    fn from_iter(mut iterator: IntoIter<T>) -> Self {
        // A common case is passing a deque into a function which immediately
        // re-collects into a deque. We can short circuit this if the IntoIter
        // has not been advanced at all.
        if iterator.buf.as_ptr() as *const _ == iterator.ptr {
            unsafe {
                let deq = Self::from_raw_parts(
                    iterator.buf.as_ptr(),
                    iterator.cap,
                    iterator.elems(),
                );
                #[allow(clippy::mem_forget)]
                mem::forget(iterator);
                deq
            }
        } else {
            let mut deque = Self::new();
            deque.spec_extend(iterator);
            deque
        }
    }

    fn spec_extend(&mut self, mut iterator: IntoIter<T>) {
        unsafe {
            self.append_elements(iterator.as_slice() as _);
        }
        iterator.ptr = iterator.end;
    }
}

#[cfg(not(feature = "unstable"))]
impl<'a, T: 'a, I> SpecExtend<&'a T, I> for SliceDeque<T>
where
    I: Iterator<Item = &'a T>,
    T: Clone,
{
    fn from_iter(iterator: I) -> Self {
        SpecExtend::from_iter(iterator.cloned())
    }

    fn spec_extend(&mut self, iterator: I) {
        self.spec_extend(iterator.cloned())
    }
}

#[cfg(feature = "unstable")]
impl<'a, T: 'a, I> SpecExtend<&'a T, I> for SliceDeque<T>
where
    I: Iterator<Item = &'a T>,
    T: Clone,
{
    default fn from_iter(iterator: I) -> Self {
        SpecExtend::from_iter(iterator.cloned())
    }

    default fn spec_extend(&mut self, iterator: I) {
        self.spec_extend(iterator.cloned())
    }
}

#[cfg(feature = "unstable")]
impl<'a, T: 'a> SpecExtend<&'a T, slice::Iter<'a, T>> for SliceDeque<T>
where
    T: Copy,
{
    fn spec_extend(&mut self, iterator: slice::Iter<'a, T>) {
        let slice = iterator.as_slice();
        self.reserve(slice.len());
        unsafe {
            let len = self.len();
            self.move_tail_unchecked(slice.len() as isize);
            self.get_unchecked_mut(len..).copy_from_slice(slice);
        }
    }
}

impl<T> iter::FromIterator<T> for SliceDeque<T> {
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        <Self as SpecExtend<T, I::IntoIter>>::from_iter(iter.into_iter())
    }
}

/// This code generalises `extend_with_{element,default}`.
trait ExtendWith<T> {
    /// TODO: docs
    fn next(&self) -> T;
    /// TODO: docs
    fn last(self) -> T;
}

/// TODO: docs
struct ExtendElement<T>(T);
impl<T: Clone> ExtendWith<T> for ExtendElement<T> {
    fn next(&self) -> T {
        self.0.clone()
    }
    fn last(self) -> T {
        self.0
    }
}

/// TODO: docs
struct ExtendDefault;
impl<T: Default> ExtendWith<T> for ExtendDefault {
    fn next(&self) -> T {
        Default::default()
    }
    fn last(self) -> T {
        Default::default()
    }
}

/// TODO: docs
/// FIXME: not used, this should be used by the sdeq! macro? Remove this maybe.
#[doc(hidden)]
pub fn from_elem<T: Clone>(elem: T, n: usize) -> SliceDeque<T> {
    <T as SpecFromElem>::from_elem(elem, n)
}

/// Specialization trait used for `SliceDeque::from_elem`.
trait SpecFromElem: Sized {
    /// TODO: docs
    fn from_elem(elem: Self, n: usize) -> SliceDeque<Self>;
}

impl<T: Clone> SpecFromElem for T {
    #[cfg(feature = "unstable")]
    default fn from_elem(elem: Self, n: usize) -> SliceDeque<Self> {
        let mut v = SliceDeque::with_capacity(n);
        v.extend_with(n, ExtendElement(elem));
        v
    }

    #[cfg(not(feature = "unstable"))]
    fn from_elem(elem: Self, n: usize) -> SliceDeque<Self> {
        let mut v = SliceDeque::with_capacity(n);
        v.extend_with(n, ExtendElement(elem));
        v
    }
}

#[cfg(feature = "unstable")]
impl SpecFromElem for u8 {
    #[inline]
    fn from_elem(elem: Self, n: usize) -> SliceDeque<Self> {
        unsafe {
            let mut v = SliceDeque::with_capacity(n);
            ptr::write_bytes(v.as_mut_ptr(), elem, n);
            v.move_tail_unchecked(n as isize);
            v
        }
    }
}

macro_rules! impl_spec_from_elem {
    ($t:ty, $is_zero:expr) => {
        #[cfg(feature = "unstable")]
        impl SpecFromElem for $t {
            #[inline]
            fn from_elem(elem: Self, n: usize) -> SliceDeque<Self> {
                let mut v = SliceDeque::with_capacity(n);
                v.extend_with(n, ExtendElement(elem));
                v
            }
        }
    };
}

impl_spec_from_elem!(i8, |x| x == 0);
impl_spec_from_elem!(i16, |x| x == 0);
impl_spec_from_elem!(i32, |x| x == 0);
impl_spec_from_elem!(i64, |x| x == 0);
#[cfg(feature = "unstable")]
impl_spec_from_elem!(i128, |x| x == 0);
impl_spec_from_elem!(isize, |x| x == 0);

impl_spec_from_elem!(u16, |x| x == 0);
impl_spec_from_elem!(u32, |x| x == 0);
impl_spec_from_elem!(u64, |x| x == 0);
#[cfg(feature = "unstable")]
impl_spec_from_elem!(u128, |x| x == 0);
impl_spec_from_elem!(usize, |x| x == 0);

impl_spec_from_elem!(f32, |x: f32| x == 0. && x.is_sign_positive());
impl_spec_from_elem!(f64, |x: f64| x == 0. && x.is_sign_positive());

/// Extend implementation that copies elements out of references before
/// pushing them onto the `SliceDeque`.
///
/// This implementation is specialized for slice iterators, where it uses
/// [`copy_from_slice`] to append the entire slice at once.
///
/// [`copy_from_slice`]: ../../std/primitive.slice.html#method.copy_from_slice
impl<'a, T: 'a + Copy> Extend<&'a T> for SliceDeque<T> {
    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
        self.spec_extend(iter.into_iter())
    }
}

/// A splicing iterator for `SliceDeque`.
///
/// This struct is created by the [`splice()`] method on [`SliceDeque`]. See
/// its documentation for more.
///
/// [`splice()`]: struct.SliceDeque.html#method.splice
/// [`SliceDeque`]: struct.SliceDeque.html
#[derive(Debug)]
pub struct Splice<'a, I: Iterator + 'a> {
    /// TODO: docs
    drain: Drain<'a, I::Item>,
    /// TODO: docs
    replace_with: I,
}

impl<'a, I: Iterator> Iterator for Splice<'a, I> {
    type Item = I::Item;
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.drain.next()
    }
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.drain.size_hint()
    }
}

impl<'a, I: Iterator> DoubleEndedIterator for Splice<'a, I> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        self.drain.next_back()
    }
}

#[cfg(feature = "unstable")]
impl<'a, I: Iterator> ExactSizeIterator for Splice<'a, I> {}

// TODO: re-evaluate this
#[cfg(feature = "unstable")]
impl<'a, I: Iterator> iter::FusedIterator for Splice<'a, I> {}

impl<'a, I: Iterator> Drop for Splice<'a, I> {
    fn drop(&mut self) {
        // exhaust drain first
        while let Some(_) = self.drain.next() {}

        unsafe {
            if self.drain.tail_len == 0 {
                self.drain.deq.as_mut().extend(self.replace_with.by_ref());
                return;
            }

            // First fill the range left by drain().
            if !self.drain.fill(&mut self.replace_with) {
                return;
            }

            // There may be more elements. Use the lower bound as an estimate.
            // FIXME: Is the upper bound a better guess? Or something else?
            let (lower_bound, _upper_bound) = self.replace_with.size_hint();
            if lower_bound > 0 {
                self.drain.move_tail_unchecked(lower_bound);
                if !self.drain.fill(&mut self.replace_with) {
                    return;
                }
            }

            // Collect any remaining elements.
            // This is a zero-length deque which does not allocate if
            // `lower_bound` was exact.
            let mut collected = self
                .replace_with
                .by_ref()
                .collect::<SliceDeque<I::Item>>()
                .into_iter();
            // Now we have an exact count.
            if collected.size_hint().0 > 0 {
                self.drain.move_tail_unchecked(collected.size_hint().0);
                let filled = self.drain.fill(&mut collected);
                debug_assert!(filled);
                debug_assert_eq!(collected.size_hint().0, 0);
            }
        }
        // Let `Drain::drop` move the tail back if necessary and restore
        // `deq.tail`.
    }
}

/// Private helper methods for `Splice::drop`
impl<'a, T> Drain<'a, T> {
    /// The range from `self.deq.tail` to `self.tail()_start` contains elements
    /// that have been moved out.
    /// Fill that range as much as possible with new elements from the
    /// `replace_with` iterator. Return whether we filled the entire
    /// range. (`replace_with.next()` didn’t return `None`.)
    unsafe fn fill<I: Iterator<Item = T>>(
        &mut self, replace_with: &mut I,
    ) -> bool {
        let deq = self.deq.as_mut();
        let range_start = deq.len();
        let range_end = self.tail_start;
        let range_slice = slice::from_raw_parts_mut(
            deq.as_mut_ptr().add(range_start),
            range_end - range_start,
        );

        for place in range_slice {
            if let Some(new_item) = replace_with.next() {
                ptr::write(place, new_item);
                deq.move_tail_unchecked(1);
            } else {
                return false;
            }
        }
        true
    }

    /// Make room for inserting more elements before the tail.
    unsafe fn move_tail_unchecked(&mut self, extra_capacity: usize) {
        let deq = self.deq.as_mut();
        let used_capacity = self.tail_start + self.tail_len;
        deq.reserve_capacity(used_capacity + extra_capacity)
            .expect("oom");

        let new_tail_start = self.tail_start + extra_capacity;
        let src = deq.as_ptr().add(self.tail_start);
        let dst = deq.as_mut_ptr().add(new_tail_start);
        ptr::copy(src, dst, self.tail_len);
        self.tail_start = new_tail_start;
    }
}

/// An iterator produced by calling `drain_filter` on `SliceDeque`.
#[derive(Debug)]
pub struct DrainFilter<'a, T: 'a, F>
where
    F: FnMut(&mut T) -> bool,
{
    /// TODO: docs
    deq: &'a mut SliceDeque<T>,
    /// TODO: docs
    idx: usize,
    /// TODO: docs
    del: usize,
    /// TODO: docs
    old_len: usize,
    /// TODO: docs
    pred: F,
}

impl<'a, T, F> Iterator for DrainFilter<'a, T, F>
where
    F: FnMut(&mut T) -> bool,
{
    type Item = T;

    fn next(&mut self) -> Option<T> {
        unsafe {
            while self.idx != self.old_len {
                let i = self.idx;
                self.idx += 1;
                let v = slice::from_raw_parts_mut(
                    self.deq.as_mut_ptr(),
                    self.old_len,
                );
                if (self.pred)(&mut v[i]) {
                    self.del += 1;
                    return Some(ptr::read(&v[i]));
                } else if self.del > 0 {
                    let del = self.del;
                    let src: *const T = &v[i];
                    let dst: *mut T = &mut v[i - del];
                    // This is safe because self.deq has length 0
                    // thus its elements will not have Drop::drop
                    // called on them in the event of a panic.
                    ptr::copy_nonoverlapping(src, dst, 1);
                }
            }
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, Some(self.old_len - self.idx))
    }
}

impl<'a, T, F> Drop for DrainFilter<'a, T, F>
where
    F: FnMut(&mut T) -> bool,
{
    fn drop(&mut self) {
        for _ in self.by_ref() {}

        unsafe {
            let new_len = self.old_len - self.del;
            self.deq.move_tail_unchecked(new_len as isize);
        }
    }
}

impl<T> convert::AsRef<[T]> for SliceDeque<T> {
    fn as_ref(&self) -> &[T] {
        &*self
    }
}

impl<T> convert::AsMut<[T]> for SliceDeque<T> {
    fn as_mut(&mut self) -> &mut [T] {
        &mut *self
    }
}

#[cfg(all(feature = "bytes_buf", feature = "use_std"))]
impl ::bytes::BufMut for SliceDeque<u8> {
    #[inline]
    fn remaining_mut(&self) -> usize {
        usize::max_value() - self.len()
    }
    #[inline]
    unsafe fn bytes_mut(&mut self) -> &mut [u8] {
        if self.capacity() == self.len() {
            self.reserve(64); // Grow the deque
        }

        let cap = self.capacity();
        let len = self.len();

        let ptr = self.as_mut_ptr();
        &mut slice::from_raw_parts_mut(ptr, cap)[len..]
    }
    #[inline]
    unsafe fn advance_mut(&mut self, cnt: usize) {
        let len = self.len();
        let remaining = self.capacity() - len;
        if cnt > remaining {
            // Reserve additional capacity, and ensure that the total length
            // will not overflow usize.
            self.reserve(cnt);
        }

        self.move_tail_unchecked(cnt as isize);
    }
}

#[cfg(all(feature = "bytes_buf", feature = "use_std"))]
impl ::bytes::IntoBuf for SliceDeque<u8> {
    type Buf = io::Cursor<SliceDeque<u8>>;

    fn into_buf(self) -> Self::Buf {
        io::Cursor::new(self)
    }
}

#[cfg(all(feature = "bytes_buf", feature = "use_std"))]
impl<'a> ::bytes::IntoBuf for &'a SliceDeque<u8> {
    type Buf = io::Cursor<&'a [u8]>;

    fn into_buf(self) -> Self::Buf {
        io::Cursor::new(&self[..])
    }
}

#[cfg(all(feature = "bytes_buf", feature = "use_std"))]
impl ::bytes::buf::FromBuf for SliceDeque<u8> {
    fn from_buf<T>(buf: T) -> Self
    where
        T: ::bytes::IntoBuf,
    {
        use bytes::{Buf, BufMut};
        let buf = buf.into_buf();
        let mut ret = SliceDeque::with_capacity(buf.remaining());
        ret.put(buf);
        ret
    }
}

#[cfg(test)]
mod tests {
    use self::collections::HashMap;
    use super::SliceDeque;
    use std::cell::RefCell;
    use std::rc::Rc;
    use std::{collections, fmt, hash, mem};

    #[derive(Clone, Debug)]
    struct WithDrop {
        counter: Rc<RefCell<usize>>,
    }

    impl Drop for WithDrop {
        fn drop(&mut self) {
            *self.counter.borrow_mut() += 1;
        }
    }

    fn sizes_to_test() -> Vec<usize> {
        let sample = vec![
            /* powers of 2 */ 2, 4, 8, 16, 32, 64,
            128, /*
                256,
                512,
                1024,
                2048,
                4096,
                8192, 16_384, 32_768,  65_536, 131_072, 262_144,
                */
                /*
                // powers of 2 - 1 or primes
                1, 3, 7, 13, 17, 31, 61, 127, 257, 509, 1021, 2039, 4093,
                8191, 16_381, 32_749,  65_537, 131_071, 262_143, 4_194_301,
                // powers of 10
                10, 100, 1000, 10_000, 100_000, 1_000_000_usize,*/
        ];
        sample.into_iter().collect()
    }

    fn linear_usize_deque(size: usize) -> SliceDeque<usize> {
        let mut v: SliceDeque<usize> = SliceDeque::new();
        for i in 0..size {
            v.push_back(i);
            assert_eq!(v.len(), i + 1);
            for j in 0..v.len() {
                assert_eq!(*v.get(j).unwrap(), j);
            }
        }
        assert_eq!(v.len(), size);
        for i in 0..size {
            assert_eq!(*v.get(i).unwrap(), i);
        }
        v
    }

    fn constant_deque<T: Clone + fmt::Debug>(
        size: usize, val: &T,
    ) -> SliceDeque<T> {
        let mut v: SliceDeque<T> = SliceDeque::with_capacity(size);
        for i in 0..size {
            let copy = val.clone();
            v.push_back(copy);
            assert_eq!(v.len(), i + 1);
        }
        assert_eq!(v.len(), size);
        v
    }

    #[test]
    fn get() {
        let mut deq = SliceDeque::new();
        deq.push_back(3);
        deq.push_back(4);
        deq.push_back(5);
        assert_eq!(deq.get(1), Some(&4));
    }

    #[test]
    fn get_mut() {
        let mut deq = SliceDeque::new();
        deq.push_back(3);
        deq.push_back(4);
        deq.push_back(5);
        assert_eq!(deq.get(1), Some(&4));
        if let Some(elem) = deq.get_mut(1) {
            *elem = 7;
        }
        assert_eq!(deq[1], 7);
    }

    #[test]
    fn is_empty() {
        let mut deq = SliceDeque::new();
        assert!(deq.is_empty());
        deq.push_back(4);
        assert!(!deq.is_empty());
        deq.pop_front();
        assert!(deq.is_empty());
    }

    #[test]
    fn push_pop_front() {
        for size in sizes_to_test() {
            let mut v: SliceDeque<usize> = SliceDeque::new();
            for i in 0..size {
                v.push_front(i);
                assert_eq!(v.len(), i + 1);
                for j in 0..v.len() {
                    assert_eq!(*v.get(v.len() - j - 1).unwrap(), j);
                }
            }
            assert_eq!(v.len(), size);
            for i in 0..size {
                assert_eq!(*v.get(i).unwrap(), size - i - 1);
            }
            for i in 0..size {
                assert_eq!(v.len(), size - i);
                v.pop_front();
                for j in 0..v.len() {
                    assert_eq!(*v.get(v.len() - j - 1).unwrap(), j);
                }
            }
            assert_eq!(v.len(), 0);
        }
    }

    #[test]
    fn push_pop_back() {
        for size in sizes_to_test() {
            let mut v = linear_usize_deque(size);
            for i in 0..size {
                assert_eq!(v.len(), size - i);
                v.pop_back();
                for j in 0..v.len() {
                    assert_eq!(*v.get(j).unwrap(), j);
                }
            }
            assert_eq!(v.len(), 0);
        }
    }

    #[test]
    fn all_head_tails() {
        for size in sizes_to_test() {
            let mut v = linear_usize_deque(size);
            let permutations = 6 * v.capacity();

            // rotate from left to right
            for _ in 0..permutations {
                v.push_back(0);
                for j in (0..v.len() - 1).rev() {
                    *v.get_mut(j + 1).unwrap() = *v.get(j).unwrap();
                }
                v.pop_front();
                assert_eq!(v.len(), size);
                for k in 0..size {
                    assert_eq!(*v.get(k).unwrap(), k);
                }
            }

            // rotate from right to left
            for _ in 0..permutations {
                v.push_front(0);
                for j in 0..v.len() - 1 {
                    *v.get_mut(j).unwrap() = *v.get(j + 1).unwrap()
                }
                v.pop_back();
                assert_eq!(v.len(), size);
                for k in 0..size {
                    assert_eq!(*v.get(k).unwrap(), k);
                }
            }
        }
    }

    #[test]
    fn drop() {
        for size in sizes_to_test() {
            let counter = Rc::new(RefCell::new(0));
            let val = WithDrop {
                counter: counter.clone(),
            };
            {
                let _v = constant_deque(size, &val);
            }
            assert_eq!(*counter.borrow(), size);
        }
    }

    #[test]
    fn clear() {
        for size in sizes_to_test() {
            let counter = Rc::new(RefCell::new(0));
            let val = WithDrop {
                counter: counter.clone(),
            };
            assert_eq!(*counter.borrow(), 0);
            let mut v = constant_deque(size, &val);
            assert_eq!(*counter.borrow(), 0);
            v.clear();
            assert_eq!(*counter.borrow(), size);
            assert_eq!(v.len(), 0);
        }
    }

    #[test]
    fn reserve_no_cap_change() {
        let mut slice = SliceDeque::<u8>::with_capacity(4096);
        let cap = slice.capacity();
        assert!(cap >= 4096);
        slice.reserve(cap);
        // capacity should not change if the existing capacity is already
        // sufficient.
        assert_eq!(slice.capacity(), cap);
    }

    #[test]
    fn resize() {
        for size in sizes_to_test() {
            let mut v = linear_usize_deque(size);
            let mut v_ref = linear_usize_deque(size / 2);
            v.resize(size / 2, 0);
            assert_eq!(v.len(), size / 2);
            assert_eq!(v.as_slice(), v_ref.as_slice());
            while v_ref.len() < size {
                v_ref.push_back(3);
            }
            v.resize(size, 3);
            assert_eq!(v.len(), size);
            assert_eq!(v_ref.len(), size);
            assert_eq!(v.as_slice(), v_ref.as_slice());

            v.resize(0, 3);
            assert_eq!(v.len(), 0);

            v.resize(size, 3);
            let v_ref = constant_deque(size, &3);
            assert_eq!(v.len(), size);
            assert_eq!(v_ref.len(), size);
            assert_eq!(v.as_slice(), v_ref.as_slice());
        }
    }

    #[test]
    fn default() {
        let d = SliceDeque::<u8>::default();
        let r = SliceDeque::<u8>::new();
        assert_eq!(d.as_slice(), r.as_slice());
    }

    #[test]
    fn shrink_to_fit() {
        let page_size = 4096;
        for size in sizes_to_test() {
            let mut deq = constant_deque(size, &(3 as u8));
            let old_cap = deq.capacity();
            deq.resize(size / 4, 3);
            deq.shrink_to_fit();
            if size <= page_size {
                assert_eq!(deq.capacity(), old_cap);
            } else {
                assert!(deq.capacity() < old_cap);
            }
        }
    }

    #[test]
    fn iter() {
        let mut deq = SliceDeque::new();
        deq.push_back(5);
        deq.push_back(3);
        deq.push_back(4);
        let b: &[_] = &[&5, &3, &4];
        let c: Vec<&i32> = deq.iter().collect();
        assert_eq!(&c[..], b);
    }

    #[test]
    fn iter_mut() {
        let mut deq = SliceDeque::new();
        deq.push_back(5);
        deq.push_back(3);
        deq.push_back(4);
        for num in deq.iter_mut() {
            *num = *num - 2;
        }
        let b: &[_] = &[&mut 3, &mut 1, &mut 2];
        assert_eq!(&deq.iter_mut().collect::<Vec<&mut i32>>()[..], b);
    }

    #[test]
    fn hash_map() {
        let mut hm: HashMap<SliceDeque<u32>, u32> = HashMap::new();
        let mut a = SliceDeque::new();
        a.push_back(1);
        a.push_back(2);
        hm.insert(a.clone(), 3);
        let b = SliceDeque::new();
        assert_eq!(hm.get(&a), Some(&3));
        assert_eq!(hm.get(&b), None);
    }

    #[test]
    fn partial_ord_eq() {
        let mut a = SliceDeque::new();
        a.push_back(1);
        a.push_back(2);
        a.push_back(3);
        assert!(a == a);
        assert!(!(a != a));

        let mut b = SliceDeque::new();
        b.push_back(1);
        b.push_back(3);
        b.push_back(2);
        assert!(a < b);
        assert!(b > a);
        assert!(a != b);

        let mut c = SliceDeque::new();
        c.push_back(2);
        assert!(c > a);
        assert!(a < c);
    }

    struct DropCounter<'a> {
        count: &'a mut u32,
    }

    impl<'a> Drop for DropCounter<'a> {
        fn drop(&mut self) {
            *self.count += 1;
        }
    }

    #[test]
    fn vec_double_drop() {
        struct TwoSliceDeque<T> {
            x: SliceDeque<T>,
            y: SliceDeque<T>,
        }

        let (mut count_x, mut count_y) = (0, 0);
        {
            let mut tv = TwoSliceDeque {
                x: SliceDeque::new(),
                y: SliceDeque::new(),
            };
            tv.x.push_back(DropCounter {
                count: &mut count_x,
            });
            tv.y.push_back(DropCounter {
                count: &mut count_y,
            });

            // If SliceDeque had a drop flag, here is where it would be zeroed.
            // Instead, it should rely on its internal state to prevent
            // doing anything significant when dropped multiple times.
            mem::drop(tv.x);

            // Here tv goes out of scope, tv.y should be dropped, but not tv.x.
        }

        assert_eq!(count_x, 1);
        assert_eq!(count_y, 1);
    }

    #[test]
    fn vec_reserve() {
        let mut v = SliceDeque::new();
        assert_eq!(v.capacity(), 0);

        v.reserve(2);
        assert!(v.capacity() >= 2);

        for i in 0..16 {
            v.push_back(i);
        }

        assert!(v.capacity() >= 16);
        v.reserve(16);
        assert!(v.capacity() >= 32);

        v.push_back(16);

        v.reserve(16);
        assert!(v.capacity() >= 33)
    }

    #[test]
    fn vec_extend() {
        let mut v = SliceDeque::new();
        let mut w = SliceDeque::new();

        v.extend(w.clone());
        assert_eq!(v, &[]);

        v.extend(0..3);
        for i in 0..3 {
            w.push_back(i)
        }

        assert_eq!(v, w);

        v.extend(3..10);
        for i in 3..10 {
            w.push_back(i)
        }

        assert_eq!(v, w);

        v.extend(w.clone()); // specializes to `append`
        assert!(v.iter().eq(w.iter().chain(w.iter())));

        // Double drop
        let mut count_x = 0;
        {
            let mut x = SliceDeque::new();
            let mut y = SliceDeque::new();
            y.push_back(DropCounter {
                count: &mut count_x,
            });
            x.extend(y);
        }
        assert_eq!(count_x, 1);
    }

    #[test]
    fn vec_extend_zst() {
        // Zero sized types
        #[derive(PartialEq, Debug)]
        struct Foo;

        let mut a = SliceDeque::new();
        let b = sdeq![Foo, Foo];

        a.extend(b);
        assert_eq!(a, &[Foo, Foo]);
    }

    #[test]
    fn vec_extend_ref() {
        let mut v = SliceDeque::new();
        for &i in &[1, 2] {
            v.push_back(i);
        }
        v.extend(&[3, 4, 5]);

        assert_eq!(v.len(), 5);
        assert_eq!(v, [1, 2, 3, 4, 5]);

        let mut w = SliceDeque::new();
        for &i in &[6, 7] {
            w.push_back(i);
        }
        v.extend(&w);

        assert_eq!(v.len(), 7);
        assert_eq!(v, [1, 2, 3, 4, 5, 6, 7]);
    }

    #[test]
    fn vec_slice_from_mut() {
        let mut values = sdeq![1, 2, 3, 4, 5];
        {
            let slice = &mut values[2..];
            assert!(slice == [3, 4, 5]);
            for p in slice {
                *p += 2;
            }
        }

        assert!(values == [1, 2, 5, 6, 7]);
    }

    #[test]
    fn vec_slice_to_mut() {
        let mut values = sdeq![1, 2, 3, 4, 5];
        {
            let slice = &mut values[..2];
            assert!(slice == [1, 2]);
            for p in slice {
                *p += 1;
            }
        }

        assert!(values == [2, 3, 3, 4, 5]);
    }

    #[test]
    fn vec_split_at_mut() {
        let mut values = sdeq![1, 2, 3, 4, 5];
        {
            let (left, right) = values.split_at_mut(2);
            {
                let left: &[_] = left;
                assert!(&left[..left.len()] == &[1, 2]);
            }
            for p in left {
                *p += 1;
            }

            {
                let right: &[_] = right;
                assert!(&right[..right.len()] == &[3, 4, 5]);
            }
            for p in right {
                *p += 2;
            }
        }

        assert_eq!(values, [2, 3, 5, 6, 7]);
    }

    #[test]
    fn vec_clone() {
        let v: SliceDeque<i32> = sdeq![];
        let w = sdeq![1, 2, 3];

        assert_eq!(v, v.clone());

        let z = w.clone();
        assert_eq!(w, z);
        // they should be disjoint in memory.
        assert!(w.as_ptr() != z.as_ptr())
    }

    #[cfg(feature = "unstable")]
    #[test]
    fn vec_clone_from() {
        let mut v = sdeq![];
        let three: SliceDeque<Box<_>> = sdeq![box 1, box 2, box 3];
        let two: SliceDeque<Box<_>> = sdeq![box 4, box 5];

        // zero, long
        v.clone_from(&three);
        assert_eq!(v, three);

        // equal
        v.clone_from(&three);
        assert_eq!(v, three);

        // long, short
        v.clone_from(&two);
        assert_eq!(v, two);

        // short, long
        v.clone_from(&three);
        assert_eq!(v, three)
    }

    #[test]
    fn vec_retain() {
        let mut deq = sdeq![1, 2, 3, 4];
        deq.retain(|&x| x % 2 == 0);
        assert_eq!(deq, [2, 4]);
    }

    #[test]
    fn vec_dedup() {
        fn case(a: SliceDeque<i32>, b: SliceDeque<i32>) {
            let mut v = a;
            v.dedup();
            assert_eq!(v, b);
        }
        case(sdeq![], sdeq![]);
        case(sdeq![1], sdeq![1]);
        case(sdeq![1, 1], sdeq![1]);
        case(sdeq![1, 2, 3], sdeq![1, 2, 3]);
        case(sdeq![1, 1, 2, 3], sdeq![1, 2, 3]);
        case(sdeq![1, 2, 2, 3], sdeq![1, 2, 3]);
        case(sdeq![1, 2, 3, 3], sdeq![1, 2, 3]);
        case(sdeq![1, 1, 2, 2, 2, 3, 3], sdeq![1, 2, 3]);
    }

    #[test]
    fn vec_dedup_by_key() {
        fn case(a: SliceDeque<i32>, b: SliceDeque<i32>) {
            let mut v = a;
            v.dedup_by_key(|i| *i / 10);
            assert_eq!(v, b);
        }
        case(sdeq![], sdeq![]);
        case(sdeq![10], sdeq![10]);
        case(sdeq![10, 11], sdeq![10]);
        case(sdeq![10, 20, 30], sdeq![10, 20, 30]);
        case(sdeq![10, 11, 20, 30], sdeq![10, 20, 30]);
        case(sdeq![10, 20, 21, 30], sdeq![10, 20, 30]);
        case(sdeq![10, 20, 30, 31], sdeq![10, 20, 30]);
        case(sdeq![10, 11, 20, 21, 22, 30, 31], sdeq![10, 20, 30]);
    }

    #[test]
    fn vec_dedup_by() {
        let mut deq = sdeq!["foo", "bar", "Bar", "baz", "bar"];
        deq.dedup_by(|a, b| a.eq_ignore_ascii_case(b));

        assert_eq!(deq, ["foo", "bar", "baz", "bar"]);

        let mut deq: SliceDeque<(&'static str, i32)> =
            sdeq![("foo", 1), ("foo", 2), ("bar", 3), ("bar", 4), ("bar", 5)];
        deq.dedup_by(|a, b| {
            a.0 == b.0 && {
                b.1 += a.1;
                true
            }
        });

        assert_eq!(deq, [("foo", 3), ("bar", 12)]);
    }

    #[cfg(feature = "unstable")]
    #[test]
    fn vec_dedup_unique() {
        let mut v0: SliceDeque<Box<_>> = sdeq![box 1, box 1, box 2, box 3];
        v0.dedup();
        let mut v1: SliceDeque<Box<_>> = sdeq![box 1, box 2, box 2, box 3];
        v1.dedup();
        let mut v2: SliceDeque<Box<_>> = sdeq![box 1, box 2, box 3, box 3];
        v2.dedup();
        // If the boxed pointers were leaked or otherwise misused, valgrind
        // and/or rt should raise errors.
    }

    #[test]
    fn zero_sized_values() {
        let mut v = SliceDeque::new();
        assert_eq!(v.len(), 0);
        v.push_back(());
        assert_eq!(v.len(), 1);
        v.push_back(());
        assert_eq!(v.len(), 2);
        assert_eq!(v.pop_back(), Some(()));
        assert_eq!(v.pop_back(), Some(()));
        assert_eq!(v.pop_back(), None);

        assert_eq!(v.iter().count(), 0);
        v.push_back(());
        assert_eq!(v.iter().count(), 1);
        v.push_back(());
        assert_eq!(v.iter().count(), 2);

        for &() in &v {}

        assert_eq!(v.iter_mut().count(), 2);
        v.push_back(());
        assert_eq!(v.iter_mut().count(), 3);
        v.push_back(());
        assert_eq!(v.iter_mut().count(), 4);

        for &mut () in &mut v {}
        unsafe {
            let len = v.len() as isize;
            v.move_tail_unchecked(-len);
        }
        assert_eq!(v.iter_mut().count(), 0);
    }

    #[test]
    fn vec_partition() {
        assert_eq!(
            sdeq![].into_iter().partition(|x: &i32| *x < 3),
            (sdeq![], sdeq![])
        );
        assert_eq!(
            sdeq![1, 2, 3].into_iter().partition(|x| *x < 4),
            (sdeq![1, 2, 3], sdeq![])
        );
        assert_eq!(
            sdeq![1, 2, 3].into_iter().partition(|x| *x < 2),
            (sdeq![1], sdeq![2, 3])
        );
        assert_eq!(
            sdeq![1, 2, 3].into_iter().partition(|x| *x < 0),
            (sdeq![], sdeq![1, 2, 3])
        );
    }

    #[test]
    fn vec_zip_unzip() {
        let z1 = sdeq![(1, 4), (2, 5), (3, 6)];

        let (left, right): (SliceDeque<_>, SliceDeque<_>) =
            z1.iter().cloned().unzip();

        assert_eq!((1, 4), (left[0], right[0]));
        assert_eq!((2, 5), (left[1], right[1]));
        assert_eq!((3, 6), (left[2], right[2]));
    }

    #[test]
    fn vec_vec_truncate_drop() {
        static mut DROPS: u32 = 0;
        struct Elem(i32);
        impl Drop for Elem {
            fn drop(&mut self) {
                unsafe {
                    DROPS += 1;
                }
            }
        }

        let mut v = sdeq![Elem(1), Elem(2), Elem(3), Elem(4), Elem(5)];
        assert_eq!(unsafe { DROPS }, 0);
        v.truncate(3);
        assert_eq!(unsafe { DROPS }, 2);
        v.truncate(0);
        assert_eq!(unsafe { DROPS }, 5);
    }

    #[test]
    fn vec_vec_truncate_front_drop() {
        static mut DROPS: u32 = 0;
        struct Elem(i32);
        impl Drop for Elem {
            fn drop(&mut self) {
                unsafe {
                    DROPS += 1;
                }
            }
        }

        let mut v = sdeq![Elem(1), Elem(2), Elem(3), Elem(4), Elem(5)];
        assert_eq!(unsafe { DROPS }, 0);
        v.truncate_front(3);
        assert_eq!(unsafe { DROPS }, 2);
        v.truncate_front(0);
        assert_eq!(unsafe { DROPS }, 5);
    }

    #[test]
    #[should_panic]
    fn vec_vec_truncate_fail() {
        struct BadElem(i32);
        impl Drop for BadElem {
            fn drop(&mut self) {
                let BadElem(ref mut x) = *self;
                if *x == 0xbadbeef {
                    panic!("BadElem panic: 0xbadbeef")
                }
            }
        }

        let mut v =
            sdeq![BadElem(1), BadElem(2), BadElem(0xbadbeef), BadElem(4)];
        v.truncate(0);
    }

    #[test]
    fn vec_index() {
        let deq = sdeq![1, 2, 3];
        assert!(deq[1] == 2);
    }

    #[test]
    #[should_panic]
    fn vec_index_out_of_bounds() {
        let deq = sdeq![1, 2, 3];
        let _ = deq[3];
    }

    #[test]
    #[should_panic]
    fn vec_slice_out_of_bounds_1() {
        let x = sdeq![1, 2, 3, 4, 5];
        &x[!0..];
    }

    #[test]
    #[should_panic]
    fn vec_slice_out_of_bounds_2() {
        let x = sdeq![1, 2, 3, 4, 5];
        &x[..6];
    }

    #[test]
    #[should_panic]
    fn vec_slice_out_of_bounds_3() {
        let x = sdeq![1, 2, 3, 4, 5];
        &x[!0..4];
    }

    #[test]
    #[should_panic]
    fn vec_slice_out_of_bounds_4() {
        let x = sdeq![1, 2, 3, 4, 5];
        &x[1..6];
    }

    #[test]
    #[should_panic]
    fn vec_slice_out_of_bounds_5() {
        let x = sdeq![1, 2, 3, 4, 5];
        &x[3..2];
    }

    #[test]
    fn vec_swap_remove_empty() {
        let mut deq = SliceDeque::<i32>::new();
        assert_eq!(deq.swap_remove_back(0), None);
    }

    #[test]
    fn vec_move_items() {
        let deq = sdeq![1, 2, 3];
        let mut deq2 = sdeq![];
        for i in deq {
            deq2.push_back(i);
        }
        assert_eq!(deq2, [1, 2, 3]);
    }

    #[test]
    fn vec_move_items_reverse() {
        let deq = sdeq![1, 2, 3];
        let mut deq2 = sdeq![];
        for i in deq.into_iter().rev() {
            deq2.push_back(i);
        }
        assert_eq!(deq2, [3, 2, 1]);
    }

    #[test]
    fn vec_move_items_zero_sized() {
        let deq = sdeq![(), (), ()];
        let mut deq2 = sdeq![];
        for i in deq {
            deq2.push_back(i);
        }
        assert_eq!(deq2, [(), (), ()]);
    }

    #[test]
    fn vec_drain_items() {
        let mut deq = sdeq![1, 2, 3];
        let mut deq2 = sdeq![];
        for i in deq.drain(..) {
            deq2.push_back(i);
        }
        assert_eq!(deq, []);
        assert_eq!(deq2, [1, 2, 3]);
    }

    #[test]
    fn vec_drain_items_reverse() {
        let mut deq = sdeq![1, 2, 3];
        let mut deq2 = sdeq![];
        for i in deq.drain(..).rev() {
            deq2.push_back(i);
        }
        assert_eq!(deq, []);
        assert_eq!(deq2, [3, 2, 1]);
    }

    #[test]
    fn vec_drain_items_zero_sized() {
        let mut deq = sdeq![(), (), ()];
        let mut deq2 = sdeq![];
        for i in deq.drain(..) {
            deq2.push_back(i);
        }
        assert_eq!(deq, []);
        assert_eq!(deq2, [(), (), ()]);
    }

    #[test]
    #[should_panic]
    fn vec_drain_out_of_bounds() {
        let mut v = sdeq![1, 2, 3, 4, 5];
        v.drain(5..6);
    }

    #[test]
    fn vec_drain_range() {
        let mut v = sdeq![1, 2, 3, 4, 5];
        for _ in v.drain(4..) {}
        assert_eq!(v, &[1, 2, 3, 4]);

        let mut v: SliceDeque<_> = (1..6).map(|x| x.to_string()).collect();
        for _ in v.drain(1..4) {}
        assert_eq!(v, &[1.to_string(), 5.to_string()]);

        let mut v: SliceDeque<_> = (1..6).map(|x| x.to_string()).collect();
        for _ in v.drain(1..4).rev() {}
        assert_eq!(v, &[1.to_string(), 5.to_string()]);
    }

    #[test]
    fn vec_drain_range_zst() {
        let mut v: SliceDeque<_> = sdeq![(); 5];
        for _ in v.drain(1..4).rev() {}
        assert_eq!(v, &[(), ()]);
    }

    #[test]
    fn vec_drain_inclusive_range() {
        let mut v = sdeq!['a', 'b', 'c', 'd', 'e'];
        for _ in v.drain(1..=3) {}
        assert_eq!(v, &['a', 'e']);

        let mut v: SliceDeque<_> = (0..=5).map(|x| x.to_string()).collect();
        for _ in v.drain(1..=5) {}
        assert_eq!(v, &["0".to_string()]);

        let mut v: SliceDeque<String> =
            (0..=5).map(|x| x.to_string()).collect();
        for _ in v.drain(0..=5) {}
        assert_eq!(v, SliceDeque::<String>::new());

        let mut v: SliceDeque<_> = (0..=5).map(|x| x.to_string()).collect();
        for _ in v.drain(0..=3) {}
        assert_eq!(v, &["4".to_string(), "5".to_string()]);

        let mut v: SliceDeque<_> = (0..=1).map(|x| x.to_string()).collect();
        for _ in v.drain(..=0) {}
        assert_eq!(v, &["1".to_string()]);
    }

    #[test]
    fn vec_drain_max_vec_size() {
        const M: usize = isize::max_value() as usize;
        let mut v = SliceDeque::<()>::with_capacity(M);
        unsafe { v.move_tail_unchecked(M as isize) };
        assert_eq!(v.len(), M as usize);
        for _ in v.drain(M - 1..) {}
        assert_eq!(v.len(), M - 1);

        let mut v = SliceDeque::<()>::with_capacity(M);
        unsafe { v.move_tail_unchecked(M as isize) };
        assert_eq!(v.len(), M as usize);
        for _ in v.drain(M - 1..=M - 1) {}
        assert_eq!(v.len(), M - 1);
    }

    #[test]
    #[should_panic]
    fn vec_drain_inclusive_out_of_bounds() {
        let mut v = sdeq![1, 2, 3, 4, 5];
        v.drain(5..=5);
    }

    #[test]
    fn vec_splice() {
        let mut v = sdeq![1, 2, 3, 4, 5];
        let a = [10, 11, 12];
        v.splice(2..4, a.iter().cloned());
        assert_eq!(v, &[1, 2, 10, 11, 12, 5]);
        v.splice(1..3, Some(20));
        assert_eq!(v, &[1, 20, 11, 12, 5]);
    }

    #[test]
    fn vec_splice_inclusive_range() {
        let mut v = sdeq![1, 2, 3, 4, 5];
        let a = [10, 11, 12];
        let t1: SliceDeque<_> = v.splice(2..=3, a.iter().cloned()).collect();
        assert_eq!(v, &[1, 2, 10, 11, 12, 5]);
        assert_eq!(t1, &[3, 4]);
        let t2: SliceDeque<_> = v.splice(1..=2, Some(20)).collect();
        assert_eq!(v, &[1, 20, 11, 12, 5]);
        assert_eq!(t2, &[2, 10]);
    }

    #[test]
    #[should_panic]
    fn vec_splice_out_of_bounds() {
        let mut v = sdeq![1, 2, 3, 4, 5];
        let a = [10, 11, 12];
        v.splice(5..6, a.iter().cloned());
    }

    #[test]
    #[should_panic]
    fn vec_splice_inclusive_out_of_bounds() {
        let mut v = sdeq![1, 2, 3, 4, 5];
        let a = [10, 11, 12];
        v.splice(5..=5, a.iter().cloned());
    }

    #[test]
    fn vec_splice_items_zero_sized() {
        let mut deq = sdeq![(), (), ()];
        let deq2 = sdeq![];
        let t: SliceDeque<_> =
            deq.splice(1..2, deq2.iter().cloned()).collect();
        assert_eq!(deq, &[(), ()]);
        assert_eq!(t, &[()]);
    }

    #[test]
    fn vec_splice_unbounded() {
        let mut deq = sdeq![1, 2, 3, 4, 5];
        let t: SliceDeque<_> = deq.splice(.., None).collect();
        assert_eq!(deq, &[]);
        assert_eq!(t, &[1, 2, 3, 4, 5]);
    }

    #[test]
    fn vec_splice_forget() {
        let mut v = sdeq![1, 2, 3, 4, 5];
        let a = [10, 11, 12];
        mem::forget(v.splice(2..4, a.iter().cloned()));
        assert_eq!(v, &[1, 2]);
    }

    /* into_boxed_slice probably can't be supported portably
    #[test]
    fn vec_into_boxed_slice() {
        let xs = sdeq![1, 2, 3];
        let ys = xs.into_boxed_slice();
        assert_eq!(&*ys, [1, 2, 3]);
    }
    */

    #[test]
    fn vec_append() {
        let mut deq = sdeq![1, 2, 3];
        let mut deq2 = sdeq![4, 5, 6];
        deq.append(&mut deq2);
        assert_eq!(deq, [1, 2, 3, 4, 5, 6]);
        assert_eq!(deq2, []);
    }

    #[test]
    fn vec_split_off() {
        let mut deq = sdeq![1, 2, 3, 4, 5, 6];
        let deq2 = deq.split_off(4);
        assert_eq!(deq, [1, 2, 3, 4]);
        assert_eq!(deq2, [5, 6]);
    }

    #[test]
    fn vec_into_iter_as_slice() {
        let deq = sdeq!['a', 'b', 'c'];
        let mut into_iter = deq.into_iter();
        assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
        let _ = into_iter.next().unwrap();
        assert_eq!(into_iter.as_slice(), &['b', 'c']);
        let _ = into_iter.next().unwrap();
        let _ = into_iter.next().unwrap();
        assert_eq!(into_iter.as_slice(), &[]);
    }

    #[test]
    fn vec_into_iter_as_mut_slice() {
        let deq = sdeq!['a', 'b', 'c'];
        let mut into_iter = deq.into_iter();
        assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
        into_iter.as_mut_slice()[0] = 'x';
        into_iter.as_mut_slice()[1] = 'y';
        assert_eq!(into_iter.next().unwrap(), 'x');
        assert_eq!(into_iter.as_slice(), &['y', 'c']);
    }

    #[test]
    fn vec_into_iter_debug() {
        let deq = sdeq!['a', 'b', 'c'];
        let into_iter = deq.into_iter();
        let debug = format!("{:?}", into_iter);
        assert_eq!(debug, "IntoIter(['a', 'b', 'c'])");
    }

    #[test]
    fn vec_into_iter_count() {
        assert_eq!(sdeq![1, 2, 3].into_iter().count(), 3);
    }

    #[test]
    fn vec_into_iter_clone() {
        fn iter_equal<I: Iterator<Item = i32>>(it: I, slice: &[i32]) {
            let v: SliceDeque<i32> = it.collect();
            assert_eq!(&v[..], slice);
        }
        let deq = sdeq![1, 2, 3];
        let mut it = deq.into_iter();
        let it_c = it.clone();
        iter_equal(it_c, &[1, 2, 3]);
        assert_eq!(it.next(), Some(1));
        let mut it = it.rev();
        iter_equal(it.clone(), &[3, 2]);
        assert_eq!(it.next(), Some(3));
        iter_equal(it.clone(), &[2]);
        assert_eq!(it.next(), Some(2));
        iter_equal(it.clone(), &[]);
        assert_eq!(it.next(), None);
    }

    /* TODO: Cow support
    #[test]
        fn vec_cow_from() {
            use std::borrow::Cow;
        let borrowed: &[_] = &["borrowed", "(slice)"];
        let owned = sdeq!["owned", "(vec)"];
        match (Cow::from(owned.clone()), Cow::from(borrowed)) {
            (Cow::Owned(o), Cow::Borrowed(b)) => assert!(o == owned && b == borrowed),
            _ => panic!("invalid `Cow::from`"),
        }
    }

    #[test]
        fn vec_from_cow() {
            use std::borrow::Cow;
        let borrowed: &[_] = &["borrowed", "(slice)"];
        let owned = sdeq!["owned", "(vec)"];
        assert_eq!(SliceDeque::from(Cow::Borrowed(borrowed)), sdeq!["borrowed", "(slice)"]);
        assert_eq!(SliceDeque::from(Cow::Owned(owned)), sdeq!["owned", "(vec)"]);
    }
         */

    /* TODO: covariance
    use super::{Drain, IntoIter};

    #[allow(dead_code)]
    fn assert_covariance() {
        fn drain<'new>(d: Drain<'static, &'static str>) -> Drain<'new, &'new str> {
            d
        }
        fn into_iter<'new>(i: IntoIter<&'static str>) -> IntoIter<&'new str> {
            i
        }
    }
        */

    #[test]
    fn from_into_inner() {
        let deq = sdeq![1, 2, 3];
        #[allow(unused_variables)]
        let ptr = deq.as_ptr();
        let deq = deq.into_iter().collect::<SliceDeque<_>>();
        assert_eq!(deq, [1, 2, 3]);
        #[cfg(feature = "unstable")]
        {
            assert_eq!(deq.as_ptr(), ptr);
        }

        let ptr = &deq[1] as *const _;
        let mut it = deq.into_iter();
        it.next().unwrap();
        let deq = it.collect::<SliceDeque<_>>();
        assert_eq!(deq, [2, 3]);
        assert!(ptr != deq.as_ptr());
    }

    #[cfg(feature = "unstable")]
    #[test]
    fn overaligned_allocations() {
        #[repr(align(256))]
        struct Foo(usize);
        let mut v = sdeq![Foo(273)];
        for i in 0..0x1000 {
            v.reserve_exact(i);
            assert!(v[0].0 == 273);
            assert!(v.as_ptr() as usize & 0xff == 0);
            v.shrink_to_fit();
            assert!(v[0].0 == 273);
            assert!(v.as_ptr() as usize & 0xff == 0);
        }
    }

    #[test]
    fn drain_filter_empty() {
        let mut deq: SliceDeque<i32> = sdeq![];

        {
            let mut iter = deq.drain_filter(|_| true);
            assert_eq!(iter.size_hint(), (0, Some(0)));
            assert_eq!(iter.next(), None);
            assert_eq!(iter.size_hint(), (0, Some(0)));
            assert_eq!(iter.next(), None);
            assert_eq!(iter.size_hint(), (0, Some(0)));
        }
        assert_eq!(deq.len(), 0);
        assert_eq!(deq, sdeq![]);
    }

    #[test]
    fn drain_filter_zst() {
        let mut deq = sdeq![(), (), (), (), ()];
        let initial_len = deq.len();
        let mut count = 0;
        {
            let mut iter = deq.drain_filter(|_| true);
            assert_eq!(iter.size_hint(), (0, Some(initial_len)));
            while let Some(_) = iter.next() {
                count += 1;
                assert_eq!(iter.size_hint(), (0, Some(initial_len - count)));
            }
            assert_eq!(iter.size_hint(), (0, Some(0)));
            assert_eq!(iter.next(), None);
            assert_eq!(iter.size_hint(), (0, Some(0)));
        }

        assert_eq!(count, initial_len);
        assert_eq!(deq.len(), 0);
        assert_eq!(deq, sdeq![]);
    }

    #[test]
    fn drain_filter_false() {
        let mut deq = sdeq![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

        let initial_len = deq.len();
        let mut count = 0;
        {
            let mut iter = deq.drain_filter(|_| false);
            assert_eq!(iter.size_hint(), (0, Some(initial_len)));
            for _ in iter.by_ref() {
                count += 1;
            }
            assert_eq!(iter.size_hint(), (0, Some(0)));
            assert_eq!(iter.next(), None);
            assert_eq!(iter.size_hint(), (0, Some(0)));
        }

        assert_eq!(count, 0);
        assert_eq!(deq.len(), initial_len);
        assert_eq!(deq, sdeq![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
    }

    #[test]
    fn drain_filter_true() {
        let mut deq = sdeq![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

        let initial_len = deq.len();
        let mut count = 0;
        {
            let mut iter = deq.drain_filter(|_| true);
            assert_eq!(iter.size_hint(), (0, Some(initial_len)));
            while let Some(_) = iter.next() {
                count += 1;
                assert_eq!(iter.size_hint(), (0, Some(initial_len - count)));
            }
            assert_eq!(iter.size_hint(), (0, Some(0)));
            assert_eq!(iter.next(), None);
            assert_eq!(iter.size_hint(), (0, Some(0)));
        }

        assert_eq!(count, initial_len);
        assert_eq!(deq.len(), 0);
        assert_eq!(deq, sdeq![]);
    }

    #[test]
    fn drain_filter_complex() {
        {
            //                [+xxx++++++xxxxx++++x+x++]
            let mut deq = sdeq![
                1, 2, 4, 6, 7, 9, 11, 13, 15, 17, 18, 20, 22, 24, 26, 27, 29,
                31, 33, 34, 35, 36, 37, 39,
            ];

            let removed =
                deq.drain_filter(|x| *x % 2 == 0).collect::<SliceDeque<_>>();
            assert_eq!(removed.len(), 10);
            assert_eq!(removed, sdeq![2, 4, 6, 18, 20, 22, 24, 26, 34, 36]);

            assert_eq!(deq.len(), 14);
            assert_eq!(
                deq,
                sdeq![1, 7, 9, 11, 13, 15, 17, 27, 29, 31, 33, 35, 37, 39]
            );
        }

        {
            //                [xxx++++++xxxxx++++x+x++]
            let mut deq = sdeq![
                2, 4, 6, 7, 9, 11, 13, 15, 17, 18, 20, 22, 24, 26, 27, 29, 31,
                33, 34, 35, 36, 37, 39,
            ];

            let removed =
                deq.drain_filter(|x| *x % 2 == 0).collect::<SliceDeque<_>>();
            assert_eq!(removed.len(), 10);
            assert_eq!(removed, sdeq![2, 4, 6, 18, 20, 22, 24, 26, 34, 36]);

            assert_eq!(deq.len(), 13);
            assert_eq!(
                deq,
                sdeq![7, 9, 11, 13, 15, 17, 27, 29, 31, 33, 35, 37, 39]
            );
        }

        {
            //                [xxx++++++xxxxx++++x+x]
            let mut deq = sdeq![
                2, 4, 6, 7, 9, 11, 13, 15, 17, 18, 20, 22, 24, 26, 27, 29, 31,
                33, 34, 35, 36,
            ];

            let removed =
                deq.drain_filter(|x| *x % 2 == 0).collect::<SliceDeque<_>>();
            assert_eq!(removed.len(), 10);
            assert_eq!(removed, sdeq![2, 4, 6, 18, 20, 22, 24, 26, 34, 36]);

            assert_eq!(deq.len(), 11);
            assert_eq!(deq, sdeq![7, 9, 11, 13, 15, 17, 27, 29, 31, 33, 35]);
        }

        {
            //                [xxxxxxxxxx+++++++++++]
            let mut deq = sdeq![
                2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 1, 3, 5, 7, 9, 11, 13, 15,
                17, 19,
            ];

            let removed =
                deq.drain_filter(|x| *x % 2 == 0).collect::<SliceDeque<_>>();
            assert_eq!(removed.len(), 10);
            assert_eq!(removed, sdeq![2, 4, 6, 8, 10, 12, 14, 16, 18, 20]);

            assert_eq!(deq.len(), 10);
            assert_eq!(deq, sdeq![1, 3, 5, 7, 9, 11, 13, 15, 17, 19]);
        }

        {
            //                [+++++++++++xxxxxxxxxx]
            let mut deq = sdeq![
                1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 2, 4, 6, 8, 10, 12, 14, 16,
                18, 20,
            ];

            let removed =
                deq.drain_filter(|x| *x % 2 == 0).collect::<SliceDeque<_>>();
            assert_eq!(removed.len(), 10);
            assert_eq!(removed, sdeq![2, 4, 6, 8, 10, 12, 14, 16, 18, 20]);

            assert_eq!(deq.len(), 10);
            assert_eq!(deq, sdeq![1, 3, 5, 7, 9, 11, 13, 15, 17, 19]);
        }
    }

    #[test]
    fn vecdeque_simple() {
        let mut d = SliceDeque::new();
        assert_eq!(d.len(), 0);
        d.push_front(17);
        d.push_front(42);
        d.push_back(137);
        assert_eq!(d.len(), 3);
        d.push_back(137);
        assert_eq!(d.len(), 4);
        assert_eq!(*d.front().unwrap(), 42);
        assert_eq!(*d.back().unwrap(), 137);
        let mut i = d.pop_front();
        assert_eq!(i, Some(42));
        i = d.pop_back();
        assert_eq!(i, Some(137));
        i = d.pop_back();
        assert_eq!(i, Some(137));
        i = d.pop_back();
        assert_eq!(i, Some(17));
        assert_eq!(d.len(), 0);
        d.push_back(3);
        assert_eq!(d.len(), 1);
        d.push_front(2);
        assert_eq!(d.len(), 2);
        d.push_back(4);
        assert_eq!(d.len(), 3);
        d.push_front(1);
        assert_eq!(d.len(), 4);
        assert_eq!(d[0], 1);
        assert_eq!(d[1], 2);
        assert_eq!(d[2], 3);
        assert_eq!(d[3], 4);
    }

    #[cfg(test)]
    fn vecdeque_parameterized<T: Clone + PartialEq + fmt::Debug>(
        a: T, b: T, c: T, d: T,
    ) {
        let mut deq = SliceDeque::new();
        assert_eq!(deq.len(), 0);
        deq.push_front(a.clone());
        deq.push_front(b.clone());
        deq.push_back(c.clone());
        assert_eq!(deq.len(), 3);
        deq.push_back(d.clone());
        assert_eq!(deq.len(), 4);
        assert_eq!((*deq.front().unwrap()).clone(), b.clone());
        assert_eq!((*deq.back().unwrap()).clone(), d.clone());
        assert_eq!(deq.pop_front().unwrap(), b.clone());
        assert_eq!(deq.pop_back().unwrap(), d.clone());
        assert_eq!(deq.pop_back().unwrap(), c.clone());
        assert_eq!(deq.pop_back().unwrap(), a.clone());
        assert_eq!(deq.len(), 0);
        deq.push_back(c.clone());
        assert_eq!(deq.len(), 1);
        deq.push_front(b.clone());
        assert_eq!(deq.len(), 2);
        deq.push_back(d.clone());
        assert_eq!(deq.len(), 3);
        deq.push_front(a.clone());
        assert_eq!(deq.len(), 4);
        assert_eq!(deq[0].clone(), a.clone());
        assert_eq!(deq[1].clone(), b.clone());
        assert_eq!(deq[2].clone(), c.clone());
        assert_eq!(deq[3].clone(), d.clone());
    }

    #[test]
    fn vecdeque_push_front_grow() {
        let mut deq = SliceDeque::new();
        for i in 0..66 {
            deq.push_front(i);
        }
        assert_eq!(deq.len(), 66);

        for i in 0..66 {
            assert_eq!(deq[i], 65 - i);
        }

        let mut deq = SliceDeque::new();
        for i in 0..66 {
            deq.push_back(i);
        }

        for i in 0..66 {
            assert_eq!(deq[i], i);
        }
    }

    #[test]
    fn vecdeque_index() {
        let mut deq = SliceDeque::new();
        for i in 1..4 {
            deq.push_front(i);
        }
        assert_eq!(deq[1], 2);
    }

    #[test]
    #[should_panic]
    fn vecdeque_index_out_of_bounds() {
        let mut deq = SliceDeque::new();
        for i in 1..4 {
            deq.push_front(i);
        }
        deq[3];
    }

    #[derive(Clone, PartialEq, Debug)]
    enum Taggy {
        One(i32),
        Two(i32, i32),
        Three(i32, i32, i32),
    }

    #[derive(Clone, PartialEq, Debug)]
    enum Taggypar<T> {
        Onepar(T),
        Twopar(T, T),
        Threepar(T, T, T),
    }

    #[derive(Clone, PartialEq, Debug)]
    struct RecCy {
        x: i32,
        y: i32,
        t: Taggy,
    }

    use self::Taggy::*;
    use self::Taggypar::*;

    fn hash<T: hash::Hash>(t: &T) -> u64 {
        let mut s = collections::hash_map::DefaultHasher::new();
        use hash::Hasher;
        t.hash(&mut s);
        s.finish()
    }

    #[test]
    fn vecdeque_param_int() {
        vecdeque_parameterized::<i32>(5, 72, 64, 175);
    }

    #[test]
    fn vecdeque_param_taggy() {
        vecdeque_parameterized::<Taggy>(
            One(1),
            Two(1, 2),
            Three(1, 2, 3),
            Two(17, 42),
        );
    }

    #[test]
    fn vecdeque_param_taggypar() {
        vecdeque_parameterized::<Taggypar<i32>>(
            Onepar::<i32>(1),
            Twopar::<i32>(1, 2),
            Threepar::<i32>(1, 2, 3),
            Twopar::<i32>(17, 42),
        );
    }

    #[test]
    fn vecdeque_param_reccy() {
        let reccy1 = RecCy {
            x: 1,
            y: 2,
            t: One(1),
        };
        let reccy2 = RecCy {
            x: 345,
            y: 2,
            t: Two(1, 2),
        };
        let reccy3 = RecCy {
            x: 1,
            y: 777,
            t: Three(1, 2, 3),
        };
        let reccy4 = RecCy {
            x: 19,
            y: 252,
            t: Two(17, 42),
        };
        vecdeque_parameterized::<RecCy>(reccy1, reccy2, reccy3, reccy4);
    }

    #[test]
    fn vecdeque_with_capacity() {
        let mut d = SliceDeque::with_capacity(0);
        d.push_back(1);
        assert_eq!(d.len(), 1);
        let mut d = SliceDeque::with_capacity(50);
        d.push_back(1);
        assert_eq!(d.len(), 1);
    }

    #[test]
    fn vecdeque_with_capacity_non_power_two() {
        let mut d3 = SliceDeque::with_capacity(3);
        d3.push_back(1);

        // X = None, | = lo
        // [|1, X, X]
        assert_eq!(d3.pop_front(), Some(1));
        // [X, |X, X]
        assert_eq!(d3.front(), None);

        // [X, |3, X]
        d3.push_back(3);
        // [X, |3, 6]
        d3.push_back(6);
        // [X, X, |6]
        assert_eq!(d3.pop_front(), Some(3));

        // Pushing the lo past half way point to trigger
        // the 'B' scenario for growth
        // [9, X, |6]
        d3.push_back(9);
        // [9, 12, |6]
        d3.push_back(12);

        d3.push_back(15);
        // There used to be a bug here about how the
        // SliceDeque made growth assumptions about the
        // underlying Vec which didn't hold and lead
        // to corruption.
        // (Vec grows to next power of two)
        // good- [9, 12, 15, X, X, X, X, |6]
        // bug-  [15, 12, X, X, X, |6, X, X]
        assert_eq!(d3.pop_front(), Some(6));

        // Which leads us to the following state which
        // would be a failure case.
        // bug-  [15, 12, X, X, X, X, |X, X]
        assert_eq!(d3.front(), Some(&9));
    }

    #[test]
    fn vecdeque_reserve_exact() {
        let mut d = SliceDeque::new();
        d.push_back(0);
        d.reserve_exact(50);
        assert!(d.capacity() >= 51);
    }

    #[test]
    fn vecdeque_reserve() {
        let mut d = SliceDeque::new();
        d.push_back(0);
        d.reserve(50);
        assert!(d.capacity() >= 51);
    }

    #[test]
    fn vecdeque_swap() {
        let mut d: SliceDeque<_> = (0..5).collect();
        d.pop_front();
        d.swap(0, 3);
        assert_eq!(d.iter().cloned().collect::<Vec<_>>(), [4, 2, 3, 1]);
    }

    #[test]
    fn vecdeque_iter() {
        let mut d = SliceDeque::new();
        assert_eq!(d.iter().next(), None);
        assert_eq!(d.iter().size_hint(), (0, Some(0)));

        for i in 0..5 {
            d.push_back(i);
        }
        {
            let b: &[_] = &[&0, &1, &2, &3, &4];
            assert_eq!(d.iter().collect::<Vec<_>>(), b);
        }

        for i in 6..9 {
            d.push_front(i);
        }
        {
            let b: &[_] = &[&8, &7, &6, &0, &1, &2, &3, &4];
            assert_eq!(d.iter().collect::<Vec<_>>(), b);
        }

        let mut it = d.iter();
        let mut len = d.len();
        loop {
            match it.next() {
                None => break,
                _ => {
                    len -= 1;
                    assert_eq!(it.size_hint(), (len, Some(len)))
                }
            }
        }
    }

    #[test]
    fn vecdeque_rev_iter() {
        let mut d = SliceDeque::new();
        assert_eq!(d.iter().rev().next(), None);

        for i in 0..5 {
            d.push_back(i);
        }
        {
            let b: &[_] = &[&4, &3, &2, &1, &0];
            assert_eq!(d.iter().rev().collect::<Vec<_>>(), b);
        }

        for i in 6..9 {
            d.push_front(i);
        }
        let b: &[_] = &[&4, &3, &2, &1, &0, &6, &7, &8];
        assert_eq!(d.iter().rev().collect::<Vec<_>>(), b);
    }

    #[test]
    fn vecdeque_mut_rev_iter_wrap() {
        let mut d = SliceDeque::with_capacity(3);
        assert!(d.iter_mut().rev().next().is_none());

        d.push_back(1);
        d.push_back(2);
        d.push_back(3);
        assert_eq!(d.pop_front(), Some(1));
        d.push_back(4);

        assert_eq!(
            d.iter_mut().rev().map(|x| *x).collect::<Vec<_>>(),
            vec![4, 3, 2]
        );
    }

    #[test]
    fn vecdeque_mut_iter() {
        let mut d = SliceDeque::new();
        assert!(d.iter_mut().next().is_none());

        for i in 0..3 {
            d.push_front(i);
        }

        for (i, elt) in d.iter_mut().enumerate() {
            assert_eq!(*elt, 2 - i);
            *elt = i;
        }

        {
            let mut it = d.iter_mut();
            assert_eq!(*it.next().unwrap(), 0);
            assert_eq!(*it.next().unwrap(), 1);
            assert_eq!(*it.next().unwrap(), 2);
            assert!(it.next().is_none());
        }
    }

    #[test]
    fn vecdeque_mut_rev_iter() {
        let mut d = SliceDeque::new();
        assert!(d.iter_mut().rev().next().is_none());

        for i in 0..3 {
            d.push_front(i);
        }

        for (i, elt) in d.iter_mut().rev().enumerate() {
            assert_eq!(*elt, i);
            *elt = i;
        }

        {
            let mut it = d.iter_mut().rev();
            assert_eq!(*it.next().unwrap(), 0);
            assert_eq!(*it.next().unwrap(), 1);
            assert_eq!(*it.next().unwrap(), 2);
            assert!(it.next().is_none());
        }
    }

    #[test]
    fn vecdeque_into_iter() {
        // Empty iter
        {
            let d: SliceDeque<i32> = SliceDeque::new();
            let mut iter = d.into_iter();

            assert_eq!(iter.size_hint(), (0, Some(0)));
            assert_eq!(iter.next(), None);
            assert_eq!(iter.size_hint(), (0, Some(0)));
        }

        // simple iter
        {
            let mut d = SliceDeque::new();
            for i in 0..5 {
                d.push_back(i);
            }

            let b = vec![0, 1, 2, 3, 4];
            assert_eq!(d.into_iter().collect::<Vec<_>>(), b);
        }

        // wrapped iter
        {
            let mut d = SliceDeque::new();
            for i in 0..5 {
                d.push_back(i);
            }
            for i in 6..9 {
                d.push_front(i);
            }

            let b = vec![8, 7, 6, 0, 1, 2, 3, 4];
            assert_eq!(d.into_iter().collect::<Vec<_>>(), b);
        }

        // partially used
        {
            let mut d = SliceDeque::new();
            for i in 0..5 {
                d.push_back(i);
            }
            for i in 6..9 {
                d.push_front(i);
            }

            let mut it = d.into_iter();
            assert_eq!(it.size_hint(), (8, Some(8)));
            assert_eq!(it.next(), Some(8));
            assert_eq!(it.size_hint(), (7, Some(7)));
            assert_eq!(it.next_back(), Some(4));
            assert_eq!(it.size_hint(), (6, Some(6)));
            assert_eq!(it.next(), Some(7));
            assert_eq!(it.size_hint(), (5, Some(5)));
        }
    }

    #[test]
    fn vecdeque_drain() {
        // Empty iter
        {
            let mut d: SliceDeque<i32> = SliceDeque::new();

            {
                let mut iter = d.drain(..);

                assert_eq!(iter.size_hint(), (0, Some(0)));
                assert_eq!(iter.next(), None);
                assert_eq!(iter.size_hint(), (0, Some(0)));
            }

            assert!(d.is_empty());
        }

        // simple iter
        {
            let mut d = SliceDeque::new();
            for i in 0..5 {
                d.push_back(i);
            }

            assert_eq!(d.drain(..).collect::<Vec<_>>(), [0, 1, 2, 3, 4]);
            assert!(d.is_empty());
        }

        // wrapped iter
        {
            let mut d = SliceDeque::new();
            for i in 0..5 {
                d.push_back(i);
            }
            for i in 6..9 {
                d.push_front(i);
            }

            assert_eq!(
                d.drain(..).collect::<Vec<_>>(),
                [8, 7, 6, 0, 1, 2, 3, 4]
            );
            assert!(d.is_empty());
        }

        // partially used
        {
            let mut d: SliceDeque<_> = SliceDeque::new();
            for i in 0..5 {
                d.push_back(i);
            }
            for i in 6..9 {
                d.push_front(i);
            }

            {
                let mut it = d.drain(..);
                assert_eq!(it.size_hint(), (8, Some(8)));
                assert_eq!(it.next(), Some(8));
                assert_eq!(it.size_hint(), (7, Some(7)));
                assert_eq!(it.next_back(), Some(4));
                assert_eq!(it.size_hint(), (6, Some(6)));
                assert_eq!(it.next(), Some(7));
                assert_eq!(it.size_hint(), (5, Some(5)));
            }
            assert!(d.is_empty());
        }
    }

    #[cfg(feature = "unstable")]
    #[test]
    fn vecdeque_from_iter() {
        let v = vec![1, 2, 3, 4, 5, 6, 7];
        let deq: SliceDeque<_> = v.iter().cloned().collect();
        let u: Vec<_> = deq.iter().cloned().collect();
        assert_eq!(u, v);

        let seq = (0..).step_by(2).take(256);
        let deq: SliceDeque<_> = seq.collect();
        for (i, &x) in deq.iter().enumerate() {
            assert_eq!(2 * i, x);
        }
        assert_eq!(deq.len(), 256);
    }

    #[test]
    fn vecdeque_clone() {
        let mut d = SliceDeque::new();
        d.push_front(17);
        d.push_front(42);
        d.push_back(137);
        d.push_back(137);
        assert_eq!(d.len(), 4);
        let mut e = d.clone();
        assert_eq!(e.len(), 4);
        while !d.is_empty() {
            assert_eq!(d.pop_back(), e.pop_back());
        }
        assert_eq!(d.len(), 0);
        assert_eq!(e.len(), 0);
    }

    #[test]
    fn vecdeque_eq() {
        let mut d = SliceDeque::new();
        assert!(d == SliceDeque::with_capacity(0));
        d.push_front(137);
        d.push_front(17);
        d.push_front(42);
        d.push_back(137);
        let mut e = SliceDeque::with_capacity(0);
        e.push_back(42);
        e.push_back(17);
        e.push_back(137);
        e.push_back(137);
        assert!(&e == &d);
        e.pop_back();
        e.push_back(0);
        assert!(e != d);
        e.clear();
        assert!(e == SliceDeque::new());
    }

    #[test]
    fn vecdeque_partial_eq_array() {
        let d = SliceDeque::<char>::new();
        assert!(d == []);

        let mut d = SliceDeque::new();
        d.push_front('a');
        assert!(d == ['a']);

        let mut d = SliceDeque::new();
        d.push_back('a');
        assert!(d == ['a']);

        let mut d = SliceDeque::new();
        d.push_back('a');
        d.push_back('b');
        assert!(d == ['a', 'b']);
    }

    #[test]
    fn vecdeque_hash() {
        let mut x = SliceDeque::new();
        let mut y = SliceDeque::new();

        x.push_back(1);
        x.push_back(2);
        x.push_back(3);

        y.push_back(0);
        y.push_back(1);
        y.pop_front();
        y.push_back(2);
        y.push_back(3);

        assert!(hash(&x) == hash(&y));
    }

    #[test]
    fn vecdeque_hash_after_rotation() {
        // test that two deques hash equal even if elements are laid out
        // differently
        let len = 28;
        let mut ring: SliceDeque<i32> = (0..len as i32).collect();
        let orig = ring.clone();
        for _ in 0..ring.capacity() {
            // shift values 1 step to the right by pop, sub one, push
            ring.pop_front();
            for elt in &mut ring {
                *elt -= 1;
            }
            ring.push_back(len - 1);
            assert_eq!(hash(&orig), hash(&ring));
            assert_eq!(orig, ring);
            assert_eq!(ring, orig);
        }
    }

    #[test]
    fn vecdeque_eq_after_rotation() {
        // test that two deques are equal even if elements are laid out
        // differently
        let len = 28;
        let mut ring: SliceDeque<i32> = (0..len as i32).collect();
        let mut shifted = ring.clone();
        for _ in 0..10 {
            // shift values 1 step to the right by pop, sub one, push
            ring.pop_front();
            for elt in &mut ring {
                *elt -= 1;
            }
            ring.push_back(len - 1);
        }

        // try every shift
        for _ in 0..shifted.capacity() {
            shifted.pop_front();
            for elt in &mut shifted {
                *elt -= 1;
            }
            shifted.push_back(len - 1);
            assert_eq!(shifted, ring);
            assert_eq!(ring, shifted);
        }
    }

    #[test]
    fn vecdeque_ord() {
        let x = SliceDeque::new();
        let mut y = SliceDeque::new();
        y.push_back(1);
        y.push_back(2);
        y.push_back(3);
        assert!(x < y);
        assert!(y > x);
        assert!(x <= x);
        assert!(x >= x);
    }

    #[test]
    fn vecdeque_show() {
        let ringbuf: SliceDeque<_> = (0..10).collect();
        assert_eq!(format!("{:?}", ringbuf), "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");

        let ringbuf: SliceDeque<_> = vec!["just", "one", "test", "more"]
            .iter()
            .cloned()
            .collect();
        assert_eq!(
            format!("{:?}", ringbuf),
            "[\"just\", \"one\", \"test\", \"more\"]"
        );
    }

    #[test]
    fn vecdeque_drop_zst() {
        static mut DROPS: i32 = 0;
        struct Elem;
        impl Drop for Elem {
            fn drop(&mut self) {
                unsafe {
                    DROPS += 1;
                }
            }
        }

        let mut ring = SliceDeque::new();
        ring.push_back(Elem);
        ring.push_front(Elem);
        ring.push_back(Elem);
        ring.push_front(Elem);
        mem::drop(ring);

        assert_eq!(unsafe { DROPS }, 4);
    }

    #[test]
    fn vecdeque_drop() {
        static mut DROPS: i32 = 0;
        #[derive(Clone)]
        struct Elem(i32);
        impl Drop for Elem {
            fn drop(&mut self) {
                unsafe {
                    DROPS += 1;
                }
            }
        }

        let mut ring = SliceDeque::new();
        ring.push_back(Elem(0));
        ring.push_front(Elem(1));
        ring.push_back(Elem(2));
        ring.push_front(Elem(3));
        mem::drop(ring);

        assert_eq!(unsafe { DROPS }, 4);
    }

    #[test]
    fn vecdeque_drop_with_pop_zst() {
        static mut DROPS: i32 = 0;
        struct Elem;
        impl Drop for Elem {
            fn drop(&mut self) {
                unsafe {
                    DROPS += 1;
                }
            }
        }

        let mut ring = SliceDeque::new();
        ring.push_back(Elem);
        ring.push_front(Elem);
        ring.push_back(Elem);
        ring.push_front(Elem);

        mem::drop(ring.pop_back());
        mem::drop(ring.pop_front());
        assert_eq!(unsafe { DROPS }, 2);

        mem::drop(ring);
        assert_eq!(unsafe { DROPS }, 4);
    }

    #[test]
    fn vecdeque_drop_with_pop() {
        static mut DROPS: i32 = 0;
        struct Elem(i32);
        impl Drop for Elem {
            fn drop(&mut self) {
                unsafe {
                    DROPS += 1;
                }
            }
        }

        let mut ring = SliceDeque::new();
        ring.push_back(Elem(0));
        ring.push_front(Elem(0));
        ring.push_back(Elem(0));
        ring.push_front(Elem(0));

        mem::drop(ring.pop_back());
        mem::drop(ring.pop_front());
        assert_eq!(unsafe { DROPS }, 2);

        mem::drop(ring);
        assert_eq!(unsafe { DROPS }, 4);
    }

    #[test]
    fn vecdeque_drop_clear_zst() {
        static mut DROPS: i32 = 0;
        struct Elem;
        impl Drop for Elem {
            fn drop(&mut self) {
                unsafe {
                    DROPS += 1;
                }
            }
        }

        let mut ring = SliceDeque::new();
        ring.push_back(Elem);
        ring.push_front(Elem);
        ring.push_back(Elem);
        ring.push_front(Elem);
        ring.clear();
        assert_eq!(unsafe { DROPS }, 4);

        mem::drop(ring);
        assert_eq!(unsafe { DROPS }, 4);
    }

    #[test]
    fn vecdeque_drop_clear() {
        static mut DROPS: i32 = 0;
        struct Elem(i32);
        impl Drop for Elem {
            fn drop(&mut self) {
                unsafe {
                    DROPS += 1;
                }
            }
        }

        let mut ring = SliceDeque::new();
        ring.push_back(Elem(0));
        ring.push_front(Elem(0));
        ring.push_back(Elem(0));
        ring.push_front(Elem(0));
        ring.clear();
        assert_eq!(unsafe { DROPS }, 4);

        mem::drop(ring);
        assert_eq!(unsafe { DROPS }, 4);
    }

    #[test]
    fn vecdeque_reserve_grow() {
        // test growth path A
        // [T o o H] -> [T o o H . . . . ]
        let mut ring = SliceDeque::with_capacity(4);
        for i in 0..3 {
            ring.push_back(i);
        }
        ring.reserve(7);
        for i in 0..3 {
            assert_eq!(ring.pop_front(), Some(i));
        }

        // test growth path B
        // [H T o o] -> [. T o o H . . . ]
        let mut ring = SliceDeque::with_capacity(4);
        for i in 0..1 {
            ring.push_back(i);
            assert_eq!(ring.pop_front(), Some(i));
        }
        for i in 0..3 {
            ring.push_back(i);
        }
        ring.reserve(7);
        for i in 0..3 {
            assert_eq!(ring.pop_front(), Some(i));
        }

        // test growth path C
        // [o o H T] -> [o o H . . . . T ]
        let mut ring = SliceDeque::with_capacity(4);
        for i in 0..3 {
            ring.push_back(i);
            assert_eq!(ring.pop_front(), Some(i));
        }
        for i in 0..3 {
            ring.push_back(i);
        }
        ring.reserve(7);
        for i in 0..3 {
            assert_eq!(ring.pop_front(), Some(i));
        }
    }

    #[test]
    fn vecdeque_get() {
        let mut ring = SliceDeque::new();
        ring.push_back(0);
        assert_eq!(ring.get(0), Some(&0));
        assert_eq!(ring.get(1), None);

        ring.push_back(1);
        assert_eq!(ring.get(0), Some(&0));
        assert_eq!(ring.get(1), Some(&1));
        assert_eq!(ring.get(2), None);

        ring.push_back(2);
        assert_eq!(ring.get(0), Some(&0));
        assert_eq!(ring.get(1), Some(&1));
        assert_eq!(ring.get(2), Some(&2));
        assert_eq!(ring.get(3), None);

        assert_eq!(ring.pop_front(), Some(0));
        assert_eq!(ring.get(0), Some(&1));
        assert_eq!(ring.get(1), Some(&2));
        assert_eq!(ring.get(2), None);

        assert_eq!(ring.pop_front(), Some(1));
        assert_eq!(ring.get(0), Some(&2));
        assert_eq!(ring.get(1), None);

        assert_eq!(ring.pop_front(), Some(2));
        assert_eq!(ring.get(0), None);
        assert_eq!(ring.get(1), None);
    }

    #[test]
    fn vecdeque_get_mut() {
        let mut ring = SliceDeque::new();
        for i in 0..3 {
            ring.push_back(i);
        }

        match ring.get_mut(1) {
            Some(x) => *x = -1,
            None => (),
        };

        assert_eq!(ring.get_mut(0), Some(&mut 0));
        assert_eq!(ring.get_mut(1), Some(&mut -1));
        assert_eq!(ring.get_mut(2), Some(&mut 2));
        assert_eq!(ring.get_mut(3), None);

        assert_eq!(ring.pop_front(), Some(0));
        assert_eq!(ring.get_mut(0), Some(&mut -1));
        assert_eq!(ring.get_mut(1), Some(&mut 2));
        assert_eq!(ring.get_mut(2), None);
    }

    #[test]
    fn vecdeque_front() {
        let mut ring = SliceDeque::new();
        ring.push_back(10);
        ring.push_back(20);
        assert_eq!(ring.front(), Some(&10));
        ring.pop_front();
        assert_eq!(ring.front(), Some(&20));
        ring.pop_front();
        assert_eq!(ring.front(), None);
    }

    #[test]
    fn vecdeque_as_slices() {
        let mut ring: SliceDeque<i32> = SliceDeque::with_capacity(127);
        let cap = ring.capacity() as i32;
        let first = cap / 2;
        let last = cap - first;
        for i in 0..first {
            ring.push_back(i);

            let (left, right) = ring.as_slices();
            let expected: Vec<_> = (0..i + 1).collect();
            assert_eq!(left, &expected[..]);
            assert_eq!(right, []);
        }

        for j in -last..0 {
            ring.push_front(j);
            let (left, right) = ring.as_slices();
            let mut expected_left: Vec<_> = (-last..j + 1).rev().collect();
            expected_left.extend(0..first);
            assert_eq!(left, &expected_left[..]);
            assert_eq!(right, []);
        }

        assert_eq!(ring.len() as i32, cap);
        assert_eq!(ring.capacity() as i32, cap);
    }

    #[test]
    fn vecdeque_as_mut_slices() {
        let mut ring: SliceDeque<i32> = SliceDeque::with_capacity(127);
        let cap = ring.capacity() as i32;
        let first = cap / 2;
        let last = cap - first;
        for i in 0..first {
            ring.push_back(i);

            let (left, right) = ring.as_mut_slices();
            let expected: Vec<_> = (0..i + 1).collect();
            assert_eq!(left, &expected[..]);
            assert_eq!(right, []);
        }

        for j in -last..0 {
            ring.push_front(j);
            let (left, right) = ring.as_mut_slices();
            let mut expected_left: Vec<_> = (-last..j + 1).rev().collect();
            expected_left.extend(0..first);
            assert_eq!(left, &expected_left[..]);
            assert_eq!(right, []);
        }

        assert_eq!(ring.len() as i32, cap);
        assert_eq!(ring.capacity() as i32, cap);
    }

    #[test]
    fn vecdeque_append() {
        let mut a: SliceDeque<_> = vec![1, 2, 3].into_iter().collect();
        let mut b: SliceDeque<_> = vec![4, 5, 6].into_iter().collect();

        // normal append
        a.append(&mut b);
        assert_eq!(a.iter().cloned().collect::<Vec<_>>(), [1, 2, 3, 4, 5, 6]);
        assert_eq!(b.iter().cloned().collect::<Vec<_>>(), []);

        // append nothing to something
        a.append(&mut b);
        assert_eq!(a.iter().cloned().collect::<Vec<_>>(), [1, 2, 3, 4, 5, 6]);
        assert_eq!(b.iter().cloned().collect::<Vec<_>>(), []);

        // append something to nothing
        b.append(&mut a);
        assert_eq!(b.iter().cloned().collect::<Vec<_>>(), [1, 2, 3, 4, 5, 6]);
        assert_eq!(a.iter().cloned().collect::<Vec<_>>(), []);
    }

    #[test]
    fn vecdeque_retain() {
        let mut buf = SliceDeque::new();
        buf.extend(1..5);
        buf.retain(|&x| x % 2 == 0);
        let v: Vec<_> = buf.into_iter().collect();
        assert_eq!(&v[..], &[2, 4]);
    }

    #[test]
    fn vecdeque_extend_ref() {
        let mut v = SliceDeque::new();
        v.push_back(1);
        v.extend(&[2, 3, 4]);

        assert_eq!(v.len(), 4);
        assert_eq!(v[0], 1);
        assert_eq!(v[1], 2);
        assert_eq!(v[2], 3);
        assert_eq!(v[3], 4);

        let mut w = SliceDeque::new();
        w.push_back(5);
        w.push_back(6);
        v.extend(&w);

        assert_eq!(v.len(), 6);
        assert_eq!(v[0], 1);
        assert_eq!(v[1], 2);
        assert_eq!(v[2], 3);
        assert_eq!(v[3], 4);
        assert_eq!(v[4], 5);
        assert_eq!(v[5], 6);
    }

    #[test]
    fn vecdeque_contains() {
        let mut v = SliceDeque::new();
        v.extend(&[2, 3, 4]);

        assert!(v.contains(&3));
        assert!(!v.contains(&1));

        v.clear();

        assert!(!v.contains(&3));
    }

    /* TODO: covariance
    #[allow(dead_code)]
    fn assert_covariance() {
        fn drain<'new>(d: Drain<'static, &'static str>) -> Drain<'new, &'new str> {
            d
        }
    }
        */

    #[cfg(feature = "unstable")]
    #[test]
    fn vecdeque_is_empty() {
        let mut v = SliceDeque::<i32>::new();
        assert!(v.is_empty());
        assert!(v.iter().is_empty());
        assert!(v.iter_mut().is_empty());
        v.extend(&[2, 3, 4]);
        assert!(!v.is_empty());
        assert!(!v.iter().is_empty());
        assert!(!v.iter_mut().is_empty());
        while let Some(_) = v.pop_front() {
            assert_eq!(v.is_empty(), v.len() == 0);
            assert_eq!(v.iter().is_empty(), v.iter().len() == 0);
            assert_eq!(v.iter_mut().is_empty(), v.iter_mut().len() == 0);
        }
        assert!(v.is_empty());
        assert!(v.iter().is_empty());
        assert!(v.iter_mut().is_empty());
        assert!(v.into_iter().is_empty());
    }

    #[cfg(all(feature = "bytes_buf", feature = "use_std"))]
    #[test]
    fn bytes_bufmut() {
        use bytes::{BigEndian, BufMut};
        use std::io::Write;

        {
            let mut buf = sdeq![];

            buf.put("hello world");

            assert_eq!(buf, b"hello world");
        }
        {
            let mut buf = SliceDeque::with_capacity(16);

            unsafe {
                buf.bytes_mut()[0] = b'h';
                buf.bytes_mut()[1] = b'e';

                buf.advance_mut(2);

                buf.bytes_mut()[0] = b'l';
                buf.bytes_mut()[1..3].copy_from_slice(b"lo");

                buf.advance_mut(3);
            }

            assert_eq!(5, buf.len());
            assert_eq!(buf, b"hello");
        }
        {
            let mut buf = SliceDeque::with_capacity(16);

            unsafe {
                buf.bytes_mut()[0] = b'h';
                buf.bytes_mut()[1] = b'e';

                buf.advance_mut(2);

                buf.bytes_mut()[0] = b'l';
                buf.bytes_mut()[1..3].copy_from_slice(b"lo");

                buf.advance_mut(3);
            }

            assert_eq!(5, buf.len());
            assert_eq!(buf, b"hello");
        }
        {
            let mut buf = sdeq![];

            buf.put(b'h');
            buf.put(&b"ello"[..]);
            buf.put(" world");

            assert_eq!(buf, b"hello world");
        }
        {
            let mut buf = sdeq![];
            buf.put_u8(0x01);
            assert_eq!(buf, b"\x01");
        }
        {
            let mut buf = sdeq![];
            buf.put_i8(0x01);
            assert_eq!(buf, b"\x01");
        }
        {
            let mut buf = sdeq![];
            buf.put_u16::<BigEndian>(0x0809);
            assert_eq!(buf, b"\x08\x09");
        }
        {
            let mut buf = sdeq![];

            {
                let reference = buf.by_ref();

                // Adapt reference to `std::io::Write`.
                let mut writer = reference.writer();

                // Use the buffer as a writter
                Write::write(&mut writer, &b"hello world"[..]).unwrap();
            } // drop our &mut reference so that we can use `buf` again

            assert_eq!(buf, &b"hello world"[..]);
        }
        {
            let mut buf = sdeq![].writer();

            let num = buf.write(&b"hello world"[..]).unwrap();
            assert_eq!(11, num);

            let buf = buf.into_inner();

            assert_eq!(*buf, b"hello world"[..]);
        }
    }

    #[cfg(all(feature = "bytes_buf", feature = "use_std"))]
    #[test]
    fn bytes_buf() {
        {
            use bytes::{Buf, Bytes, IntoBuf};

            let buf = Bytes::from(&b"hello world"[..]).into_buf();
            let vec: SliceDeque<u8> = buf.collect();

            assert_eq!(vec, &b"hello world"[..]);
        }
        {
            use bytes::{Buf, BufMut};
            use std::io::Cursor;

            let mut buf = Cursor::new("hello world").take(5);
            let mut dst = sdeq![];

            dst.put(&mut buf);
            assert_eq!(dst, b"hello");

            let mut buf = buf.into_inner();
            dst.clear();
            dst.put(&mut buf);
            assert_eq!(dst, b" world");
        }
        {
            use bytes::{Buf, BufMut};
            use std::io::Cursor;

            let mut buf = Cursor::new("hello world");
            let mut dst = sdeq![];

            {
                let reference = buf.by_ref();
                dst.put(&mut reference.take(5));
                assert_eq!(dst, b"hello");
            } // drop our &mut reference so we can use `buf` again

            dst.clear();
            dst.put(&mut buf);
            assert_eq!(dst, b" world");
        }
    }

    #[test]
    fn issue_42() {
        // https://github.com/gnzlbg/slice_deque/issues/42
        let page_size = crate::mirrored::allocation_granularity();
        let mut deque = SliceDeque::<u8>::with_capacity(page_size);
        let page_size = page_size as isize;

        let slice = unsafe {
            deque.move_tail(page_size);
            deque.move_head(page_size / 100 * 99);
            deque.move_tail(page_size / 100 * 99);
            deque.move_head(page_size / 100 * 99);
            deque.tail_head_slice()
        };

        for i in 0..slice.len() {
            // segfault:
            slice[i] = 0;
        }
    }

    #[test]
    fn issue_45() {
        // https://github.com/gnzlbg/slice_deque/issues/45
        fn refill(buf: &mut SliceDeque<u8>) {
            let data = [0u8; MAX_SAMPLES_PER_FRAME * 5];
            buf.extend(data.iter());
        }

        const MAX_SAMPLES_PER_FRAME: usize = 1152 * 2;
        const BUFFER_SIZE: usize = MAX_SAMPLES_PER_FRAME * 15;
        const REFILL_TRIGGER: usize = MAX_SAMPLES_PER_FRAME * 8;

        let mut buf = SliceDeque::with_capacity(BUFFER_SIZE);
        for _ in 0..10_000 {
            if buf.len() < REFILL_TRIGGER {
                refill(&mut buf);
            }

            let cur_len = buf.len();
            buf.truncate_front(cur_len - 10);
        }
    }

    #[test]
    fn issue_47() {
        let page_size = crate::mirrored::allocation_granularity();
        let mut sdq = SliceDeque::<u8>::new();
        let vec = vec![0_u8; page_size + 1];
        sdq.extend(vec);
    }

    #[test]
    fn issue_50() {
        use std::fs::File;
        use std::io::Write;
        use std::path::Path;

        let out_buffer = SliceDeque::new();

        let p = if cfg!(target_os = "windows") {
            "slice_deque_test"
        } else {
            "/tmp/slice_deque_test"
        };

        let mut out_file = File::create(Path::new(p)).unwrap();
        let res = out_file.write(&out_buffer[..]);
        println!("Result was {:?}", res);
        println!("Buffer size: {}", out_buffer.len());
        println!("Address of buffer was: {:?}", out_buffer.as_ptr());
    }

    #[test]
    fn empty_ptr() {
        {
            let sdeq = SliceDeque::<i8>::new();
            let v = Vec::<i8>::new();
            assert_eq!(sdeq.as_ptr() as usize, mem::align_of::<i8>());
            assert_eq!(v.as_ptr() as usize, mem::align_of::<i8>());
        }
        {
            let sdeq = SliceDeque::<i16>::new();
            let v = Vec::<i16>::new();
            assert_eq!(sdeq.as_ptr() as usize, mem::align_of::<i16>());
            assert_eq!(v.as_ptr() as usize, mem::align_of::<i16>());
        }
        {
            let sdeq = SliceDeque::<i32>::new();
            let v = Vec::<i32>::new();
            assert_eq!(sdeq.as_ptr() as usize, mem::align_of::<i32>());
            assert_eq!(v.as_ptr() as usize, mem::align_of::<i32>());
        }
        {
            let sdeq = SliceDeque::<i64>::new();
            let v = Vec::<i64>::new();
            assert_eq!(sdeq.as_ptr() as usize, mem::align_of::<i64>());
            assert_eq!(v.as_ptr() as usize, mem::align_of::<i64>());
        }
        {
            #[repr(align(32))]
            struct Foo(i8);
            let sdeq = SliceDeque::<Foo>::new();
            let v = Vec::<Foo>::new();
            assert_eq!(sdeq.as_ptr() as usize, mem::align_of::<Foo>());
            assert_eq!(v.as_ptr() as usize, mem::align_of::<Foo>());
        }
    }

    #[test]
    fn issue_57() {
        const C: [i16; 3] = [42; 3];

        let mut deque = SliceDeque::new();

        for _ in 0..918 {
            deque.push_front(C);
        }

        for _ in 0..237 {
            assert_eq!(deque.pop_front(), Some(C));
            assert!(!deque.is_empty());
            assert_eq!(*deque.back().unwrap(), C);
        }
    }

    #[test]
    fn drop_count() {
        #[repr(C)]
        struct Foo(*mut usize);
        impl Drop for Foo {
            fn drop(&mut self) {
                unsafe {
                    *self.0 += 1;
                }
            }
        }

        let mut count = 0_usize;
        {
            let mut deque = SliceDeque::new();
            for _ in 0..10 {
                deque.push_back(Foo(&mut count as *mut _));
                deque.pop_front();
            }
        }
        assert_eq!(count, 10);
    }

    #[test]
    fn non_fitting_elem_type() {
        // This type does not perfectly fit in an "allocation granularity"
        // unit (e.g. a memory page). A new type has always (1, 2, 3),
        // while free-ing the type writes (4, 5, 6) to the memory.
        #[repr(C)]
        struct NonFitting(u8, u8, u8);
        impl NonFitting {
            fn new() -> Self {
                Self(1, 2, 3)
            }
            fn valid(&self) -> bool {
                //dbg!("valid", self as *const Self as usize);
                if self.0 == 1 && self.1 == 2 && self.2 == 3 {
                    true
                } else {
                    dbg!((self.0, self.1, self.2));
                    false
                }
            }
        }

        impl Drop for NonFitting {
            fn drop(&mut self) {
                //dbg!(("drop", self as *mut Self as usize));
                unsafe {
                    let ptr = self as *mut Self as *mut u8;
                    ptr.write_volatile(4);
                    ptr.add(1).write_volatile(5);
                    ptr.add(2).write_volatile(6);
                }
            }
        }

        let page_size = crate::mirrored::allocation_granularity();
        let elem_size = mem::size_of::<NonFitting>();

        assert!(elem_size % page_size != 0);
        let no_elements_that_fit = page_size / elem_size;

        // Create a deque, which has a single element
        // right at the end of the first page.
        //
        // We do that by shifting a single element till the end, which can be
        // achieved by pushing an element and while popping the previous one.
        let mut deque = SliceDeque::new();
        deque.push_back(NonFitting::new());

        for i in 0..no_elements_that_fit {
            if i > no_elements_that_fit - 2 {
                //dbg!((i, deque.len()));
            }
            //dbg!(("push_back", deque.len()));
            deque.push_back(NonFitting::new());
            //dbg!(("pop_front", deque.len()));
            deque.truncate_front(1);
            assert_eq!(deque.len(), 1);
            assert!(deque[0].valid());
        }
    }

    #[test]
    fn issue_57_2() {
        let mut deque = SliceDeque::new();
        for _ in 0..30_000 {
            deque.push_back(String::from("test"));
            if deque.len() == 8 {
                deque.pop_front();
            }
        }
    }

    #[test]
    fn zst() {
        struct A;
        let mut s = SliceDeque::<A>::new();
        assert_eq!(s.len(), 0);
        assert_eq!(s.capacity(), isize::max_value() as usize);

        for _ in 0..10 {
            s.push_back(A);
        }
        assert_eq!(s.len(), 10);
    }

    #[test]
    fn sync() {
        fn assert_sync<T: Sync>(_: T) {}

        struct S(*mut u8);
        unsafe impl Sync for S {}
        let x = SliceDeque::<S>::new();
        assert_sync(x);
    }

    #[test]
    fn send() {
        fn assert_send<T: Send>(_: T) {}

        struct S(*mut u8);
        unsafe impl Send for S {}
        let x = SliceDeque::<S>::new();
        assert_send(x);
    }
}