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
//! 使用可增长的环形缓冲区实现的双端队列。
//!
//! 此队列具有 *O*(1) 容器两端的摊销插入和删除。
//! 它还具有像 vector 一样的 *O*(1) 索引。
//! 所包含的元素不需要是可复制的,并且如果所包含的类型是可发送的,则队列将是可发送的。
//!
#![stable(feature = "rust1", since = "1.0.0")]
use core::cmp::{self, Ordering};
use core::fmt;
use core::hash::{Hash, Hasher};
use core::iter::{repeat_with, FromIterator};
use core::marker::PhantomData;
use core::mem::{self, ManuallyDrop};
use core::ops::{Index, IndexMut, Range, RangeBounds};
use core::ptr::{self, NonNull};
use core::slice;
use crate::alloc::{Allocator, Global};
use crate::collections::TryReserveError;
use crate::collections::TryReserveErrorKind;
use crate::raw_vec::RawVec;
use crate::vec::Vec;
#[macro_use]
mod macros;
#[stable(feature = "drain", since = "1.6.0")]
pub use self::drain::Drain;
mod drain;
#[stable(feature = "rust1", since = "1.0.0")]
pub use self::iter_mut::IterMut;
mod iter_mut;
#[stable(feature = "rust1", since = "1.0.0")]
pub use self::into_iter::IntoIter;
mod into_iter;
#[stable(feature = "rust1", since = "1.0.0")]
pub use self::iter::Iter;
mod iter;
use self::pair_slices::PairSlices;
mod pair_slices;
use self::ring_slices::RingSlices;
mod ring_slices;
#[cfg(test)]
mod tests;
const INITIAL_CAPACITY: usize = 7; // 2^3 - 1
const MINIMUM_CAPACITY: usize = 1; // 2 - 1
const MAXIMUM_ZST_CAPACITY: usize = 1 << (usize::BITS - 1); // 可能的最大两倍
/// 使用可增长的环形缓冲区实现的双端队列。
///
/// "default" 作为队列的这种用法是使用 [`push_back`] 添加到队列,使用 [`pop_front`] 从队列中删除。
///
/// [`extend`] 和 [`append`] 以这种方式推到后面,并从前到后迭代 `VecDeque`。
///
/// 可以从数组初始化具有已知项列表的 `VecDeque`:
///
/// ```
/// use std::collections::VecDeque;
///
/// let deq = VecDeque::from([-1, 0, 1]);
/// ```
///
/// 由于 `VecDeque` 是环形缓冲区,因此它的元素在内存中不一定是连续的。
/// 如果要以单个切片的形式访问元素 (例如为了进行有效的排序),则可以使用 [`make_contiguous`]。
/// 它旋转 `VecDeque`,以使其元素不环绕,并向当前连续的元素序列返回可变切片。
///
/// [`push_back`]: VecDeque::push_back
/// [`pop_front`]: VecDeque::pop_front
/// [`extend`]: VecDeque::extend
/// [`append`]: VecDeque::append
/// [`make_contiguous`]: VecDeque::make_contiguous
///
///
///
#[cfg_attr(not(test), rustc_diagnostic_item = "VecDeque")]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_insignificant_dtor]
pub struct VecDeque<
T,
#[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
> {
// tail 和 head 是指向缓冲区的指针。
// Tail 总是指向可以读取的第一个元素,Head 总是指向应该写入数据的位置。
//
// 如果 tail == head,则缓冲区为空。环形缓冲区的长度定义为两者之间的距离。
//
tail: usize,
head: usize,
buf: RawVec<T, A>,
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Clone, A: Allocator + Clone> Clone for VecDeque<T, A> {
fn clone(&self) -> Self {
let mut deq = Self::with_capacity_in(self.len(), self.allocator().clone());
deq.extend(self.iter().cloned());
deq
}
fn clone_from(&mut self, other: &Self) {
self.truncate(other.len());
let mut iter = PairSlices::from(self, other);
while let Some((dst, src)) = iter.next() {
dst.clone_from_slice(&src);
}
if iter.has_remainder() {
for remainder in iter.remainder() {
self.extend(remainder.iter().cloned());
}
}
}
}
#[stable(feature = "rust1", since = "1.0.0")]
unsafe impl<#[may_dangle] T, A: Allocator> Drop for VecDeque<T, A> {
fn drop(&mut self) {
/// 当切片被丢弃时 (正常情况下或在展开期间),对切片中的所有项运行析构函数。
///
struct Dropper<'a, T>(&'a mut [T]);
impl<'a, T> Drop for Dropper<'a, T> {
fn drop(&mut self) {
unsafe {
ptr::drop_in_place(self.0);
}
}
}
let (front, back) = self.as_mut_slices();
unsafe {
let _back_dropper = Dropper(back);
// use drop for [T]
ptr::drop_in_place(front);
}
// RawVec 处理重新分配
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Default for VecDeque<T> {
/// 创建一个空的 `VecDeque<T>`。
#[inline]
fn default() -> VecDeque<T> {
VecDeque::new()
}
}
impl<T, A: Allocator> VecDeque<T, A> {
/// 稍微方便一点
#[inline]
fn ptr(&self) -> *mut T {
self.buf.ptr()
}
/// 稍微方便一点
#[inline]
fn cap(&self) -> usize {
if mem::size_of::<T>() == 0 {
// 对于零大小类型,我们始终处于最大容量
MAXIMUM_ZST_CAPACITY
} else {
self.buf.capacity()
}
}
/// 将 ptr 变成切片
#[inline]
unsafe fn buffer_as_slice(&self) -> &[T] {
unsafe { slice::from_raw_parts(self.ptr(), self.cap()) }
}
/// 将 ptr 变成 mut 切片
#[inline]
unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T] {
unsafe { slice::from_raw_parts_mut(self.ptr(), self.cap()) }
}
/// 将元素移出缓冲区
#[inline]
unsafe fn buffer_read(&mut self, off: usize) -> T {
unsafe { ptr::read(self.ptr().add(off)) }
}
/// 将元素写入缓冲区,然后将其移动。
#[inline]
unsafe fn buffer_write(&mut self, off: usize, value: T) {
unsafe {
ptr::write(self.ptr().add(off), value);
}
}
/// 如果缓冲区已满,则返回 `true`。
#[inline]
fn is_full(&self) -> bool {
self.cap() - self.len() == 1
}
/// 返回给定逻辑元素索引的底层缓冲区中的索引。
///
#[inline]
fn wrap_index(&self, idx: usize) -> usize {
wrap_index(idx, self.cap())
}
/// 返回给定逻辑元素索引 + 加数的底层缓冲区中的索引。
///
#[inline]
fn wrap_add(&self, idx: usize, addend: usize) -> usize {
wrap_index(idx.wrapping_add(addend), self.cap())
}
/// 返回给定逻辑元素索引 - 减数的底层缓冲区中的索引。
///
#[inline]
fn wrap_sub(&self, idx: usize, subtrahend: usize) -> usize {
wrap_index(idx.wrapping_sub(subtrahend), self.cap())
}
/// 将一个连续的 len 长的内存块从 src 复制到 dst
#[inline]
unsafe fn copy(&self, dst: usize, src: usize, len: usize) {
debug_assert!(
dst + len <= self.cap(),
"cpy dst={} src={} len={} cap={}",
dst,
src,
len,
self.cap()
);
debug_assert!(
src + len <= self.cap(),
"cpy dst={} src={} len={} cap={}",
dst,
src,
len,
self.cap()
);
unsafe {
ptr::copy(self.ptr().add(src), self.ptr().add(dst), len);
}
}
/// 将一个连续的 len 长的内存块从 src 复制到 dst
#[inline]
unsafe fn copy_nonoverlapping(&self, dst: usize, src: usize, len: usize) {
debug_assert!(
dst + len <= self.cap(),
"cno dst={} src={} len={} cap={}",
dst,
src,
len,
self.cap()
);
debug_assert!(
src + len <= self.cap(),
"cno dst={} src={} len={} cap={}",
dst,
src,
len,
self.cap()
);
unsafe {
ptr::copy_nonoverlapping(self.ptr().add(src), self.ptr().add(dst), len);
}
}
/// 从 src 复制一个长度为 len 的潜在包装内存块到 dest。
/// (abs(dst - src) + len) 不得大于 cap() (src 与 dest 之间最多应有一个连续的重叠区域)。
///
unsafe fn wrap_copy(&self, dst: usize, src: usize, len: usize) {
#[allow(dead_code)]
fn diff(a: usize, b: usize) -> usize {
if a <= b { b - a } else { a - b }
}
debug_assert!(
cmp::min(diff(dst, src), self.cap() - diff(dst, src)) + len <= self.cap(),
"wrc dst={} src={} len={} cap={}",
dst,
src,
len,
self.cap()
);
if src == dst || len == 0 {
return;
}
let dst_after_src = self.wrap_sub(dst, src) < len;
let src_pre_wrap_len = self.cap() - src;
let dst_pre_wrap_len = self.cap() - dst;
let src_wraps = src_pre_wrap_len < len;
let dst_wraps = dst_pre_wrap_len < len;
match (dst_after_src, src_wraps, dst_wraps) {
(_, false, false) => {
// src 不换行,dst 不换行
//
//
// S . . .
// 1 [_ _ A A B B C C _]
// 2 [_ _ A A A A B B _] D . . .
//
unsafe {
self.copy(dst, src, len);
}
}
(false, false, true) => {
// src 之前的 dst,src 不环绕,dst 环绕
//
//
// S . . .
// 1 [A A B B _ _ _ C C]
// 2 [A A B B _ _ _ A A]
// 3 [B B B B _ _ _ A A] .. D .
//
unsafe {
self.copy(dst, src, dst_pre_wrap_len);
self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
}
}
(true, false, true) => {
// dst 之前的 src,src 不换行,dst 换行
//
//
// S . . .
// 1 [C C _ _ _ A A B B]
// 2 [B B _ _ _ A A B B]
// 3 [B B _ _ _ A A A A] .. D .
//
unsafe {
self.copy(0, src + dst_pre_wrap_len, len - dst_pre_wrap_len);
self.copy(dst, src, dst_pre_wrap_len);
}
}
(false, true, false) => {
// src 之前的 dst,src 换行,dst 不换行
//
//
// .. S .
// 1 [C C _ _ _ A A B B]
// 2 [C C _ _ _ B B B B]
// 3 [C C _ _ _ B B C C] D . . .
//
unsafe {
self.copy(dst, src, src_pre_wrap_len);
self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
}
}
(true, true, false) => {
// dst 之前的 src,src 换行,dst 不换行
//
//
// .. S .
// 1 [A A B B _ _ _ C C]
// 2 [A A A A _ _ _ C C]
// 3 [C C A A _ _ _ C C] D . . .
//
unsafe {
self.copy(dst + src_pre_wrap_len, 0, len - src_pre_wrap_len);
self.copy(dst, src, src_pre_wrap_len);
}
}
(false, true, true) => {
// src 之前的 dst,src 换行,dst 换行
//
//
// . .. S .
// 1 [A B C D _ E F G H]
// 2 [A B C D _ E G H H]
// 3 [A B C D _ E G H A]
// 4 [B C C D _ E G H A] .. D . .
//
debug_assert!(dst_pre_wrap_len > src_pre_wrap_len);
let delta = dst_pre_wrap_len - src_pre_wrap_len;
unsafe {
self.copy(dst, src, src_pre_wrap_len);
self.copy(dst + src_pre_wrap_len, 0, delta);
self.copy(0, delta, len - dst_pre_wrap_len);
}
}
(true, true, true) => {
// dst 之前的 src,src 换行,dst 换行
//
//
// .. S . .
// 1 [A B C D _ E F G H]
// 2 [A A B D _ E F G H]
// 3 [H A B D _ E F G H]
// 4 [H A B D _ E F F G] . .. D .
//
debug_assert!(src_pre_wrap_len > dst_pre_wrap_len);
let delta = src_pre_wrap_len - dst_pre_wrap_len;
unsafe {
self.copy(delta, 0, len - src_pre_wrap_len);
self.copy(0, self.cap() - delta, delta);
self.copy(dst, src, dst_pre_wrap_len);
}
}
}
}
/// 将所有值从 `src` 复制到 `dst`,并在需要时进行包装。
/// 假设容量足够。
#[inline]
unsafe fn copy_slice(&mut self, dst: usize, src: &[T]) {
debug_assert!(src.len() <= self.cap());
let head_room = self.cap() - dst;
if src.len() <= head_room {
unsafe {
ptr::copy_nonoverlapping(src.as_ptr(), self.ptr().add(dst), src.len());
}
} else {
let (left, right) = src.split_at(head_room);
unsafe {
ptr::copy_nonoverlapping(left.as_ptr(), self.ptr().add(dst), left.len());
ptr::copy_nonoverlapping(right.as_ptr(), self.ptr(), right.len());
}
}
}
/// 绕着 head 和 tail 进行处理,以处理我们刚刚重新分配的事实。
/// 不安全,因为它信任 old_capacity。
#[inline]
unsafe fn handle_capacity_increase(&mut self, old_capacity: usize) {
let new_capacity = self.cap();
// 移动环形缓冲区 TH 的最短连续部分
//
// [o o o o o o o . ]
// T H A [o o o o o o o . . . . . . . . . ] H T
// [o o . o o o o o ]
// T H B [. . . o o o o o o o . . . . . . ] H T
// [o o o o o . o o ]
// H T C [o o o o o . . . . . . . . . o o ]
//
//
//
//
//
if self.tail <= self.head {
// A Nop
//
} else if self.head < old_capacity - self.tail {
// B
unsafe {
self.copy_nonoverlapping(old_capacity, 0, self.head);
}
self.head += old_capacity;
debug_assert!(self.head > self.tail);
} else {
// C
let new_tail = new_capacity - (old_capacity - self.tail);
unsafe {
self.copy_nonoverlapping(new_tail, self.tail, old_capacity - self.tail);
}
self.tail = new_tail;
debug_assert!(self.head < self.tail);
}
debug_assert!(self.head < self.cap());
debug_assert!(self.tail < self.cap());
debug_assert!(self.cap().count_ones() == 1);
}
}
impl<T> VecDeque<T> {
/// 创建一个空的 `VecDeque`。
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let vector: VecDeque<u32> = VecDeque::new();
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use]
pub fn new() -> VecDeque<T> {
VecDeque::new_in(Global)
}
/// 创建一个空的 `VecDeque`,其中至少有 `capacity` 元素的空间。
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let vector: VecDeque<u32> = VecDeque::with_capacity(10);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use]
pub fn with_capacity(capacity: usize) -> VecDeque<T> {
Self::with_capacity_in(capacity, Global)
}
}
impl<T, A: Allocator> VecDeque<T, A> {
/// 创建一个空的 `VecDeque`。
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let vector: VecDeque<u32> = VecDeque::new();
/// ```
#[inline]
#[unstable(feature = "allocator_api", issue = "32838")]
pub fn new_in(alloc: A) -> VecDeque<T, A> {
VecDeque::with_capacity_in(INITIAL_CAPACITY, alloc)
}
/// 创建一个空的 `VecDeque`,其中至少有 `capacity` 元素的空间。
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let vector: VecDeque<u32> = VecDeque::with_capacity(10);
/// ```
#[unstable(feature = "allocator_api", issue = "32838")]
pub fn with_capacity_in(capacity: usize, alloc: A) -> VecDeque<T, A> {
assert!(capacity < 1_usize << usize::BITS - 1, "capacity overflow");
// +1,因为环形缓冲区始终将一个空间留空
let cap = cmp::max(capacity + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
VecDeque { tail: 0, head: 0, buf: RawVec::with_capacity_in(cap, alloc) }
}
/// 提供给定索引处元素的引用。
///
/// 索引为 0 的元素在队列的最前面。
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut buf = VecDeque::new();
/// buf.push_back(3);
/// buf.push_back(4);
/// buf.push_back(5);
/// assert_eq!(buf.get(1), Some(&4));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn get(&self, index: usize) -> Option<&T> {
if index < self.len() {
let idx = self.wrap_add(self.tail, index);
unsafe { Some(&*self.ptr().add(idx)) }
} else {
None
}
}
/// 提供给定索引处元素的可变引用。
///
/// 索引为 0 的元素在队列的最前面。
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut buf = VecDeque::new();
/// buf.push_back(3);
/// buf.push_back(4);
/// buf.push_back(5);
/// if let Some(elem) = buf.get_mut(1) {
/// *elem = 7;
/// }
///
/// assert_eq!(buf[1], 7);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
if index < self.len() {
let idx = self.wrap_add(self.tail, index);
unsafe { Some(&mut *self.ptr().add(idx)) }
} else {
None
}
}
/// 交换索引为 `i` 和 `j` 的元素。
///
/// `i` 和 `j` 可能是相等的。
///
/// 索引为 0 的元素在队列的最前面。
///
/// # Panics
///
/// 如果任一索引越界,就会出现 panics。
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut buf = VecDeque::new();
/// buf.push_back(3);
/// buf.push_back(4);
/// buf.push_back(5);
/// assert_eq!(buf, [3, 4, 5]);
/// buf.swap(0, 2);
/// assert_eq!(buf, [5, 4, 3]);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn swap(&mut self, i: usize, j: usize) {
assert!(i < self.len());
assert!(j < self.len());
let ri = self.wrap_add(self.tail, i);
let rj = self.wrap_add(self.tail, j);
unsafe { ptr::swap(self.ptr().add(ri), self.ptr().add(rj)) }
}
/// 返回 `VecDeque` 无需重新分配即可容纳的元素数。
///
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
/// assert!(buf.capacity() >= 10);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn capacity(&self) -> usize {
self.cap() - 1
}
/// 保留最小容量,以便在给定的 `VecDeque` 中精确插入 `additional` 个元素。
/// 如果容量已经足够,则不执行任何操作。
///
/// 请注意,分配器可能会给集合提供比其请求更多的空间。
/// 因此,不能依靠容量来精确地将其最小化。
/// 如果预计将来会插入,则最好使用 [`reserve`]。
///
/// # Panics
///
/// 如果新容量溢出 `usize`,就会出现 panics。
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
/// buf.reserve_exact(10);
/// assert!(buf.capacity() >= 11);
/// ```
///
/// [`reserve`]: VecDeque::reserve
#[stable(feature = "rust1", since = "1.0.0")]
pub fn reserve_exact(&mut self, additional: usize) {
self.reserve(additional);
}
/// 为给定的 `VecDeque` 至少保留 `additional` 个要插入的元素保留容量。
/// 该集合可以保留更多空间,以避免频繁的重新分配。
///
/// # Panics
///
/// 如果新容量溢出 `usize`,就会出现 panics。
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
/// buf.reserve(10);
/// assert!(buf.capacity() >= 11);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn reserve(&mut self, additional: usize) {
let old_cap = self.cap();
let used_cap = self.len() + 1;
let new_cap = used_cap
.checked_add(additional)
.and_then(|needed_cap| needed_cap.checked_next_power_of_two())
.expect("capacity overflow");
if new_cap > old_cap {
self.buf.reserve_exact(used_cap, new_cap - used_cap);
unsafe {
self.handle_capacity_increase(old_cap);
}
}
}
/// 尝试保留最小容量,以便在给定的 `VecDeque<T>` 中精确插入 `additional` 个元素。
///
/// 调用 `try_reserve_exact` 后,容量将大于或等于 `self.len() + additional`。
/// 如果容量已经足够,则不执行任何操作。
///
/// 请注意,分配器可能会给集合提供比其请求更多的空间。
/// 因此,不能依靠容量来精确地最小化。
/// 如果希望将来插入,则首选 [`try_reserve`]。
///
/// [`try_reserve`]: VecDeque::try_reserve
///
/// # Errors
///
/// 如果容量溢出 `usize`,或者分配器报告失败,则返回错误。
///
/// # Examples
///
/// ```
/// use std::collections::TryReserveError;
/// use std::collections::VecDeque;
///
/// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
/// let mut output = VecDeque::new();
///
/// // 预先保留内存,如果不能,则退出
/// output.try_reserve_exact(data.len())?;
///
/// // 现在我们知道这不能 OOM(Out-Of-Memory) 完成我们复杂的工作
/// output.extend(data.iter().map(|&val| {
/// val * 2 + 5 // 非常复杂
/// }));
///
/// Ok(output)
/// }
/// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
/// ```
///
#[stable(feature = "try_reserve", since = "1.57.0")]
pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
self.try_reserve(additional)
}
/// 尝试为给 `VecDeque<T>` 至少插入 `additional` 个元素保留容量。
/// 该集合可以保留更多空间,以避免频繁的重新分配。
/// 调用 `try_reserve` 后,容量将大于或等于 `self.len() + additional`。
/// 如果容量已经足够,则不执行任何操作。
///
/// # Errors
///
/// 如果容量溢出 `usize`,或者分配器报告失败,则返回错误。
///
/// # Examples
///
/// ```
/// use std::collections::TryReserveError;
/// use std::collections::VecDeque;
///
/// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
/// let mut output = VecDeque::new();
///
/// // 预先保留内存,如果不能,则退出
/// output.try_reserve(data.len())?;
///
/// // 现在我们知道在我们复杂的工作中这不能 OOM
/// output.extend(data.iter().map(|&val| {
/// val * 2 + 5 // 非常复杂
/// }));
///
/// Ok(output)
/// }
/// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
/// ```
///
///
#[stable(feature = "try_reserve", since = "1.57.0")]
pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
let old_cap = self.cap();
let used_cap = self.len() + 1;
let new_cap = used_cap
.checked_add(additional)
.and_then(|needed_cap| needed_cap.checked_next_power_of_two())
.ok_or(TryReserveErrorKind::CapacityOverflow)?;
if new_cap > old_cap {
self.buf.try_reserve_exact(used_cap, new_cap - used_cap)?;
unsafe {
self.handle_capacity_increase(old_cap);
}
}
Ok(())
}
/// 尽可能缩小 `VecDeque` 的容量。
///
/// 它将 drop 到尽可能接近长度的位置,但分配器仍可能通知 `VecDeque` 还有空间容纳更多的元素。
///
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut buf = VecDeque::with_capacity(15);
/// buf.extend(0..4);
/// assert_eq!(buf.capacity(), 15);
/// buf.shrink_to_fit();
/// assert!(buf.capacity() >= 4);
/// ```
#[stable(feature = "deque_extras_15", since = "1.5.0")]
pub fn shrink_to_fit(&mut self) {
self.shrink_to(0);
}
/// 降低 `VecDeque` 的容量。
///
/// 容量将至少保持与长度和提供的值一样大。
///
///
/// 如果当前容量小于下限,则为无操作。
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut buf = VecDeque::with_capacity(15);
/// buf.extend(0..4);
/// assert_eq!(buf.capacity(), 15);
/// buf.shrink_to(6);
/// assert!(buf.capacity() >= 6);
/// buf.shrink_to(0);
/// assert!(buf.capacity() >= 4);
/// ```
#[stable(feature = "shrink_to", since = "1.56.0")]
pub fn shrink_to(&mut self, min_capacity: usize) {
let min_capacity = cmp::min(min_capacity, self.capacity());
// 我们不必担心溢出,因为 `self.len()` 和 `self.capacity()` 都不可能是 `usize::MAX`。
// +1,因为环形缓冲区始终将一个空间留空。
let target_cap = cmp::max(cmp::max(min_capacity, self.len()) + 1, MINIMUM_CAPACITY + 1)
.next_power_of_two();
if target_cap < self.cap() {
// 有以下三种有趣的情况:
// 所有元素都超出期望的范围元素是连续的,并且头超出了期望的范围元素是不连续的,并且尾部超出了期望的范围
//
//
// 在其他所有时间,元素位置均不受影响。
//
// 指示应该移动顶部的元素。
//
let head_outside = self.head == 0 || self.head >= target_cap;
// 将元素移出所需范围 (位于 target_cap 之后的位置)
if self.tail >= target_cap && head_outside {
// T H
// [. . . . . . . . o o o o o o o . ]
// T H
// [o o o o o o o . ]
unsafe {
self.copy_nonoverlapping(0, self.tail, self.len());
}
self.head = self.len();
self.tail = 0;
} else if self.tail != 0 && self.tail < target_cap && head_outside {
// T H
// [. . . o o o o o o o . . . . . . ]
// H T
// [o o . o o o o o ]
let len = self.wrap_sub(self.head, target_cap);
unsafe {
self.copy_nonoverlapping(0, target_cap, len);
}
self.head = len;
debug_assert!(self.head < self.tail);
} else if self.tail >= target_cap {
// H T
// [o o o o o . . . . . . . . . o o ]
// H T
// [o o o o o . o o ]
debug_assert!(self.wrap_sub(self.head, 1) < target_cap);
let len = self.cap() - self.tail;
let new_tail = target_cap - len;
unsafe {
self.copy_nonoverlapping(new_tail, self.tail, len);
}
self.tail = new_tail;
debug_assert!(self.head < self.tail);
}
self.buf.shrink_to_fit(target_cap);
debug_assert!(self.head < self.cap());
debug_assert!(self.tail < self.cap());
debug_assert!(self.cap().count_ones() == 1);
}
}
/// 缩短 `VecDeque`,保留第一个 `len` 元素,然后丢弃其余的元素。
///
///
/// 如果 `len` 大于 `VecDeque' 的当前长度,则无效。
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut buf = VecDeque::new();
/// buf.push_back(5);
/// buf.push_back(10);
/// buf.push_back(15);
/// assert_eq!(buf, [5, 10, 15]);
/// buf.truncate(1);
/// assert_eq!(buf, [5]);
/// ```
///
#[stable(feature = "deque_extras", since = "1.16.0")]
pub fn truncate(&mut self, len: usize) {
/// 当切片被丢弃时 (正常情况下或在展开期间),对切片中的所有项运行析构函数。
///
struct Dropper<'a, T>(&'a mut [T]);
impl<'a, T> Drop for Dropper<'a, T> {
fn drop(&mut self) {
unsafe {
ptr::drop_in_place(self.0);
}
}
}
// 安全是因为:
//
// * 传递给 `drop_in_place` 的任何切片都是有效的; 第二种情况为 `len <= front.len()`,返回 `len > self.len()` 可确保第一种情况为 `begin <= back.len()`
//
// * VecDeque 的头部在调用 `drop_in_place` 之前已移动,因此如果 `drop_in_place` panics 没有两次删除任何值
//
//
unsafe {
if len > self.len() {
return;
}
let num_dropped = self.len() - len;
let (front, back) = self.as_mut_slices();
if len > front.len() {
let begin = len - front.len();
let drop_back = back.get_unchecked_mut(begin..) as *mut _;
self.head = self.wrap_sub(self.head, num_dropped);
ptr::drop_in_place(drop_back);
} else {
let drop_back = back as *mut _;
let drop_front = front.get_unchecked_mut(len..) as *mut _;
self.head = self.wrap_sub(self.head, num_dropped);
// 即使第一个中的析构函数发生 panic,也要确保后半部分被丢弃。
//
let _back_dropper = Dropper(&mut *drop_back);
ptr::drop_in_place(drop_front);
}
}
}
/// 返回底层分配器的引用。
#[unstable(feature = "allocator_api", issue = "32838")]
#[inline]
pub fn allocator(&self) -> &A {
self.buf.allocator()
}
/// 返回从前到后的迭代器。
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut buf = VecDeque::new();
/// buf.push_back(5);
/// buf.push_back(3);
/// buf.push_back(4);
/// let b: &[_] = &[&5, &3, &4];
/// let c: Vec<&i32> = buf.iter().collect();
/// assert_eq!(&c[..], b);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn iter(&self) -> Iter<'_, T> {
Iter { tail: self.tail, head: self.head, ring: unsafe { self.buffer_as_slice() } }
}
/// 返回从前到后的迭代器,该迭代器返回可变引用。
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut buf = VecDeque::new();
/// buf.push_back(5);
/// buf.push_back(3);
/// buf.push_back(4);
/// for num in buf.iter_mut() {
/// *num = *num - 2;
/// }
/// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
/// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn iter_mut(&mut self) -> IterMut<'_, T> {
// SAFETY: 建立内部 `IterMut` 安全不变量是因为我们创建的 `ring` 是生命周期 '_. 的可解引用切片。
//
let ring = ptr::slice_from_raw_parts_mut(self.ptr(), self.cap());
unsafe { IterMut::new(ring, self.tail, self.head, PhantomData) }
}
/// 返回一对切片,这些切片按顺序包含 `VecDeque` 的内容。
///
/// 如果先前调用了 [`make_contiguous`],则 `VecDeque` 的所有元素都将位于第一个切片中,而第二个切片将为空。
///
///
/// [`make_contiguous`]: VecDeque::make_contiguous
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut vector = VecDeque::new();
///
/// vector.push_back(0);
/// vector.push_back(1);
/// vector.push_back(2);
///
/// assert_eq!(vector.as_slices(), (&[0, 1, 2][..], &[][..]));
///
/// vector.push_front(10);
/// vector.push_front(9);
///
/// assert_eq!(vector.as_slices(), (&[9, 10][..], &[0, 1, 2][..]));
/// ```
///
#[inline]
#[stable(feature = "deque_extras_15", since = "1.5.0")]
pub fn as_slices(&self) -> (&[T], &[T]) {
unsafe {
let buf = self.buffer_as_slice();
RingSlices::ring_slices(buf, self.head, self.tail)
}
}
/// 返回一对切片,这些切片按顺序包含 `VecDeque` 的内容。
///
/// 如果先前调用了 [`make_contiguous`],则 `VecDeque` 的所有元素都将位于第一个切片中,而第二个切片将为空。
///
///
/// [`make_contiguous`]: VecDeque::make_contiguous
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut vector = VecDeque::new();
///
/// vector.push_back(0);
/// vector.push_back(1);
///
/// vector.push_front(10);
/// vector.push_front(9);
///
/// vector.as_mut_slices().0[0] = 42;
/// vector.as_mut_slices().1[0] = 24;
/// assert_eq!(vector.as_slices(), (&[42, 10][..], &[24, 1][..]));
/// ```
///
#[inline]
#[stable(feature = "deque_extras_15", since = "1.5.0")]
pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
unsafe {
let head = self.head;
let tail = self.tail;
let buf = self.buffer_as_mut_slice();
RingSlices::ring_slices(buf, head, tail)
}
}
/// 返回 `VecDeque` 中的元素数。
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut v = VecDeque::new();
/// assert_eq!(v.len(), 0);
/// v.push_back(1);
/// assert_eq!(v.len(), 1);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn len(&self) -> usize {
count(self.tail, self.head, self.cap())
}
/// 如果 `VecDeque` 为空,则返回 `true`。
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut v = VecDeque::new();
/// assert!(v.is_empty());
/// v.push_front(1);
/// assert!(!v.is_empty());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn is_empty(&self) -> bool {
self.tail == self.head
}
fn range_tail_head<R>(&self, range: R) -> (usize, usize)
where
R: RangeBounds<usize>,
{
let Range { start, end } = slice::range(range, ..self.len());
let tail = self.wrap_add(self.tail, start);
let head = self.wrap_add(self.tail, end);
(tail, head)
}
/// 创建一个覆盖 `VecDeque` 中指定范围的迭代器。
///
/// # Panics
///
/// 如果起点大于终点或终点大于 vector 的长度,就会出现 panics。
///
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let v: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
/// let range = v.range(2..).copied().collect::<VecDeque<_>>();
/// assert_eq!(range, [3]);
///
/// // 全方位涵盖所有内容
/// let all = v.range(..);
/// assert_eq!(all.len(), 3);
/// ```
#[inline]
#[stable(feature = "deque_range", since = "1.51.0")]
pub fn range<R>(&self, range: R) -> Iter<'_, T>
where
R: RangeBounds<usize>,
{
let (tail, head) = self.range_tail_head(range);
Iter {
tail,
head,
// &self 中的共享引用保留在 Iter 的 '_中。
ring: unsafe { self.buffer_as_slice() },
}
}
/// 创建一个覆盖 `VecDeque` 中指定的可变范围的迭代器。
///
/// # Panics
///
/// 如果起点大于终点或终点大于 vector 的长度,就会出现 panics。
///
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut v: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
/// for v in v.range_mut(2..) {
/// *v *= 2;
/// }
/// assert_eq!(v, vec![1, 2, 6]);
///
/// // 全方位涵盖所有内容
/// for v in v.range_mut(..) {
/// *v *= 2;
/// }
/// assert_eq!(v, vec![2, 4, 12]);
/// ```
#[inline]
#[stable(feature = "deque_range", since = "1.51.0")]
pub fn range_mut<R>(&mut self, range: R) -> IterMut<'_, T>
where
R: RangeBounds<usize>,
{
let (tail, head) = self.range_tail_head(range);
// SAFETY: 建立内部 `IterMut` 安全不变量是因为我们创建的 `ring` 是生命周期 '_. 的可解引用切片。
//
let ring = ptr::slice_from_raw_parts_mut(self.ptr(), self.cap());
unsafe { IterMut::new(ring, tail, head, PhantomData) }
}
/// 创建一个 draining 迭代器,该迭代器将删除 `VecDeque` 中的指定范围并产生已删除的项。
///
/// 注意 1: 即使直到最后才消耗迭代器,元素范围也会被删除。
///
/// 注意 2: 如果 `Drain` 值没有被丢弃,但持有的借用已过期 (例如,由于 `mem::forget`),则未指定从双端队列中删除了多少个元素。
///
///
/// # Panics
///
/// 如果起点大于终点或终点大于 vector 的长度,就会出现 panics。
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut v: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
/// let drained = v.drain(2..).collect::<VecDeque<_>>();
/// assert_eq!(drained, [3]);
/// assert_eq!(v, [1, 2]);
///
/// // 全系列清除所有内容
/// v.drain(..);
/// assert!(v.is_empty());
/// ```
///
///
///
///
#[inline]
#[stable(feature = "drain", since = "1.6.0")]
pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A>
where
R: RangeBounds<usize>,
{
// 内存安全
//
// 首次创建 Drain 时,将缩短源双端队列,以确保在 Drain 的析构函数从不运行的情况下,根本无法访问未初始化或移出的元素。
//
//
// Drain 将 ptr::read 取出要删除的值。
// 完成后,剩余的数据将被复制回以覆盖 hole,并且 head/tail 值将被正确恢复。
//
//
//
let (drain_tail, drain_head) = self.range_tail_head(range);
// 双端队列的元素分为三个部分:
// * self.tail -> drain_tail
// * drain_tail -> drain_head
// * drain_head -> self.head
//
// T = self.tail; H = self.head; t = drain_tail; h = drain_head
//
// 我们将 drain_tail 存储为 self.head,并将 drain_head 和 self.head 分别存储为 Drain 上的 after_tail 和 after_head。
// 这也将截断有效数组,以使如果 Drain 泄漏,我们将在 drain 开始后忘记可能移动的值。
//
//
// T t h H
// [. . . o o x x o o . . .]
//
//
//
let head = self.head;
// "forget" 关于 drain 开始之后的值,直到 drain 完成并且 Drain 析构函数运行之后。
//
self.head = drain_tail;
let deque = NonNull::from(&mut *self);
let iter = Iter {
tail: drain_tail,
head: drain_head,
// 至关重要的是,我们仅在此处从 `self` 创建共享引用并从中读取。
// 我们既不写 `self`,也不重新借用可变引用。
// 因此,我们上面为 `deque` 创建的裸指针仍然有效。
ring: unsafe { self.buffer_as_slice() },
};
unsafe { Drain::new(drain_head, head, iter, deque) }
}
/// 清除 `VecDeque`,删除所有值。
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut v = VecDeque::new();
/// v.push_back(1);
/// v.clear();
/// assert!(v.is_empty());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn clear(&mut self) {
self.truncate(0);
}
/// 如果 `VecDeque` 包含等于给定值的元素,则返回 `true`。
///
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut vector: VecDeque<u32> = VecDeque::new();
///
/// vector.push_back(0);
/// vector.push_back(1);
///
/// assert_eq!(vector.contains(&1), true);
/// assert_eq!(vector.contains(&10), false);
/// ```
#[stable(feature = "vec_deque_contains", since = "1.12.0")]
pub fn contains(&self, x: &T) -> bool
where
T: PartialEq<T>,
{
let (a, b) = self.as_slices();
a.contains(x) || b.contains(x)
}
/// 提供对前元素的引用,如果 `VecDeque` 为空,则为 `None`。
///
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut d = VecDeque::new();
/// assert_eq!(d.front(), None);
///
/// d.push_back(1);
/// d.push_back(2);
/// assert_eq!(d.front(), Some(&1));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn front(&self) -> Option<&T> {
self.get(0)
}
/// 为前元素提供可变引用,如果 `VecDeque` 为空,则为 `None`。
///
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut d = VecDeque::new();
/// assert_eq!(d.front_mut(), None);
///
/// d.push_back(1);
/// d.push_back(2);
/// match d.front_mut() {
/// Some(x) => *x = 9,
/// None => (),
/// }
/// assert_eq!(d.front(), Some(&9));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn front_mut(&mut self) -> Option<&mut T> {
self.get_mut(0)
}
/// 提供对 back 元素的引用,如果 `VecDeque` 为空,则提供 `None`。
///
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut d = VecDeque::new();
/// assert_eq!(d.back(), None);
///
/// d.push_back(1);
/// d.push_back(2);
/// assert_eq!(d.back(), Some(&2));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn back(&self) -> Option<&T> {
self.get(self.len().wrapping_sub(1))
}
/// 提供对 back 元素的可变引用,如果 `VecDeque` 为空,则提供 `None`。
///
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut d = VecDeque::new();
/// assert_eq!(d.back(), None);
///
/// d.push_back(1);
/// d.push_back(2);
/// match d.back_mut() {
/// Some(x) => *x = 9,
/// None => (),
/// }
/// assert_eq!(d.back(), Some(&9));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn back_mut(&mut self) -> Option<&mut T> {
self.get_mut(self.len().wrapping_sub(1))
}
/// 删除第一个元素并返回它,如果 `VecDeque` 为空,则返回 `None`。
///
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut d = VecDeque::new();
/// d.push_back(1);
/// d.push_back(2);
///
/// assert_eq!(d.pop_front(), Some(1));
/// assert_eq!(d.pop_front(), Some(2));
/// assert_eq!(d.pop_front(), None);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn pop_front(&mut self) -> Option<T> {
if self.is_empty() {
None
} else {
let tail = self.tail;
self.tail = self.wrap_add(self.tail, 1);
unsafe { Some(self.buffer_read(tail)) }
}
}
/// 从 `VecDeque` 中删除最后一个元素并返回它; 如果它为空,则返回 `None`。
///
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut buf = VecDeque::new();
/// assert_eq!(buf.pop_back(), None);
/// buf.push_back(1);
/// buf.push_back(3);
/// assert_eq!(buf.pop_back(), Some(3));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn pop_back(&mut self) -> Option<T> {
if self.is_empty() {
None
} else {
self.head = self.wrap_sub(self.head, 1);
let head = self.head;
unsafe { Some(self.buffer_read(head)) }
}
}
/// 将元素添加到 `VecDeque`。
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut d = VecDeque::new();
/// d.push_front(1);
/// d.push_front(2);
/// assert_eq!(d.front(), Some(&2));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn push_front(&mut self, value: T) {
if self.is_full() {
self.grow();
}
self.tail = self.wrap_sub(self.tail, 1);
let tail = self.tail;
unsafe {
self.buffer_write(tail, value);
}
}
/// 将一个元素追加到 `VecDeque` 的后面。
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut buf = VecDeque::new();
/// buf.push_back(1);
/// buf.push_back(3);
/// assert_eq!(3, *buf.back().unwrap());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn push_back(&mut self, value: T) {
if self.is_full() {
self.grow();
}
let head = self.head;
self.head = self.wrap_add(self.head, 1);
unsafe { self.buffer_write(head, value) }
}
#[inline]
fn is_contiguous(&self) -> bool {
// FIXME: 我们是否应该认为 `head == 0` 表示 `self` 是连续的?
//
self.tail <= self.head
}
/// 从 `VecDeque` 的任何位置删除一个元素并返回,并用第一个元素替换它。
///
///
/// 这不会保留顺序,而是 *O*(1)。
///
/// 如果 `index` 越界,则返回 `None`。
///
/// 索引为 0 的元素在队列的最前面。
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut buf = VecDeque::new();
/// assert_eq!(buf.swap_remove_front(0), None);
/// buf.push_back(1);
/// buf.push_back(2);
/// buf.push_back(3);
/// assert_eq!(buf, [1, 2, 3]);
///
/// assert_eq!(buf.swap_remove_front(2), Some(3));
/// assert_eq!(buf, [2, 1]);
/// ```
#[stable(feature = "deque_extras_15", since = "1.5.0")]
pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
let length = self.len();
if length > 0 && index < length && index != 0 {
self.swap(index, 0);
} else if index >= length {
return None;
}
self.pop_front()
}
/// 从 `VecDeque` 中的任何位置删除元素,然后将其返回,并用最后一个元素替换。
///
///
/// 这不会保留顺序,而是 *O*(1)。
///
/// 如果 `index` 越界,则返回 `None`。
///
/// 索引为 0 的元素在队列的最前面。
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut buf = VecDeque::new();
/// assert_eq!(buf.swap_remove_back(0), None);
/// buf.push_back(1);
/// buf.push_back(2);
/// buf.push_back(3);
/// assert_eq!(buf, [1, 2, 3]);
///
/// assert_eq!(buf.swap_remove_back(0), Some(1));
/// assert_eq!(buf, [3, 2]);
/// ```
#[stable(feature = "deque_extras_15", since = "1.5.0")]
pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
let length = self.len();
if length > 0 && index < length - 1 {
self.swap(index, length - 1);
} else if index >= length {
return None;
}
self.pop_back()
}
/// 在 `VecDeque` 内的 `index` 处插入一个元素,将所有索引大于或等于 `index` 的元素向后移动。
///
///
/// 索引为 0 的元素在队列的最前面。
///
/// # Panics
///
/// 如果 `index` 大于 `VecDeque` 的长度,就会出现 panics
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut vec_deque = VecDeque::new();
/// vec_deque.push_back('a');
/// vec_deque.push_back('b');
/// vec_deque.push_back('c');
/// assert_eq!(vec_deque, &['a', 'b', 'c']);
///
/// vec_deque.insert(1, 'd');
/// assert_eq!(vec_deque, &['a', 'd', 'b', 'c']);
/// ```
#[stable(feature = "deque_extras_15", since = "1.5.0")]
pub fn insert(&mut self, index: usize, value: T) {
assert!(index <= self.len(), "index out of bounds");
if self.is_full() {
self.grow();
}
// 在环形缓冲区中移动最少数量的元素并插入给定的对象
//
// 最多移动 `len/2 - 1`个元素。O(min(n, n-i))
//
// 主要有以下三种情况:
// 元素是连续的
// - tail 为 0 时的特殊情况元素不连续且插入在尾部元素不连续且插入在头部
//
//
// 对于每种情况,还有两种情况:
// 插入物更靠近尾部插入物更靠近头
//
// Key: H - self.head T - self.tail o - 有效元素 I - 插入元素 A - 插入点之后的元素 M - 指示元素已移动
//
//
//
//
//
//
//
//
let idx = self.wrap_add(self.tail, index);
let distance_to_tail = index;
let distance_to_head = self.len() - index;
let contiguous = self.is_contiguous();
match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
(true, true, _) if index == 0 => {
// push_front
//
// T I H
// [A o o o o o o . . . . . . .
// .
// .]
//
// H T
// [A o o o o o o o . . . . . I]
self.tail = self.wrap_sub(self.tail, 1);
}
(true, true, _) => {
unsafe {
// 连续的,插入到更靠近尾部的位置:
//
// T I H
// [. . . o o A o o o o . . . . . .]
//
// T H
// [. . o o I A o o o o . . . . . .]
// M M
//
// 连续,插入时靠近尾部 ,并且尾部为 0:
//
//
// T I H
// [o o A o o o o . . . . . . . . .]
//
// H T
// [o I A o o o o o . . . . . . . o]
// M M
let new_tail = self.wrap_sub(self.tail, 1);
self.copy(new_tail, self.tail, 1);
// 已经移动了尾部,因此我们仅复制 `index - 1` 元素。
self.copy(self.tail, self.tail + 1, index - 1);
self.tail = new_tail;
}
}
(true, false, _) => {
unsafe {
// 连续的,靠近头部插入:
//
// T I H
// [. . . o o o o A o o . . . . . .]
//
// T H
// [. . . o o o o I A o o . . . . .]
// M M M
self.copy(idx + 1, idx, self.head - idx);
self.head = self.wrap_add(self.head, 1);
}
}
(false, true, true) => {
unsafe {
// 不连续的,靠近尾部插入,尾部部分:
//
// H T I
// [o o o o o o . . . . . o o A o o]
//
// H T
// [o o o o o o . . . . o o I A o o]
// M M
self.copy(self.tail - 1, self.tail, index);
self.tail -= 1;
}
}
(false, false, true) => {
unsafe {
// 不连续的,插入得更靠近头部,尾部部分:
//
// H T I
// [o o . . . . . . . o o o o o A o]
//
// H T
// [o o o . . . . . . o o o o o I A]
// M M M M
// 复制元素直到新的头部
self.copy(1, 0, self.head);
// 将最后一个元素复制到缓冲区底部的空白处
self.copy(0, self.cap() - 1, 1);
// 将元素从 idx 移动到结束,不包括 ^ 元素
self.copy(idx + 1, idx, self.cap() - 1 - idx);
self.head += 1;
}
}
(false, true, false) if idx == 0 => {
unsafe {
// 不连续,insert 更靠近尾部,头部,并且在内部缓冲区中的索引为零:
//
//
// I H T
// [A o o o o o o o o o . . . o o o]
//
// H T
// [A o o o o o o o o o . . o o o I]
// M M M
// 复制元素直到新尾
self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
// 将最后一个元素复制到缓冲区底部的空白处
self.copy(self.cap() - 1, 0, 1);
self.tail -= 1;
}
}
(false, true, false) => {
unsafe {
// 不连续的,靠近尾部插入,头部部分:
//
// I H T
// [o o o A o o o o o o . . . o o o]
//
// H T
// [o o I A o o o o o o . . o o o o]
// M M M M M M
// 复制元素直到新尾
self.copy(self.tail - 1, self.tail, self.cap() - self.tail);
// 将最后一个元素复制到缓冲区底部的空白处
self.copy(self.cap() - 1, 0, 1);
// 将元素从 idx-1 移至末尾,不包括 ^ 元素
self.copy(0, 1, idx - 1);
self.tail -= 1;
}
}
(false, false, false) => {
unsafe {
// 不连续的,靠近头部插入,头部部分:
//
// I H T
// [o o o o A o o . . . . . . o o o]
//
// H T
// [o o o o I A o o . . . . . o o o]
// M M M
self.copy(idx + 1, idx, self.head - idx);
self.head += 1;
}
}
}
// 尾部可能已更改,因此我们需要重新计算
let new_idx = self.wrap_add(self.tail, index);
unsafe {
self.buffer_write(new_idx, value);
}
}
/// 从 `VecDeque` 删除 `index` 处的元素,并返回该元素。
/// 靠近移除点的任意一端将被移动以腾出空间,所有受影响的元素将被移动到新位置。
///
/// 如果 `index` 越界,则返回 `None`。
///
/// 索引为 0 的元素在队列的最前面。
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut buf = VecDeque::new();
/// buf.push_back(1);
/// buf.push_back(2);
/// buf.push_back(3);
/// assert_eq!(buf, [1, 2, 3]);
///
/// assert_eq!(buf.remove(1), Some(2));
/// assert_eq!(buf, [1, 3]);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn remove(&mut self, index: usize) -> Option<T> {
if self.is_empty() || self.len() <= index {
return None;
}
// 主要有以下三种情况:
// 元素是连续的元素是不连续的,并且去除在尾部元素是不连续的,并且去除在头部
// - 特殊情况下,元素在技术上是连续的,但是 self.head = 0
//
// 对于每种情况,还有两种情况:
// 插入物更靠近尾部插入物更靠近头
//
// Key: H-self.head T-self.tail o - 有效元素 x - 标记为要删除的元素 R - 表示要删除的元素 M - 表示元素已移动
//
//
//
//
//
//
//
//
//
let idx = self.wrap_add(self.tail, index);
let elem = unsafe { Some(self.buffer_read(idx)) };
let distance_to_tail = index;
let distance_to_head = self.len() - index;
let contiguous = self.is_contiguous();
match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
(true, true, _) => {
unsafe {
// 连续,移近尾部删除:
//
// T R H
// [. . . o o x o o o o . . . . . .]
//
// T H
// [. . . . o o o o o o . . . . . .]
// M M
self.copy(self.tail + 1, self.tail, index);
self.tail += 1;
}
}
(true, false, _) => {
unsafe {
// 连续,靠近头部删除:
//
// T R H
// [. . . o o o o x o o . . . . . .]
//
// T H
// [. . . o o o o o o . . . . . . .]
// M M
self.copy(idx, idx + 1, self.head - idx - 1);
self.head -= 1;
}
}
(false, true, true) => {
unsafe {
// 不连续的,靠近尾部删除,尾部部分:
//
// H T R
// [o o o o o o . . . . . o o x o o]
//
// H T
// [o o o o o o . . . . . . o o o o]
// M M
self.copy(self.tail + 1, self.tail, index);
self.tail = self.wrap_add(self.tail, 1);
}
}
(false, false, false) => {
unsafe {
// 不连续的,靠近头部删除,头部:
//
// R H T
// [o o o o x o o . . . . . . o o o]
//
// H T
// [o o o o o o . . . . . . . o o o]
// M M
self.copy(idx, idx + 1, self.head - idx - 1);
self.head -= 1;
}
}
(false, false, true) => {
unsafe {
// 不连续的,删除靠近头部,尾部的部分:
//
// H T R
// [o o o . . . . . . o o o o o x o]
//
// H T
// [o o . . . . . . . o o o o o o o]
// M M M M
//
// 或类似不连续,删除靠近头部和尾部的部分:
//
// H T R
// [. . . . . . . . . o o o o o x o]
//
// T H
// [. . . . . . . . . o o o o o o .]
// M
// 在尾部绘制元素
self.copy(idx, idx + 1, self.cap() - idx - 1);
// 防止下溢。
if self.head != 0 {
// 将第一个元素复制到空位置
self.copy(self.cap() - 1, 0, 1);
// 向后移动头部的元素
self.copy(0, 1, self.head - 1);
}
self.head = self.wrap_sub(self.head, 1);
}
}
(false, true, false) => {
unsafe {
// 不连续的,靠近尾部、头部部分删除:
//
// R H T
// [o o x o o o o o o o . . . o o o]
//
// H T
// [o o o o o o o o o o . . . . o o]
// M M M M M
// 绘制多达 idx 的元素
self.copy(1, 0, idx);
// 将最后一个元素复制到空白处
self.copy(0, self.cap() - 1, 1);
// 将元素从尾部向前移动到末尾,不包括最后一个
self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1);
self.tail = self.wrap_add(self.tail, 1);
}
}
}
elem
}
/// 在给定的索引处将 `VecDeque` 拆分为两个。
///
/// 返回新分配的 `VecDeque`。
/// `self` 包含元素 `[0, at)`,返回的 `VecDeque` 包含元素 `[at, len)`。
///
/// 请注意,`self` 的容量不会改变。
///
/// 索引为 0 的元素在队列的最前面。
///
/// # Panics
///
/// 如果为 `at > len`,就会出现 panics。
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut buf: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
/// let buf2 = buf.split_off(1);
/// assert_eq!(buf, [1]);
/// assert_eq!(buf2, [2, 3]);
/// ```
#[inline]
#[must_use = "use `.truncate()` if you don't need the other half"]
#[stable(feature = "split_off", since = "1.4.0")]
pub fn split_off(&mut self, at: usize) -> Self
where
A: Clone,
{
let len = self.len();
assert!(at <= len, "`at` out of bounds");
let other_len = len - at;
let mut other = VecDeque::with_capacity_in(other_len, self.allocator().clone());
unsafe {
let (first_half, second_half) = self.as_slices();
let first_len = first_half.len();
let second_len = second_half.len();
if at < first_len {
// `at` 位于前半部分。
let amount_in_first = first_len - at;
ptr::copy_nonoverlapping(first_half.as_ptr().add(at), other.ptr(), amount_in_first);
// 下半部分全部拿下。
ptr::copy_nonoverlapping(
second_half.as_ptr(),
other.ptr().add(amount_in_first),
second_len,
);
} else {
// `at` 位于后半部分,需要考虑我们在前半部分跳过的元素。
//
let offset = at - first_len;
let amount_in_second = second_len - offset;
ptr::copy_nonoverlapping(
second_half.as_ptr().add(offset),
other.ptr(),
amount_in_second,
);
}
}
// 清理缓冲区末端的位置
self.head = self.wrap_sub(self.head, other_len);
other.head = other.wrap_index(other_len);
other
}
/// 将 `other` 的所有元素移到 `self`,将 `other` 留空。
///
/// # Panics
///
/// 如果 self 中的新元素数溢出了一个 `usize`,就会出现 panics。
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut buf: VecDeque<_> = vec![1, 2].into_iter().collect();
/// let mut buf2: VecDeque<_> = vec![3, 4].into_iter().collect();
/// buf.append(&mut buf2);
/// assert_eq!(buf, [1, 2, 3, 4]);
/// assert_eq!(buf2, []);
/// ```
#[inline]
#[stable(feature = "append", since = "1.4.0")]
pub fn append(&mut self, other: &mut Self) {
self.reserve(other.len());
unsafe {
let (left, right) = other.as_slices();
self.copy_slice(self.head, left);
self.copy_slice(self.wrap_add(self.head, left.len()), right);
}
// SAFETY: 复制后更新指针,以避免在 panics 的情况下留下分身。
//
self.head = self.wrap_add(self.head, other.len());
// 默默地丢弃 `other` 中的值。
other.tail = other.head;
}
/// 仅保留谓词指定的元素。
///
/// 换句话说,删除所有元素 `e`,以使 `f(&e)` 返回 false。
/// 此方法在原位运行,以原始顺序恰好一次访问每个元素,并保留保留元素的顺序。
///
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut buf = VecDeque::new();
/// buf.extend(1..5);
/// buf.retain(|&x| x % 2 == 0);
/// assert_eq!(buf, [2, 4]);
/// ```
///
/// 由于按原始顺序仅对元素进行过一次访问,因此可以使用外部状态来确定要保留哪些元素。
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut buf = VecDeque::new();
/// buf.extend(1..6);
///
/// let keep = [false, true, true, false, true];
/// let mut iter = keep.iter();
/// buf.retain(|_| *iter.next().unwrap());
/// assert_eq!(buf, [2, 3, 5]);
/// ```
///
#[stable(feature = "vec_deque_retain", since = "1.4.0")]
pub fn retain<F>(&mut self, mut f: F)
where
F: FnMut(&T) -> bool,
{
self.retain_mut(|elem| f(elem));
}
/// 仅保留谓词指定的元素。
///
/// 换句话说,删除所有元素 `e`,以使 `f(&e)` 返回 false。
/// 此方法在原位运行,以原始顺序恰好一次访问每个元素,并保留保留元素的顺序。
///
///
/// # Examples
///
/// ```
/// #![feature(vec_retain_mut)]
///
/// use std::collections::VecDeque;
///
/// let mut buf = VecDeque::new();
/// buf.extend(1..5);
/// buf.retain_mut(|x| if *x % 2 == 0 {
/// *x += 1;
/// true
/// } else {
/// false
/// });
/// assert_eq!(buf, [3, 5]);
/// ```
#[unstable(feature = "vec_retain_mut", issue = "90829")]
pub fn retain_mut<F>(&mut self, mut f: F)
where
F: FnMut(&mut T) -> bool,
{
let len = self.len();
let mut idx = 0;
let mut cur = 0;
// 第 1 阶段:保留所有值。
while cur < len {
if !f(&mut self[cur]) {
cur += 1;
break;
}
cur += 1;
idx += 1;
}
// 第 2 阶段:将保留值交换为当前 idx。
while cur < len {
if !f(&mut self[cur]) {
cur += 1;
continue;
}
self.swap(idx, cur);
cur += 1;
idx += 1;
}
// 阶段 3: 截断 idx 之后的所有值。
if cur != idx {
self.truncate(idx);
}
}
// 将缓冲区大小增加一倍。
// 这个方法是 inline(never),所以我们希望它只在 cold 路径中被调用。
// 这可能会导致 panic 或终止
#[inline(never)]
fn grow(&mut self) {
// 当有效的用例出现时,扩展或者可能删除这个断言,从而在缓冲区没有满的情况下增长它
//
debug_assert!(self.is_full());
let old_cap = self.cap();
self.buf.reserve_exact(old_cap, old_cap);
assert!(self.cap() == old_cap * 2);
unsafe {
self.handle_capacity_increase(old_cap);
}
debug_assert!(!self.is_full());
}
/// 在原位修改 `VecDeque`,以使 `len()` 等于 `new_len`,可以从后面删除多余的元素,也可以在后面追加通过调用 `generator` 生成的元素。
///
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut buf = VecDeque::new();
/// buf.push_back(5);
/// buf.push_back(10);
/// buf.push_back(15);
/// assert_eq!(buf, [5, 10, 15]);
///
/// buf.resize_with(5, Default::default);
/// assert_eq!(buf, [5, 10, 15, 0, 0]);
///
/// buf.resize_with(2, || unreachable!());
/// assert_eq!(buf, [5, 10]);
///
/// let mut state = 100;
/// buf.resize_with(5, || { state += 1; state });
/// assert_eq!(buf, [5, 10, 101, 102, 103]);
/// ```
///
#[stable(feature = "vec_resize_with", since = "1.33.0")]
pub fn resize_with(&mut self, new_len: usize, generator: impl FnMut() -> T) {
let len = self.len();
if new_len > len {
self.extend(repeat_with(generator).take(new_len - len))
} else {
self.truncate(new_len);
}
}
/// 重新排列此双端队列的内部存储,使其成为一个连续的切片,然后将其返回。
///
/// 此方法不分配也不更改插入元素的顺序。当它返回可变切片时,可用于对双端队列进行排序。
///
/// 内部存储器连续后,[`as_slices`] 和 [`as_mut_slices`] 方法将在单个切片中返回 `VecDeque` 的全部内容。
///
///
/// [`as_slices`]: VecDeque::as_slices
/// [`as_mut_slices`]: VecDeque::as_mut_slices
///
/// # Examples
///
/// 对双端队列的内容进行排序。
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut buf = VecDeque::with_capacity(15);
///
/// buf.push_back(2);
/// buf.push_back(1);
/// buf.push_front(3);
///
/// // 排序双端队列
/// buf.make_contiguous().sort();
/// assert_eq!(buf.as_slices(), (&[1, 2, 3] as &[_], &[] as &[_]));
///
/// // 反向排序
/// buf.make_contiguous().sort_by(|a, b| b.cmp(a));
/// assert_eq!(buf.as_slices(), (&[3, 2, 1] as &[_], &[] as &[_]));
/// ```
///
/// 不可变地访问连续的切片。
///
/// ```rust
/// use std::collections::VecDeque;
///
/// let mut buf = VecDeque::new();
///
/// buf.push_back(2);
/// buf.push_back(1);
/// buf.push_front(3);
///
/// buf.make_contiguous();
/// if let (slice, &[]) = buf.as_slices() {
/// // 现在,我们可以确定 `slice` 包含了双端队列的所有元素,同时仍具有对 `buf` 的不可变访问权限。
/////
/// assert_eq!(buf.len(), slice.len());
/// assert_eq!(slice, &[3, 2, 1] as &[_]);
/// }
/// ```
///
///
///
///
#[stable(feature = "deque_make_contiguous", since = "1.48.0")]
pub fn make_contiguous(&mut self) -> &mut [T] {
if self.is_contiguous() {
let tail = self.tail;
let head = self.head;
return unsafe { RingSlices::ring_slices(self.buffer_as_mut_slice(), head, tail).0 };
}
let buf = self.buf.ptr();
let cap = self.cap();
let len = self.len();
let free = self.tail - self.head;
let tail_len = cap - self.tail;
if free >= tail_len {
// 有足够的可用空间来一次性复制尾部,这意味着我们先将头向后移动,然后再将尾部复制到正确的位置。
//
//
// 从: DEFGH....ABC 到: ABCDEFGH....
//
//
unsafe {
ptr::copy(buf, buf.add(tail_len), self.head);
// ...DEFGH.ABC
ptr::copy_nonoverlapping(buf.add(self.tail), buf, tail_len);
// ABCDEFGH....
self.tail = 0;
self.head = len;
}
} else if free > self.head {
// FIXME: 我们目前不认为 ....ABCDEFGH 是连续的,因为在这种情况下 `head` 将为 `0`。
// 尽管我们可能想更改它,但这并不是一件容易的事,因为有些地方期望 `is_contiguous` 表示我们可以使用 `buf[tail..head]` 进行切片。
//
//
//
// 有足够的自由空间可以一次性复制头部,这意味着我们先将尾部向前移动,然后再将头部复制到正确的位置。
//
//
// 从: FGH....ABCDE 到: ...ABCDEFGH。
//
//
unsafe {
ptr::copy(buf.add(self.tail), buf.add(self.head), tail_len);
// FGHABCDE....
ptr::copy_nonoverlapping(buf, buf.add(self.head + tail_len), self.head);
// ...ABCDEFGH.
self.tail = self.head;
self.head = self.wrap_add(self.tail, len);
}
} else {
// free 小于头和尾,这意味着我们必须缓慢地 "swap" 尾和头。
//
//
// 从: EFGHI...ABCD 或 HIJK.ABCDEFG 到: ABCDEFGHI... or ABCDEFGHIJK.
//
let mut left_edge: usize = 0;
let mut right_edge: usize = self.tail;
unsafe {
// 一般问题如下所示: GHIJKLM ... ABCDEF - 进行任何交换之前 ABCDEFM ... GHIJKL - 进行 1 次交换之后 ABCDEFGHIJM ... KL - 交换直到左 edge 到达临时存储
// - 然后使用新的 (smaller) 存储区重新启动算法。有时,当右边缘位于缓冲区的末尾时,便达到了临时存储区 - 这意味着我们以更少的交换找到了正确的顺序!
//
// E.g
// EF..ABCD ABCDEF.. - 仅四次交换后,我们就完成了
//
//
//
//
//
while left_edge < len && right_edge != cap {
let mut right_offset = 0;
for i in left_edge..right_edge {
right_offset = (i - left_edge) % (cap - right_edge);
let src: isize = (right_edge + right_offset) as isize;
ptr::swap(buf.add(i), buf.offset(src));
}
let n_ops = right_edge - left_edge;
left_edge += n_ops;
right_edge += right_offset + 1;
}
self.tail = 0;
self.head = len;
}
}
let tail = self.tail;
let head = self.head;
unsafe { RingSlices::ring_slices(self.buffer_as_mut_slice(), head, tail).0 }
}
/// 将双端队列 `mid` 放置到左侧。
///
/// Equivalently,
/// - 将项 `mid` 旋转到第一个位置。
/// - 弹出第一个 `mid` 项并将其推到末尾。
/// - 向右旋转 `len() - mid` 位置。
///
/// # Panics
///
/// 如果 `mid` 大于 `len()`。
/// 请注意,`mid == len()` 执行 _not_ panic,并且是无操作旋转。
///
/// # Complexity
///
/// 花费 `*O*(min(mid, len() - mid))` 的时间,没有多余的空间。
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut buf: VecDeque<_> = (0..10).collect();
///
/// buf.rotate_left(3);
/// assert_eq!(buf, [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]);
///
/// for i in 1..10 {
/// assert_eq!(i * 3 % 10, buf[0]);
/// buf.rotate_left(3);
/// }
/// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
/// ```
#[stable(feature = "vecdeque_rotate", since = "1.36.0")]
pub fn rotate_left(&mut self, mid: usize) {
assert!(mid <= self.len());
let k = self.len() - mid;
if mid <= k {
unsafe { self.rotate_left_inner(mid) }
} else {
unsafe { self.rotate_right_inner(k) }
}
}
/// 向右旋转 `k` 位置的双端队列。
///
/// Equivalently,
/// - 将第一个项旋转到位置 `k`。
/// - 弹出最后一个 `k` 项并将其推到前面。
/// - 将 `len() - k` 位置向左旋转。
///
/// # Panics
///
/// 如果 `k` 大于 `len()`。
/// 请注意,`k == len()` 执行 _not_ panic,并且是无操作旋转。
///
/// # Complexity
///
/// 花费 `*O*(min(k, len() - k))` 的时间,没有多余的空间。
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut buf: VecDeque<_> = (0..10).collect();
///
/// buf.rotate_right(3);
/// assert_eq!(buf, [7, 8, 9, 0, 1, 2, 3, 4, 5, 6]);
///
/// for i in 1..10 {
/// assert_eq!(0, buf[i * 3 % 10]);
/// buf.rotate_right(3);
/// }
/// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
/// ```
#[stable(feature = "vecdeque_rotate", since = "1.36.0")]
pub fn rotate_right(&mut self, k: usize) {
assert!(k <= self.len());
let mid = self.len() - k;
if k <= mid {
unsafe { self.rotate_right_inner(k) }
} else {
unsafe { self.rotate_left_inner(mid) }
}
}
// SAFETY: 以下两种方法要求旋转量小于双端队列的长度的一半。
//
// `wrap_copy` 需要 `min(x, cap() - x) + copy_len <= cap()`,但 `min` 永远不会超过容量的一半,无论 x 是多少,所以在这里调用是合理的,因为我们调用的长度小于一半,永远不会超过容量的一半。
//
//
//
//
unsafe fn rotate_left_inner(&mut self, mid: usize) {
debug_assert!(mid * 2 <= self.len());
unsafe {
self.wrap_copy(self.head, self.tail, mid);
}
self.head = self.wrap_add(self.head, mid);
self.tail = self.wrap_add(self.tail, mid);
}
unsafe fn rotate_right_inner(&mut self, k: usize) {
debug_assert!(k * 2 <= self.len());
self.head = self.wrap_sub(self.head, k);
self.tail = self.wrap_sub(self.tail, k);
unsafe {
self.wrap_copy(self.tail, self.head, k);
}
}
/// Binary 在此排序的 `VecDeque` 上搜索给定的元素。
///
/// 如果找到该值,则返回 [`Result::Ok`],其中包含匹配元素的索引。
/// 如果有多个匹配项,则可以返回任何一个匹配项。
/// 如果找不到该值,则返回 [`Result::Err`],其中包含在保留排序顺序的同时可以在其中插入匹配元素的索引。
///
///
/// 另请参见 [`binary_search_by`],[`binary_search_by_key`] 和 [`partition_point`]。
///
/// [`binary_search_by`]: VecDeque::binary_search_by
/// [`binary_search_by_key`]: VecDeque::binary_search_by_key
/// [`partition_point`]: VecDeque::partition_point
///
/// # Examples
///
/// 查找一系列四个元素。
/// 找到第一个,具有唯一确定的位置; 没有找到第二个和第三个; 第四个可以匹配 `[1, 4]` 中的任何位置。
///
/// ```
/// use std::collections::VecDeque;
///
/// let deque: VecDeque<_> = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
///
/// assert_eq!(deque.binary_search(&13), Ok(9));
/// assert_eq!(deque.binary_search(&4), Err(7));
/// assert_eq!(deque.binary_search(&100), Err(13));
/// let r = deque.binary_search(&1);
/// assert!(matches!(r, Ok(1..=4)));
/// ```
///
/// 如果要在已排序的 `VecDeque` 上插入项目,同时保持排序顺序:
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut deque: VecDeque<_> = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
/// let num = 42;
/// let idx = deque.binary_search(&num).unwrap_or_else(|x| x);
/// deque.insert(idx, num);
/// assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
/// ```
///
///
///
#[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
#[inline]
pub fn binary_search(&self, x: &T) -> Result<usize, usize>
where
T: Ord,
{
self.binary_search_by(|e| e.cmp(x))
}
/// Binary 使用比较器函数搜索此排序的 `VecDeque`。
///
/// 比较器函数应该实现一个与底层 `VecDeque` 的排序顺序一致的顺序,返回一个顺序代码,指示其参数是比所需目标是 `Less`、`Equal` 还是 `Greater`。
///
///
/// 如果找到该值,则返回 [`Result::Ok`],其中包含匹配元素的索引。如果有多个匹配项,则可以返回任何一个匹配项。
/// 如果找不到该值,则返回 [`Result::Err`],其中包含在保留排序顺序的同时可以在其中插入匹配元素的索引。
///
/// 另请参见 [`binary_search`],[`binary_search_by_key`] 和 [`partition_point`]。
///
/// [`binary_search`]: VecDeque::binary_search
/// [`binary_search_by_key`]: VecDeque::binary_search_by_key
/// [`partition_point`]: VecDeque::partition_point
///
/// # Examples
///
/// 查找一系列四个元素。找到第一个,具有唯一确定的位置; 没有找到第二个和第三个; 第四个可以匹配 `[1, 4]` 中的任何位置。
///
/// ```
/// use std::collections::VecDeque;
///
/// let deque: VecDeque<_> = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].into();
///
/// assert_eq!(deque.binary_search_by(|x| x.cmp(&13)), Ok(9));
/// assert_eq!(deque.binary_search_by(|x| x.cmp(&4)), Err(7));
/// assert_eq!(deque.binary_search_by(|x| x.cmp(&100)), Err(13));
/// let r = deque.binary_search_by(|x| x.cmp(&1));
/// assert!(matches!(r, Ok(1..=4)));
/// ```
///
///
///
///
///
///
///
#[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
where
F: FnMut(&'a T) -> Ordering,
{
let (front, back) = self.as_slices();
let cmp_back = back.first().map(|elem| f(elem));
if let Some(Ordering::Equal) = cmp_back {
Ok(front.len())
} else if let Some(Ordering::Less) = cmp_back {
back.binary_search_by(f).map(|idx| idx + front.len()).map_err(|idx| idx + front.len())
} else {
front.binary_search_by(f)
}
}
/// Binary 使用关键字提取函数搜索此排序的 `VecDeque`。
///
/// 假设 `VecDeque` 是按键排序的,例如 [`make_contiguous().sort_by_key()`] 使用相同的键提取函数。
///
/// 如果找到该值,则返回 [`Result::Ok`],其中包含匹配元素的索引。
/// 如果有多个匹配项,则可以返回任何一个匹配项。
/// 如果找不到该值,则返回 [`Result::Err`],其中包含在保留排序顺序的同时可以在其中插入匹配元素的索引。
///
///
/// 另请参见 [`binary_search`],[`binary_search_by`] 和 [`partition_point`]。
///
/// [`make_contiguous().sort_by_key()`]: VecDeque::make_contiguous
/// [`binary_search`]: VecDeque::binary_search
/// [`binary_search_by`]: VecDeque::binary_search_by
/// [`partition_point`]: VecDeque::partition_point
///
/// # Examples
///
/// 在成对的切片中按其第二个元素排序的一系列四个元素中查找。
/// 找到第一个,具有唯一确定的位置; 没有找到第二个和第三个; 第四个可以匹配 `[1, 4]` 中的任何位置。
///
/// ```
/// use std::collections::VecDeque;
///
/// let deque: VecDeque<_> = vec![(0, 0), (2, 1), (4, 1), (5, 1),
/// (3, 1), (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
/// (1, 21), (2, 34), (4, 55)].into();
///
/// assert_eq!(deque.binary_search_by_key(&13, |&(a, b)| b), Ok(9));
/// assert_eq!(deque.binary_search_by_key(&4, |&(a, b)| b), Err(7));
/// assert_eq!(deque.binary_search_by_key(&100, |&(a, b)| b), Err(13));
/// let r = deque.binary_search_by_key(&1, |&(a, b)| b);
/// assert!(matches!(r, Ok(1..=4)));
/// ```
///
///
///
///
#[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
#[inline]
pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
where
F: FnMut(&'a T) -> B,
B: Ord,
{
self.binary_search_by(|k| f(k).cmp(b))
}
/// 根据给定的谓词返回分区点的索引 (第二个分区的第一个元素的索引)。
///
/// 假定双端队列根据给定的谓词进行了分区。
/// 这意味着谓词返回 true 的所有元素都在双端队列的开头,而谓词返回 false 的所有元素都在末尾。
///
/// 例如,[7, 15, 3, 5, 4, 12, 6] 在谓词 `x % 2 != 0` 下进行了分区 (所有的奇数都在开头,所有的偶数都在结尾)。
///
/// 如果此双端队列未分区,则返回的结果是未指定且无意义的,因为此方法执行一种二分查找。
///
/// 另请参见 [`binary_search`],[`binary_search_by`] 和 [`binary_search_by_key`]。
///
/// [`binary_search`]: VecDeque::binary_search
/// [`binary_search_by`]: VecDeque::binary_search_by
/// [`binary_search_by_key`]: VecDeque::binary_search_by_key
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let deque: VecDeque<_> = vec![1, 2, 3, 3, 5, 6, 7].into();
/// let i = deque.partition_point(|&x| x < 5);
///
/// assert_eq!(i, 4);
/// assert!(deque.iter().take(i).all(|&x| x < 5));
/// assert!(deque.iter().skip(i).all(|&x| !(x < 5)));
/// ```
///
///
///
#[stable(feature = "vecdeque_binary_search", since = "1.54.0")]
pub fn partition_point<P>(&self, mut pred: P) -> usize
where
P: FnMut(&T) -> bool,
{
let (front, back) = self.as_slices();
if let Some(true) = back.first().map(|v| pred(v)) {
back.partition_point(pred) + front.len()
} else {
front.partition_point(pred)
}
}
}
impl<T: Clone, A: Allocator> VecDeque<T, A> {
/// 就地修改 `VecDeque`,使 `len()` 等于 new_len,要么从后面删除多余的元素,要么在后面追加 `value` 的克隆。
///
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut buf = VecDeque::new();
/// buf.push_back(5);
/// buf.push_back(10);
/// buf.push_back(15);
/// assert_eq!(buf, [5, 10, 15]);
///
/// buf.resize(2, 0);
/// assert_eq!(buf, [5, 10]);
///
/// buf.resize(5, 20);
/// assert_eq!(buf, [5, 10, 20, 20, 20]);
/// ```
///
#[stable(feature = "deque_extras", since = "1.16.0")]
pub fn resize(&mut self, new_len: usize, value: T) {
self.resize_with(new_len, || value.clone());
}
}
/// 返回给定逻辑元素索引的底层缓冲区中的索引。
#[inline]
fn wrap_index(index: usize, size: usize) -> usize {
// 大小始终是 2 的幂
debug_assert!(size.is_power_of_two());
index & (size - 1)
}
/// 计算要在缓冲区中读取的剩余元素数
#[inline]
fn count(tail: usize, head: usize, size: usize) -> usize {
// 大小始终是 2 的幂
(head.wrapping_sub(tail)) & (size - 1)
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: PartialEq, A: Allocator> PartialEq for VecDeque<T, A> {
fn eq(&self, other: &Self) -> bool {
if self.len() != other.len() {
return false;
}
let (sa, sb) = self.as_slices();
let (oa, ob) = other.as_slices();
if sa.len() == oa.len() {
sa == oa && sb == ob
} else if sa.len() < oa.len() {
// 始终可分为三部分,例如:
// self: [a b c|d e f] other: [0 1 2 3|4 5] front = 3, mid = 1, [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
//
//
//
let front = sa.len();
let mid = oa.len() - front;
let (oa_front, oa_mid) = oa.split_at(front);
let (sb_mid, sb_back) = sb.split_at(mid);
debug_assert_eq!(sa.len(), oa_front.len());
debug_assert_eq!(sb_mid.len(), oa_mid.len());
debug_assert_eq!(sb_back.len(), ob.len());
sa == oa_front && sb_mid == oa_mid && sb_back == ob
} else {
let front = oa.len();
let mid = sa.len() - front;
let (sa_front, sa_mid) = sa.split_at(front);
let (ob_mid, ob_back) = ob.split_at(mid);
debug_assert_eq!(sa_front.len(), oa.len());
debug_assert_eq!(sa_mid.len(), ob_mid.len());
debug_assert_eq!(sb.len(), ob_back.len());
sa_front == oa && sa_mid == ob_mid && sb == ob_back
}
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Eq, A: Allocator> Eq for VecDeque<T, A> {}
__impl_slice_eq1! { [] VecDeque<T, A>, Vec<U, A>, }
__impl_slice_eq1! { [] VecDeque<T, A>, &[U], }
__impl_slice_eq1! { [] VecDeque<T, A>, &mut [U], }
__impl_slice_eq1! { [const N: usize] VecDeque<T, A>, [U; N], }
__impl_slice_eq1! { [const N: usize] VecDeque<T, A>, &[U; N], }
__impl_slice_eq1! { [const N: usize] VecDeque<T, A>, &mut [U; N], }
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: PartialOrd, A: Allocator> PartialOrd for VecDeque<T, A> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.iter().partial_cmp(other.iter())
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Ord, A: Allocator> Ord for VecDeque<T, A> {
#[inline]
fn cmp(&self, other: &Self) -> Ordering {
self.iter().cmp(other.iter())
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Hash, A: Allocator> Hash for VecDeque<T, A> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.len().hash(state);
// 在 as_slices 方法返回的切片上无法使用 Hash::hash_slice,因为它们的长度会因其他双端队列相同而有所不同。
//
//
// Hasher 仅保证对其方法的完全相同的调用集是等效的。
//
//
self.iter().for_each(|elem| elem.hash(state));
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T, A: Allocator> Index<usize> for VecDeque<T, A> {
type Output = T;
#[inline]
fn index(&self, index: usize) -> &T {
self.get(index).expect("Out of bounds access")
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T, A: Allocator> IndexMut<usize> for VecDeque<T, A> {
#[inline]
fn index_mut(&mut self, index: usize) -> &mut T {
self.get_mut(index).expect("Out of bounds access")
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> FromIterator<T> for VecDeque<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> VecDeque<T> {
let iterator = iter.into_iter();
let (lower, _) = iterator.size_hint();
let mut deq = VecDeque::with_capacity(lower);
deq.extend(iterator);
deq
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T, A: Allocator> IntoIterator for VecDeque<T, A> {
type Item = T;
type IntoIter = IntoIter<T, A>;
/// 将 `VecDeque` 消费为从前到后的迭代器,按值产生元素。
///
fn into_iter(self) -> IntoIter<T, A> {
IntoIter::new(self)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T, A: Allocator> IntoIterator for &'a VecDeque<T, A> {
type Item = &'a T;
type IntoIter = Iter<'a, T>;
fn into_iter(self) -> Iter<'a, T> {
self.iter()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T, A: Allocator> IntoIterator for &'a mut VecDeque<T, A> {
type Item = &'a mut T;
type IntoIter = IterMut<'a, T>;
fn into_iter(self) -> IterMut<'a, T> {
self.iter_mut()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T, A: Allocator> Extend<T> for VecDeque<T, A> {
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
// 这个功能应该是 moral 上的等价物:
//
// for item in iter.into_iter() {
// self.push_back(item);
// }
let mut iter = iter.into_iter();
while let Some(element) = iter.next() {
if self.len() == self.capacity() {
let (lower, _) = iter.size_hint();
self.reserve(lower.saturating_add(1));
}
let head = self.head;
self.head = self.wrap_add(self.head, 1);
unsafe {
self.buffer_write(head, element);
}
}
}
#[inline]
fn extend_one(&mut self, elem: T) {
self.push_back(elem);
}
#[inline]
fn extend_reserve(&mut self, additional: usize) {
self.reserve(additional);
}
}
#[stable(feature = "extend_ref", since = "1.2.0")]
impl<'a, T: 'a + Copy, A: Allocator> Extend<&'a T> for VecDeque<T, A> {
fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
self.extend(iter.into_iter().cloned());
}
#[inline]
fn extend_one(&mut self, &elem: &T) {
self.push_back(elem);
}
#[inline]
fn extend_reserve(&mut self, additional: usize) {
self.reserve(additional);
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Debug, A: Allocator> fmt::Debug for VecDeque<T, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self).finish()
}
}
#[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
impl<T, A: Allocator> From<Vec<T, A>> for VecDeque<T, A> {
/// 将 [`Vec<T>`] 变成 [`VecDeque<T>`]。
///
/// [`Vec<T>`]: crate::vec::Vec
/// [`VecDeque<T>`]: crate::collections::VecDeque
///
/// 这样可以避免在可能的情况下进行重新分配,但是这样做的条件很严格,并且随时可能更改,因此除非 `Vec<T>` 来自 `From<VecDeque<T>>` 并且尚未重新分配,否则不应依赖它。
///
///
fn from(mut other: Vec<T, A>) -> Self {
let len = other.len();
if mem::size_of::<T>() == 0 {
// 没有实际分配给 ZST 来担心容量的问题,但是 `VecDeque` 不能处理比 `Vec` 更长的长度。
//
assert!(len < MAXIMUM_ZST_CAPACITY, "capacity overflow");
} else {
// 如果容量不是 2 的幂,太小或没有至少一个可用空间,则需要调整大小。
// 我们在它仍在 `Vec` 中时执行此操作,所以该项会因为 panic 而被丢弃。
//
let min_cap = cmp::max(MINIMUM_CAPACITY, len) + 1;
let cap = cmp::max(min_cap, other.capacity()).next_power_of_two();
if other.capacity() != cap {
other.reserve_exact(cap - len);
}
}
unsafe {
let (other_buf, len, capacity, alloc) = other.into_raw_parts_with_alloc();
let buf = RawVec::from_raw_parts_in(other_buf, capacity, alloc);
VecDeque { tail: 0, head: len, buf }
}
}
}
#[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
impl<T, A: Allocator> From<VecDeque<T, A>> for Vec<T, A> {
/// 将 [`VecDeque<T>`] 变成 [`Vec<T>`]。
///
/// [`Vec<T>`]: crate::vec::Vec
/// [`VecDeque<T>`]: crate::collections::VecDeque
///
/// 这永远不需要重新分配,但是如果循环缓冲区恰好不在分配开始时,则确实需要进行 *O*(*n*) 数据移动。
///
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// // 这是 *O*(1)。
/// let deque: VecDeque<_> = (1..5).collect();
/// let ptr = deque.as_slices().0.as_ptr();
/// let vec = Vec::from(deque);
/// assert_eq!(vec, [1, 2, 3, 4]);
/// assert_eq!(vec.as_ptr(), ptr);
///
/// // 这一项需要重新整理数据。
/// let mut deque: VecDeque<_> = (1..5).collect();
/// deque.push_front(9);
/// deque.push_front(8);
/// let ptr = deque.as_slices().1.as_ptr();
/// let vec = Vec::from(deque);
/// assert_eq!(vec, [8, 9, 1, 2, 3, 4]);
/// assert_eq!(vec.as_ptr(), ptr);
/// ```
fn from(mut other: VecDeque<T, A>) -> Self {
other.make_contiguous();
unsafe {
let other = ManuallyDrop::new(other);
let buf = other.buf.ptr();
let len = other.len();
let cap = other.cap();
let alloc = ptr::read(other.allocator());
if other.tail != 0 {
ptr::copy(buf.add(other.tail), buf, len);
}
Vec::from_raw_parts_in(buf, len, cap, alloc)
}
}
}
#[stable(feature = "std_collections_from_array", since = "1.56.0")]
impl<T, const N: usize> From<[T; N]> for VecDeque<T> {
/// ```
/// use std::collections::VecDeque;
///
/// let deq1 = VecDeque::from([1, 2, 3, 4]);
/// let deq2: VecDeque<_> = [1, 2, 3, 4].into();
/// assert_eq!(deq1, deq2);
/// ```
fn from(arr: [T; N]) -> Self {
let mut deq = VecDeque::with_capacity(N);
let arr = ManuallyDrop::new(arr);
if mem::size_of::<T>() != 0 {
// SAFETY: VecDeque::with_capacity 确保有足够的容量。
unsafe {
ptr::copy_nonoverlapping(arr.as_ptr(), deq.ptr(), N);
}
}
deq.tail = 0;
deq.head = N;
deq
}
}