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
// Copyright 2016 Amanieu d'Antras
// Copyright 2020 Amari Robinson
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
//! Intrusive red-black tree.
use core::borrow::Borrow;
use core::cell::Cell;
use core::cmp::Ordering;
use core::fmt;
use core::mem;
use core::ptr::NonNull;
use core::sync::atomic::{self, AtomicUsize};
use crate::Bound::{self, Excluded, Included, Unbounded};
use crate::link_ops::{self, DefaultLinkOps};
use crate::linked_list::LinkedListOps;
use crate::pointer_ops::PointerOps;
use crate::singly_linked_list::SinglyLinkedListOps;
use crate::xor_linked_list::XorLinkedListOps;
use crate::Adapter;
use crate::KeyAdapter;
// Necessary for Rust 1.56 compatability
#[allow(unused_imports)]
use crate::unchecked_option::UncheckedOptionExt;
// =============================================================================
// RBTreeOps
// =============================================================================
/// The color of a red-black tree node.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
#[allow(missing_docs)]
pub enum Color {
Red,
Black,
}
/// Link operations for `RBTree`.
pub unsafe trait RBTreeOps: link_ops::LinkOps {
/// Returns the left child of `ptr`.
///
/// # Safety
/// An implementation of `left` must not panic.
unsafe fn left(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr>;
/// Returns the right child of `ptr`.
///
/// # Safety
/// An implementation of `right` must not panic.
unsafe fn right(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr>;
/// Returns the parent of `ptr`.
///
/// # Safety
/// An implementation of `parent` must not panic.
unsafe fn parent(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr>;
/// Returns the color of `ptr`.
///
/// # Safety
/// An implementation of `color` must not panic.
unsafe fn color(&self, ptr: Self::LinkPtr) -> Color;
/// Sets the left child of `ptr`.
///
/// # Safety
/// An implementation of `set_left` must not panic.
unsafe fn set_left(&mut self, ptr: Self::LinkPtr, left: Option<Self::LinkPtr>);
/// Sets the right child of `ptr`.
///
/// # Safety
/// An implementation of `set_right` must not panic.
unsafe fn set_right(&mut self, ptr: Self::LinkPtr, right: Option<Self::LinkPtr>);
/// Sets the parent of `ptr`.
///
/// # Safety
/// An implementation of `set_parent` must not panic.
unsafe fn set_parent(&mut self, ptr: Self::LinkPtr, parent: Option<Self::LinkPtr>);
/// Sets the color of `ptr`.
///
/// # Safety
/// An implementation of `set_color` must not panic.
unsafe fn set_color(&mut self, ptr: Self::LinkPtr, color: Color);
}
// =============================================================================
// Link
// =============================================================================
/// Intrusive link that allows an object to be inserted into a
/// `RBTree`.
#[repr(align(2))]
pub struct Link {
left: Cell<Option<NonNull<Link>>>,
right: Cell<Option<NonNull<Link>>>,
parent_color: Cell<usize>,
}
// Use a special value to indicate an unlinked node. This value represents a
// red root node, which is impossible in a valid red-black tree.
const UNLINKED_MARKER: usize = 0;
impl Link {
/// Creates a new `Link`.
#[inline]
pub const fn new() -> Link {
Link {
left: Cell::new(None),
right: Cell::new(None),
parent_color: Cell::new(UNLINKED_MARKER),
}
}
/// Checks whether the `Link` is linked into a `RBTree`.
#[inline]
pub fn is_linked(&self) -> bool {
self.parent_color.get() != UNLINKED_MARKER
}
/// Forcibly unlinks an object from a `RBTree`.
///
/// # Safety
///
/// It is undefined behavior to call this function while still linked into a
/// `RBTree`. The only situation where this function is useful is
/// after calling `fast_clear` on a `RBTree`, since this clears
/// the collection without marking the nodes as unlinked.
#[inline]
pub unsafe fn force_unlink(&self) {
self.parent_color.set(UNLINKED_MARKER);
}
}
impl DefaultLinkOps for Link {
type Ops = LinkOps;
const NEW: Self::Ops = LinkOps;
}
// An object containing a link can be sent to another thread if it is unlinked.
unsafe impl Send for Link {}
// Provide an implementation of Clone which simply initializes the new link as
// unlinked. This allows structs containing a link to derive Clone.
impl Clone for Link {
#[inline]
fn clone(&self) -> Link {
Link::new()
}
}
// Same as above
impl Default for Link {
#[inline]
fn default() -> Link {
Link::new()
}
}
// Provide an implementation of Debug so that structs containing a link can
// still derive Debug.
impl fmt::Debug for Link {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// There isn't anything sensible to print here except whether the link
// is currently in a tree.
if self.is_linked() {
write!(f, "linked")
} else {
write!(f, "unlinked")
}
}
}
// =============================================================================
// LinkOps
// =============================================================================
/// Default `LinkOps` implementation for `RBTree`.
#[derive(Clone, Copy, Default)]
pub struct LinkOps;
impl LinkOps {
#[inline]
unsafe fn set_parent_color(
self,
ptr: <Self as link_ops::LinkOps>::LinkPtr,
parent: Option<<Self as link_ops::LinkOps>::LinkPtr>,
color: Color,
) {
assert!(mem::align_of::<Link>() >= 2);
let bit = match color {
Color::Red => 0,
Color::Black => 1,
};
let parent_usize = parent.map(|x| x.as_ptr() as usize).unwrap_or(0);
ptr.as_ref().parent_color.set((parent_usize & !1) | bit);
}
}
unsafe impl link_ops::LinkOps for LinkOps {
type LinkPtr = NonNull<Link>;
#[inline]
unsafe fn acquire_link(&mut self, ptr: Self::LinkPtr) -> bool {
if ptr.as_ref().is_linked() {
false
} else {
self.set_parent_color(ptr, None, Color::Black);
true
}
}
#[inline]
unsafe fn release_link(&mut self, ptr: Self::LinkPtr) {
ptr.as_ref().parent_color.set(UNLINKED_MARKER);
}
}
unsafe impl RBTreeOps for LinkOps {
#[inline]
unsafe fn left(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr> {
ptr.as_ref().left.get()
}
#[inline]
unsafe fn right(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr> {
ptr.as_ref().right.get()
}
#[inline]
unsafe fn parent(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr> {
let parent_usize = ptr.as_ref().parent_color.get() & !1;
NonNull::new(parent_usize as *mut Link)
}
#[inline]
unsafe fn color(&self, ptr: Self::LinkPtr) -> Color {
if ptr.as_ref().parent_color.get() & 1 == 1 {
Color::Black
} else {
Color::Red
}
}
#[inline]
unsafe fn set_left(&mut self, ptr: Self::LinkPtr, left: Option<Self::LinkPtr>) {
ptr.as_ref().left.set(left);
}
#[inline]
unsafe fn set_right(&mut self, ptr: Self::LinkPtr, right: Option<Self::LinkPtr>) {
ptr.as_ref().right.set(right);
}
#[inline]
unsafe fn set_parent(&mut self, ptr: Self::LinkPtr, parent: Option<Self::LinkPtr>) {
self.set_parent_color(ptr, parent, self.color(ptr));
}
#[inline]
unsafe fn set_color(&mut self, ptr: Self::LinkPtr, color: Color) {
self.set_parent_color(ptr, self.parent(ptr), color);
}
}
unsafe impl SinglyLinkedListOps for LinkOps {
#[inline]
unsafe fn next(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr> {
self.right(ptr)
}
#[inline]
unsafe fn set_next(&mut self, ptr: Self::LinkPtr, next: Option<Self::LinkPtr>) {
self.set_right(ptr, next);
}
}
unsafe impl LinkedListOps for LinkOps {
#[inline]
unsafe fn next(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr> {
self.right(ptr)
}
#[inline]
unsafe fn prev(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr> {
self.left(ptr)
}
#[inline]
unsafe fn set_next(&mut self, ptr: Self::LinkPtr, next: Option<Self::LinkPtr>) {
self.set_right(ptr, next);
}
#[inline]
unsafe fn set_prev(&mut self, ptr: Self::LinkPtr, prev: Option<Self::LinkPtr>) {
self.set_left(ptr, prev);
}
}
unsafe impl XorLinkedListOps for LinkOps {
#[inline]
unsafe fn next(
&self,
ptr: Self::LinkPtr,
prev: Option<Self::LinkPtr>,
) -> Option<Self::LinkPtr> {
let packed = self.right(ptr).map(|x| x.as_ptr() as usize).unwrap_or(0);
let raw = packed ^ prev.map(|x| x.as_ptr() as usize).unwrap_or(0);
NonNull::new(raw as *mut _)
}
#[inline]
unsafe fn prev(
&self,
ptr: Self::LinkPtr,
next: Option<Self::LinkPtr>,
) -> Option<Self::LinkPtr> {
let packed = self.right(ptr).map(|x| x.as_ptr() as usize).unwrap_or(0);
let raw = packed ^ next.map(|x| x.as_ptr() as usize).unwrap_or(0);
NonNull::new(raw as *mut _)
}
#[inline]
unsafe fn set(
&mut self,
ptr: Self::LinkPtr,
prev: Option<Self::LinkPtr>,
next: Option<Self::LinkPtr>,
) {
let new_packed = prev.map(|x| x.as_ptr() as usize).unwrap_or(0)
^ next.map(|x| x.as_ptr() as usize).unwrap_or(0);
let new_next = NonNull::new(new_packed as *mut _);
self.set_right(ptr, new_next);
}
#[inline]
unsafe fn replace_next_or_prev(
&mut self,
ptr: Self::LinkPtr,
old: Option<Self::LinkPtr>,
new: Option<Self::LinkPtr>,
) {
let packed = self.right(ptr).map(|x| x.as_ptr() as usize).unwrap_or(0);
let new_packed = packed
^ old.map(|x| x.as_ptr() as usize).unwrap_or(0)
^ new.map(|x| x.as_ptr() as usize).unwrap_or(0);
let new_next = NonNull::new(new_packed as *mut _);
self.set_right(ptr, new_next);
}
}
// =============================================================================
// AtomicLink
// =============================================================================
/// Intrusive link that allows an object to be inserted into a
/// `RBTree`. This link allows the structure to be shared between threads.
#[repr(align(2))]
pub struct AtomicLink {
left: Cell<Option<NonNull<AtomicLink>>>,
right: Cell<Option<NonNull<AtomicLink>>>,
parent_color: AtomicUsize,
}
impl AtomicLink {
#[inline]
/// Creates a new `AtomicLink`.
pub const fn new() -> AtomicLink {
AtomicLink {
left: Cell::new(None),
right: Cell::new(None),
parent_color: AtomicUsize::new(UNLINKED_MARKER),
}
}
/// Checks whether the `AtomicLink` is linked into a `RBTree`.
#[inline]
pub fn is_linked(&self) -> bool {
self.parent_color.load(atomic::Ordering::Relaxed) != UNLINKED_MARKER
}
/// Forcibly unlinks an object from a `RBTree`.
///
/// # Safety
///
/// It is undefined behavior to call this function while still linked into a
/// `RBTree`. The only situation where this function is useful is
/// after calling `fast_clear` on a `RBTree`, since this clears
/// the collection without marking the nodes as unlinked.
#[inline]
pub unsafe fn force_unlink(&self) {
self.parent_color
.store(UNLINKED_MARKER, atomic::Ordering::Release);
}
/// Access `parent_color` in an exclusive context.
///
/// # Safety
///
/// This can only be called after `acquire_link` has been succesfully called.
#[inline]
unsafe fn parent_color_exclusive(&self) -> &Cell<usize> {
// This is safe because currently AtomicUsize has the same representation Cell<usize>.
core::mem::transmute(&self.parent_color)
}
}
impl DefaultLinkOps for AtomicLink {
type Ops = AtomicLinkOps;
const NEW: Self::Ops = AtomicLinkOps;
}
// An object containing a link can be sent to another thread since `acquire_link` is atomic.
unsafe impl Send for AtomicLink {}
// An object containing a link can be shared between threads since `acquire_link` is atomic.
unsafe impl Sync for AtomicLink {}
impl Clone for AtomicLink {
#[inline]
fn clone(&self) -> AtomicLink {
AtomicLink::new()
}
}
impl Default for AtomicLink {
#[inline]
fn default() -> AtomicLink {
AtomicLink::new()
}
}
// Provide an implementation of Debug so that structs containing a link can
// still derive Debug.
impl fmt::Debug for AtomicLink {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// There isn't anything sensible to print here except whether the link
// is currently in a list.
if self.is_linked() {
write!(f, "linked")
} else {
write!(f, "unlinked")
}
}
}
// =============================================================================
// AtomicLinkOps
// =============================================================================
/// Default `LinkOps` implementation for `RBTree`.
#[derive(Clone, Copy, Default)]
pub struct AtomicLinkOps;
impl AtomicLinkOps {
#[inline]
unsafe fn set_parent_color(
self,
ptr: <Self as link_ops::LinkOps>::LinkPtr,
parent: Option<<Self as link_ops::LinkOps>::LinkPtr>,
color: Color,
) {
assert!(mem::align_of::<Link>() >= 2);
let bit = match color {
Color::Red => 0,
Color::Black => 1,
};
let parent_usize = parent.map(|x| x.as_ptr() as usize).unwrap_or(0);
ptr.as_ref()
.parent_color_exclusive()
.set((parent_usize & !1) | bit);
}
}
const LINKED_DEFAULT_VALUE: usize = 1;
unsafe impl link_ops::LinkOps for AtomicLinkOps {
type LinkPtr = NonNull<AtomicLink>;
#[inline]
unsafe fn acquire_link(&mut self, ptr: Self::LinkPtr) -> bool {
ptr.as_ref()
.parent_color
.compare_exchange(
UNLINKED_MARKER,
LINKED_DEFAULT_VALUE,
atomic::Ordering::Acquire,
atomic::Ordering::Relaxed,
)
.is_ok()
}
#[inline]
unsafe fn release_link(&mut self, ptr: Self::LinkPtr) {
ptr.as_ref()
.parent_color
.store(UNLINKED_MARKER, atomic::Ordering::Release)
}
}
unsafe impl RBTreeOps for AtomicLinkOps {
#[inline]
unsafe fn left(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr> {
ptr.as_ref().left.get()
}
#[inline]
unsafe fn right(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr> {
ptr.as_ref().right.get()
}
#[inline]
unsafe fn parent(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr> {
let parent_usize = ptr.as_ref().parent_color_exclusive().get() & !1;
NonNull::new(parent_usize as *mut AtomicLink)
}
#[inline]
unsafe fn color(&self, ptr: Self::LinkPtr) -> Color {
if ptr.as_ref().parent_color_exclusive().get() & 1 == 1 {
Color::Black
} else {
Color::Red
}
}
#[inline]
unsafe fn set_left(&mut self, ptr: Self::LinkPtr, left: Option<Self::LinkPtr>) {
ptr.as_ref().left.set(left);
}
#[inline]
unsafe fn set_right(&mut self, ptr: Self::LinkPtr, right: Option<Self::LinkPtr>) {
ptr.as_ref().right.set(right);
}
#[inline]
unsafe fn set_parent(&mut self, ptr: Self::LinkPtr, parent: Option<Self::LinkPtr>) {
self.set_parent_color(ptr, parent, self.color(ptr));
}
#[inline]
unsafe fn set_color(&mut self, ptr: Self::LinkPtr, color: Color) {
self.set_parent_color(ptr, self.parent(ptr), color);
}
}
unsafe impl SinglyLinkedListOps for AtomicLinkOps {
#[inline]
unsafe fn next(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr> {
self.right(ptr)
}
#[inline]
unsafe fn set_next(&mut self, ptr: Self::LinkPtr, next: Option<Self::LinkPtr>) {
self.set_right(ptr, next);
}
}
unsafe impl LinkedListOps for AtomicLinkOps {
#[inline]
unsafe fn next(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr> {
self.right(ptr)
}
#[inline]
unsafe fn prev(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr> {
self.left(ptr)
}
#[inline]
unsafe fn set_next(&mut self, ptr: Self::LinkPtr, next: Option<Self::LinkPtr>) {
self.set_right(ptr, next);
}
#[inline]
unsafe fn set_prev(&mut self, ptr: Self::LinkPtr, prev: Option<Self::LinkPtr>) {
self.set_left(ptr, prev);
}
}
unsafe impl XorLinkedListOps for AtomicLinkOps {
#[inline]
unsafe fn next(
&self,
ptr: Self::LinkPtr,
prev: Option<Self::LinkPtr>,
) -> Option<Self::LinkPtr> {
let packed = self.right(ptr).map(|x| x.as_ptr() as usize).unwrap_or(0);
let raw = packed ^ prev.map(|x| x.as_ptr() as usize).unwrap_or(0);
NonNull::new(raw as *mut _)
}
#[inline]
unsafe fn prev(
&self,
ptr: Self::LinkPtr,
next: Option<Self::LinkPtr>,
) -> Option<Self::LinkPtr> {
let packed = self.right(ptr).map(|x| x.as_ptr() as usize).unwrap_or(0);
let raw = packed ^ next.map(|x| x.as_ptr() as usize).unwrap_or(0);
NonNull::new(raw as *mut _)
}
#[inline]
unsafe fn set(
&mut self,
ptr: Self::LinkPtr,
prev: Option<Self::LinkPtr>,
next: Option<Self::LinkPtr>,
) {
let new_packed = prev.map(|x| x.as_ptr() as usize).unwrap_or(0)
^ next.map(|x| x.as_ptr() as usize).unwrap_or(0);
let new_next = NonNull::new(new_packed as *mut _);
self.set_right(ptr, new_next);
}
#[inline]
unsafe fn replace_next_or_prev(
&mut self,
ptr: Self::LinkPtr,
old: Option<Self::LinkPtr>,
new: Option<Self::LinkPtr>,
) {
let packed = self.right(ptr).map(|x| x.as_ptr() as usize).unwrap_or(0);
let new_packed = packed
^ old.map(|x| x.as_ptr() as usize).unwrap_or(0)
^ new.map(|x| x.as_ptr() as usize).unwrap_or(0);
let new_next = NonNull::new(new_packed as *mut _);
self.set_right(ptr, new_next);
}
}
#[inline]
unsafe fn is_left_child<T: RBTreeOps>(link_ops: &T, ptr: T::LinkPtr, parent: T::LinkPtr) -> bool {
link_ops.left(parent) == Some(ptr)
}
#[inline]
unsafe fn first_child<T: RBTreeOps>(link_ops: &T, ptr: T::LinkPtr) -> T::LinkPtr {
let mut x = ptr;
while let Some(y) = link_ops.left(x) {
x = y;
}
x
}
#[inline]
unsafe fn last_child<T: RBTreeOps>(link_ops: &T, ptr: T::LinkPtr) -> T::LinkPtr {
let mut x = ptr;
while let Some(y) = link_ops.right(x) {
x = y;
}
x
}
#[inline]
unsafe fn next<T: RBTreeOps>(link_ops: &T, ptr: T::LinkPtr) -> Option<T::LinkPtr> {
if let Some(right) = link_ops.right(ptr) {
Some(first_child(link_ops, right))
} else {
let mut x = ptr;
loop {
if let Some(parent) = link_ops.parent(x) {
if is_left_child(link_ops, x, parent) {
return Some(parent);
}
x = parent;
} else {
return None;
}
}
}
}
#[inline]
unsafe fn prev<T: RBTreeOps>(link_ops: &T, ptr: T::LinkPtr) -> Option<T::LinkPtr> {
if let Some(left) = link_ops.left(ptr) {
Some(last_child(link_ops, left))
} else {
let mut x = ptr;
loop {
if let Some(parent) = link_ops.parent(x) {
if !is_left_child(link_ops, x, parent) {
return Some(parent);
}
x = parent;
} else {
return None;
}
}
}
}
#[inline]
unsafe fn replace_with<T: RBTreeOps>(
link_ops: &mut T,
ptr: T::LinkPtr,
new: T::LinkPtr,
root: &mut Option<T::LinkPtr>,
) {
if let Some(parent) = link_ops.parent(ptr) {
if is_left_child(link_ops, ptr, parent) {
link_ops.set_left(parent, Some(new));
} else {
link_ops.set_right(parent, Some(new));
}
} else {
*root = Some(new);
}
if let Some(left) = link_ops.left(ptr) {
link_ops.set_parent(left, Some(new));
}
if let Some(right) = link_ops.right(ptr) {
link_ops.set_parent(right, Some(new));
}
link_ops.set_left(new, link_ops.left(ptr));
link_ops.set_right(new, link_ops.right(ptr));
link_ops.set_parent(new, link_ops.parent(ptr));
link_ops.set_color(new, link_ops.color(ptr));
link_ops.release_link(ptr);
}
#[inline]
unsafe fn insert_left<T: RBTreeOps>(
link_ops: &mut T,
ptr: T::LinkPtr,
new: T::LinkPtr,
root: &mut Option<T::LinkPtr>,
) {
link_ops.set_parent(new, Some(ptr));
link_ops.set_color(new, Color::Red);
link_ops.set_left(new, None);
link_ops.set_right(new, None);
link_ops.set_left(ptr, Some(new));
post_insert(link_ops, new, root);
}
#[inline]
unsafe fn insert_right<T: RBTreeOps>(
link_ops: &mut T,
ptr: T::LinkPtr,
new: T::LinkPtr,
root: &mut Option<T::LinkPtr>,
) {
link_ops.set_parent(new, Some(ptr));
link_ops.set_color(new, Color::Red);
link_ops.set_left(new, None);
link_ops.set_right(new, None);
link_ops.set_right(ptr, Some(new));
post_insert(link_ops, new, root);
}
unsafe fn rotate_left<T: RBTreeOps>(
link_ops: &mut T,
ptr: T::LinkPtr,
root: &mut Option<T::LinkPtr>,
) {
let y = link_ops.right(ptr).unwrap_unchecked();
link_ops.set_right(ptr, link_ops.left(y));
if let Some(right) = link_ops.right(ptr) {
link_ops.set_parent(right, Some(ptr));
}
link_ops.set_parent(y, link_ops.parent(ptr));
if let Some(parent) = link_ops.parent(ptr) {
if is_left_child(link_ops, ptr, parent) {
link_ops.set_left(parent, Some(y));
} else {
link_ops.set_right(parent, Some(y));
}
} else {
*root = Some(y);
}
link_ops.set_left(y, Some(ptr));
link_ops.set_parent(ptr, Some(y));
}
unsafe fn rotate_right<T: RBTreeOps>(
link_ops: &mut T,
ptr: T::LinkPtr,
root: &mut Option<T::LinkPtr>,
) {
let y = link_ops.left(ptr).unwrap_unchecked();
link_ops.set_left(ptr, link_ops.right(y));
if let Some(left) = link_ops.left(ptr) {
link_ops.set_parent(left, Some(ptr));
}
link_ops.set_parent(y, link_ops.parent(ptr));
if let Some(parent) = link_ops.parent(ptr) {
if is_left_child(link_ops, ptr, parent) {
link_ops.set_left(parent, Some(y));
} else {
link_ops.set_right(parent, Some(y));
}
} else {
*root = Some(y);
}
link_ops.set_right(y, Some(ptr));
link_ops.set_parent(ptr, Some(y));
}
// This code is based on the red-black tree implementation in libc++
unsafe fn post_insert<T: RBTreeOps>(
link_ops: &mut T,
ptr: T::LinkPtr,
root: &mut Option<T::LinkPtr>,
) {
let mut x = ptr;
while let Some(parent) = link_ops.parent(x) {
if link_ops.color(parent) != Color::Red {
break;
}
// SAFETY: The root of the tree must be black, and `parent` cannot be the root if it is red.
let grandparent = link_ops.parent(parent).unwrap_unchecked();
if is_left_child(link_ops, parent, grandparent) {
let y = link_ops.right(grandparent);
if let Some(y) = y {
if link_ops.color(y) == Color::Red {
x = parent;
link_ops.set_color(x, Color::Black);
x = grandparent;
if link_ops.parent(x).is_none() {
link_ops.set_color(x, Color::Black);
} else {
link_ops.set_color(x, Color::Red);
}
link_ops.set_color(y, Color::Black);
continue;
}
}
if !is_left_child(link_ops, x, parent) {
x = parent;
rotate_left(link_ops, x, root);
}
x = link_ops.parent(x).unwrap_unchecked();
link_ops.set_color(x, Color::Black);
x = link_ops.parent(x).unwrap_unchecked();
link_ops.set_color(x, Color::Red);
rotate_right(link_ops, x, root);
} else {
let y = link_ops.left(grandparent);
if let Some(y) = y {
if link_ops.color(y) == Color::Red {
x = parent;
link_ops.set_color(x, Color::Black);
x = grandparent;
if link_ops.parent(x).is_none() {
link_ops.set_color(x, Color::Black);
} else {
link_ops.set_color(x, Color::Red);
}
link_ops.set_color(y, Color::Black);
continue;
}
}
if is_left_child(link_ops, x, parent) {
x = parent;
rotate_right(link_ops, x, root);
}
x = link_ops.parent(x).unwrap_unchecked();
link_ops.set_color(x, Color::Black);
x = link_ops.parent(x).unwrap_unchecked();
link_ops.set_color(x, Color::Red);
rotate_left(link_ops, x, root);
}
break;
}
}
// This code is based on the red-black tree implementation in libc++
unsafe fn remove<T: RBTreeOps>(link_ops: &mut T, ptr: T::LinkPtr, root: &mut Option<T::LinkPtr>) {
let y = if link_ops.left(ptr).is_none() || link_ops.right(ptr).is_none() {
ptr
} else {
next(link_ops, ptr).unwrap_unchecked()
};
let x = if link_ops.left(y).is_some() {
link_ops.left(y)
} else {
link_ops.right(y)
};
let mut w = None;
if let Some(x) = x {
link_ops.set_parent(x, link_ops.parent(y));
}
if let Some(y_parent) = link_ops.parent(y) {
if is_left_child(link_ops, y, y_parent) {
link_ops.set_left(y_parent, x);
w = link_ops.right(y_parent);
} else {
link_ops.set_right(y_parent, x);
w = link_ops.left(y_parent);
}
} else {
*root = x;
}
let removed_black = link_ops.color(y) == Color::Black;
if y != ptr {
if let Some(parent) = link_ops.parent(ptr) {
link_ops.set_parent(y, Some(parent));
if is_left_child(link_ops, ptr, parent) {
link_ops.set_left(parent, Some(y));
} else {
link_ops.set_right(parent, Some(y));
}
} else {
link_ops.set_parent(y, None);
*root = Some(y);
}
link_ops.set_left(y, link_ops.left(ptr));
link_ops.set_parent(link_ops.left(y).unwrap_unchecked(), Some(y));
link_ops.set_right(y, link_ops.right(ptr));
if let Some(y_right) = link_ops.right(y) {
link_ops.set_parent(y_right, Some(y));
}
link_ops.set_color(y, link_ops.color(ptr));
}
if removed_black && !root.is_none() {
if let Some(x) = x {
link_ops.set_color(x, Color::Black);
} else {
let mut w = w.unwrap_unchecked();
loop {
let mut w_parent = link_ops.parent(w).unwrap_unchecked();
if !is_left_child(link_ops, w, w_parent) {
if link_ops.color(w) == Color::Red {
link_ops.set_color(w, Color::Black);
link_ops.set_color(w_parent, Color::Red);
rotate_left(link_ops, w_parent, root);
w = link_ops
.right(link_ops.left(w).unwrap_unchecked())
.unwrap_unchecked();
w_parent = link_ops.parent(w).unwrap_unchecked();
}
let left_color = link_ops.left(w).map(|x| link_ops.color(x));
let right_color = link_ops.right(w).map(|x| link_ops.color(x));
if (left_color != Some(Color::Red)) && (right_color != Some(Color::Red)) {
link_ops.set_color(w, Color::Red);
if link_ops.parent(w_parent).is_none()
|| link_ops.color(w_parent) == Color::Red
{
link_ops.set_color(w_parent, Color::Black);
break;
}
let w_grandparent = link_ops.parent(w_parent).unwrap_unchecked();
w = if is_left_child(link_ops, w_parent, w_grandparent) {
link_ops.right(w_grandparent).unwrap_unchecked()
} else {
link_ops.left(w_grandparent).unwrap_unchecked()
};
} else {
if link_ops.right(w).map(|x| link_ops.color(x)) != Some(Color::Red) {
link_ops.set_color(link_ops.left(w).unwrap_unchecked(), Color::Black);
link_ops.set_color(w, Color::Red);
rotate_right(link_ops, w, root);
w = link_ops.parent(w).unwrap_unchecked();
w_parent = link_ops.parent(w).unwrap_unchecked();
}
link_ops.set_color(w, link_ops.color(w_parent));
link_ops.set_color(w_parent, Color::Black);
link_ops.set_color(link_ops.right(w).unwrap_unchecked(), Color::Black);
rotate_left(link_ops, w_parent, root);
break;
}
} else {
if link_ops.color(w) == Color::Red {
link_ops.set_color(w, Color::Black);
link_ops.set_color(w_parent, Color::Red);
rotate_right(link_ops, w_parent, root);
w = link_ops
.left(link_ops.right(w).unwrap_unchecked())
.unwrap_unchecked();
w_parent = link_ops.parent(w).unwrap_unchecked();
}
let left_color = link_ops.left(w).map(|x| link_ops.color(x));
let right_color = link_ops.right(w).map(|x| link_ops.color(x));
if (left_color != Some(Color::Red)) && (right_color != Some(Color::Red)) {
link_ops.set_color(w, Color::Red);
if link_ops.parent(w_parent).is_none()
|| link_ops.color(w_parent) == Color::Red
{
link_ops.set_color(w_parent, Color::Black);
break;
}
w = if is_left_child(
link_ops,
w_parent,
link_ops.parent(w_parent).unwrap_unchecked(),
) {
link_ops
.right(link_ops.parent(w_parent).unwrap_unchecked())
.unwrap_unchecked()
} else {
link_ops
.left(link_ops.parent(w_parent).unwrap_unchecked())
.unwrap_unchecked()
};
} else {
if link_ops.left(w).map(|x| link_ops.color(x)) != Some(Color::Red) {
link_ops.set_color(link_ops.right(w).unwrap_unchecked(), Color::Black);
link_ops.set_color(w, Color::Red);
rotate_left(link_ops, w, root);
w = link_ops.parent(w).unwrap_unchecked();
w_parent = link_ops.parent(w).unwrap_unchecked();
}
link_ops.set_color(w, link_ops.color(w_parent));
link_ops.set_color(w_parent, Color::Black);
link_ops.set_color(link_ops.left(w).unwrap_unchecked(), Color::Black);
rotate_right(link_ops, w_parent, root);
break;
}
}
}
}
}
link_ops.release_link(ptr);
}
// =============================================================================
// Cursor, CursorMut, CursorOwning
// =============================================================================
/// A cursor which provides read-only access to a `RBTree`.
pub struct Cursor<'a, A: Adapter>
where
A::LinkOps: RBTreeOps,
{
current: Option<<A::LinkOps as link_ops::LinkOps>::LinkPtr>,
tree: &'a RBTree<A>,
}
impl<'a, A: Adapter> Clone for Cursor<'a, A>
where
A::LinkOps: RBTreeOps,
{
#[inline]
fn clone(&self) -> Cursor<'a, A> {
Cursor {
current: self.current,
tree: self.tree,
}
}
}
impl<'a, A: Adapter> Cursor<'a, A>
where
A::LinkOps: RBTreeOps,
{
/// Checks if the cursor is currently pointing to the null object.
#[inline]
pub fn is_null(&self) -> bool {
self.current.is_none()
}
/// Returns a reference to the object that the cursor is currently
/// pointing to.
///
/// This returns `None` if the cursor is currently pointing to the null
/// object.
#[inline]
pub fn get(&self) -> Option<&'a <A::PointerOps as PointerOps>::Value> {
Some(unsafe { &*self.tree.adapter.get_value(self.current?) })
}
/// Clones and returns the pointer that points to the element that the
/// cursor is referencing.
///
/// This returns `None` if the cursor is currently pointing to the null
/// object.
#[inline]
pub fn clone_pointer(&self) -> Option<<A::PointerOps as PointerOps>::Pointer>
where
<A::PointerOps as PointerOps>::Pointer: Clone,
{
let raw_pointer = unsafe { self.tree.adapter.get_value(self.current?) };
Some(unsafe {
crate::pointer_ops::clone_pointer_from_raw(self.tree.adapter.pointer_ops(), raw_pointer)
})
}
/// Moves the cursor to the next element of the `RBTree`.
///
/// If the cursor is pointer to the null object then this will move it to
/// the first element of the `RBTree`. If it is pointing to the last
/// element of the `RBTree` then this will move it to the null object.
#[inline]
pub fn move_next(&mut self) {
if let Some(current) = self.current {
self.current = unsafe { next(self.tree.adapter.link_ops(), current) };
} else if let Some(root) = self.tree.root {
self.current = Some(unsafe { first_child(self.tree.adapter.link_ops(), root) });
} else {
self.current = None;
}
}
/// Moves the cursor to the previous element of the `RBTree`.
///
/// If the cursor is pointer to the null object then this will move it to
/// the last element of the `RBTree`. If it is pointing to the first
/// element of the `RBTree` then this will move it to the null object.
#[inline]
pub fn move_prev(&mut self) {
if let Some(current) = self.current {
self.current = unsafe { prev(self.tree.adapter.link_ops(), current) };
} else if let Some(root) = self.tree.root {
self.current = Some(unsafe { last_child(self.tree.adapter.link_ops(), root) });
} else {
self.current = None;
}
}
/// Returns a cursor pointing to the next element of the `RBTree`.
///
/// If the cursor is pointer to the null object then this will return the
/// first element of the `RBTree`. If it is pointing to the last
/// element of the `RBTree` then this will return a null cursor.
#[inline]
pub fn peek_next(&self) -> Cursor<'_, A> {
let mut next = self.clone();
next.move_next();
next
}
/// Returns a cursor pointing to the previous element of the `RBTree`.
///
/// If the cursor is pointer to the null object then this will return the
/// last element of the `RBTree`. If it is pointing to the first
/// element of the `RBTree` then this will return a null cursor.
#[inline]
pub fn peek_prev(&self) -> Cursor<'_, A> {
let mut prev = self.clone();
prev.move_prev();
prev
}
}
/// A cursor which provides mutable access to a `RBTree`.
pub struct CursorMut<'a, A: Adapter>
where
A::LinkOps: RBTreeOps,
{
current: Option<<A::LinkOps as link_ops::LinkOps>::LinkPtr>,
tree: &'a mut RBTree<A>,
}
impl<'a, A: Adapter> CursorMut<'a, A>
where
A::LinkOps: RBTreeOps,
{
/// Checks if the cursor is currently pointing to the null object.
#[inline]
pub fn is_null(&self) -> bool {
self.current.is_none()
}
/// Returns a reference to the object that the cursor is currently
/// pointing to.
///
/// This returns None if the cursor is currently pointing to the null
/// object.
#[inline]
pub fn get(&self) -> Option<&<A::PointerOps as PointerOps>::Value> {
Some(unsafe { &*self.tree.adapter.get_value(self.current?) })
}
/// Returns a read-only cursor pointing to the current element.
///
/// The lifetime of the returned `Cursor` is bound to that of the
/// `CursorMut`, which means it cannot outlive the `CursorMut` and that the
/// `CursorMut` is frozen for the lifetime of the `Cursor`.
#[inline]
pub fn as_cursor(&self) -> Cursor<'_, A> {
Cursor {
current: self.current,
tree: self.tree,
}
}
/// Moves the cursor to the next element of the `RBTree`.
///
/// If the cursor is pointer to the null object then this will move it to
/// the first element of the `RBTree`. If it is pointing to the last
/// element of the `RBTree` then this will move it to the null object.
#[inline]
pub fn move_next(&mut self) {
if let Some(current) = self.current {
self.current = unsafe { next(self.tree.adapter.link_ops(), current) };
} else if let Some(root) = self.tree.root {
self.current = Some(unsafe { first_child(self.tree.adapter.link_ops(), root) });
} else {
self.current = None;
}
}
/// Moves the cursor to the previous element of the `RBTree`.
///
/// If the cursor is pointer to the null object then this will move it to
/// the last element of the `RBTree`. If it is pointing to the first
/// element of the `RBTree` then this will move it to the null object.
#[inline]
pub fn move_prev(&mut self) {
if let Some(current) = self.current {
self.current = unsafe { prev(self.tree.adapter.link_ops(), current) };
} else if let Some(root) = self.tree.root {
self.current = Some(unsafe { last_child(self.tree.adapter.link_ops(), root) });
} else {
self.current = None;
}
}
/// Returns a cursor pointing to the next element of the `RBTree`.
///
/// If the cursor is pointer to the null object then this will return the
/// first element of the `RBTree`. If it is pointing to the last
/// element of the `RBTree` then this will return a null cursor.
#[inline]
pub fn peek_next(&self) -> Cursor<'_, A> {
let mut next = self.as_cursor();
next.move_next();
next
}
/// Returns a cursor pointing to the previous element of the `RBTree`.
///
/// If the cursor is pointer to the null object then this will return the
/// last element of the `RBTree`. If it is pointing to the first
/// element of the `RBTree` then this will return a null cursor.
#[inline]
pub fn peek_prev(&self) -> Cursor<'_, A> {
let mut prev = self.as_cursor();
prev.move_prev();
prev
}
/// Removes the current element from the `RBTree`.
///
/// A pointer to the element that was removed is returned, and the cursor is
/// moved to point to the next element in the `RBTree`.
///
/// If the cursor is currently pointing to the null object then no element
/// is removed and `None` is returned.
#[inline]
pub fn remove(&mut self) -> Option<<A::PointerOps as PointerOps>::Pointer> {
unsafe {
if let Some(current) = self.current {
let next = next(self.tree.adapter.link_ops(), current);
let result = current;
remove(
self.tree.adapter.link_ops_mut(),
current,
&mut self.tree.root,
);
self.current = next;
Some(
self.tree
.adapter
.pointer_ops()
.from_raw(self.tree.adapter.get_value(result)),
)
} else {
None
}
}
}
/// Removes the current element from the `RBTree` and inserts another
/// object in its place.
///
/// A pointer to the element that was removed is returned, and the cursor is
/// modified to point to the newly added element.
///
/// When using this function you must ensure that the elements in the
/// collection are maintained in increasing order. Failure to do this may
/// lead to `find`, `upper_bound`, `lower_bound` and `range` returning
/// incorrect results.
///
/// If the cursor is currently pointing to the null object then an error is
/// returned containing the given `val` parameter.
///
/// # Panics
///
/// Panics if the new element is already linked to a different intrusive
/// collection.
#[inline]
pub fn replace_with(
&mut self,
val: <A::PointerOps as PointerOps>::Pointer,
) -> Result<<A::PointerOps as PointerOps>::Pointer, <A::PointerOps as PointerOps>::Pointer>
{
unsafe {
if let Some(current) = self.current {
let new = self.tree.node_from_value(val);
let result = current;
replace_with(
self.tree.adapter.link_ops_mut(),
current,
new,
&mut self.tree.root,
);
self.current = Some(new);
Ok(self
.tree
.adapter
.pointer_ops()
.from_raw(self.tree.adapter.get_value(result)))
} else {
Err(val)
}
}
}
/// Inserts a new element into the `RBTree` after the current one.
///
/// When using this function you must ensure that the elements in the
/// collection are maintained in increasing order. Failure to do this may
/// lead to `find`, `upper_bound`, `lower_bound` and `range` returning
/// incorrect results.
///
/// If the cursor is pointing at the null object then the new element is
/// inserted at the start of the `RBTree`.
///
/// # Panics
///
/// Panics if the new element is already linked to a different intrusive
/// collection.
#[inline]
pub fn insert_after(&mut self, val: <A::PointerOps as PointerOps>::Pointer) {
unsafe {
let new = self.tree.node_from_value(val);
let link_ops = self.tree.adapter.link_ops_mut();
if let Some(root) = self.tree.root {
if let Some(current) = self.current {
if link_ops.right(current).is_some() {
let next = next(link_ops, current).unwrap_unchecked();
insert_left(link_ops, next, new, &mut self.tree.root);
} else {
insert_right(link_ops, current, new, &mut self.tree.root);
}
} else {
insert_left(
link_ops,
first_child(link_ops, root),
new,
&mut self.tree.root,
);
}
} else {
self.tree.insert_root(new);
}
}
}
/// Inserts a new element into the `RBTree` before the current one.
///
/// When using this function you must ensure that the elements in the
/// collection are maintained in increasing order. Failure to do this may
/// lead to `find`, `upper_bound`, `lower_bound` and `range` returning
/// incorrect results.
///
/// If the cursor is pointing at the null object then the new element is
/// inserted at the end of the `RBTree`.
///
/// # Panics
///
/// Panics if the new element is already linked to a different intrusive
/// collection.
#[inline]
pub fn insert_before(&mut self, val: <A::PointerOps as PointerOps>::Pointer) {
unsafe {
let new = self.tree.node_from_value(val);
let link_ops = self.tree.adapter.link_ops_mut();
if let Some(root) = self.tree.root {
if let Some(current) = self.current {
if link_ops.left(current).is_some() {
let prev = prev(link_ops, current).unwrap_unchecked();
insert_right(link_ops, prev, new, &mut self.tree.root);
} else {
insert_left(link_ops, current, new, &mut self.tree.root);
}
} else {
insert_right(
link_ops,
last_child(link_ops, root),
new,
&mut self.tree.root,
);
}
} else {
self.tree.insert_root(new);
}
}
}
/// Consumes `CursorMut` and returns a reference to the object that
/// the cursor is currently pointing to. Unlike [get](Self::get),
/// the returned reference's lifetime is tied to `RBTree`'s lifetime.
///
/// This returns None if the cursor is currently pointing to the null object.
#[inline]
pub fn into_ref(self) -> Option<&'a <A::PointerOps as PointerOps>::Value> {
Some(unsafe { &*self.tree.adapter.get_value(self.current?) })
}
}
impl<'a, A: for<'b> KeyAdapter<'b>> CursorMut<'a, A>
where
<A as Adapter>::LinkOps: RBTreeOps,
{
/// Inserts a new element into the `RBTree`.
///
/// The new element will be inserted at the correct position in the tree
/// based on its key, regardless of the current cursor position.
///
/// # Panics
///
/// Panics if the new element is already linked to a different intrusive
/// collection.
#[inline]
pub fn insert<'c>(&'c mut self, val: <A::PointerOps as PointerOps>::Pointer)
where
<A as KeyAdapter<'c>>::Key: Ord,
{
// We explicitly drop the returned CursorMut here, otherwise we would
// end up with multiple CursorMut in the same collection.
self.tree.insert(val);
}
}
/// A cursor with ownership over the `RBTree` it points into.
pub struct CursorOwning<A: Adapter>
where
A::LinkOps: RBTreeOps,
{
current: Option<<A::LinkOps as link_ops::LinkOps>::LinkPtr>,
tree: RBTree<A>,
}
impl<A: Adapter> CursorOwning<A>
where
A::LinkOps: RBTreeOps,
{
/// Consumes self and returns the inner `RBTree`.
#[inline]
pub fn into_inner(self) -> RBTree<A> {
self.tree
}
/// Returns a read-only cursor pointing to the current element.
///
/// The lifetime of the returned `Cursor` is bound to that of the
/// `CursorOwning`, which means it cannot outlive the `CursorOwning` and that the
/// `CursorOwning` is frozen for the lifetime of the `Cursor`.
///
/// Mutations of the returned cursor are _not_ reflected in the original.
#[inline]
pub fn as_cursor(&self) -> Cursor<'_, A> {
Cursor {
current: self.current,
tree: &self.tree,
}
}
/// Perform action with mutable reference to the cursor.
///
/// All mutations of the cursor are reflected in the original.
#[inline]
pub fn with_cursor_mut<T>(&mut self, f: impl FnOnce(&mut CursorMut<'_, A>) -> T) -> T {
let mut cursor = CursorMut {
current: self.current,
tree: &mut self.tree,
};
let ret = f(&mut cursor);
self.current = cursor.current;
ret
}
}
unsafe impl<A: Adapter> Send for CursorOwning<A>
where
RBTree<A>: Send,
A::LinkOps: RBTreeOps,
{
}
// =============================================================================
// RBTree
// =============================================================================
/// An intrusive red-black tree.
///
/// When this collection is dropped, all elements linked into it will be
/// converted back to owned pointers and dropped.
///
/// Note that you are responsible for ensuring that the elements in a `RBTree`
/// remain in ascending key order. This property can be violated, either because
/// the key of an element was modified, or because the
/// `insert_before`/`insert_after` methods of `CursorMut` were incorrectly used.
/// If this situation occurs, memory safety will not be violated but the `find`,
/// `upper_bound`, `lower_bound` and `range` may return incorrect results.
pub struct RBTree<A: Adapter>
where
A::LinkOps: RBTreeOps,
{
root: Option<<A::LinkOps as link_ops::LinkOps>::LinkPtr>,
adapter: A,
}
impl<A: Adapter> RBTree<A>
where
A::LinkOps: RBTreeOps,
{
#[inline]
fn node_from_value(
&mut self,
val: <A::PointerOps as PointerOps>::Pointer,
) -> <A::LinkOps as link_ops::LinkOps>::LinkPtr {
use link_ops::LinkOps;
unsafe {
let raw = self.adapter.pointer_ops().into_raw(val);
let link = self.adapter.get_link(raw);
if !self.adapter.link_ops_mut().acquire_link(link) {
// convert the node back into a pointer
self.adapter.pointer_ops().from_raw(raw);
panic!("attempted to insert an object that is already linked");
}
link
}
}
/// Creates an empty `RBTree`.
#[cfg(not(feature = "nightly"))]
#[inline]
pub fn new(adapter: A) -> RBTree<A> {
RBTree {
root: None,
adapter,
}
}
/// Creates an empty `RBTree`.
#[cfg(feature = "nightly")]
#[inline]
pub const fn new(adapter: A) -> RBTree<A> {
RBTree {
root: None,
adapter,
}
}
/// Returns `true` if the `RBTree` is empty.
#[inline]
pub fn is_empty(&self) -> bool {
self.root.is_none()
}
/// Returns a null `Cursor` for this tree.
#[inline]
pub fn cursor(&self) -> Cursor<'_, A> {
Cursor {
current: None,
tree: self,
}
}
/// Returns a null `CursorMut` for this tree.
#[inline]
pub fn cursor_mut(&mut self) -> CursorMut<'_, A> {
CursorMut {
current: None,
tree: self,
}
}
/// Returns a null `CursorOwning` for this tree.
#[inline]
pub fn cursor_owning(self) -> CursorOwning<A> {
CursorOwning {
current: None,
tree: self,
}
}
/// Creates a `Cursor` from a pointer to an element.
///
/// # Safety
///
/// `ptr` must be a pointer to an object that is part of this tree.
#[inline]
pub unsafe fn cursor_from_ptr(
&self,
ptr: *const <A::PointerOps as PointerOps>::Value,
) -> Cursor<'_, A> {
Cursor {
current: Some(self.adapter.get_link(ptr)),
tree: self,
}
}
/// Creates a `CursorMut` from a pointer to an element.
///
/// # Safety
///
/// `ptr` must be a pointer to an object that is part of this tree.
#[inline]
pub unsafe fn cursor_mut_from_ptr(
&mut self,
ptr: *const <A::PointerOps as PointerOps>::Value,
) -> CursorMut<'_, A> {
CursorMut {
current: Some(self.adapter.get_link(ptr)),
tree: self,
}
}
/// Creates a `CursorOwning` from a pointer to an element.
///
/// # Safety
///
/// `ptr` must be a pointer to an object that is part of this tree.
#[inline]
pub unsafe fn cursor_owning_from_ptr(
self,
ptr: *const <A::PointerOps as PointerOps>::Value,
) -> CursorOwning<A> {
CursorOwning {
current: Some(self.adapter.get_link(ptr)),
tree: self,
}
}
/// Returns a `Cursor` pointing to the first element of the tree. If the
/// tree is empty then a null cursor is returned.
#[inline]
pub fn front(&self) -> Cursor<'_, A> {
let mut cursor = self.cursor();
cursor.move_next();
cursor
}
/// Returns a `CursorMut` pointing to the first element of the tree. If the
/// the tree is empty then a null cursor is returned.
#[inline]
pub fn front_mut(&mut self) -> CursorMut<'_, A> {
let mut cursor = self.cursor_mut();
cursor.move_next();
cursor
}
/// Returns a `CursorOwning` pointing to the first element of the tree. If the
/// the tree is empty then a null cursor is returned.
#[inline]
pub fn front_owning(self) -> CursorOwning<A> {
let mut cursor = self.cursor_owning();
cursor.with_cursor_mut(|c| c.move_next());
cursor
}
/// Returns a `Cursor` pointing to the last element of the tree. If the tree
/// is empty then a null cursor is returned.
#[inline]
pub fn back(&self) -> Cursor<'_, A> {
let mut cursor = self.cursor();
cursor.move_prev();
cursor
}
/// Returns a `CursorMut` pointing to the last element of the tree. If the
/// tree is empty then a null cursor is returned.
#[inline]
pub fn back_mut(&mut self) -> CursorMut<'_, A> {
let mut cursor = self.cursor_mut();
cursor.move_prev();
cursor
}
/// Returns a `CursorOwning` pointing to the last element of the tree. If the
/// tree is empty then a null cursor is returned.
#[inline]
pub fn back_owning(self) -> CursorOwning<A> {
let mut cursor = self.cursor_owning();
cursor.with_cursor_mut(|c| c.move_prev());
cursor
}
#[inline]
unsafe fn insert_root(&mut self, node: <A::LinkOps as link_ops::LinkOps>::LinkPtr) {
self.adapter.link_ops_mut().set_parent(node, None);
self.adapter.link_ops_mut().set_color(node, Color::Black);
self.adapter.link_ops_mut().set_left(node, None);
self.adapter.link_ops_mut().set_right(node, None);
self.root = Some(node);
}
/// Gets an iterator over the objects in the `RBTree`.
#[inline]
pub fn iter(&self) -> Iter<'_, A> {
let link_ops = self.adapter.link_ops();
if let Some(root) = self.root {
Iter {
head: Some(unsafe { first_child(link_ops, root) }),
tail: Some(unsafe { last_child(link_ops, root) }),
tree: self,
}
} else {
Iter {
head: None,
tail: None,
tree: self,
}
}
}
#[inline]
fn clear_recurse(&mut self, current: Option<<A::LinkOps as link_ops::LinkOps>::LinkPtr>) {
use link_ops::LinkOps;
// If adapter.get_value or Pointer::from_raw panic here, it will leak
// the nodes and keep them linked. However this is harmless since there
// is nothing you can do with just a Link.
if let Some(current) = current {
unsafe {
let left = self.adapter.link_ops_mut().left(current);
let right = self.adapter.link_ops_mut().right(current);
self.clear_recurse(left);
self.clear_recurse(right);
self.adapter.link_ops_mut().release_link(current);
self.adapter
.pointer_ops()
.from_raw(self.adapter.get_value(current));
}
}
}
/// Removes all elements from the `RBTree`.
///
/// This will unlink all object currently in the tree, which requires
/// iterating through all elements in the `RBTree`. Each element is
/// converted back to an owned pointer and then dropped.
#[inline]
pub fn clear(&mut self) {
let root = self.root.take();
self.clear_recurse(root);
}
/// Empties the `RBTree` without unlinking or freeing objects in it.
///
/// Since this does not unlink any objects, any attempts to link these
/// objects into another `RBTree` will fail but will not cause any
/// memory unsafety. To unlink those objects manually, you must call the
/// `force_unlink` function on them.
#[inline]
pub fn fast_clear(&mut self) {
self.root = None;
}
/// Takes all the elements out of the `RBTree`, leaving it empty. The
/// taken elements are returned as a new `RBTree`.
#[inline]
pub fn take(&mut self) -> RBTree<A>
where
A: Clone,
{
let tree = RBTree {
root: self.root,
adapter: self.adapter.clone(),
};
self.root = None;
tree
}
}
impl<A: for<'a> KeyAdapter<'a>> RBTree<A>
where
<A as Adapter>::LinkOps: RBTreeOps,
{
#[inline]
fn find_internal<'a, Q: ?Sized + Ord>(
&self,
key: &Q,
) -> Option<<A::LinkOps as link_ops::LinkOps>::LinkPtr>
where
<A as KeyAdapter<'a>>::Key: Borrow<Q>,
<A::PointerOps as PointerOps>::Value: 'a,
{
let link_ops = self.adapter.link_ops();
let mut tree = self.root;
while let Some(x) = tree {
let current = unsafe { &*self.adapter.get_value(x) };
match key.cmp(self.adapter.get_key(current).borrow()) {
Ordering::Less => tree = unsafe { link_ops.left(x) },
Ordering::Equal => return tree,
Ordering::Greater => tree = unsafe { link_ops.right(x) },
}
}
None
}
/// Returns a `Cursor` pointing to an element with the given key. If no such
/// element is found then a null cursor is returned.
///
/// If multiple elements with an identical key are found then an arbitrary
/// one is returned.
#[inline]
pub fn find<'a, 'b, Q: ?Sized + Ord>(&'a self, key: &Q) -> Cursor<'a, A>
where
<A as KeyAdapter<'b>>::Key: Borrow<Q>,
'a: 'b,
{
Cursor {
current: self.find_internal(key),
tree: self,
}
}
/// Returns a `CursorMut` pointing to an element with the given key. If no
/// such element is found then a null cursor is returned.
///
/// If multiple elements with an identical key are found then an arbitrary
/// one is returned.
#[inline]
pub fn find_mut<'a, 'b, Q: ?Sized + Ord>(&'a mut self, key: &Q) -> CursorMut<'a, A>
where
<A as KeyAdapter<'b>>::Key: Borrow<Q>,
'a: 'b,
{
CursorMut {
current: self.find_internal(key),
tree: self,
}
}
// Returns a `CursorOwning` pointing to an element with the given key. If no
/// such element is found then a null cursor is returned.
///
/// If multiple elements with an identical key are found then an arbitrary
/// one is returned.
#[inline]
pub fn find_owning<'a, Q: ?Sized + Ord>(self, key: &Q) -> CursorOwning<A>
where
<A as KeyAdapter<'a>>::Key: Borrow<Q>,
Self: 'a,
{
CursorOwning {
current: self.find_internal(key),
tree: self,
}
}
#[inline]
fn lower_bound_internal<'a, Q: ?Sized + Ord>(
&self,
bound: Bound<&Q>,
) -> Option<<A::LinkOps as link_ops::LinkOps>::LinkPtr>
where
<A as KeyAdapter<'a>>::Key: Borrow<Q>,
<A::PointerOps as PointerOps>::Value: 'a,
{
let link_ops = self.adapter.link_ops();
let mut tree = self.root;
let mut result = None;
while let Some(x) = tree {
let current = unsafe { &*self.adapter.get_value(x) };
let cond = match bound {
Unbounded => true,
Included(key) => key <= self.adapter.get_key(current).borrow(),
Excluded(key) => key < self.adapter.get_key(current).borrow(),
};
if cond {
result = tree;
tree = unsafe { link_ops.left(x) };
} else {
tree = unsafe { link_ops.right(x) };
}
}
result
}
/// Returns a `Cursor` pointing to the lowest element whose key is above
/// the given bound. If no such element is found then a null cursor is
/// returned.
#[inline]
pub fn lower_bound<'a, 'b, Q: ?Sized + Ord>(&'a self, bound: Bound<&Q>) -> Cursor<'a, A>
where
<A as KeyAdapter<'b>>::Key: Borrow<Q>,
'a: 'b,
{
Cursor {
current: self.lower_bound_internal(bound),
tree: self,
}
}
/// Returns a `CursorMut` pointing to the first element whose key is
/// above the given bound. If no such element is found then a null
/// cursor is returned.
#[inline]
pub fn lower_bound_mut<'a, 'b, Q: ?Sized + Ord>(
&'a mut self,
bound: Bound<&Q>,
) -> CursorMut<'a, A>
where
<A as KeyAdapter<'b>>::Key: Borrow<Q>,
'a: 'b,
{
CursorMut {
current: self.lower_bound_internal(bound),
tree: self,
}
}
/// Returns a `CursorOwning` pointing to the first element whose key is
/// above the given bound. If no such element is found then a null
/// cursor is returned.
#[inline]
pub fn lower_bound_owning<'a, Q: ?Sized + Ord>(self, bound: Bound<&Q>) -> CursorOwning<A>
where
<A as KeyAdapter<'a>>::Key: Borrow<Q>,
Self: 'a,
{
CursorOwning {
current: self.lower_bound_internal(bound),
tree: self,
}
}
#[inline]
fn upper_bound_internal<'a, Q: ?Sized + Ord>(
&self,
bound: Bound<&Q>,
) -> Option<<A::LinkOps as link_ops::LinkOps>::LinkPtr>
where
<A as KeyAdapter<'a>>::Key: Borrow<Q>,
<A::PointerOps as PointerOps>::Value: 'a,
{
let link_ops = self.adapter.link_ops();
let mut tree = self.root;
let mut result = None;
while let Some(x) = tree {
let current = unsafe { &*self.adapter.get_value(x) };
let cond = match bound {
Unbounded => false,
Included(key) => key < self.adapter.get_key(current).borrow(),
Excluded(key) => key <= self.adapter.get_key(current).borrow(),
};
if cond {
tree = unsafe { link_ops.left(x) };
} else {
result = tree;
tree = unsafe { link_ops.right(x) };
}
}
result
}
/// Returns a `Cursor` pointing to the last element whose key is below
/// the given bound. If no such element is found then a null cursor is
/// returned.
#[inline]
pub fn upper_bound<'a, 'b, Q: ?Sized + Ord>(&'a self, bound: Bound<&Q>) -> Cursor<'a, A>
where
<A as KeyAdapter<'b>>::Key: Borrow<Q>,
'a: 'b,
{
Cursor {
current: self.upper_bound_internal(bound),
tree: self,
}
}
/// Returns a `CursorMut` pointing to the last element whose key is
/// below the given bound. If no such element is found then a null
/// cursor is returned.
#[inline]
pub fn upper_bound_mut<'a, 'b, Q: ?Sized + Ord>(
&'a mut self,
bound: Bound<&Q>,
) -> CursorMut<'a, A>
where
<A as KeyAdapter<'b>>::Key: Borrow<Q>,
'a: 'b,
{
CursorMut {
current: self.upper_bound_internal(bound),
tree: self,
}
}
/// Returns a `CursorOwning` pointing to the last element whose key is
/// below the given bound. If no such element is found then a null
/// cursor is returned.
#[inline]
pub fn upper_bound_owning<'a, Q: ?Sized + Ord>(self, bound: Bound<&Q>) -> CursorOwning<A>
where
<A as KeyAdapter<'a>>::Key: Borrow<Q>,
Self: 'a,
{
CursorOwning {
current: self.upper_bound_internal(bound),
tree: self,
}
}
/// Inserts a new element into the `RBTree`.
///
/// The new element will be inserted at the correct position in the tree
/// based on its key.
///
/// Returns a mutable cursor pointing to the newly added element.
///
/// # Panics
///
/// Panics if the new element is already linked to a different intrusive
/// collection.
#[inline]
pub fn insert<'a>(&'a mut self, val: <A::PointerOps as PointerOps>::Pointer) -> CursorMut<'_, A>
where
<A as KeyAdapter<'a>>::Key: Ord,
{
unsafe {
let new = self.node_from_value(val);
let raw = self.adapter.get_value(new);
if let Some(root) = self.root {
let key = self.adapter.get_key(&*raw);
let mut tree = root;
loop {
let current = &*self.adapter.get_value(tree);
if key < self.adapter.get_key(current) {
if let Some(left) = self.adapter.link_ops().left(tree) {
tree = left;
} else {
insert_left(self.adapter.link_ops_mut(), tree, new, &mut self.root);
break;
}
} else {
if let Some(right) = self.adapter.link_ops().right(tree) {
tree = right;
} else {
insert_right(self.adapter.link_ops_mut(), tree, new, &mut self.root);
break;
}
}
}
} else {
self.insert_root(new);
}
CursorMut {
current: Some(new),
tree: self,
}
}
}
/// Returns an `Entry` for the given key which contains a `CursorMut` to an
/// element with the given key or an `InsertCursor` which points to a place
/// in which to insert a new element with the given key.
///
/// This is more efficient than calling `find` followed by `insert` since
/// the tree does not have to be searched a second time to find a place to
/// insert the new element.
///
/// If multiple elements with an identical key are found then an arbitrary
/// one is returned.
#[inline]
pub fn entry<'a, Q: ?Sized + Ord>(&'a mut self, key: &Q) -> Entry<'a, A>
where
<A as KeyAdapter<'a>>::Key: Borrow<Q>,
{
unsafe {
if let Some(root) = self.root {
let mut tree = root;
loop {
let current = &*self.adapter.get_value(tree);
match key.cmp(self.adapter.get_key(current).borrow()) {
Ordering::Less => {
if let Some(left) = self.adapter.link_ops().left(tree) {
tree = left;
} else {
return Entry::Vacant(InsertCursor {
parent: Some(tree),
insert_left: true,
tree: self,
});
}
}
Ordering::Equal => {
return Entry::Occupied(CursorMut {
current: Some(tree),
tree: self,
});
}
Ordering::Greater => {
if let Some(right) = self.adapter.link_ops().right(tree) {
tree = right;
} else {
return Entry::Vacant(InsertCursor {
parent: Some(tree),
insert_left: false,
tree: self,
});
}
}
}
}
} else {
Entry::Vacant(InsertCursor {
parent: None,
insert_left: false,
tree: self,
})
}
}
}
/// Constructs a double-ended iterator over a sub-range of elements in the
/// tree, starting at min, and ending at max. If min is `Unbounded`, then it
/// will be treated as "negative infinity", and if max is `Unbounded`, then
/// it will be treated as "positive infinity". Thus
/// `range(Unbounded, Unbounded)` will yield the whole collection.
#[inline]
pub fn range<'a, Min: ?Sized + Ord, Max: ?Sized + Ord>(
&'a self,
min: Bound<&Min>,
max: Bound<&Max>,
) -> Iter<'a, A>
where
<A as KeyAdapter<'a>>::Key: Borrow<Min> + Borrow<Max>,
<A as KeyAdapter<'a>>::Key: Ord,
{
let lower = self.lower_bound_internal(min);
let upper = self.upper_bound_internal(max);
if let (Some(lower), Some(upper)) = (lower, upper) {
let lower_key = unsafe { self.adapter.get_key(&*self.adapter.get_value(lower)) };
let upper_key = unsafe { self.adapter.get_key(&*self.adapter.get_value(upper)) };
if upper_key >= lower_key {
return Iter {
head: Some(lower),
tail: Some(upper),
tree: self,
};
}
}
Iter {
head: None,
tail: None,
tree: self,
}
}
}
// Allow read-only access to values from multiple threads
unsafe impl<A: Adapter + Sync> Sync for RBTree<A>
where
<A::PointerOps as PointerOps>::Value: Sync,
A::LinkOps: RBTreeOps,
{
}
// Allow sending to another thread if the ownership (represented by the <A::PointerOps as PointerOps>::Pointer owned
// pointer type) can be transferred to another thread.
unsafe impl<A: Adapter + Send> Send for RBTree<A>
where
<A::PointerOps as PointerOps>::Pointer: Send,
A::LinkOps: RBTreeOps,
{
}
// Drop all owned pointers if the collection is dropped
impl<A: Adapter> Drop for RBTree<A>
where
A::LinkOps: RBTreeOps,
{
#[inline]
fn drop(&mut self) {
self.clear();
}
}
impl<A: Adapter> IntoIterator for RBTree<A>
where
A::LinkOps: RBTreeOps,
{
type Item = <A::PointerOps as PointerOps>::Pointer;
type IntoIter = IntoIter<A>;
#[inline]
fn into_iter(self) -> IntoIter<A> {
let link_ops = self.adapter.link_ops();
if let Some(root) = self.root {
IntoIter {
head: Some(unsafe { first_child(link_ops, root) }),
tail: Some(unsafe { last_child(link_ops, root) }),
tree: self,
}
} else {
IntoIter {
head: None,
tail: None,
tree: self,
}
}
}
}
impl<'a, A: Adapter + 'a> IntoIterator for &'a RBTree<A>
where
A::LinkOps: RBTreeOps,
{
type Item = &'a <A::PointerOps as PointerOps>::Value;
type IntoIter = Iter<'a, A>;
#[inline]
fn into_iter(self) -> Iter<'a, A> {
self.iter()
}
}
impl<A: Adapter + Default> Default for RBTree<A>
where
A::LinkOps: RBTreeOps,
{
fn default() -> RBTree<A> {
RBTree::new(A::default())
}
}
impl<A: Adapter> fmt::Debug for RBTree<A>
where
A::LinkOps: RBTreeOps,
<A::PointerOps as PointerOps>::Value: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_set().entries(self.iter()).finish()
}
}
// =============================================================================
// InsertCursor, Entry
// =============================================================================
/// A cursor pointing to a slot in which an element can be inserted into a
/// `RBTree`.
pub struct InsertCursor<'a, A: Adapter>
where
A::LinkOps: RBTreeOps,
{
parent: Option<<A::LinkOps as link_ops::LinkOps>::LinkPtr>,
insert_left: bool,
tree: &'a mut RBTree<A>,
}
impl<'a, A: Adapter + 'a> InsertCursor<'a, A>
where
A::LinkOps: RBTreeOps,
{
/// Inserts a new element into the `RBTree` at the location indicated by
/// this `InsertCursor`.
///
/// # Panics
///
/// Panics if the new element is already linked to a different intrusive
/// collection.
pub fn insert(self, val: <A::PointerOps as PointerOps>::Pointer) -> CursorMut<'a, A> {
unsafe {
let new = self.tree.node_from_value(val);
let link_ops = self.tree.adapter.link_ops_mut();
if let Some(parent) = self.parent {
if self.insert_left {
insert_left(link_ops, parent, new, &mut self.tree.root);
} else {
insert_right(link_ops, parent, new, &mut self.tree.root);
}
} else {
self.tree.insert_root(new);
}
CursorMut {
current: Some(new),
tree: self.tree,
}
}
}
}
/// An entry in a `RBTree`.
///
/// See the documentation for `RBTree::entry`.
pub enum Entry<'a, A: Adapter>
where
A::LinkOps: RBTreeOps,
{
/// An occupied entry.
Occupied(CursorMut<'a, A>),
/// A vacant entry.
Vacant(InsertCursor<'a, A>),
}
impl<'a, A: Adapter + 'a> Entry<'a, A>
where
A::LinkOps: RBTreeOps,
{
/// Inserts an element into the `RBTree` if the entry is vacant, returning
/// a `CursorMut` to the resulting value. If the entry is occupied then a
/// `CursorMut` pointing to the element is returned.
///
/// # Panics
///
/// Panics if the `Entry` is vacant and the new element is already linked to
/// a different intrusive collection.
pub fn or_insert(self, val: <A::PointerOps as PointerOps>::Pointer) -> CursorMut<'a, A> {
match self {
Entry::Occupied(entry) => entry,
Entry::Vacant(entry) => entry.insert(val),
}
}
/// Calls the given function and inserts the result into the `RBTree` if the
/// entry is vacant, returning a `CursorMut` to the resulting value. If the
/// entry is occupied then a `CursorMut` pointing to the element is
/// returned and the function is not executed.
///
/// # Panics
///
/// Panics if the `Entry` is vacant and the new element is already linked to
/// a different intrusive collection.
pub fn or_insert_with<F>(self, default: F) -> CursorMut<'a, A>
where
F: FnOnce() -> <A::PointerOps as PointerOps>::Pointer,
{
match self {
Entry::Occupied(entry) => entry,
Entry::Vacant(entry) => entry.insert(default()),
}
}
}
// =============================================================================
// Iter
// =============================================================================
/// An iterator over references to the items of a `RBTree`.
pub struct Iter<'a, A: Adapter>
where
A::LinkOps: RBTreeOps,
{
head: Option<<A::LinkOps as link_ops::LinkOps>::LinkPtr>,
tail: Option<<A::LinkOps as link_ops::LinkOps>::LinkPtr>,
tree: &'a RBTree<A>,
}
impl<'a, A: Adapter + 'a> Iterator for Iter<'a, A>
where
A::LinkOps: RBTreeOps,
{
type Item = &'a <A::PointerOps as PointerOps>::Value;
#[inline]
fn next(&mut self) -> Option<&'a <A::PointerOps as PointerOps>::Value> {
let head = self.head?;
if Some(head) == self.tail {
self.head = None;
self.tail = None;
} else {
self.head = unsafe { next(self.tree.adapter.link_ops(), head) };
}
Some(unsafe { &*self.tree.adapter.get_value(head) })
}
}
impl<'a, A: Adapter + 'a> DoubleEndedIterator for Iter<'a, A>
where
A::LinkOps: RBTreeOps,
{
#[inline]
fn next_back(&mut self) -> Option<&'a <A::PointerOps as PointerOps>::Value> {
let tail = self.tail?;
if Some(tail) == self.head {
self.head = None;
self.tail = None;
} else {
self.tail = unsafe { prev(self.tree.adapter.link_ops(), tail) };
}
Some(unsafe { &*self.tree.adapter.get_value(tail) })
}
}
impl<'a, A: Adapter + 'a> Clone for Iter<'a, A>
where
A::LinkOps: RBTreeOps,
{
#[inline]
fn clone(&self) -> Iter<'a, A> {
Iter {
head: self.head,
tail: self.tail,
tree: self.tree,
}
}
}
// =============================================================================
// IntoIter
// =============================================================================
/// An iterator which consumes a `RBTree`.
pub struct IntoIter<A: Adapter>
where
A::LinkOps: RBTreeOps,
{
head: Option<<A::LinkOps as link_ops::LinkOps>::LinkPtr>,
tail: Option<<A::LinkOps as link_ops::LinkOps>::LinkPtr>,
tree: RBTree<A>,
}
impl<A: Adapter> Iterator for IntoIter<A>
where
A::LinkOps: RBTreeOps,
{
type Item = <A::PointerOps as PointerOps>::Pointer;
#[inline]
fn next(&mut self) -> Option<<A::PointerOps as PointerOps>::Pointer> {
use link_ops::LinkOps;
let head = self.head?;
let link_ops = self.tree.adapter.link_ops_mut();
unsafe {
// Remove the node from the tree. Since head is always the
// left-most node, we can infer the following:
// - head.left is null.
// - head is a left child of its parent (or the root node).
if let Some(parent) = link_ops.parent(head) {
link_ops.set_left(parent, link_ops.right(head));
} else {
self.tree.root = link_ops.right(head);
if link_ops.right(head).is_none() {
self.tail = None;
}
}
if let Some(right) = link_ops.right(head) {
link_ops.set_parent(right, link_ops.parent(head));
self.head = Some(first_child(link_ops, right));
} else {
self.head = link_ops.parent(head);
}
link_ops.release_link(head);
Some(
self.tree
.adapter
.pointer_ops()
.from_raw(self.tree.adapter.get_value(head)),
)
}
}
}
impl<A: Adapter> DoubleEndedIterator for IntoIter<A>
where
A::LinkOps: RBTreeOps,
{
#[inline]
fn next_back(&mut self) -> Option<<A::PointerOps as PointerOps>::Pointer> {
use link_ops::LinkOps;
let tail = self.tail?;
let link_ops = self.tree.adapter.link_ops_mut();
unsafe {
// Remove the node from the tree. Since tail is always the
// right-most node, we can infer the following:
// - tail.right is null.
// - tail is a right child of its parent (or the root node).
if let Some(parent) = link_ops.parent(tail) {
link_ops.set_right(parent, link_ops.left(tail));
} else {
self.tree.root = link_ops.left(tail);
if link_ops.left(tail).is_none() {
self.tail = None;
}
}
if let Some(left) = link_ops.left(tail) {
link_ops.set_parent(left, link_ops.parent(tail));
self.tail = Some(last_child(link_ops, left));
} else {
self.tail = link_ops.parent(tail);
}
link_ops.release_link(tail);
Some(
self.tree
.adapter
.pointer_ops()
.from_raw(self.tree.adapter.get_value(tail)),
)
}
}
}
// =============================================================================
// Tests
// =============================================================================
#[cfg(test)]
mod tests {
use super::{CursorOwning, Entry, KeyAdapter, Link, PointerOps, RBTree};
use crate::{Bound::*, UnsafeRef};
use alloc::boxed::Box;
use rand::prelude::*;
use rand_xorshift::XorShiftRng;
use std::fmt;
use std::rc::Rc;
use std::vec::Vec;
use std::{format, vec};
#[derive(Clone)]
struct Obj {
link: Link,
value: i32,
}
impl fmt::Debug for Obj {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.value)
}
}
intrusive_adapter!(RcObjAdapter = Rc<Obj>: Obj { link: Link });
impl<'a> KeyAdapter<'a> for RcObjAdapter {
type Key = i32;
fn get_key(&self, value: &'a <Self::PointerOps as PointerOps>::Value) -> i32 {
value.value
}
}
intrusive_adapter!(UnsafeRefObjAdapter = UnsafeRef<Obj>: Obj { link: Link });
impl<'a> KeyAdapter<'a> for UnsafeRefObjAdapter {
type Key = i32;
fn get_key(&self, value: &'a <Self::PointerOps as PointerOps>::Value) -> i32 {
value.value
}
}
fn make_rc_obj(value: i32) -> Rc<Obj> {
Rc::new(make_obj(value))
}
fn make_obj(value: i32) -> Obj {
Obj {
link: Link::new(),
value,
}
}
#[test]
fn test_link() {
let a = make_rc_obj(1);
assert!(!a.link.is_linked());
assert_eq!(format!("{:?}", a.link), "unlinked");
let mut b = RBTree::<RcObjAdapter>::default();
assert!(b.is_empty());
assert_eq!(b.insert(a.clone()).get().unwrap().value, 1);
assert!(!b.is_empty());
assert!(a.link.is_linked());
assert_eq!(format!("{:?}", a.link), "linked");
let c = a.as_ref().clone();
assert!(!c.link.is_linked());
unsafe {
assert_eq!(b.cursor_from_ptr(a.as_ref()).get().unwrap().value, 1);
assert_eq!(b.cursor_mut_from_ptr(a.as_ref()).get().unwrap().value, 1);
}
assert_eq!(
b.front_mut().remove().unwrap().as_ref() as *const _,
a.as_ref() as *const _
);
assert!(b.is_empty());
assert!(!a.link.is_linked());
}
#[test]
fn test_cursor() {
let a = make_rc_obj(1);
let b = make_rc_obj(2);
let c = make_rc_obj(3);
let mut t = RBTree::new(RcObjAdapter::new());
let mut cur = t.cursor_mut();
assert!(cur.is_null());
assert!(cur.get().is_none());
assert!(cur.remove().is_none());
cur.insert_before(a.clone());
cur.insert_before(c.clone());
cur.move_prev();
cur.insert(b.clone());
assert!(cur.peek_next().is_null());
cur.move_next();
assert!(cur.is_null());
cur.move_next();
assert!(cur.peek_prev().is_null());
assert!(!cur.is_null());
assert_eq!(cur.get().unwrap() as *const _, a.as_ref() as *const _);
{
let mut cur2 = cur.as_cursor();
assert_eq!(cur2.get().unwrap() as *const _, a.as_ref() as *const _);
assert_eq!(cur2.peek_next().get().unwrap().value, 2);
cur2.move_next();
assert_eq!(cur2.get().unwrap().value, 2);
cur2.move_next();
assert_eq!(cur2.peek_prev().get().unwrap().value, 2);
assert_eq!(cur2.get().unwrap() as *const _, c.as_ref() as *const _);
cur2.move_prev();
assert_eq!(cur2.get().unwrap() as *const _, b.as_ref() as *const _);
cur2.move_next();
assert_eq!(cur2.get().unwrap() as *const _, c.as_ref() as *const _);
cur2.move_next();
assert!(cur2.is_null());
assert!(cur2.clone().get().is_none());
}
assert_eq!(cur.get().unwrap() as *const _, a.as_ref() as *const _);
let a2 = make_rc_obj(1);
let b2 = make_rc_obj(2);
let c2 = make_rc_obj(3);
assert_eq!(
cur.replace_with(a2).unwrap().as_ref() as *const _,
a.as_ref() as *const _
);
assert!(!a.link.is_linked());
cur.move_next();
assert_eq!(
cur.replace_with(b2).unwrap().as_ref() as *const _,
b.as_ref() as *const _
);
assert!(!b.link.is_linked());
cur.move_next();
assert_eq!(
cur.replace_with(c2).unwrap().as_ref() as *const _,
c.as_ref() as *const _
);
assert!(!c.link.is_linked());
cur.move_next();
assert_eq!(
cur.replace_with(c.clone()).unwrap_err().as_ref() as *const _,
c.as_ref() as *const _
);
}
#[test]
fn test_cursor_owning() {
struct Container {
cur: CursorOwning<RcObjAdapter>,
}
let mut t = RBTree::new(RcObjAdapter::new());
t.insert(make_rc_obj(1));
t.insert(make_rc_obj(2));
t.insert(make_rc_obj(3));
t.insert(make_rc_obj(4));
let mut con = Container {
cur: t.cursor_owning(),
};
assert!(con.cur.as_cursor().is_null());
con.cur = con.cur.into_inner().front_owning();
assert_eq!(con.cur.as_cursor().get().unwrap().value, 1);
con.cur = con.cur.into_inner().back_owning();
assert_eq!(con.cur.as_cursor().get().unwrap().value, 4);
con.cur = con.cur.into_inner().find_owning(&2);
assert_eq!(con.cur.as_cursor().get().unwrap().value, 2);
con.cur.with_cursor_mut(|c| c.move_next());
assert_eq!(con.cur.as_cursor().get().unwrap().value, 3);
}
#[test]
fn test_insert_remove() {
let len = if cfg!(miri) { 10 } else { 100 };
let v = (0..len).map(make_rc_obj).collect::<Vec<_>>();
assert!(v.iter().all(|x| !x.link.is_linked()));
let mut t = RBTree::new(RcObjAdapter::new());
assert!(t.is_empty());
let mut rng = XorShiftRng::seed_from_u64(0);
{
let mut expected = Vec::new();
for x in v.iter() {
t.insert(x.clone());
expected.push(x.value);
assert_eq!(t.iter().map(|x| x.value).collect::<Vec<_>>(), expected);
}
while let Some(x) = t.front_mut().remove() {
assert_eq!(x.value, expected.remove(0));
assert_eq!(t.iter().map(|x| x.value).collect::<Vec<_>>(), expected);
}
assert!(expected.is_empty());
assert!(t.is_empty());
}
{
let mut expected = Vec::new();
for x in v.iter().rev() {
t.insert(x.clone());
expected.insert(0, x.value);
assert_eq!(t.iter().map(|x| x.value).collect::<Vec<_>>(), expected);
}
while let Some(x) = t.back_mut().remove() {
assert_eq!(x.value, expected.pop().unwrap());
assert_eq!(t.iter().map(|x| x.value).collect::<Vec<_>>(), expected);
}
assert!(expected.is_empty());
assert!(t.is_empty());
}
{
let mut indices = (0..v.len()).collect::<Vec<_>>();
indices.shuffle(&mut rng);
let mut expected = Vec::new();
for i in indices {
t.insert(v[i].clone());
expected.push(v[i].value);
expected[..].sort_unstable();
assert_eq!(t.iter().map(|x| x.value).collect::<Vec<_>>(), expected);
}
while !expected.is_empty() {
{
let index = rng.gen_range(0..expected.len());
let mut c = t.cursor_mut();
for _ in 0..(index + 1) {
c.move_next();
}
assert_eq!(c.remove().unwrap().value, expected.remove(index));
}
assert_eq!(t.iter().map(|x| x.value).collect::<Vec<_>>(), expected);
}
assert!(t.is_empty());
}
{
let mut indices = (0..v.len()).collect::<Vec<_>>();
indices.shuffle(&mut rng);
let mut expected = Vec::new();
for i in indices {
{
let mut c = t.front_mut();
loop {
if let Some(x) = c.get() {
if x.value > v[i].value {
break;
}
} else {
break;
}
c.move_next();
}
c.insert_before(v[i].clone());
}
expected.push(v[i].value);
expected[..].sort_unstable();
assert_eq!(t.iter().map(|x| x.value).collect::<Vec<_>>(), expected);
}
t.clear();
assert!(t.is_empty());
}
{
let mut indices = (0..v.len()).collect::<Vec<_>>();
indices.shuffle(&mut rng);
let mut expected = Vec::new();
for i in indices {
{
let mut c = t.back_mut();
loop {
if let Some(x) = c.get() {
if x.value < v[i].value {
break;
}
} else {
break;
}
c.move_prev();
}
c.insert_after(v[i].clone());
}
expected.push(v[i].value);
expected[..].sort_unstable();
assert_eq!(t.iter().map(|x| x.value).collect::<Vec<_>>(), expected);
}
}
}
#[test]
fn test_iter() {
let v = (0..10).map(|x| make_rc_obj(x * 10)).collect::<Vec<_>>();
let mut t = RBTree::new(RcObjAdapter::new());
for x in v.iter() {
t.insert(x.clone());
}
assert_eq!(
format!("{:?}", t),
"{0, 10, 20, 30, 40, 50, 60, 70, 80, 90}"
);
assert_eq!(
t.iter().clone().map(|x| x.value).collect::<Vec<_>>(),
vec![0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
);
assert_eq!(
(&t).into_iter().rev().map(|x| x.value).collect::<Vec<_>>(),
vec![90, 80, 70, 60, 50, 40, 30, 20, 10, 0]
);
assert_eq!(
t.range(Unbounded, Unbounded)
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
);
assert_eq!(
t.range(Included(&0), Unbounded)
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
);
assert_eq!(
t.range(Excluded(&0), Unbounded)
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![10, 20, 30, 40, 50, 60, 70, 80, 90]
);
assert_eq!(
t.range(Included(&25), Unbounded)
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![30, 40, 50, 60, 70, 80, 90]
);
assert_eq!(
t.range(Excluded(&25), Unbounded)
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![30, 40, 50, 60, 70, 80, 90]
);
assert_eq!(
t.range(Included(&70), Unbounded)
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![70, 80, 90]
);
assert_eq!(
t.range(Excluded(&70), Unbounded)
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![80, 90]
);
assert_eq!(
t.range(Included(&100), Unbounded)
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![]
);
assert_eq!(
t.range(Excluded(&100), Unbounded)
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![]
);
assert_eq!(
t.range(Unbounded, Included(&90))
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
);
assert_eq!(
t.range(Unbounded, Excluded(&90))
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![0, 10, 20, 30, 40, 50, 60, 70, 80]
);
assert_eq!(
t.range(Unbounded, Included(&25))
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![0, 10, 20]
);
assert_eq!(
t.range(Unbounded, Excluded(&25))
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![0, 10, 20]
);
assert_eq!(
t.range(Unbounded, Included(&70))
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![0, 10, 20, 30, 40, 50, 60, 70]
);
assert_eq!(
t.range(Unbounded, Excluded(&70))
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![0, 10, 20, 30, 40, 50, 60]
);
assert_eq!(
t.range(Unbounded, Included(&-1))
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![]
);
assert_eq!(
t.range(Unbounded, Excluded(&-1))
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![]
);
assert_eq!(
t.range(Included(&25), Included(&80))
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![30, 40, 50, 60, 70, 80]
);
assert_eq!(
t.range(Included(&25), Excluded(&80))
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![30, 40, 50, 60, 70]
);
assert_eq!(
t.range(Excluded(&25), Included(&80))
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![30, 40, 50, 60, 70, 80]
);
assert_eq!(
t.range(Excluded(&25), Excluded(&80))
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![30, 40, 50, 60, 70]
);
assert_eq!(
t.range(Included(&25), Included(&25))
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![]
);
assert_eq!(
t.range(Included(&25), Excluded(&25))
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![]
);
assert_eq!(
t.range(Excluded(&25), Included(&25))
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![]
);
assert_eq!(
t.range(Excluded(&25), Excluded(&25))
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![]
);
assert_eq!(
t.range(Included(&50), Included(&50))
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![50]
);
assert_eq!(
t.range(Included(&50), Excluded(&50))
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![]
);
assert_eq!(
t.range(Excluded(&50), Included(&50))
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![]
);
assert_eq!(
t.range(Excluded(&50), Excluded(&50))
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![]
);
assert_eq!(
t.range(Included(&100), Included(&-2))
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![]
);
assert_eq!(
t.range(Included(&100), Excluded(&-2))
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![]
);
assert_eq!(
t.range(Excluded(&100), Included(&-2))
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![]
);
assert_eq!(
t.range(Excluded(&100), Excluded(&-2))
.map(|x| x.value)
.collect::<Vec<_>>(),
vec![]
);
let mut v2 = Vec::new();
for x in t.take() {
v2.push(x.value);
}
assert_eq!(v2, vec![0, 10, 20, 30, 40, 50, 60, 70, 80, 90]);
assert!(t.is_empty());
for _ in t.take() {
unreachable!();
}
for x in v.iter() {
t.insert(x.clone());
}
v2.clear();
for x in t.into_iter().rev() {
v2.push(x.value);
}
assert_eq!(v2, vec![90, 80, 70, 60, 50, 40, 30, 20, 10, 0]);
}
#[test]
fn test_find() {
let v = (0..10).map(|x| make_rc_obj(x * 10)).collect::<Vec<_>>();
let mut t = RBTree::new(RcObjAdapter::new());
for x in v.iter() {
t.insert(x.clone());
}
for i in -9..100 {
fn mod10(x: i32) -> i32 {
if x < 0 {
10 + x % 10
} else {
x % 10
}
}
{
let c = t.find(&i);
assert_eq!(
c.get().map(|x| x.value),
if i % 10 == 0 { Some(i) } else { None }
);
}
{
let c = t.find_mut(&i);
assert_eq!(
c.get().map(|x| x.value),
if i % 10 == 0 { Some(i) } else { None }
);
}
{
let c = t.upper_bound(Unbounded);
assert_eq!(c.get().map(|x| x.value), Some(90));
}
{
let c = t.upper_bound_mut(Unbounded);
assert_eq!(c.get().map(|x| x.value), Some(90));
}
{
let c = t.upper_bound(Included(&i));
assert_eq!(
c.get().map(|x| x.value),
if i >= 0 { Some(i - mod10(i)) } else { None }
);
}
{
let c = t.upper_bound_mut(Included(&i));
assert_eq!(
c.get().map(|x| x.value),
if i >= 0 { Some(i - mod10(i)) } else { None }
);
}
{
let c = t.upper_bound(Excluded(&i));
assert_eq!(
c.get().map(|x| x.value),
if i > 0 {
Some(i - 1 - mod10(i - 1))
} else {
None
}
);
}
{
let c = t.upper_bound_mut(Excluded(&i));
assert_eq!(
c.get().map(|x| x.value),
if i > 0 {
Some(i - 1 - mod10(i - 1))
} else {
None
}
);
}
{
let c = t.lower_bound(Unbounded);
assert_eq!(c.get().map(|x| x.value), Some(0));
}
{
let c = t.lower_bound_mut(Unbounded);
assert_eq!(c.get().map(|x| x.value), Some(0));
}
{
let c = t.lower_bound(Included(&i));
assert_eq!(
c.get().map(|x| x.value),
if i <= 90 {
Some((i + 9) - mod10(i + 9))
} else {
None
}
);
}
{
let c = t.lower_bound_mut(Included(&i));
assert_eq!(
c.get().map(|x| x.value),
if i <= 90 {
Some((i + 9) - mod10(i + 9))
} else {
None
}
);
}
{
let c = t.lower_bound(Excluded(&i));
assert_eq!(
c.get().map(|x| x.value),
if i < 90 {
Some((i + 10) - mod10(i + 10))
} else {
None
}
);
}
{
let c = t.lower_bound_mut(Excluded(&i));
assert_eq!(
c.get().map(|x| x.value),
if i < 90 {
Some((i + 10) - mod10(i + 10))
} else {
None
}
);
}
}
}
#[test]
fn test_fast_clear_force_unlink() {
let mut t = RBTree::new(UnsafeRefObjAdapter::new());
let a = UnsafeRef::from_box(Box::new(make_obj(1)));
let b = UnsafeRef::from_box(Box::new(make_obj(2)));
let c = UnsafeRef::from_box(Box::new(make_obj(3)));
t.insert(a.clone());
t.insert(b.clone());
t.insert(c.clone());
t.fast_clear();
assert!(t.is_empty());
unsafe {
assert!(a.link.is_linked());
assert!(b.link.is_linked());
assert!(c.link.is_linked());
a.link.force_unlink();
b.link.force_unlink();
c.link.force_unlink();
assert!(t.is_empty());
assert!(!a.link.is_linked());
assert!(!b.link.is_linked());
assert!(!c.link.is_linked());
}
unsafe {
UnsafeRef::into_box(a);
UnsafeRef::into_box(b);
UnsafeRef::into_box(c);
}
}
#[test]
fn test_entry() {
let mut t = RBTree::new(RcObjAdapter::new());
let a = make_rc_obj(1);
let b = make_rc_obj(2);
let c = make_rc_obj(3);
let d = make_rc_obj(4);
let e = make_rc_obj(5);
let f = make_rc_obj(6);
t.entry(&3).or_insert(c);
t.entry(&2).or_insert(b.clone());
t.entry(&1).or_insert(a);
match t.entry(&2) {
Entry::Vacant(_) => unreachable!(),
Entry::Occupied(c) => assert_eq!(c.get().unwrap().value, 2),
}
assert_eq!(t.entry(&2).or_insert(b.clone()).get().unwrap().value, 2);
assert_eq!(
t.entry(&2)
.or_insert_with(|| b.clone())
.get()
.unwrap()
.value,
2
);
match t.entry(&5) {
Entry::Vacant(c) => assert_eq!(c.insert(e.clone()).get().unwrap().value, 5),
Entry::Occupied(_) => unreachable!(),
}
assert!(e.link.is_linked());
assert_eq!(t.entry(&4).or_insert(d.clone()).get().unwrap().value, 4);
assert!(d.link.is_linked());
assert_eq!(
t.entry(&6)
.or_insert_with(|| f.clone())
.get()
.unwrap()
.value,
6
);
assert!(f.link.is_linked());
}
#[test]
fn test_non_static() {
#[derive(Clone)]
struct Obj<'a, T> {
link: Link,
value: &'a T,
}
intrusive_adapter!(RcObjAdapter<'a, T> = &'a Obj<'a, T>: Obj<'a, T> {link: Link} where T: 'a);
impl<'a, 'b, T: 'a + 'b> KeyAdapter<'a> for RcObjAdapter<'b, T> {
type Key = &'a T;
fn get_key(&self, value: &'a Obj<'b, T>) -> &'a T {
value.value
}
}
let v = 5;
let a = Obj {
link: Link::default(),
value: &v,
};
let b = a.clone();
let mut l = RBTree::new(RcObjAdapter::new());
l.insert(&a);
l.insert(&b);
assert_eq!(*l.front().get().unwrap().value, 5);
assert_eq!(*l.back().get().unwrap().value, 5);
}
macro_rules! test_clone_pointer {
($ptr: ident, $ptr_import: path) => {
use $ptr_import;
#[derive(Clone)]
struct Obj {
link: Link,
value: usize,
}
intrusive_adapter!(RcObjAdapter = $ptr<Obj>: Obj { link: Link });
impl<'a> KeyAdapter<'a> for RcObjAdapter {
type Key = usize;
fn get_key(&self, value: &'a Obj) -> usize {
value.value
}
}
let a = $ptr::new(Obj {
link: Link::new(),
value: 5,
});
let mut l = RBTree::new(RcObjAdapter::new());
l.insert(a.clone());
assert_eq!(2, $ptr::strong_count(&a));
let pointer = l.front().clone_pointer().unwrap();
assert_eq!(pointer.value, 5);
assert_eq!(3, $ptr::strong_count(&a));
l.front_mut().remove();
assert!(l.front().clone_pointer().is_none());
};
}
#[test]
fn test_clone_pointer_rc() {
test_clone_pointer!(Rc, std::rc::Rc);
}
#[test]
fn test_clone_pointer_arc() {
test_clone_pointer!(Arc, std::sync::Arc);
}
}