/usr/include/stx/btree.h is in stx-btree-dev 0.9-2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 | /**
* \file include/stx/btree.h
* Contains the main B+ tree implementation template class btree.
*/
/*
* STX B+ Tree Template Classes v0.9
* Copyright (C) 2008-2013 Timo Bingmann <tb@panthema.net>
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer, must
* be included in all copies of the Software, in whole or in part, and all
* derivative works of the Software, unless such copies or derivative works are
* solely in the form of machine-executable object code generated by a source
* language processor.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#ifndef _STX_BTREE_H_
#define _STX_BTREE_H_
// *** Required Headers from the STL
#include <algorithm>
#include <functional>
#include <istream>
#include <ostream>
#include <memory>
#include <cstddef>
#include <assert.h>
// *** Debugging Macros
#ifdef BTREE_DEBUG
#include <iostream>
/// Print out debug information to std::cout if BTREE_DEBUG is defined.
#define BTREE_PRINT(x) do { if (debug) (std::cout << x << std::endl); } while(0)
/// Assertion only if BTREE_DEBUG is defined. This is not used in verify().
#define BTREE_ASSERT(x) do { assert(x); } while(0)
#else
/// Print out debug information to std::cout if BTREE_DEBUG is defined.
#define BTREE_PRINT(x) do { } while(0)
/// Assertion only if BTREE_DEBUG is defined. This is not used in verify().
#define BTREE_ASSERT(x) do { } while(0)
#endif
/// The maximum of a and b. Used in some compile-time formulas.
#define BTREE_MAX(a,b) ((a) < (b) ? (b) : (a))
#ifndef BTREE_FRIENDS
/// The macro BTREE_FRIENDS can be used by outside class to access the B+
/// tree internals. This was added for wxBTreeDemo to be able to draw the
/// tree.
#define BTREE_FRIENDS friend class btree_friend;
#endif
/// STX - Some Template Extensions namespace
namespace stx {
/** Generates default traits for a B+ tree used as a set. It estimates leaf and
* inner node sizes by assuming a cache line size of 256 bytes. */
template <typename _Key>
struct btree_default_set_traits
{
/// If true, the tree will self verify it's invariants after each insert()
/// or erase(). The header must have been compiled with BTREE_DEBUG defined.
static const bool selfverify = false;
/// If true, the tree will print out debug information and a tree dump
/// during insert() or erase() operation. The header must have been
/// compiled with BTREE_DEBUG defined and key_type must be std::ostream
/// printable.
static const bool debug = false;
/// Number of slots in each leaf of the tree. Estimated so that each node
/// has a size of about 256 bytes.
static const int leafslots = BTREE_MAX( 8, 256 / (sizeof(_Key)) );
/// Number of slots in each inner node of the tree. Estimated so that each node
/// has a size of about 256 bytes.
static const int innerslots = BTREE_MAX( 8, 256 / (sizeof(_Key) + sizeof(void*)) );
/// As of stx-btree-0.9, the code does linear search in find_lower() and
/// find_upper() instead of binary_search, unless the node size is larger
/// than this threshold. See notes at
/// http://panthema.net/2013/0504-STX-B+Tree-Binary-vs-Linear-Search
static const size_t binsearch_threshold = 256;
};
/** Generates default traits for a B+ tree used as a map. It estimates leaf and
* inner node sizes by assuming a cache line size of 256 bytes. */
template <typename _Key, typename _Data>
struct btree_default_map_traits
{
/// If true, the tree will self verify it's invariants after each insert()
/// or erase(). The header must have been compiled with BTREE_DEBUG defined.
static const bool selfverify = false;
/// If true, the tree will print out debug information and a tree dump
/// during insert() or erase() operation. The header must have been
/// compiled with BTREE_DEBUG defined and key_type must be std::ostream
/// printable.
static const bool debug = false;
/// Number of slots in each leaf of the tree. Estimated so that each node
/// has a size of about 256 bytes.
static const int leafslots = BTREE_MAX( 8, 256 / (sizeof(_Key) + sizeof(_Data)) );
/// Number of slots in each inner node of the tree. Estimated so that each node
/// has a size of about 256 bytes.
static const int innerslots = BTREE_MAX( 8, 256 / (sizeof(_Key) + sizeof(void*)) );
/// As of stx-btree-0.9, the code does linear search in find_lower() and
/// find_upper() instead of binary_search, unless the node size is larger
/// than this threshold. See notes at
/// http://panthema.net/2013/0504-STX-B+Tree-Binary-vs-Linear-Search
static const size_t binsearch_threshold = 256;
};
/** @brief Basic class implementing a base B+ tree data structure in memory.
*
* The base implementation of a memory B+ tree. It is based on the
* implementation in Cormen's Introduction into Algorithms, Jan Jannink's paper
* and other algorithm resources. Almost all STL-required function calls are
* implemented. The asymptotic time requirements of the STL are not always
* fulfilled in theory, however in practice this B+ tree performs better than a
* red-black tree by using more memory. The insertion function splits the nodes
* on the recursion unroll. Erase is largely based on Jannink's ideas.
*
* This class is specialized into btree_set, btree_multiset, btree_map and
* btree_multimap using default template parameters and facade functions.
*/
template <typename _Key, typename _Data,
typename _Value = std::pair<_Key, _Data>,
typename _Compare = std::less<_Key>,
typename _Traits = btree_default_map_traits<_Key, _Data>,
bool _Duplicates = false,
typename _Alloc = std::allocator<_Value>,
bool _UsedAsSet = false >
class btree
{
public:
// *** Template Parameter Types
/// First template parameter: The key type of the B+ tree. This is stored
/// in inner nodes and leaves
typedef _Key key_type;
/// Second template parameter: The data type associated with each
/// key. Stored in the B+ tree's leaves
typedef _Data data_type;
/// Third template parameter: Composition pair of key and data types, this
/// is required by the STL standard. The B+ tree does not store key and
/// data together. If value_type == key_type then the B+ tree implements a
/// set.
typedef _Value value_type;
/// Fourth template parameter: Key comparison function object
typedef _Compare key_compare;
/// Fifth template parameter: Traits object used to define more parameters
/// of the B+ tree
typedef _Traits traits;
/// Sixth template parameter: Allow duplicate keys in the B+ tree. Used to
/// implement multiset and multimap.
static const bool allow_duplicates = _Duplicates;
/// Seventh template parameter: STL allocator for tree nodes
typedef _Alloc allocator_type;
/// Eighth template parameter: boolean indicator whether the btree is used
/// as a set. In this case all operations on the data arrays are
/// omitted. This flag is kind of hacky, but required because
/// sizeof(empty_struct) = 1 due to the C standard. Without the flag, lots
/// of superfluous copying would occur.
static const bool used_as_set = _UsedAsSet;
// The macro BTREE_FRIENDS can be used by outside class to access the B+
// tree internals. This was added for wxBTreeDemo to be able to draw the
// tree.
BTREE_FRIENDS
public:
// *** Constructed Types
/// Typedef of our own type
typedef btree<key_type, data_type, value_type, key_compare,
traits, allow_duplicates, allocator_type, used_as_set> btree_self;
/// Size type used to count keys
typedef size_t size_type;
/// The pair of key_type and data_type, this may be different from value_type.
typedef std::pair<key_type, data_type> pair_type;
public:
// *** Static Constant Options and Values of the B+ Tree
/// Base B+ tree parameter: The number of key/data slots in each leaf
static const unsigned short leafslotmax = traits::leafslots;
/// Base B+ tree parameter: The number of key slots in each inner node,
/// this can differ from slots in each leaf.
static const unsigned short innerslotmax = traits::innerslots;
/// Computed B+ tree parameter: The minimum number of key/data slots used
/// in a leaf. If fewer slots are used, the leaf will be merged or slots
/// shifted from it's siblings.
static const unsigned short minleafslots = (leafslotmax / 2);
/// Computed B+ tree parameter: The minimum number of key slots used
/// in an inner node. If fewer slots are used, the inner node will be
/// merged or slots shifted from it's siblings.
static const unsigned short mininnerslots = (innerslotmax / 2);
/// Debug parameter: Enables expensive and thorough checking of the B+ tree
/// invariants after each insert/erase operation.
static const bool selfverify = traits::selfverify;
/// Debug parameter: Prints out lots of debug information about how the
/// algorithms change the tree. Requires the header file to be compiled
/// with BTREE_DEBUG and the key type must be std::ostream printable.
static const bool debug = traits::debug;
private:
// *** Node Classes for In-Memory Nodes
/// The header structure of each node in-memory. This structure is extended
/// by inner_node or leaf_node.
struct node
{
/// Level in the b-tree, if level == 0 -> leaf node
unsigned short level;
/// Number of key slotuse use, so number of valid children or data
/// pointers
unsigned short slotuse;
/// Delayed initialisation of constructed node
inline void initialize(const unsigned short l)
{
level = l;
slotuse = 0;
}
/// True if this is a leaf node
inline bool isleafnode() const
{
return (level == 0);
}
};
/// Extended structure of a inner node in-memory. Contains only keys and no
/// data items.
struct inner_node : public node
{
/// Define an related allocator for the inner_node structs.
typedef typename _Alloc::template rebind<inner_node>::other alloc_type;
/// Keys of children or data pointers
key_type slotkey[innerslotmax];
/// Pointers to children
node* childid[innerslotmax+1];
/// Set variables to initial values
inline void initialize(const unsigned short l)
{
node::initialize(l);
}
/// True if the node's slots are full
inline bool isfull() const
{
return (node::slotuse == innerslotmax);
}
/// True if few used entries, less than half full
inline bool isfew() const
{
return (node::slotuse <= mininnerslots);
}
/// True if node has too few entries
inline bool isunderflow() const
{
return (node::slotuse < mininnerslots);
}
};
/// Extended structure of a leaf node in memory. Contains pairs of keys and
/// data items. Key and data slots are kept in separate arrays, because the
/// key array is traversed very often compared to accessing the data items.
struct leaf_node : public node
{
/// Define an related allocator for the leaf_node structs.
typedef typename _Alloc::template rebind<leaf_node>::other alloc_type;
/// Double linked list pointers to traverse the leaves
leaf_node *prevleaf;
/// Double linked list pointers to traverse the leaves
leaf_node *nextleaf;
/// Keys of children or data pointers
key_type slotkey[leafslotmax];
/// Array of data
data_type slotdata[used_as_set ? 1 : leafslotmax];
/// Set variables to initial values
inline void initialize()
{
node::initialize(0);
prevleaf = nextleaf = NULL;
}
/// True if the node's slots are full
inline bool isfull() const
{
return (node::slotuse == leafslotmax);
}
/// True if few used entries, less than half full
inline bool isfew() const
{
return (node::slotuse <= minleafslots);
}
/// True if node has too few entries
inline bool isunderflow() const
{
return (node::slotuse < minleafslots);
}
/// Set the (key,data) pair in slot. Overloaded function used by
/// bulk_load().
inline void set_slot(unsigned short slot, const pair_type& value)
{
BTREE_ASSERT(used_as_set == false);
BTREE_ASSERT(slot < node::slotuse);
slotkey[slot] = value.first;
slotdata[slot] = value.second;
}
/// Set the key pair in slot. Overloaded function used by
/// bulk_load().
inline void set_slot(unsigned short slot, const key_type& key)
{
BTREE_ASSERT(used_as_set == true);
BTREE_ASSERT(slot < node::slotuse);
slotkey[slot] = key;
}
};
private:
// *** Template Magic to Convert a pair or key/data types to a value_type
/// For sets the second pair_type is an empty struct, so the value_type
/// should only be the first.
template <typename value_type, typename pair_type>
struct btree_pair_to_value
{
/// Convert a fake pair type to just the first component
inline value_type operator()(pair_type& p) const {
return p.first;
}
/// Convert a fake pair type to just the first component
inline value_type operator()(const pair_type& p) const {
return p.first;
}
};
/// For maps value_type is the same as the pair_type
template <typename value_type>
struct btree_pair_to_value<value_type, value_type>
{
/// Identity "convert" a real pair type to just the first component
inline value_type operator()(pair_type& p) const {
return p;
}
/// Identity "convert" a real pair type to just the first component
inline value_type operator()(const pair_type& p) const {
return p;
}
};
/// Using template specialization select the correct converter used by the
/// iterators
typedef btree_pair_to_value<value_type, pair_type> pair_to_value_type;
public:
// *** Iterators and Reverse Iterators
class iterator;
class const_iterator;
class reverse_iterator;
class const_reverse_iterator;
/// STL-like iterator object for B+ tree items. The iterator points to a
/// specific slot number in a leaf.
class iterator
{
public:
// *** Types
/// The key type of the btree. Returned by key().
typedef typename btree::key_type key_type;
/// The data type of the btree. Returned by data().
typedef typename btree::data_type data_type;
/// The value type of the btree. Returned by operator*().
typedef typename btree::value_type value_type;
/// The pair type of the btree.
typedef typename btree::pair_type pair_type;
/// Reference to the value_type. STL required.
typedef value_type& reference;
/// Pointer to the value_type. STL required.
typedef value_type* pointer;
/// STL-magic iterator category
typedef std::bidirectional_iterator_tag iterator_category;
/// STL-magic
typedef ptrdiff_t difference_type;
/// Our own type
typedef iterator self;
private:
// *** Members
/// The currently referenced leaf node of the tree
typename btree::leaf_node* currnode;
/// Current key/data slot referenced
unsigned short currslot;
/// Friendly to the const_iterator, so it may access the two data items
/// directly.
friend class const_iterator;
/// Also friendly to the reverse_iterator, so it may access the two
/// data items directly.
friend class reverse_iterator;
/// Also friendly to the const_reverse_iterator, so it may access the
/// two data items directly.
friend class const_reverse_iterator;
/// Also friendly to the base btree class, because erase_iter() needs
/// to read the currnode and currslot values directly.
friend class btree<key_type, data_type, value_type, key_compare,
traits, allow_duplicates, allocator_type, used_as_set>;
/// Evil! A temporary value_type to STL-correctly deliver operator* and
/// operator->
mutable value_type temp_value;
// The macro BTREE_FRIENDS can be used by outside class to access the B+
// tree internals. This was added for wxBTreeDemo to be able to draw the
// tree.
BTREE_FRIENDS
public:
// *** Methods
/// Default-Constructor of a mutable iterator
inline iterator()
: currnode(NULL), currslot(0)
{ }
/// Initializing-Constructor of a mutable iterator
inline iterator(typename btree::leaf_node *l, unsigned short s)
: currnode(l), currslot(s)
{ }
/// Copy-constructor from a reverse iterator
inline iterator(const reverse_iterator &it)
: currnode(it.currnode), currslot(it.currslot)
{ }
/// Dereference the iterator, this is not a value_type& because key and
/// value are not stored together
inline reference operator*() const
{
temp_value = pair_to_value_type()( pair_type(key(),data()) );
return temp_value;
}
/// Dereference the iterator. Do not use this if possible, use key()
/// and data() instead. The B+ tree does not stored key and data
/// together.
inline pointer operator->() const
{
temp_value = pair_to_value_type()( pair_type(key(),data()) );
return &temp_value;
}
/// Key of the current slot
inline const key_type& key() const
{
return currnode->slotkey[currslot];
}
/// Writable reference to the current data object
inline data_type& data() const
{
return currnode->slotdata[used_as_set ? 0 : currslot];
}
/// Prefix++ advance the iterator to the next slot
inline self& operator++()
{
if (currslot + 1 < currnode->slotuse) {
++currslot;
}
else if (currnode->nextleaf != NULL) {
currnode = currnode->nextleaf;
currslot = 0;
}
else {
// this is end()
currslot = currnode->slotuse;
}
return *this;
}
/// Postfix++ advance the iterator to the next slot
inline self operator++(int)
{
self tmp = *this; // copy ourselves
if (currslot + 1 < currnode->slotuse) {
++currslot;
}
else if (currnode->nextleaf != NULL) {
currnode = currnode->nextleaf;
currslot = 0;
}
else {
// this is end()
currslot = currnode->slotuse;
}
return tmp;
}
/// Prefix-- backstep the iterator to the last slot
inline self& operator--()
{
if (currslot > 0) {
--currslot;
}
else if (currnode->prevleaf != NULL) {
currnode = currnode->prevleaf;
currslot = currnode->slotuse - 1;
}
else {
// this is begin()
currslot = 0;
}
return *this;
}
/// Postfix-- backstep the iterator to the last slot
inline self operator--(int)
{
self tmp = *this; // copy ourselves
if (currslot > 0) {
--currslot;
}
else if (currnode->prevleaf != NULL) {
currnode = currnode->prevleaf;
currslot = currnode->slotuse - 1;
}
else {
// this is begin()
currslot = 0;
}
return tmp;
}
/// Equality of iterators
inline bool operator==(const self& x) const
{
return (x.currnode == currnode) && (x.currslot == currslot);
}
/// Inequality of iterators
inline bool operator!=(const self& x) const
{
return (x.currnode != currnode) || (x.currslot != currslot);
}
};
/// STL-like read-only iterator object for B+ tree items. The iterator
/// points to a specific slot number in a leaf.
class const_iterator
{
public:
// *** Types
/// The key type of the btree. Returned by key().
typedef typename btree::key_type key_type;
/// The data type of the btree. Returned by data().
typedef typename btree::data_type data_type;
/// The value type of the btree. Returned by operator*().
typedef typename btree::value_type value_type;
/// The pair type of the btree.
typedef typename btree::pair_type pair_type;
/// Reference to the value_type. STL required.
typedef const value_type& reference;
/// Pointer to the value_type. STL required.
typedef const value_type* pointer;
/// STL-magic iterator category
typedef std::bidirectional_iterator_tag iterator_category;
/// STL-magic
typedef ptrdiff_t difference_type;
/// Our own type
typedef const_iterator self;
private:
// *** Members
/// The currently referenced leaf node of the tree
const typename btree::leaf_node* currnode;
/// Current key/data slot referenced
unsigned short currslot;
/// Friendly to the reverse_const_iterator, so it may access the two
/// data items directly
friend class const_reverse_iterator;
/// Evil! A temporary value_type to STL-correctly deliver operator* and
/// operator->
mutable value_type temp_value;
// The macro BTREE_FRIENDS can be used by outside class to access the B+
// tree internals. This was added for wxBTreeDemo to be able to draw the
// tree.
BTREE_FRIENDS
public:
// *** Methods
/// Default-Constructor of a const iterator
inline const_iterator()
: currnode(NULL), currslot(0)
{ }
/// Initializing-Constructor of a const iterator
inline const_iterator(const typename btree::leaf_node *l, unsigned short s)
: currnode(l), currslot(s)
{ }
/// Copy-constructor from a mutable iterator
inline const_iterator(const iterator &it)
: currnode(it.currnode), currslot(it.currslot)
{ }
/// Copy-constructor from a mutable reverse iterator
inline const_iterator(const reverse_iterator &it)
: currnode(it.currnode), currslot(it.currslot)
{ }
/// Copy-constructor from a const reverse iterator
inline const_iterator(const const_reverse_iterator &it)
: currnode(it.currnode), currslot(it.currslot)
{ }
/// Dereference the iterator. Do not use this if possible, use key()
/// and data() instead. The B+ tree does not stored key and data
/// together.
inline reference operator*() const
{
temp_value = pair_to_value_type()( pair_type(key(),data()) );
return temp_value;
}
/// Dereference the iterator. Do not use this if possible, use key()
/// and data() instead. The B+ tree does not stored key and data
/// together.
inline pointer operator->() const
{
temp_value = pair_to_value_type()( pair_type(key(),data()) );
return &temp_value;
}
/// Key of the current slot
inline const key_type& key() const
{
return currnode->slotkey[currslot];
}
/// Read-only reference to the current data object
inline const data_type& data() const
{
return currnode->slotdata[used_as_set ? 0 : currslot];
}
/// Prefix++ advance the iterator to the next slot
inline self& operator++()
{
if (currslot + 1 < currnode->slotuse) {
++currslot;
}
else if (currnode->nextleaf != NULL) {
currnode = currnode->nextleaf;
currslot = 0;
}
else {
// this is end()
currslot = currnode->slotuse;
}
return *this;
}
/// Postfix++ advance the iterator to the next slot
inline self operator++(int)
{
self tmp = *this; // copy ourselves
if (currslot + 1 < currnode->slotuse) {
++currslot;
}
else if (currnode->nextleaf != NULL) {
currnode = currnode->nextleaf;
currslot = 0;
}
else {
// this is end()
currslot = currnode->slotuse;
}
return tmp;
}
/// Prefix-- backstep the iterator to the last slot
inline self& operator--()
{
if (currslot > 0) {
--currslot;
}
else if (currnode->prevleaf != NULL) {
currnode = currnode->prevleaf;
currslot = currnode->slotuse - 1;
}
else {
// this is begin()
currslot = 0;
}
return *this;
}
/// Postfix-- backstep the iterator to the last slot
inline self operator--(int)
{
self tmp = *this; // copy ourselves
if (currslot > 0) {
--currslot;
}
else if (currnode->prevleaf != NULL) {
currnode = currnode->prevleaf;
currslot = currnode->slotuse - 1;
}
else {
// this is begin()
currslot = 0;
}
return tmp;
}
/// Equality of iterators
inline bool operator==(const self& x) const
{
return (x.currnode == currnode) && (x.currslot == currslot);
}
/// Inequality of iterators
inline bool operator!=(const self& x) const
{
return (x.currnode != currnode) || (x.currslot != currslot);
}
};
/// STL-like mutable reverse iterator object for B+ tree items. The
/// iterator points to a specific slot number in a leaf.
class reverse_iterator
{
public:
// *** Types
/// The key type of the btree. Returned by key().
typedef typename btree::key_type key_type;
/// The data type of the btree. Returned by data().
typedef typename btree::data_type data_type;
/// The value type of the btree. Returned by operator*().
typedef typename btree::value_type value_type;
/// The pair type of the btree.
typedef typename btree::pair_type pair_type;
/// Reference to the value_type. STL required.
typedef value_type& reference;
/// Pointer to the value_type. STL required.
typedef value_type* pointer;
/// STL-magic iterator category
typedef std::bidirectional_iterator_tag iterator_category;
/// STL-magic
typedef ptrdiff_t difference_type;
/// Our own type
typedef reverse_iterator self;
private:
// *** Members
/// The currently referenced leaf node of the tree
typename btree::leaf_node* currnode;
/// One slot past the current key/data slot referenced.
unsigned short currslot;
/// Friendly to the const_iterator, so it may access the two data items
/// directly
friend class iterator;
/// Also friendly to the const_iterator, so it may access the two data
/// items directly
friend class const_iterator;
/// Also friendly to the const_iterator, so it may access the two data
/// items directly
friend class const_reverse_iterator;
/// Evil! A temporary value_type to STL-correctly deliver operator* and
/// operator->
mutable value_type temp_value;
// The macro BTREE_FRIENDS can be used by outside class to access the B+
// tree internals. This was added for wxBTreeDemo to be able to draw the
// tree.
BTREE_FRIENDS
public:
// *** Methods
/// Default-Constructor of a reverse iterator
inline reverse_iterator()
: currnode(NULL), currslot(0)
{ }
/// Initializing-Constructor of a mutable reverse iterator
inline reverse_iterator(typename btree::leaf_node *l, unsigned short s)
: currnode(l), currslot(s)
{ }
/// Copy-constructor from a mutable iterator
inline reverse_iterator(const iterator &it)
: currnode(it.currnode), currslot(it.currslot)
{ }
/// Dereference the iterator, this is not a value_type& because key and
/// value are not stored together
inline reference operator*() const
{
BTREE_ASSERT(currslot > 0);
temp_value = pair_to_value_type()( pair_type(key(),data()) );
return temp_value;
}
/// Dereference the iterator. Do not use this if possible, use key()
/// and data() instead. The B+ tree does not stored key and data
/// together.
inline pointer operator->() const
{
BTREE_ASSERT(currslot > 0);
temp_value = pair_to_value_type()( pair_type(key(),data()) );
return &temp_value;
}
/// Key of the current slot
inline const key_type& key() const
{
BTREE_ASSERT(currslot > 0);
return currnode->slotkey[currslot - 1];
}
/// Writable reference to the current data object
inline data_type& data() const
{
BTREE_ASSERT(currslot > 0);
return currnode->slotdata[used_as_set ? 0 : currslot-1];
}
/// Prefix++ advance the iterator to the next slot
inline self& operator++()
{
if (currslot > 1) {
--currslot;
}
else if (currnode->prevleaf != NULL) {
currnode = currnode->prevleaf;
currslot = currnode->slotuse;
}
else {
// this is begin() == rend()
currslot = 0;
}
return *this;
}
/// Postfix++ advance the iterator to the next slot
inline self operator++(int)
{
self tmp = *this; // copy ourselves
if (currslot > 1) {
--currslot;
}
else if (currnode->prevleaf != NULL) {
currnode = currnode->prevleaf;
currslot = currnode->slotuse;
}
else {
// this is begin() == rend()
currslot = 0;
}
return tmp;
}
/// Prefix-- backstep the iterator to the last slot
inline self& operator--()
{
if (currslot < currnode->slotuse) {
++currslot;
}
else if (currnode->nextleaf != NULL) {
currnode = currnode->nextleaf;
currslot = 1;
}
else {
// this is end() == rbegin()
currslot = currnode->slotuse;
}
return *this;
}
/// Postfix-- backstep the iterator to the last slot
inline self operator--(int)
{
self tmp = *this; // copy ourselves
if (currslot < currnode->slotuse) {
++currslot;
}
else if (currnode->nextleaf != NULL) {
currnode = currnode->nextleaf;
currslot = 1;
}
else {
// this is end() == rbegin()
currslot = currnode->slotuse;
}
return tmp;
}
/// Equality of iterators
inline bool operator==(const self& x) const
{
return (x.currnode == currnode) && (x.currslot == currslot);
}
/// Inequality of iterators
inline bool operator!=(const self& x) const
{
return (x.currnode != currnode) || (x.currslot != currslot);
}
};
/// STL-like read-only reverse iterator object for B+ tree items. The
/// iterator points to a specific slot number in a leaf.
class const_reverse_iterator
{
public:
// *** Types
/// The key type of the btree. Returned by key().
typedef typename btree::key_type key_type;
/// The data type of the btree. Returned by data().
typedef typename btree::data_type data_type;
/// The value type of the btree. Returned by operator*().
typedef typename btree::value_type value_type;
/// The pair type of the btree.
typedef typename btree::pair_type pair_type;
/// Reference to the value_type. STL required.
typedef const value_type& reference;
/// Pointer to the value_type. STL required.
typedef const value_type* pointer;
/// STL-magic iterator category
typedef std::bidirectional_iterator_tag iterator_category;
/// STL-magic
typedef ptrdiff_t difference_type;
/// Our own type
typedef const_reverse_iterator self;
private:
// *** Members
/// The currently referenced leaf node of the tree
const typename btree::leaf_node* currnode;
/// One slot past the current key/data slot referenced.
unsigned short currslot;
/// Friendly to the const_iterator, so it may access the two data items
/// directly.
friend class reverse_iterator;
/// Evil! A temporary value_type to STL-correctly deliver operator* and
/// operator->
mutable value_type temp_value;
// The macro BTREE_FRIENDS can be used by outside class to access the B+
// tree internals. This was added for wxBTreeDemo to be able to draw the
// tree.
BTREE_FRIENDS
public:
// *** Methods
/// Default-Constructor of a const reverse iterator
inline const_reverse_iterator()
: currnode(NULL), currslot(0)
{ }
/// Initializing-Constructor of a const reverse iterator
inline const_reverse_iterator(const typename btree::leaf_node *l, unsigned short s)
: currnode(l), currslot(s)
{ }
/// Copy-constructor from a mutable iterator
inline const_reverse_iterator(const iterator &it)
: currnode(it.currnode), currslot(it.currslot)
{ }
/// Copy-constructor from a const iterator
inline const_reverse_iterator(const const_iterator &it)
: currnode(it.currnode), currslot(it.currslot)
{ }
/// Copy-constructor from a mutable reverse iterator
inline const_reverse_iterator(const reverse_iterator &it)
: currnode(it.currnode), currslot(it.currslot)
{ }
/// Dereference the iterator. Do not use this if possible, use key()
/// and data() instead. The B+ tree does not stored key and data
/// together.
inline reference operator*() const
{
BTREE_ASSERT(currslot > 0);
temp_value = pair_to_value_type()( pair_type(key(),data()) );
return temp_value;
}
/// Dereference the iterator. Do not use this if possible, use key()
/// and data() instead. The B+ tree does not stored key and data
/// together.
inline pointer operator->() const
{
BTREE_ASSERT(currslot > 0);
temp_value = pair_to_value_type()( pair_type(key(),data()) );
return &temp_value;
}
/// Key of the current slot
inline const key_type& key() const
{
BTREE_ASSERT(currslot > 0);
return currnode->slotkey[currslot - 1];
}
/// Read-only reference to the current data object
inline const data_type& data() const
{
BTREE_ASSERT(currslot > 0);
return currnode->slotdata[used_as_set ? 0 : currslot-1];
}
/// Prefix++ advance the iterator to the previous slot
inline self& operator++()
{
if (currslot > 1) {
--currslot;
}
else if (currnode->prevleaf != NULL) {
currnode = currnode->prevleaf;
currslot = currnode->slotuse;
}
else {
// this is begin() == rend()
currslot = 0;
}
return *this;
}
/// Postfix++ advance the iterator to the previous slot
inline self operator++(int)
{
self tmp = *this; // copy ourselves
if (currslot > 1) {
--currslot;
}
else if (currnode->prevleaf != NULL) {
currnode = currnode->prevleaf;
currslot = currnode->slotuse;
}
else {
// this is begin() == rend()
currslot = 0;
}
return tmp;
}
/// Prefix-- backstep the iterator to the next slot
inline self& operator--()
{
if (currslot < currnode->slotuse) {
++currslot;
}
else if (currnode->nextleaf != NULL) {
currnode = currnode->nextleaf;
currslot = 1;
}
else {
// this is end() == rbegin()
currslot = currnode->slotuse;
}
return *this;
}
/// Postfix-- backstep the iterator to the next slot
inline self operator--(int)
{
self tmp = *this; // copy ourselves
if (currslot < currnode->slotuse) {
++currslot;
}
else if (currnode->nextleaf != NULL) {
currnode = currnode->nextleaf;
currslot = 1;
}
else {
// this is end() == rbegin()
currslot = currnode->slotuse;
}
return tmp;
}
/// Equality of iterators
inline bool operator==(const self& x) const
{
return (x.currnode == currnode) && (x.currslot == currslot);
}
/// Inequality of iterators
inline bool operator!=(const self& x) const
{
return (x.currnode != currnode) || (x.currslot != currslot);
}
};
public:
// *** Small Statistics Structure
/** A small struct containing basic statistics about the B+ tree. It can be
* fetched using get_stats(). */
struct tree_stats
{
/// Number of items in the B+ tree
size_type itemcount;
/// Number of leaves in the B+ tree
size_type leaves;
/// Number of inner nodes in the B+ tree
size_type innernodes;
/// Base B+ tree parameter: The number of key/data slots in each leaf
static const unsigned short leafslots = btree_self::leafslotmax;
/// Base B+ tree parameter: The number of key slots in each inner node.
static const unsigned short innerslots = btree_self::innerslotmax;
/// Zero initialized
inline tree_stats()
: itemcount(0),
leaves(0), innernodes(0)
{
}
/// Return the total number of nodes
inline size_type nodes() const
{
return innernodes + leaves;
}
/// Return the average fill of leaves
inline double avgfill_leaves() const
{
return static_cast<double>(itemcount) / (leaves * leafslots);
}
};
private:
// *** Tree Object Data Members
/// Pointer to the B+ tree's root node, either leaf or inner node
node* m_root;
/// Pointer to first leaf in the double linked leaf chain
leaf_node *m_headleaf;
/// Pointer to last leaf in the double linked leaf chain
leaf_node *m_tailleaf;
/// Other small statistics about the B+ tree
tree_stats m_stats;
/// Key comparison object. More comparison functions are generated from
/// this < relation.
key_compare m_key_less;
/// Memory allocator.
allocator_type m_allocator;
public:
// *** Constructors and Destructor
/// Default constructor initializing an empty B+ tree with the standard key
/// comparison function
explicit inline btree(const allocator_type &alloc = allocator_type())
: m_root(NULL), m_headleaf(NULL), m_tailleaf(NULL), m_allocator(alloc)
{
}
/// Constructor initializing an empty B+ tree with a special key
/// comparison object
explicit inline btree(const key_compare &kcf,
const allocator_type &alloc = allocator_type())
: m_root(NULL), m_headleaf(NULL), m_tailleaf(NULL),
m_key_less(kcf), m_allocator(alloc)
{
}
/// Constructor initializing a B+ tree with the range [first,last). The
/// range need not be sorted. To create a B+ tree from a sorted range, use
/// bulk_load().
template <class InputIterator>
inline btree(InputIterator first, InputIterator last,
const allocator_type &alloc = allocator_type())
: m_root(NULL), m_headleaf(NULL), m_tailleaf(NULL), m_allocator(alloc)
{
insert(first, last);
}
/// Constructor initializing a B+ tree with the range [first,last) and a
/// special key comparison object. The range need not be sorted. To create
/// a B+ tree from a sorted range, use bulk_load().
template <class InputIterator>
inline btree(InputIterator first, InputIterator last, const key_compare &kcf,
const allocator_type &alloc = allocator_type())
: m_root(NULL), m_headleaf(NULL), m_tailleaf(NULL),
m_key_less(kcf), m_allocator(alloc)
{
insert(first, last);
}
/// Frees up all used B+ tree memory pages
inline ~btree()
{
clear();
}
/// Fast swapping of two identical B+ tree objects.
void swap(btree_self& from)
{
std::swap(m_root, from.m_root);
std::swap(m_headleaf, from.m_headleaf);
std::swap(m_tailleaf, from.m_tailleaf);
std::swap(m_stats, from.m_stats);
std::swap(m_key_less, from.m_key_less);
std::swap(m_allocator, from.m_allocator);
}
public:
// *** Key and Value Comparison Function Objects
/// Function class to compare value_type objects. Required by the STL
class value_compare
{
protected:
/// Key comparison function from the template parameter
key_compare key_comp;
/// Constructor called from btree::value_comp()
inline value_compare(key_compare kc)
: key_comp(kc)
{ }
/// Friendly to the btree class so it may call the constructor
friend class btree<key_type, data_type, value_type, key_compare,
traits, allow_duplicates, allocator_type, used_as_set>;
public:
/// Function call "less"-operator resulting in true if x < y.
inline bool operator()(const value_type& x, const value_type& y) const
{
return key_comp(x.first, y.first);
}
};
/// Constant access to the key comparison object sorting the B+ tree
inline key_compare key_comp() const
{
return m_key_less;
}
/// Constant access to a constructed value_type comparison object. Required
/// by the STL
inline value_compare value_comp() const
{
return value_compare(m_key_less);
}
private:
// *** Convenient Key Comparison Functions Generated From key_less
/// True if a < b ? "constructed" from m_key_less()
inline bool key_less(const key_type &a, const key_type b) const
{
return m_key_less(a, b);
}
/// True if a <= b ? constructed from key_less()
inline bool key_lessequal(const key_type &a, const key_type b) const
{
return !m_key_less(b, a);
}
/// True if a > b ? constructed from key_less()
inline bool key_greater(const key_type &a, const key_type &b) const
{
return m_key_less(b, a);
}
/// True if a >= b ? constructed from key_less()
inline bool key_greaterequal(const key_type &a, const key_type b) const
{
return !m_key_less(a, b);
}
/// True if a == b ? constructed from key_less(). This requires the <
/// relation to be a total order, otherwise the B+ tree cannot be sorted.
inline bool key_equal(const key_type &a, const key_type &b) const
{
return !m_key_less(a, b) && !m_key_less(b, a);
}
public:
// *** Allocators
/// Return the base node allocator provided during construction.
allocator_type get_allocator() const
{
return m_allocator;
}
private:
// *** Node Object Allocation and Deallocation Functions
/// Return an allocator for leaf_node objects
typename leaf_node::alloc_type leaf_node_allocator()
{
return typename leaf_node::alloc_type(m_allocator);
}
/// Return an allocator for inner_node objects
typename inner_node::alloc_type inner_node_allocator()
{
return typename inner_node::alloc_type(m_allocator);
}
/// Allocate and initialize a leaf node
inline leaf_node* allocate_leaf()
{
leaf_node *n = new (leaf_node_allocator().allocate(1)) leaf_node();
n->initialize();
m_stats.leaves++;
return n;
}
/// Allocate and initialize an inner node
inline inner_node* allocate_inner(unsigned short level)
{
inner_node *n = new (inner_node_allocator().allocate(1)) inner_node();
n->initialize(level);
m_stats.innernodes++;
return n;
}
/// Correctly free either inner or leaf node, destructs all contained key
/// and value objects
inline void free_node(node *n)
{
if (n->isleafnode()) {
leaf_node *ln = static_cast<leaf_node*>(n);
typename leaf_node::alloc_type a(leaf_node_allocator());
a.destroy(ln);
a.deallocate(ln, 1);
m_stats.leaves--;
}
else {
inner_node *in = static_cast<inner_node*>(n);
typename inner_node::alloc_type a(inner_node_allocator());
a.destroy(in);
a.deallocate(in, 1);
m_stats.innernodes--;
}
}
/// Convenient template function for conditional copying of slotdata. This
/// should be used instead of std::copy for all slotdata manipulations.
template<class InputIterator, class OutputIterator>
static OutputIterator data_copy (InputIterator first, InputIterator last,
OutputIterator result)
{
if (used_as_set) return result; // no operation
else return std::copy(first, last, result);
}
/// Convenient template function for conditional copying of slotdata. This
/// should be used instead of std::copy for all slotdata manipulations.
template<class InputIterator, class OutputIterator>
static OutputIterator data_copy_backward (InputIterator first, InputIterator last,
OutputIterator result)
{
if (used_as_set) return result; // no operation
else return std::copy_backward(first, last, result);
}
public:
// *** Fast Destruction of the B+ Tree
/// Frees all key/data pairs and all nodes of the tree
void clear()
{
if (m_root)
{
clear_recursive(m_root);
free_node(m_root);
m_root = NULL;
m_headleaf = m_tailleaf = NULL;
m_stats = tree_stats();
}
BTREE_ASSERT(m_stats.itemcount == 0);
}
private:
/// Recursively free up nodes
void clear_recursive(node *n)
{
if (n->isleafnode())
{
leaf_node *leafnode = static_cast<leaf_node*>(n);
for (unsigned int slot = 0; slot < leafnode->slotuse; ++slot)
{
// data objects are deleted by leaf_node's destructor
}
}
else
{
inner_node *innernode = static_cast<inner_node*>(n);
for (unsigned short slot = 0; slot < innernode->slotuse + 1; ++slot)
{
clear_recursive(innernode->childid[slot]);
free_node(innernode->childid[slot]);
}
}
}
public:
// *** STL Iterator Construction Functions
/// Constructs a read/data-write iterator that points to the first slot in
/// the first leaf of the B+ tree.
inline iterator begin()
{
return iterator(m_headleaf, 0);
}
/// Constructs a read/data-write iterator that points to the first invalid
/// slot in the last leaf of the B+ tree.
inline iterator end()
{
return iterator(m_tailleaf, m_tailleaf ? m_tailleaf->slotuse : 0);
}
/// Constructs a read-only constant iterator that points to the first slot
/// in the first leaf of the B+ tree.
inline const_iterator begin() const
{
return const_iterator(m_headleaf, 0);
}
/// Constructs a read-only constant iterator that points to the first
/// invalid slot in the last leaf of the B+ tree.
inline const_iterator end() const
{
return const_iterator(m_tailleaf, m_tailleaf ? m_tailleaf->slotuse : 0);
}
/// Constructs a read/data-write reverse iterator that points to the first
/// invalid slot in the last leaf of the B+ tree. Uses STL magic.
inline reverse_iterator rbegin()
{
return reverse_iterator(end());
}
/// Constructs a read/data-write reverse iterator that points to the first
/// slot in the first leaf of the B+ tree. Uses STL magic.
inline reverse_iterator rend()
{
return reverse_iterator(begin());
}
/// Constructs a read-only reverse iterator that points to the first
/// invalid slot in the last leaf of the B+ tree. Uses STL magic.
inline const_reverse_iterator rbegin() const
{
return const_reverse_iterator(end());
}
/// Constructs a read-only reverse iterator that points to the first slot
/// in the first leaf of the B+ tree. Uses STL magic.
inline const_reverse_iterator rend() const
{
return const_reverse_iterator(begin());
}
private:
// *** B+ Tree Node Binary Search Functions
/// Searches for the first key in the node n greater or equal to key. Uses
/// binary search with an optional linear self-verification. This is a
/// template function, because the slotkey array is located at different
/// places in leaf_node and inner_node.
template <typename node_type>
inline int find_lower(const node_type *n, const key_type& key) const
{
if ( 0 && sizeof(n->slotkey) > traits::binsearch_threshold )
{
if (n->slotuse == 0) return 0;
int lo = 0, hi = n->slotuse;
while (lo < hi)
{
int mid = (lo + hi) >> 1;
if (key_lessequal(key, n->slotkey[mid])) {
hi = mid; // key <= mid
}
else {
lo = mid + 1; // key > mid
}
}
BTREE_PRINT("btree::find_lower: on " << n << " key " << key << " -> " << lo << " / " << hi);
// verify result using simple linear search
if (selfverify)
{
int i = 0;
while (i < n->slotuse && key_less(n->slotkey[i],key)) ++i;
BTREE_PRINT("btree::find_lower: testfind: " << i);
BTREE_ASSERT(i == lo);
}
return lo;
}
else // for nodes <= binsearch_threshold do linear search.
{
int lo = 0;
while (lo < n->slotuse && key_less(n->slotkey[lo],key)) ++lo;
return lo;
}
}
/// Searches for the first key in the node n greater than key. Uses binary
/// search with an optional linear self-verification. This is a template
/// function, because the slotkey array is located at different places in
/// leaf_node and inner_node.
template <typename node_type>
inline int find_upper(const node_type *n, const key_type& key) const
{
if ( 0 && sizeof(n->slotkey) > traits::binsearch_threshold )
{
if (n->slotuse == 0) return 0;
int lo = 0, hi = n->slotuse;
while (lo < hi)
{
int mid = (lo + hi) >> 1;
if (key_less(key, n->slotkey[mid])) {
hi = mid; // key < mid
}
else {
lo = mid + 1; // key >= mid
}
}
BTREE_PRINT("btree::find_upper: on " << n << " key " << key << " -> " << lo << " / " << hi);
// verify result using simple linear search
if (selfverify)
{
int i = 0;
while (i < n->slotuse && key_lessequal(n->slotkey[i],key)) ++i;
BTREE_PRINT("btree::find_upper testfind: " << i);
BTREE_ASSERT(i == hi);
}
return lo;
}
else // for nodes <= binsearch_threshold do linear search.
{
int lo = 0;
while (lo < n->slotuse && key_lessequal(n->slotkey[lo],key)) ++lo;
return lo;
}
}
public:
// *** Access Functions to the Item Count
/// Return the number of key/data pairs in the B+ tree
inline size_type size() const
{
return m_stats.itemcount;
}
/// Returns true if there is at least one key/data pair in the B+ tree
inline bool empty() const
{
return (size() == size_type(0));
}
/// Returns the largest possible size of the B+ Tree. This is just a
/// function required by the STL standard, the B+ Tree can hold more items.
inline size_type max_size() const
{
return size_type(-1);
}
/// Return a const reference to the current statistics.
inline const struct tree_stats& get_stats() const
{
return m_stats;
}
public:
// *** Standard Access Functions Querying the Tree by Descending to a Leaf
/// Non-STL function checking whether a key is in the B+ tree. The same as
/// (find(k) != end()) or (count() != 0).
bool exists(const key_type &key) const
{
const node *n = m_root;
if (!n) return false;
while(!n->isleafnode())
{
const inner_node *inner = static_cast<const inner_node*>(n);
int slot = find_lower(inner, key);
n = inner->childid[slot];
}
const leaf_node *leaf = static_cast<const leaf_node*>(n);
int slot = find_lower(leaf, key);
return (slot < leaf->slotuse && key_equal(key, leaf->slotkey[slot]));
}
/// Tries to locate a key in the B+ tree and returns an iterator to the
/// key/data slot if found. If unsuccessful it returns end().
iterator find(const key_type &key)
{
node *n = m_root;
if (!n) return end();
while(!n->isleafnode())
{
const inner_node *inner = static_cast<const inner_node*>(n);
int slot = find_lower(inner, key);
n = inner->childid[slot];
}
leaf_node *leaf = static_cast<leaf_node*>(n);
int slot = find_lower(leaf, key);
return (slot < leaf->slotuse && key_equal(key, leaf->slotkey[slot]))
? iterator(leaf, slot) : end();
}
/// Tries to locate a key in the B+ tree and returns an constant iterator
/// to the key/data slot if found. If unsuccessful it returns end().
const_iterator find(const key_type &key) const
{
const node *n = m_root;
if (!n) return end();
while(!n->isleafnode())
{
const inner_node *inner = static_cast<const inner_node*>(n);
int slot = find_lower(inner, key);
n = inner->childid[slot];
}
const leaf_node *leaf = static_cast<const leaf_node*>(n);
int slot = find_lower(leaf, key);
return (slot < leaf->slotuse && key_equal(key, leaf->slotkey[slot]))
? const_iterator(leaf, slot) : end();
}
/// Tries to locate a key in the B+ tree and returns the number of
/// identical key entries found.
size_type count(const key_type &key) const
{
const node *n = m_root;
if (!n) return 0;
while(!n->isleafnode())
{
const inner_node *inner = static_cast<const inner_node*>(n);
int slot = find_lower(inner, key);
n = inner->childid[slot];
}
const leaf_node *leaf = static_cast<const leaf_node*>(n);
int slot = find_lower(leaf, key);
size_type num = 0;
while (leaf && slot < leaf->slotuse && key_equal(key, leaf->slotkey[slot]))
{
++num;
if (++slot >= leaf->slotuse)
{
leaf = leaf->nextleaf;
slot = 0;
}
}
return num;
}
/// Searches the B+ tree and returns an iterator to the first pair
/// equal to or greater than key, or end() if all keys are smaller.
iterator lower_bound(const key_type& key)
{
node *n = m_root;
if (!n) return end();
while(!n->isleafnode())
{
const inner_node *inner = static_cast<const inner_node*>(n);
int slot = find_lower(inner, key);
n = inner->childid[slot];
}
leaf_node *leaf = static_cast<leaf_node*>(n);
int slot = find_lower(leaf, key);
return iterator(leaf, slot);
}
/// Searches the B+ tree and returns a constant iterator to the
/// first pair equal to or greater than key, or end() if all keys
/// are smaller.
const_iterator lower_bound(const key_type& key) const
{
const node *n = m_root;
if (!n) return end();
while(!n->isleafnode())
{
const inner_node *inner = static_cast<const inner_node*>(n);
int slot = find_lower(inner, key);
n = inner->childid[slot];
}
const leaf_node *leaf = static_cast<const leaf_node*>(n);
int slot = find_lower(leaf, key);
return const_iterator(leaf, slot);
}
/// Searches the B+ tree and returns an iterator to the first pair
/// greater than key, or end() if all keys are smaller or equal.
iterator upper_bound(const key_type& key)
{
node *n = m_root;
if (!n) return end();
while(!n->isleafnode())
{
const inner_node *inner = static_cast<const inner_node*>(n);
int slot = find_upper(inner, key);
n = inner->childid[slot];
}
leaf_node *leaf = static_cast<leaf_node*>(n);
int slot = find_upper(leaf, key);
return iterator(leaf, slot);
}
/// Searches the B+ tree and returns a constant iterator to the
/// first pair greater than key, or end() if all keys are smaller
/// or equal.
const_iterator upper_bound(const key_type& key) const
{
const node *n = m_root;
if (!n) return end();
while(!n->isleafnode())
{
const inner_node *inner = static_cast<const inner_node*>(n);
int slot = find_upper(inner, key);
n = inner->childid[slot];
}
const leaf_node *leaf = static_cast<const leaf_node*>(n);
int slot = find_upper(leaf, key);
return const_iterator(leaf, slot);
}
/// Searches the B+ tree and returns both lower_bound() and upper_bound().
inline std::pair<iterator, iterator> equal_range(const key_type& key)
{
return std::pair<iterator, iterator>(lower_bound(key), upper_bound(key));
}
/// Searches the B+ tree and returns both lower_bound() and upper_bound().
inline std::pair<const_iterator, const_iterator> equal_range(const key_type& key) const
{
return std::pair<const_iterator, const_iterator>(lower_bound(key), upper_bound(key));
}
public:
// *** B+ Tree Object Comparison Functions
/// Equality relation of B+ trees of the same type. B+ trees of the same
/// size and equal elements (both key and data) are considered
/// equal. Beware of the random ordering of duplicate keys.
inline bool operator==(const btree_self &other) const
{
return (size() == other.size()) && std::equal(begin(), end(), other.begin());
}
/// Inequality relation. Based on operator==.
inline bool operator!=(const btree_self &other) const
{
return !(*this == other);
}
/// Total ordering relation of B+ trees of the same type. It uses
/// std::lexicographical_compare() for the actual comparison of elements.
inline bool operator<(const btree_self &other) const
{
return std::lexicographical_compare(begin(), end(), other.begin(), other.end());
}
/// Greater relation. Based on operator<.
inline bool operator>(const btree_self &other) const
{
return other < *this;
}
/// Less-equal relation. Based on operator<.
inline bool operator<=(const btree_self &other) const
{
return !(other < *this);
}
/// Greater-equal relation. Based on operator<.
inline bool operator>=(const btree_self &other) const
{
return !(*this < other);
}
public:
/// *** Fast Copy: Assign Operator and Copy Constructors
/// Assignment operator. All the key/data pairs are copied
inline btree_self& operator= (const btree_self &other)
{
if (this != &other)
{
clear();
m_key_less = other.key_comp();
m_allocator = other.get_allocator();
if (other.size() != 0)
{
m_stats.leaves = m_stats.innernodes = 0;
if (other.m_root) {
m_root = copy_recursive(other.m_root);
}
m_stats = other.m_stats;
}
if (selfverify) verify();
}
return *this;
}
/// Copy constructor. The newly initialized B+ tree object will contain a
/// copy of all key/data pairs.
inline btree(const btree_self &other)
: m_root(NULL), m_headleaf(NULL), m_tailleaf(NULL),
m_stats( other.m_stats ),
m_key_less( other.key_comp() ),
m_allocator( other.get_allocator() )
{
if (size() > 0)
{
m_stats.leaves = m_stats.innernodes = 0;
if (other.m_root) {
m_root = copy_recursive(other.m_root);
}
if (selfverify) verify();
}
}
private:
/// Recursively copy nodes from another B+ tree object
struct node* copy_recursive(const node *n)
{
if (n->isleafnode())
{
const leaf_node *leaf = static_cast<const leaf_node*>(n);
leaf_node *newleaf = allocate_leaf();
newleaf->slotuse = leaf->slotuse;
std::copy(leaf->slotkey, leaf->slotkey + leaf->slotuse, newleaf->slotkey);
data_copy(leaf->slotdata, leaf->slotdata + leaf->slotuse, newleaf->slotdata);
if (m_headleaf == NULL)
{
m_headleaf = m_tailleaf = newleaf;
newleaf->prevleaf = newleaf->nextleaf = NULL;
}
else
{
newleaf->prevleaf = m_tailleaf;
m_tailleaf->nextleaf = newleaf;
m_tailleaf = newleaf;
}
return newleaf;
}
else
{
const inner_node *inner = static_cast<const inner_node*>(n);
inner_node *newinner = allocate_inner(inner->level);
newinner->slotuse = inner->slotuse;
std::copy(inner->slotkey, inner->slotkey + inner->slotuse, newinner->slotkey);
for (unsigned short slot = 0; slot <= inner->slotuse; ++slot)
{
newinner->childid[slot] = copy_recursive(inner->childid[slot]);
}
return newinner;
}
}
public:
// *** Public Insertion Functions
/// Attempt to insert a key/data pair into the B+ tree. If the tree does not
/// allow duplicate keys, then the insert may fail if it is already
/// present.
inline std::pair<iterator, bool> insert(const pair_type& x)
{
return insert_start(x.first, x.second);
}
/// Attempt to insert a key/data pair into the B+ tree. Beware that if
/// key_type == data_type, then the template iterator insert() is called
/// instead. If the tree does not allow duplicate keys, then the insert may
/// fail if it is already present.
inline std::pair<iterator, bool> insert(const key_type& key, const data_type& data)
{
return insert_start(key, data);
}
/// Attempt to insert a key/data pair into the B+ tree. This function is the
/// same as the other insert, however if key_type == data_type then the
/// non-template function cannot be called. If the tree does not allow
/// duplicate keys, then the insert may fail if it is already present.
inline std::pair<iterator, bool> insert2(const key_type& key, const data_type& data)
{
return insert_start(key, data);
}
/// Attempt to insert a key/data pair into the B+ tree. The iterator hint
/// is currently ignored by the B+ tree insertion routine.
inline iterator insert(iterator /* hint */, const pair_type &x)
{
return insert_start(x.first, x.second).first;
}
/// Attempt to insert a key/data pair into the B+ tree. The iterator hint is
/// currently ignored by the B+ tree insertion routine.
inline iterator insert2(iterator /* hint */, const key_type& key, const data_type& data)
{
return insert_start(key, data).first;
}
/// Attempt to insert the range [first,last) of value_type pairs into the
/// B+ tree. Each key/data pair is inserted individually; to bulk load the
/// tree, use a constructor with range.
template <typename InputIterator>
inline void insert(InputIterator first, InputIterator last)
{
InputIterator iter = first;
while(iter != last)
{
insert(*iter);
++iter;
}
}
private:
// *** Private Insertion Functions
/// Start the insertion descent at the current root and handle root
/// splits. Returns true if the item was inserted
std::pair<iterator, bool> insert_start(const key_type& key, const data_type& value)
{
node *newchild = NULL;
key_type newkey = key_type();
if (m_root == NULL) {
m_root = m_headleaf = m_tailleaf = allocate_leaf();
}
std::pair<iterator, bool> r = insert_descend(m_root, key, value, &newkey, &newchild);
if (newchild)
{
inner_node *newroot = allocate_inner(m_root->level + 1);
newroot->slotkey[0] = newkey;
newroot->childid[0] = m_root;
newroot->childid[1] = newchild;
newroot->slotuse = 1;
m_root = newroot;
}
// increment itemcount if the item was inserted
if (r.second) ++m_stats.itemcount;
#ifdef BTREE_DEBUG
if (debug) print(std::cout);
#endif
if (selfverify) {
verify();
BTREE_ASSERT(exists(key));
}
return r;
}
/**
* @brief Insert an item into the B+ tree.
*
* Descend down the nodes to a leaf, insert the key/data pair in a free
* slot. If the node overflows, then it must be split and the new split
* node inserted into the parent. Unroll / this splitting up to the root.
*/
std::pair<iterator, bool> insert_descend(node* n,
const key_type& key, const data_type& value,
key_type* splitkey, node** splitnode)
{
if (!n->isleafnode())
{
inner_node *inner = static_cast<inner_node*>(n);
key_type newkey = key_type();
node *newchild = NULL;
int slot = find_lower(inner, key);
BTREE_PRINT("btree::insert_descend into " << inner->childid[slot]);
std::pair<iterator, bool> r = insert_descend(inner->childid[slot],
key, value, &newkey, &newchild);
if (newchild)
{
BTREE_PRINT("btree::insert_descend newchild with key " << newkey << " node " << newchild << " at slot " << slot);
if (inner->isfull())
{
split_inner_node(inner, splitkey, splitnode, slot);
BTREE_PRINT("btree::insert_descend done split_inner: putslot: " << slot << " putkey: " << newkey << " upkey: " << *splitkey);
#ifdef BTREE_DEBUG
if (debug)
{
print_node(std::cout, inner);
print_node(std::cout, *splitnode);
}
#endif
// check if insert slot is in the split sibling node
BTREE_PRINT("btree::insert_descend switch: " << slot << " > " << inner->slotuse+1);
if (slot == inner->slotuse+1 && inner->slotuse < (*splitnode)->slotuse)
{
// special case when the insert slot matches the split
// place between the two nodes, then the insert key
// becomes the split key.
BTREE_ASSERT(inner->slotuse + 1 < innerslotmax);
inner_node *splitinner = static_cast<inner_node*>(*splitnode);
// move the split key and it's datum into the left node
inner->slotkey[inner->slotuse] = *splitkey;
inner->childid[inner->slotuse+1] = splitinner->childid[0];
inner->slotuse++;
// set new split key and move corresponding datum into right node
splitinner->childid[0] = newchild;
*splitkey = newkey;
return r;
}
else if (slot >= inner->slotuse+1)
{
// in case the insert slot is in the newly create split
// node, we reuse the code below.
slot -= inner->slotuse+1;
inner = static_cast<inner_node*>(*splitnode);
BTREE_PRINT("btree::insert_descend switching to splitted node " << inner << " slot " << slot);
}
}
// move items and put pointer to child node into correct slot
BTREE_ASSERT(slot >= 0 && slot <= inner->slotuse);
std::copy_backward(inner->slotkey + slot, inner->slotkey + inner->slotuse,
inner->slotkey + inner->slotuse+1);
std::copy_backward(inner->childid + slot, inner->childid + inner->slotuse+1,
inner->childid + inner->slotuse+2);
inner->slotkey[slot] = newkey;
inner->childid[slot + 1] = newchild;
inner->slotuse++;
}
return r;
}
else // n->isleafnode() == true
{
leaf_node *leaf = static_cast<leaf_node*>(n);
int slot = find_lower(leaf, key);
if (!allow_duplicates && slot < leaf->slotuse && key_equal(key, leaf->slotkey[slot])) {
return std::pair<iterator, bool>(iterator(leaf, slot), false);
}
if (leaf->isfull())
{
split_leaf_node(leaf, splitkey, splitnode);
// check if insert slot is in the split sibling node
if (slot >= leaf->slotuse)
{
slot -= leaf->slotuse;
leaf = static_cast<leaf_node*>(*splitnode);
}
}
// move items and put data item into correct data slot
BTREE_ASSERT(slot >= 0 && slot <= leaf->slotuse);
std::copy_backward(leaf->slotkey + slot, leaf->slotkey + leaf->slotuse,
leaf->slotkey + leaf->slotuse+1);
data_copy_backward(leaf->slotdata + slot, leaf->slotdata + leaf->slotuse,
leaf->slotdata + leaf->slotuse+1);
leaf->slotkey[slot] = key;
if (!used_as_set) leaf->slotdata[slot] = value;
leaf->slotuse++;
if (splitnode && leaf != *splitnode && slot == leaf->slotuse-1)
{
// special case: the node was split, and the insert is at the
// last slot of the old node. then the splitkey must be
// updated.
*splitkey = key;
}
return std::pair<iterator, bool>(iterator(leaf, slot), true);
}
}
/// Split up a leaf node into two equally-filled sibling leaves. Returns
/// the new nodes and it's insertion key in the two parameters.
void split_leaf_node(leaf_node* leaf, key_type* _newkey, node** _newleaf)
{
BTREE_ASSERT(leaf->isfull());
unsigned int mid = (leaf->slotuse >> 1);
BTREE_PRINT("btree::split_leaf_node on " << leaf);
leaf_node *newleaf = allocate_leaf();
newleaf->slotuse = leaf->slotuse - mid;
newleaf->nextleaf = leaf->nextleaf;
if (newleaf->nextleaf == NULL) {
BTREE_ASSERT(leaf == m_tailleaf);
m_tailleaf = newleaf;
}
else {
newleaf->nextleaf->prevleaf = newleaf;
}
std::copy(leaf->slotkey + mid, leaf->slotkey + leaf->slotuse,
newleaf->slotkey);
data_copy(leaf->slotdata + mid, leaf->slotdata + leaf->slotuse,
newleaf->slotdata);
leaf->slotuse = mid;
leaf->nextleaf = newleaf;
newleaf->prevleaf = leaf;
*_newkey = leaf->slotkey[leaf->slotuse-1];
*_newleaf = newleaf;
}
/// Split up an inner node into two equally-filled sibling nodes. Returns
/// the new nodes and it's insertion key in the two parameters. Requires
/// the slot of the item will be inserted, so the nodes will be the same
/// size after the insert.
void split_inner_node(inner_node* inner, key_type* _newkey, node** _newinner, unsigned int addslot)
{
BTREE_ASSERT(inner->isfull());
unsigned int mid = (inner->slotuse >> 1);
BTREE_PRINT("btree::split_inner: mid " << mid << " addslot " << addslot);
// if the split is uneven and the overflowing item will be put into the
// larger node, then the smaller split node may underflow
if (addslot <= mid && mid > inner->slotuse - (mid + 1))
mid--;
BTREE_PRINT("btree::split_inner: mid " << mid << " addslot " << addslot);
BTREE_PRINT("btree::split_inner_node on " << inner << " into two nodes " << mid << " and " << inner->slotuse - (mid + 1) << " sized");
inner_node *newinner = allocate_inner(inner->level);
newinner->slotuse = inner->slotuse - (mid + 1);
std::copy(inner->slotkey + mid+1, inner->slotkey + inner->slotuse,
newinner->slotkey);
std::copy(inner->childid + mid+1, inner->childid + inner->slotuse+1,
newinner->childid);
inner->slotuse = mid;
*_newkey = inner->slotkey[mid];
*_newinner = newinner;
}
public:
// *** Bulk Loader - Construct Tree from Sorted Sequence
/// Bulk load a sorted range. Loads items into leaves and constructs a
/// B-tree above them. The tree must be empty when calling this function.
template <typename Iterator>
void bulk_load(Iterator ibegin, Iterator iend)
{
BTREE_ASSERT(empty());
m_stats.itemcount = iend - ibegin;
// calculate number of leaves needed, round up.
size_t num_items = iend - ibegin;
size_t num_leaves = (num_items + leafslotmax-1) / leafslotmax;
BTREE_PRINT("btree::bulk_load, level 0: " << m_stats.itemcount << " items into " << num_leaves << " leaves with up to " << ((iend - ibegin + num_leaves-1) / num_leaves) << " items per leaf.");
Iterator it = ibegin;
for (size_t i = 0; i < num_leaves; ++i)
{
// allocate new leaf node
leaf_node* leaf = allocate_leaf();
// copy keys or (key,value) pairs into leaf nodes, uses template
// switch leaf->set_slot().
leaf->slotuse = static_cast<int>(num_items / (num_leaves-i));
for (size_t s = 0; s < leaf->slotuse; ++s, ++it)
leaf->set_slot(s, *it);
if (m_tailleaf != NULL) {
m_tailleaf->nextleaf = leaf;
leaf->prevleaf = m_tailleaf;
}
else {
m_headleaf = leaf;
}
m_tailleaf = leaf;
num_items -= leaf->slotuse;
}
BTREE_ASSERT( it == iend && num_items == 0 );
// if the btree is so small to fit into one leaf, then we're done.
if (m_headleaf == m_tailleaf) {
m_root = m_headleaf;
return;
}
BTREE_ASSERT( m_stats.leaves == num_leaves );
// create first level of inner nodes, pointing to the leaves.
size_t num_parents = (num_leaves + (innerslotmax+1)-1) / (innerslotmax+1);
BTREE_PRINT("btree::bulk_load, level 1: " << num_leaves << " leaves in " << num_parents << " inner nodes with up to " << ((num_leaves + num_parents-1) / num_parents) << " leaves per inner node.");
// save inner nodes and maxkey for next level.
typedef std::pair<inner_node*, const key_type*> nextlevel_type;
nextlevel_type* nextlevel = new nextlevel_type[num_parents];
leaf_node* leaf = m_headleaf;
for (size_t i = 0; i < num_parents; ++i)
{
// allocate new inner node at level 1
inner_node* n = allocate_inner(1);
n->slotuse = static_cast<int>(num_leaves / (num_parents-i));
BTREE_ASSERT(n->slotuse > 0);
--n->slotuse; // this counts keys, but an inner node has keys+1 children.
// copy last key from each leaf and set child
for (unsigned short s = 0; s < n->slotuse; ++s)
{
n->slotkey[s] = leaf->slotkey[leaf->slotuse-1];
n->childid[s] = leaf;
leaf = leaf->nextleaf;
}
n->childid[n->slotuse] = leaf;
// track max key of any descendant.
nextlevel[i].first = n;
nextlevel[i].second = &leaf->slotkey[leaf->slotuse-1];
leaf = leaf->nextleaf;
num_leaves -= n->slotuse+1;
}
BTREE_ASSERT( leaf == NULL && num_leaves == 0 );
// recursively build inner nodes pointing to inner nodes.
for (int level = 2; num_parents != 1; ++level)
{
size_t num_children = num_parents;
num_parents = (num_children + (innerslotmax+1)-1) / (innerslotmax+1);
BTREE_PRINT("btree::bulk_load, level " << level << ": " << num_children << " children in " << num_parents << " inner nodes with up to " << ((num_children + num_parents-1) / num_parents) << " children per inner node.");
size_t inner_index = 0;
for (size_t i = 0; i < num_parents; ++i)
{
// allocate new inner node at level
inner_node* n = allocate_inner(level);
n->slotuse = static_cast<int>(num_children / (num_parents-i));
BTREE_ASSERT(n->slotuse > 0);
--n->slotuse; // this counts keys, but an inner node has keys+1 children.
// copy children and maxkeys from nextlevel
for (unsigned short s = 0; s < n->slotuse; ++s)
{
n->slotkey[s] = *nextlevel[inner_index].second;
n->childid[s] = nextlevel[inner_index].first;
++inner_index;
}
n->childid[n->slotuse] = nextlevel[inner_index].first;
// reuse nextlevel array for parents, because we can overwrite
// slots we've already consumed.
nextlevel[i].first = n;
nextlevel[i].second = nextlevel[inner_index].second;
++inner_index;
num_children -= n->slotuse+1;
}
BTREE_ASSERT( num_children == 0 );
}
m_root = nextlevel[0].first;
delete [] nextlevel;
if (selfverify) verify();
}
private:
// *** Support Class Encapsulating Deletion Results
/// Result flags of recursive deletion.
enum result_flags_t
{
/// Deletion successful and no fix-ups necessary.
btree_ok = 0,
/// Deletion not successful because key was not found.
btree_not_found = 1,
/// Deletion successful, the last key was updated so parent slotkeys
/// need updates.
btree_update_lastkey = 2,
/// Deletion successful, children nodes were merged and the parent
/// needs to remove the empty node.
btree_fixmerge = 4
};
/// B+ tree recursive deletion has much information which is needs to be
/// passed upward.
struct result_t
{
/// Merged result flags
result_flags_t flags;
/// The key to be updated at the parent's slot
key_type lastkey;
/// Constructor of a result with a specific flag, this can also be used
/// as for implicit conversion.
inline result_t(result_flags_t f = btree_ok)
: flags(f), lastkey()
{ }
/// Constructor with a lastkey value.
inline result_t(result_flags_t f, const key_type &k)
: flags(f), lastkey(k)
{ }
/// Test if this result object has a given flag set.
inline bool has(result_flags_t f) const
{
return (flags & f) != 0;
}
/// Merge two results OR-ing the result flags and overwriting lastkeys.
inline result_t& operator|= (const result_t &other)
{
flags = result_flags_t(flags | other.flags);
// we overwrite existing lastkeys on purpose
if (other.has(btree_update_lastkey))
lastkey = other.lastkey;
return *this;
}
};
public:
// *** Public Erase Functions
/// Erases one (the first) of the key/data pairs associated with the given
/// key.
bool erase_one(const key_type &key)
{
BTREE_PRINT("btree::erase_one(" << key << ") on btree size " << size());
if (selfverify) verify();
if (!m_root) return false;
result_t result = erase_one_descend(key, m_root, NULL, NULL, NULL, NULL, NULL, 0);
if (!result.has(btree_not_found))
--m_stats.itemcount;
#ifdef BTREE_DEBUG
if (debug) print(std::cout);
#endif
if (selfverify) verify();
return !result.has(btree_not_found);
}
/// Erases all the key/data pairs associated with the given key. This is
/// implemented using erase_one().
size_type erase(const key_type &key)
{
size_type c = 0;
while( erase_one(key) )
{
++c;
if (!allow_duplicates) break;
}
return c;
}
/// Erase the key/data pair referenced by the iterator.
void erase(iterator iter)
{
BTREE_PRINT("btree::erase_iter(" << iter.currnode << "," << iter.currslot << ") on btree size " << size());
if (selfverify) verify();
if (!m_root) return;
result_t result = erase_iter_descend(iter, m_root, NULL, NULL, NULL, NULL, NULL, 0);
if (!result.has(btree_not_found))
--m_stats.itemcount;
#ifdef BTREE_DEBUG
if (debug) print(std::cout);
#endif
if (selfverify) verify();
}
#ifdef BTREE_TODO
/// Erase all key/data pairs in the range [first,last). This function is
/// currently not implemented by the B+ Tree.
void erase(iterator /* first */, iterator /* last */)
{
abort();
}
#endif
private:
// *** Private Erase Functions
/** @brief Erase one (the first) key/data pair in the B+ tree matching key.
*
* Descends down the tree in search of key. During the descent the parent,
* left and right siblings and their parents are computed and passed
* down. Once the key/data pair is found, it is removed from the leaf. If
* the leaf underflows 6 different cases are handled. These cases resolve
* the underflow by shifting key/data pairs from adjacent sibling nodes,
* merging two sibling nodes or trimming the tree.
*/
result_t erase_one_descend(const key_type& key,
node *curr,
node *left, node *right,
inner_node *leftparent, inner_node *rightparent,
inner_node *parent, unsigned int parentslot)
{
if (curr->isleafnode())
{
leaf_node *leaf = static_cast<leaf_node*>(curr);
leaf_node *leftleaf = static_cast<leaf_node*>(left);
leaf_node *rightleaf = static_cast<leaf_node*>(right);
int slot = find_lower(leaf, key);
if (slot >= leaf->slotuse || !key_equal(key, leaf->slotkey[slot]))
{
BTREE_PRINT("Could not find key " << key << " to erase.");
return btree_not_found;
}
BTREE_PRINT("Found key in leaf " << curr << " at slot " << slot);
std::copy(leaf->slotkey + slot+1, leaf->slotkey + leaf->slotuse,
leaf->slotkey + slot);
data_copy(leaf->slotdata + slot+1, leaf->slotdata + leaf->slotuse,
leaf->slotdata + slot);
leaf->slotuse--;
result_t myres = btree_ok;
// if the last key of the leaf was changed, the parent is notified
// and updates the key of this leaf
if (slot == leaf->slotuse)
{
if (parent && parentslot < parent->slotuse)
{
BTREE_ASSERT(parent->childid[parentslot] == curr);
parent->slotkey[parentslot] = leaf->slotkey[leaf->slotuse - 1];
}
else
{
if (leaf->slotuse >= 1)
{
BTREE_PRINT("Scheduling lastkeyupdate: key " << leaf->slotkey[leaf->slotuse - 1]);
myres |= result_t(btree_update_lastkey, leaf->slotkey[leaf->slotuse - 1]);
}
else
{
BTREE_ASSERT(leaf == m_root);
}
}
}
if (leaf->isunderflow() && !(leaf == m_root && leaf->slotuse >= 1))
{
// determine what to do about the underflow
// case : if this empty leaf is the root, then delete all nodes
// and set root to NULL.
if (leftleaf == NULL && rightleaf == NULL)
{
BTREE_ASSERT(leaf == m_root);
BTREE_ASSERT(leaf->slotuse == 0);
free_node(m_root);
m_root = leaf = NULL;
m_headleaf = m_tailleaf = NULL;
// will be decremented soon by insert_start()
BTREE_ASSERT(m_stats.itemcount == 1);
BTREE_ASSERT(m_stats.leaves == 0);
BTREE_ASSERT(m_stats.innernodes == 0);
return btree_ok;
}
// case : if both left and right leaves would underflow in case of
// a shift, then merging is necessary. choose the more local merger
// with our parent
else if ( (leftleaf == NULL || leftleaf->isfew()) && (rightleaf == NULL || rightleaf->isfew()) )
{
if (leftparent == parent)
myres |= merge_leaves(leftleaf, leaf, leftparent);
else
myres |= merge_leaves(leaf, rightleaf, rightparent);
}
// case : the right leaf has extra data, so balance right with current
else if ( (leftleaf != NULL && leftleaf->isfew()) && (rightleaf != NULL && !rightleaf->isfew()) )
{
if (rightparent == parent)
myres |= shift_left_leaf(leaf, rightleaf, rightparent, parentslot);
else
myres |= merge_leaves(leftleaf, leaf, leftparent);
}
// case : the left leaf has extra data, so balance left with current
else if ( (leftleaf != NULL && !leftleaf->isfew()) && (rightleaf != NULL && rightleaf->isfew()) )
{
if (leftparent == parent)
shift_right_leaf(leftleaf, leaf, leftparent, parentslot - 1);
else
myres |= merge_leaves(leaf, rightleaf, rightparent);
}
// case : both the leaf and right leaves have extra data and our
// parent, choose the leaf with more data
else if (leftparent == rightparent)
{
if (leftleaf->slotuse <= rightleaf->slotuse)
myres |= shift_left_leaf(leaf, rightleaf, rightparent, parentslot);
else
shift_right_leaf(leftleaf, leaf, leftparent, parentslot - 1);
}
else
{
if (leftparent == parent)
shift_right_leaf(leftleaf, leaf, leftparent, parentslot - 1);
else
myres |= shift_left_leaf(leaf, rightleaf, rightparent, parentslot);
}
}
return myres;
}
else // !curr->isleafnode()
{
inner_node *inner = static_cast<inner_node*>(curr);
inner_node *leftinner = static_cast<inner_node*>(left);
inner_node *rightinner = static_cast<inner_node*>(right);
node *myleft, *myright;
inner_node *myleftparent, *myrightparent;
int slot = find_lower(inner, key);
if (slot == 0) {
myleft = (left == NULL) ? NULL : (static_cast<inner_node*>(left))->childid[left->slotuse - 1];
myleftparent = leftparent;
}
else {
myleft = inner->childid[slot - 1];
myleftparent = inner;
}
if (slot == inner->slotuse) {
myright = (right == NULL) ? NULL : (static_cast<inner_node*>(right))->childid[0];
myrightparent = rightparent;
}
else {
myright = inner->childid[slot + 1];
myrightparent = inner;
}
BTREE_PRINT("erase_one_descend into " << inner->childid[slot]);
result_t result = erase_one_descend(key,
inner->childid[slot],
myleft, myright,
myleftparent, myrightparent,
inner, slot);
result_t myres = btree_ok;
if (result.has(btree_not_found))
{
return result;
}
if (result.has(btree_update_lastkey))
{
if (parent && parentslot < parent->slotuse)
{
BTREE_PRINT("Fixing lastkeyupdate: key " << result.lastkey << " into parent " << parent << " at parentslot " << parentslot);
BTREE_ASSERT(parent->childid[parentslot] == curr);
parent->slotkey[parentslot] = result.lastkey;
}
else
{
BTREE_PRINT("Forwarding lastkeyupdate: key " << result.lastkey);
myres |= result_t(btree_update_lastkey, result.lastkey);
}
}
if (result.has(btree_fixmerge))
{
// either the current node or the next is empty and should be removed
if (inner->childid[slot]->slotuse != 0)
slot++;
// this is the child slot invalidated by the merge
BTREE_ASSERT(inner->childid[slot]->slotuse == 0);
free_node(inner->childid[slot]);
std::copy(inner->slotkey + slot, inner->slotkey + inner->slotuse,
inner->slotkey + slot-1);
std::copy(inner->childid + slot+1, inner->childid + inner->slotuse+1,
inner->childid + slot);
inner->slotuse--;
if (inner->level == 1)
{
// fix split key for children leaves
slot--;
leaf_node *child = static_cast<leaf_node*>(inner->childid[slot]);
inner->slotkey[slot] = child->slotkey[ child->slotuse-1 ];
}
}
if (inner->isunderflow() && !(inner == m_root && inner->slotuse >= 1))
{
// case: the inner node is the root and has just one child. that child becomes the new root
if (leftinner == NULL && rightinner == NULL)
{
BTREE_ASSERT(inner == m_root);
BTREE_ASSERT(inner->slotuse == 0);
m_root = inner->childid[0];
inner->slotuse = 0;
free_node(inner);
return btree_ok;
}
// case : if both left and right leaves would underflow in case of
// a shift, then merging is necessary. choose the more local merger
// with our parent
else if ( (leftinner == NULL || leftinner->isfew()) && (rightinner == NULL || rightinner->isfew()) )
{
if (leftparent == parent)
myres |= merge_inner(leftinner, inner, leftparent, parentslot - 1);
else
myres |= merge_inner(inner, rightinner, rightparent, parentslot);
}
// case : the right leaf has extra data, so balance right with current
else if ( (leftinner != NULL && leftinner->isfew()) && (rightinner != NULL && !rightinner->isfew()) )
{
if (rightparent == parent)
shift_left_inner(inner, rightinner, rightparent, parentslot);
else
myres |= merge_inner(leftinner, inner, leftparent, parentslot - 1);
}
// case : the left leaf has extra data, so balance left with current
else if ( (leftinner != NULL && !leftinner->isfew()) && (rightinner != NULL && rightinner->isfew()) )
{
if (leftparent == parent)
shift_right_inner(leftinner, inner, leftparent, parentslot - 1);
else
myres |= merge_inner(inner, rightinner, rightparent, parentslot);
}
// case : both the leaf and right leaves have extra data and our
// parent, choose the leaf with more data
else if (leftparent == rightparent)
{
if (leftinner->slotuse <= rightinner->slotuse)
shift_left_inner(inner, rightinner, rightparent, parentslot);
else
shift_right_inner(leftinner, inner, leftparent, parentslot - 1);
}
else
{
if (leftparent == parent)
shift_right_inner(leftinner, inner, leftparent, parentslot - 1);
else
shift_left_inner(inner, rightinner, rightparent, parentslot);
}
}
return myres;
}
}
/** @brief Erase one key/data pair referenced by an iterator in the B+
* tree.
*
* Descends down the tree in search of an iterator. During the descent the
* parent, left and right siblings and their parents are computed and
* passed down. The difficulty is that the iterator contains only a pointer
* to a leaf_node, which means that this function must do a recursive depth
* first search for that leaf node in the subtree containing all pairs of
* the same key. This subtree can be very large, even the whole tree,
* though in practice it would not make sense to have so many duplicate
* keys.
*
* Once the referenced key/data pair is found, it is removed from the leaf
* and the same underflow cases are handled as in erase_one_descend.
*/
result_t erase_iter_descend(const iterator& iter,
node *curr,
node *left, node *right,
inner_node *leftparent, inner_node *rightparent,
inner_node *parent, unsigned int parentslot)
{
if (curr->isleafnode())
{
leaf_node *leaf = static_cast<leaf_node*>(curr);
leaf_node *leftleaf = static_cast<leaf_node*>(left);
leaf_node *rightleaf = static_cast<leaf_node*>(right);
// if this is not the correct leaf, get next step in recursive
// search
if (leaf != iter.currnode)
{
return btree_not_found;
}
if (iter.currslot >= leaf->slotuse)
{
BTREE_PRINT("Could not find iterator (" << iter.currnode << "," << iter.currslot << ") to erase. Invalid leaf node?");
return btree_not_found;
}
int slot = iter.currslot;
BTREE_PRINT("Found iterator in leaf " << curr << " at slot " << slot);
std::copy(leaf->slotkey + slot+1, leaf->slotkey + leaf->slotuse,
leaf->slotkey + slot);
data_copy(leaf->slotdata + slot+1, leaf->slotdata + leaf->slotuse,
leaf->slotdata + slot);
leaf->slotuse--;
result_t myres = btree_ok;
// if the last key of the leaf was changed, the parent is notified
// and updates the key of this leaf
if (slot == leaf->slotuse)
{
if (parent && parentslot < parent->slotuse)
{
BTREE_ASSERT(parent->childid[parentslot] == curr);
parent->slotkey[parentslot] = leaf->slotkey[leaf->slotuse - 1];
}
else
{
if (leaf->slotuse >= 1)
{
BTREE_PRINT("Scheduling lastkeyupdate: key " << leaf->slotkey[leaf->slotuse - 1]);
myres |= result_t(btree_update_lastkey, leaf->slotkey[leaf->slotuse - 1]);
}
else
{
BTREE_ASSERT(leaf == m_root);
}
}
}
if (leaf->isunderflow() && !(leaf == m_root && leaf->slotuse >= 1))
{
// determine what to do about the underflow
// case : if this empty leaf is the root, then delete all nodes
// and set root to NULL.
if (leftleaf == NULL && rightleaf == NULL)
{
BTREE_ASSERT(leaf == m_root);
BTREE_ASSERT(leaf->slotuse == 0);
free_node(m_root);
m_root = leaf = NULL;
m_headleaf = m_tailleaf = NULL;
// will be decremented soon by insert_start()
BTREE_ASSERT(m_stats.itemcount == 1);
BTREE_ASSERT(m_stats.leaves == 0);
BTREE_ASSERT(m_stats.innernodes == 0);
return btree_ok;
}
// case : if both left and right leaves would underflow in case of
// a shift, then merging is necessary. choose the more local merger
// with our parent
else if ( (leftleaf == NULL || leftleaf->isfew()) && (rightleaf == NULL || rightleaf->isfew()) )
{
if (leftparent == parent)
myres |= merge_leaves(leftleaf, leaf, leftparent);
else
myres |= merge_leaves(leaf, rightleaf, rightparent);
}
// case : the right leaf has extra data, so balance right with current
else if ( (leftleaf != NULL && leftleaf->isfew()) && (rightleaf != NULL && !rightleaf->isfew()) )
{
if (rightparent == parent)
myres |= shift_left_leaf(leaf, rightleaf, rightparent, parentslot);
else
myres |= merge_leaves(leftleaf, leaf, leftparent);
}
// case : the left leaf has extra data, so balance left with current
else if ( (leftleaf != NULL && !leftleaf->isfew()) && (rightleaf != NULL && rightleaf->isfew()) )
{
if (leftparent == parent)
shift_right_leaf(leftleaf, leaf, leftparent, parentslot - 1);
else
myres |= merge_leaves(leaf, rightleaf, rightparent);
}
// case : both the leaf and right leaves have extra data and our
// parent, choose the leaf with more data
else if (leftparent == rightparent)
{
if (leftleaf->slotuse <= rightleaf->slotuse)
myres |= shift_left_leaf(leaf, rightleaf, rightparent, parentslot);
else
shift_right_leaf(leftleaf, leaf, leftparent, parentslot - 1);
}
else
{
if (leftparent == parent)
shift_right_leaf(leftleaf, leaf, leftparent, parentslot - 1);
else
myres |= shift_left_leaf(leaf, rightleaf, rightparent, parentslot);
}
}
return myres;
}
else // !curr->isleafnode()
{
inner_node *inner = static_cast<inner_node*>(curr);
inner_node *leftinner = static_cast<inner_node*>(left);
inner_node *rightinner = static_cast<inner_node*>(right);
// find first slot below which the searched iterator might be
// located.
result_t result;
int slot = find_lower(inner, iter.key());
while (slot <= inner->slotuse)
{
node *myleft, *myright;
inner_node *myleftparent, *myrightparent;
if (slot == 0) {
myleft = (left == NULL) ? NULL : (static_cast<inner_node*>(left))->childid[left->slotuse - 1];
myleftparent = leftparent;
}
else {
myleft = inner->childid[slot - 1];
myleftparent = inner;
}
if (slot == inner->slotuse) {
myright = (right == NULL) ? NULL : (static_cast<inner_node*>(right))->childid[0];
myrightparent = rightparent;
}
else {
myright = inner->childid[slot + 1];
myrightparent = inner;
}
BTREE_PRINT("erase_iter_descend into " << inner->childid[slot]);
result = erase_iter_descend(iter,
inner->childid[slot],
myleft, myright,
myleftparent, myrightparent,
inner, slot);
if (!result.has(btree_not_found))
break;
// continue recursive search for leaf on next slot
if (slot < inner->slotuse && key_less(inner->slotkey[slot],iter.key()))
return btree_not_found;
++slot;
}
if (slot > inner->slotuse)
return btree_not_found;
result_t myres = btree_ok;
if (result.has(btree_update_lastkey))
{
if (parent && parentslot < parent->slotuse)
{
BTREE_PRINT("Fixing lastkeyupdate: key " << result.lastkey << " into parent " << parent << " at parentslot " << parentslot);
BTREE_ASSERT(parent->childid[parentslot] == curr);
parent->slotkey[parentslot] = result.lastkey;
}
else
{
BTREE_PRINT("Forwarding lastkeyupdate: key " << result.lastkey);
myres |= result_t(btree_update_lastkey, result.lastkey);
}
}
if (result.has(btree_fixmerge))
{
// either the current node or the next is empty and should be removed
if (inner->childid[slot]->slotuse != 0)
slot++;
// this is the child slot invalidated by the merge
BTREE_ASSERT(inner->childid[slot]->slotuse == 0);
free_node(inner->childid[slot]);
std::copy(inner->slotkey + slot, inner->slotkey + inner->slotuse,
inner->slotkey + slot-1);
std::copy(inner->childid + slot+1, inner->childid + inner->slotuse+1,
inner->childid + slot);
inner->slotuse--;
if (inner->level == 1)
{
// fix split key for children leaves
slot--;
leaf_node *child = static_cast<leaf_node*>(inner->childid[slot]);
inner->slotkey[slot] = child->slotkey[ child->slotuse-1 ];
}
}
if (inner->isunderflow() && !(inner == m_root && inner->slotuse >= 1))
{
// case: the inner node is the root and has just one
// child. that child becomes the new root
if (leftinner == NULL && rightinner == NULL)
{
BTREE_ASSERT(inner == m_root);
BTREE_ASSERT(inner->slotuse == 0);
m_root = inner->childid[0];
inner->slotuse = 0;
free_node(inner);
return btree_ok;
}
// case : if both left and right leaves would underflow in case of
// a shift, then merging is necessary. choose the more local merger
// with our parent
else if ( (leftinner == NULL || leftinner->isfew()) && (rightinner == NULL || rightinner->isfew()) )
{
if (leftparent == parent)
myres |= merge_inner(leftinner, inner, leftparent, parentslot - 1);
else
myres |= merge_inner(inner, rightinner, rightparent, parentslot);
}
// case : the right leaf has extra data, so balance right with current
else if ( (leftinner != NULL && leftinner->isfew()) && (rightinner != NULL && !rightinner->isfew()) )
{
if (rightparent == parent)
shift_left_inner(inner, rightinner, rightparent, parentslot);
else
myres |= merge_inner(leftinner, inner, leftparent, parentslot - 1);
}
// case : the left leaf has extra data, so balance left with current
else if ( (leftinner != NULL && !leftinner->isfew()) && (rightinner != NULL && rightinner->isfew()) )
{
if (leftparent == parent)
shift_right_inner(leftinner, inner, leftparent, parentslot - 1);
else
myres |= merge_inner(inner, rightinner, rightparent, parentslot);
}
// case : both the leaf and right leaves have extra data and our
// parent, choose the leaf with more data
else if (leftparent == rightparent)
{
if (leftinner->slotuse <= rightinner->slotuse)
shift_left_inner(inner, rightinner, rightparent, parentslot);
else
shift_right_inner(leftinner, inner, leftparent, parentslot - 1);
}
else
{
if (leftparent == parent)
shift_right_inner(leftinner, inner, leftparent, parentslot - 1);
else
shift_left_inner(inner, rightinner, rightparent, parentslot);
}
}
return myres;
}
}
/// Merge two leaf nodes. The function moves all key/data pairs from right
/// to left and sets right's slotuse to zero. The right slot is then
/// removed by the calling parent node.
result_t merge_leaves(leaf_node* left, leaf_node* right, inner_node* parent)
{
BTREE_PRINT("Merge leaf nodes " << left << " and " << right << " with common parent " << parent << ".");
(void)parent;
BTREE_ASSERT(left->isleafnode() && right->isleafnode());
BTREE_ASSERT(parent->level == 1);
BTREE_ASSERT(left->slotuse + right->slotuse < leafslotmax);
std::copy(right->slotkey, right->slotkey + right->slotuse,
left->slotkey + left->slotuse);
data_copy(right->slotdata, right->slotdata + right->slotuse,
left->slotdata + left->slotuse);
left->slotuse += right->slotuse;
left->nextleaf = right->nextleaf;
if (left->nextleaf)
left->nextleaf->prevleaf = left;
else
m_tailleaf = left;
right->slotuse = 0;
return btree_fixmerge;
}
/// Merge two inner nodes. The function moves all key/childid pairs from
/// right to left and sets right's slotuse to zero. The right slot is then
/// removed by the calling parent node.
static result_t merge_inner(inner_node* left, inner_node* right, inner_node* parent, unsigned int parentslot)
{
BTREE_PRINT("Merge inner nodes " << left << " and " << right << " with common parent " << parent << ".");
BTREE_ASSERT(left->level == right->level);
BTREE_ASSERT(parent->level == left->level + 1);
BTREE_ASSERT(parent->childid[parentslot] == left);
BTREE_ASSERT(left->slotuse + right->slotuse < innerslotmax);
if (selfverify)
{
// find the left node's slot in the parent's children
unsigned int leftslot = 0;
while(leftslot <= parent->slotuse && parent->childid[leftslot] != left)
++leftslot;
BTREE_ASSERT(leftslot < parent->slotuse);
BTREE_ASSERT(parent->childid[leftslot] == left);
BTREE_ASSERT(parent->childid[leftslot+1] == right);
BTREE_ASSERT(parentslot == leftslot);
}
// retrieve the decision key from parent
left->slotkey[left->slotuse] = parent->slotkey[parentslot];
left->slotuse++;
// copy over keys and children from right
std::copy(right->slotkey, right->slotkey + right->slotuse,
left->slotkey + left->slotuse);
std::copy(right->childid, right->childid + right->slotuse+1,
left->childid + left->slotuse);
left->slotuse += right->slotuse;
right->slotuse = 0;
return btree_fixmerge;
}
/// Balance two leaf nodes. The function moves key/data pairs from right to
/// left so that both nodes are equally filled. The parent node is updated
/// if possible.
static result_t shift_left_leaf(leaf_node *left, leaf_node *right, inner_node *parent, unsigned int parentslot)
{
BTREE_ASSERT(left->isleafnode() && right->isleafnode());
BTREE_ASSERT(parent->level == 1);
BTREE_ASSERT(left->nextleaf == right);
BTREE_ASSERT(left == right->prevleaf);
BTREE_ASSERT(left->slotuse < right->slotuse);
BTREE_ASSERT(parent->childid[parentslot] == left);
unsigned int shiftnum = (right->slotuse - left->slotuse) >> 1;
BTREE_PRINT("Shifting (leaf) " << shiftnum << " entries to left " << left << " from right " << right << " with common parent " << parent << ".");
BTREE_ASSERT(left->slotuse + shiftnum < leafslotmax);
// copy the first items from the right node to the last slot in the left node.
std::copy(right->slotkey, right->slotkey + shiftnum,
left->slotkey + left->slotuse);
data_copy(right->slotdata, right->slotdata + shiftnum,
left->slotdata + left->slotuse);
left->slotuse += shiftnum;
// shift all slots in the right node to the left
std::copy(right->slotkey + shiftnum, right->slotkey + right->slotuse,
right->slotkey);
data_copy(right->slotdata + shiftnum, right->slotdata + right->slotuse,
right->slotdata);
right->slotuse -= shiftnum;
// fixup parent
if (parentslot < parent->slotuse) {
parent->slotkey[parentslot] = left->slotkey[left->slotuse - 1];
return btree_ok;
}
else { // the update is further up the tree
return result_t(btree_update_lastkey, left->slotkey[left->slotuse - 1]);
}
}
/// Balance two inner nodes. The function moves key/data pairs from right
/// to left so that both nodes are equally filled. The parent node is
/// updated if possible.
static void shift_left_inner(inner_node *left, inner_node *right, inner_node *parent, unsigned int parentslot)
{
BTREE_ASSERT(left->level == right->level);
BTREE_ASSERT(parent->level == left->level + 1);
BTREE_ASSERT(left->slotuse < right->slotuse);
BTREE_ASSERT(parent->childid[parentslot] == left);
unsigned int shiftnum = (right->slotuse - left->slotuse) >> 1;
BTREE_PRINT("Shifting (inner) " << shiftnum << " entries to left " << left << " from right " << right << " with common parent " << parent << ".");
BTREE_ASSERT(left->slotuse + shiftnum < innerslotmax);
if (selfverify)
{
// find the left node's slot in the parent's children and compare to parentslot
unsigned int leftslot = 0;
while(leftslot <= parent->slotuse && parent->childid[leftslot] != left)
++leftslot;
BTREE_ASSERT(leftslot < parent->slotuse);
BTREE_ASSERT(parent->childid[leftslot] == left);
BTREE_ASSERT(parent->childid[leftslot+1] == right);
BTREE_ASSERT(leftslot == parentslot);
}
// copy the parent's decision slotkey and childid to the first new key on the left
left->slotkey[left->slotuse] = parent->slotkey[parentslot];
left->slotuse++;
// copy the other items from the right node to the last slots in the left node.
std::copy(right->slotkey, right->slotkey + shiftnum-1,
left->slotkey + left->slotuse);
std::copy(right->childid, right->childid + shiftnum,
left->childid + left->slotuse);
left->slotuse += shiftnum - 1;
// fixup parent
parent->slotkey[parentslot] = right->slotkey[shiftnum - 1];
// shift all slots in the right node
std::copy(right->slotkey + shiftnum, right->slotkey + right->slotuse,
right->slotkey);
std::copy(right->childid + shiftnum, right->childid + right->slotuse+1,
right->childid);
right->slotuse -= shiftnum;
}
/// Balance two leaf nodes. The function moves key/data pairs from left to
/// right so that both nodes are equally filled. The parent node is updated
/// if possible.
static void shift_right_leaf(leaf_node *left, leaf_node *right, inner_node *parent, unsigned int parentslot)
{
BTREE_ASSERT(left->isleafnode() && right->isleafnode());
BTREE_ASSERT(parent->level == 1);
BTREE_ASSERT(left->nextleaf == right);
BTREE_ASSERT(left == right->prevleaf);
BTREE_ASSERT(parent->childid[parentslot] == left);
BTREE_ASSERT(left->slotuse > right->slotuse);
unsigned int shiftnum = (left->slotuse - right->slotuse) >> 1;
BTREE_PRINT("Shifting (leaf) " << shiftnum << " entries to right " << right << " from left " << left << " with common parent " << parent << ".");
if (selfverify)
{
// find the left node's slot in the parent's children
unsigned int leftslot = 0;
while(leftslot <= parent->slotuse && parent->childid[leftslot] != left)
++leftslot;
BTREE_ASSERT(leftslot < parent->slotuse);
BTREE_ASSERT(parent->childid[leftslot] == left);
BTREE_ASSERT(parent->childid[leftslot+1] == right);
BTREE_ASSERT(leftslot == parentslot);
}
// shift all slots in the right node
BTREE_ASSERT(right->slotuse + shiftnum < leafslotmax);
std::copy_backward(right->slotkey, right->slotkey + right->slotuse,
right->slotkey + right->slotuse + shiftnum);
data_copy_backward(right->slotdata, right->slotdata + right->slotuse,
right->slotdata + right->slotuse + shiftnum);
right->slotuse += shiftnum;
// copy the last items from the left node to the first slot in the right node.
std::copy(left->slotkey + left->slotuse - shiftnum, left->slotkey + left->slotuse,
right->slotkey);
data_copy(left->slotdata + left->slotuse - shiftnum, left->slotdata + left->slotuse,
right->slotdata);
left->slotuse -= shiftnum;
parent->slotkey[parentslot] = left->slotkey[left->slotuse-1];
}
/// Balance two inner nodes. The function moves key/data pairs from left to
/// right so that both nodes are equally filled. The parent node is updated
/// if possible.
static void shift_right_inner(inner_node *left, inner_node *right, inner_node *parent, unsigned int parentslot)
{
BTREE_ASSERT(left->level == right->level);
BTREE_ASSERT(parent->level == left->level + 1);
BTREE_ASSERT(left->slotuse > right->slotuse);
BTREE_ASSERT(parent->childid[parentslot] == left);
unsigned int shiftnum = (left->slotuse - right->slotuse) >> 1;
BTREE_PRINT("Shifting (leaf) " << shiftnum << " entries to right " << right << " from left " << left << " with common parent " << parent << ".");
if (selfverify)
{
// find the left node's slot in the parent's children
unsigned int leftslot = 0;
while(leftslot <= parent->slotuse && parent->childid[leftslot] != left)
++leftslot;
BTREE_ASSERT(leftslot < parent->slotuse);
BTREE_ASSERT(parent->childid[leftslot] == left);
BTREE_ASSERT(parent->childid[leftslot+1] == right);
BTREE_ASSERT(leftslot == parentslot);
}
// shift all slots in the right node
BTREE_ASSERT(right->slotuse + shiftnum < innerslotmax);
std::copy_backward(right->slotkey, right->slotkey + right->slotuse,
right->slotkey + right->slotuse + shiftnum);
std::copy_backward(right->childid, right->childid + right->slotuse+1,
right->childid + right->slotuse+1 + shiftnum);
right->slotuse += shiftnum;
// copy the parent's decision slotkey and childid to the last new key on the right
right->slotkey[shiftnum - 1] = parent->slotkey[parentslot];
// copy the remaining last items from the left node to the first slot in the right node.
std::copy(left->slotkey + left->slotuse - shiftnum+1, left->slotkey + left->slotuse,
right->slotkey);
std::copy(left->childid + left->slotuse - shiftnum+1, left->childid + left->slotuse+1,
right->childid);
// copy the first to-be-removed key from the left node to the parent's decision slot
parent->slotkey[parentslot] = left->slotkey[left->slotuse - shiftnum];
left->slotuse -= shiftnum;
}
#ifdef BTREE_DEBUG
public:
// *** Debug Printing
/// Print out the B+ tree structure with keys onto the given ostream. This
/// function requires that the header is compiled with BTREE_DEBUG and that
/// key_type is printable via std::ostream.
void print(std::ostream &os) const
{
if (m_root) {
print_node(os, m_root, 0, true);
}
}
/// Print out only the leaves via the double linked list.
void print_leaves(std::ostream &os) const
{
os << "leaves:" << std::endl;
const leaf_node *n = m_headleaf;
while(n)
{
os << " " << n << std::endl;
n = n->nextleaf;
}
}
private:
/// Recursively descend down the tree and print out nodes.
static void print_node(std::ostream &os, const node* node, unsigned int depth=0, bool recursive=false)
{
for(unsigned int i = 0; i < depth; i++) os << " ";
os << "node " << node << " level " << node->level << " slotuse " << node->slotuse << std::endl;
if (node->isleafnode())
{
const leaf_node *leafnode = static_cast<const leaf_node*>(node);
for(unsigned int i = 0; i < depth; i++) os << " ";
os << " leaf prev " << leafnode->prevleaf << " next " << leafnode->nextleaf << std::endl;
for(unsigned int i = 0; i < depth; i++) os << " ";
for (unsigned int slot = 0; slot < leafnode->slotuse; ++slot)
{
os << leafnode->slotkey[slot] << " "; // << "(data: " << leafnode->slotdata[slot] << ") ";
}
os << std::endl;
}
else
{
const inner_node *innernode = static_cast<const inner_node*>(node);
for(unsigned int i = 0; i < depth; i++) os << " ";
for (unsigned short slot = 0; slot < innernode->slotuse; ++slot)
{
os << "(" << innernode->childid[slot] << ") " << innernode->slotkey[slot] << " ";
}
os << "(" << innernode->childid[innernode->slotuse] << ")" << std::endl;
if (recursive)
{
for (unsigned short slot = 0; slot < innernode->slotuse + 1; ++slot)
{
print_node(os, innernode->childid[slot], depth + 1, recursive);
}
}
}
}
#endif
public:
// *** Verification of B+ Tree Invariants
/// Run a thorough verification of all B+ tree invariants. The program
/// aborts via assert() if something is wrong.
void verify() const
{
key_type minkey, maxkey;
tree_stats vstats;
if (m_root)
{
verify_node(m_root, &minkey, &maxkey, vstats);
assert( vstats.itemcount == m_stats.itemcount );
assert( vstats.leaves == m_stats.leaves );
assert( vstats.innernodes == m_stats.innernodes );
verify_leaflinks();
}
}
private:
/// Recursively descend down the tree and verify each node
void verify_node(const node* n, key_type* minkey, key_type* maxkey, tree_stats &vstats) const
{
BTREE_PRINT("verifynode " << n);
if (n->isleafnode())
{
const leaf_node *leaf = static_cast<const leaf_node*>(n);
assert( leaf == m_root || !leaf->isunderflow() );
assert( leaf->slotuse > 0 );
for(unsigned short slot = 0; slot < leaf->slotuse - 1; ++slot)
{
assert(key_lessequal(leaf->slotkey[slot], leaf->slotkey[slot + 1]));
}
*minkey = leaf->slotkey[0];
*maxkey = leaf->slotkey[leaf->slotuse - 1];
vstats.leaves++;
vstats.itemcount += leaf->slotuse;
}
else // !n->isleafnode()
{
const inner_node *inner = static_cast<const inner_node*>(n);
vstats.innernodes++;
assert( inner == m_root || !inner->isunderflow() );
assert( inner->slotuse > 0 );
for(unsigned short slot = 0; slot < inner->slotuse - 1; ++slot)
{
assert(key_lessequal(inner->slotkey[slot], inner->slotkey[slot + 1]));
}
for(unsigned short slot = 0; slot <= inner->slotuse; ++slot)
{
const node *subnode = inner->childid[slot];
key_type subminkey = key_type();
key_type submaxkey = key_type();
assert(subnode->level + 1 == inner->level);
verify_node(subnode, &subminkey, &submaxkey, vstats);
BTREE_PRINT("verify subnode " << subnode << ": " << subminkey << " - " << submaxkey);
if (slot == 0)
*minkey = subminkey;
else
assert(key_greaterequal(subminkey, inner->slotkey[slot-1]));
if (slot == inner->slotuse)
*maxkey = submaxkey;
else
assert(key_equal(inner->slotkey[slot], submaxkey));
if (inner->level == 1 && slot < inner->slotuse)
{
// children are leaves and must be linked together in the
// correct order
const leaf_node *leafa = static_cast<const leaf_node*>(inner->childid[slot]);
const leaf_node *leafb = static_cast<const leaf_node*>(inner->childid[slot + 1]);
assert(leafa->nextleaf == leafb);
assert(leafa == leafb->prevleaf);
(void)leafa; (void)leafb;
}
if (inner->level == 2 && slot < inner->slotuse)
{
// verify leaf links between the adjacent inner nodes
const inner_node *parenta = static_cast<const inner_node*>(inner->childid[slot]);
const inner_node *parentb = static_cast<const inner_node*>(inner->childid[slot+1]);
const leaf_node *leafa = static_cast<const leaf_node*>(parenta->childid[parenta->slotuse]);
const leaf_node *leafb = static_cast<const leaf_node*>(parentb->childid[0]);
assert(leafa->nextleaf == leafb);
assert(leafa == leafb->prevleaf);
(void)leafa; (void)leafb;
}
}
}
}
/// Verify the double linked list of leaves.
void verify_leaflinks() const
{
const leaf_node *n = m_headleaf;
assert(n->level == 0);
assert(!n || n->prevleaf == NULL);
unsigned int testcount = 0;
while(n)
{
assert(n->level == 0);
assert(n->slotuse > 0);
for(unsigned short slot = 0; slot < n->slotuse - 1; ++slot)
{
assert(key_lessequal(n->slotkey[slot], n->slotkey[slot + 1]));
}
testcount += n->slotuse;
if (n->nextleaf)
{
assert(key_lessequal(n->slotkey[n->slotuse-1], n->nextleaf->slotkey[0]));
assert(n == n->nextleaf->prevleaf);
}
else
{
assert(m_tailleaf == n);
}
n = n->nextleaf;
}
assert(testcount == size());
}
private:
// *** Dump and Restore of B+ Trees
/// A header for the binary image containing the base properties of the B+
/// tree. These properties have to match the current template
/// instantiation.
struct dump_header
{
/// "stx-btree", just to stop the restore() function from loading garbage
char signature[12];
/// Currently 0
unsigned short version;
/// sizeof(key_type)
unsigned short key_type_size;
/// sizeof(data_type)
unsigned short data_type_size;
/// Number of slots in the leaves
unsigned short leafslots;
/// Number of slots in the inner nodes
unsigned short innerslots;
/// Allow duplicates
bool allow_duplicates;
/// The item count of the tree
size_type itemcount;
/// Fill the struct with the current B+ tree's properties, itemcount is
/// not filled.
inline void fill()
{
// don't want to include string.h just for this signature
signature[0] = 's'; signature[1] = 't'; signature[2] = 'x'; signature[3] = '-';
signature[4] = 'b'; signature[5] = 't'; signature[6] = 'r'; signature[7] = 'e';
signature[8] = 'e'; signature[9] = 0; signature[10] = 0; signature[11] = 0;
version = 0;
key_type_size = sizeof(typename btree_self::key_type);
data_type_size = sizeof(typename btree_self::data_type);
leafslots = btree_self::leafslotmax;
innerslots = btree_self::innerslotmax;
allow_duplicates = btree_self::allow_duplicates;
}
/// Returns true if the headers have the same vital properties
inline bool same(const struct dump_header &o) const
{
return (signature[0] == 's' && signature[1] == 't' && signature[2] == 'x' && signature[3] == '-' &&
signature[4] == 'b' && signature[5] == 't' && signature[6] == 'r' && signature[7] == 'e' &&
signature[8] == 'e' && signature[9] == 0 && signature[10] == 0 && signature[11] == 0)
&& (version == o.version)
&& (key_type_size == o.key_type_size)
&& (data_type_size == o.data_type_size)
&& (leafslots == o.leafslots)
&& (innerslots == o.innerslots)
&& (allow_duplicates == o.allow_duplicates);
}
};
public:
/// Dump the contents of the B+ tree out onto an ostream as a binary
/// image. The image contains memory pointers which will be fixed when the
/// image is restored. For this to work your key_type and data_type must be
/// integral types and contain no pointers or references.
void dump(std::ostream &os) const
{
struct dump_header header;
header.fill();
header.itemcount = size();
os.write(reinterpret_cast<char*>(&header), sizeof(header));
if (m_root) {
dump_node(os, m_root);
}
}
/// Restore a binary image of a dumped B+ tree from an istream. The B+ tree
/// pointers are fixed using the dump order. For dump and restore to work
/// your key_type and data_type must be integral types and contain no
/// pointers or references. Returns true if the restore was successful.
bool restore(std::istream &is)
{
struct dump_header fileheader;
is.read(reinterpret_cast<char*>(&fileheader), sizeof(fileheader));
if (!is.good()) return false;
struct dump_header myheader;
myheader.fill();
myheader.itemcount = fileheader.itemcount;
if (!myheader.same(fileheader))
{
BTREE_PRINT("btree::restore: file header does not match instantiation signature.");
return false;
}
clear();
if (fileheader.itemcount > 0)
{
m_root = restore_node(is);
if (m_root == NULL) return false;
m_stats.itemcount = fileheader.itemcount;
}
#ifdef BTREE_DEBUG
if (debug) print(std::cout);
#endif
if (selfverify) verify();
return true;
}
private:
/// Recursively descend down the tree and dump each node in a precise order
void dump_node(std::ostream &os, const node* n) const
{
BTREE_PRINT("dump_node " << n << std::endl);
if (n->isleafnode())
{
const leaf_node *leaf = static_cast<const leaf_node*>(n);
os.write(reinterpret_cast<const char*>(leaf), sizeof(*leaf));
}
else // !n->isleafnode()
{
const inner_node *inner = static_cast<const inner_node*>(n);
os.write(reinterpret_cast<const char*>(inner), sizeof(*inner));
for(unsigned short slot = 0; slot <= inner->slotuse; ++slot)
{
const node *subnode = inner->childid[slot];
dump_node(os, subnode);
}
}
}
/// Read the dump image and construct a tree from the node order in the
/// serialization.
node* restore_node(std::istream &is)
{
union {
node top;
leaf_node leaf;
inner_node inner;
} nu;
// first read only the top of the node
is.read(reinterpret_cast<char*>(&nu.top), sizeof(nu.top));
if (!is.good()) return NULL;
if (nu.top.isleafnode())
{
// read remaining data of leaf node
is.read(reinterpret_cast<char*>(&nu.leaf) + sizeof(nu.top), sizeof(nu.leaf) - sizeof(nu.top));
if (!is.good()) return NULL;
leaf_node *newleaf = allocate_leaf();
// copy over all data, the leaf nodes contain only their double linked list pointers
*newleaf = nu.leaf;
// reconstruct the linked list from the order in the file
if (m_headleaf == NULL) {
BTREE_ASSERT(newleaf->prevleaf == NULL);
m_headleaf = m_tailleaf = newleaf;
}
else {
newleaf->prevleaf = m_tailleaf;
m_tailleaf->nextleaf = newleaf;
m_tailleaf = newleaf;
}
return newleaf;
}
else
{
// read remaining data of inner node
is.read(reinterpret_cast<char*>(&nu.inner) + sizeof(nu.top), sizeof(nu.inner) - sizeof(nu.top));
if (!is.good()) return NULL;
inner_node *newinner = allocate_inner(0);
// copy over all data, the inner nodes contain only pointers to their children
*newinner = nu.inner;
for(unsigned short slot = 0; slot <= newinner->slotuse; ++slot)
{
newinner->childid[slot] = restore_node(is);
}
return newinner;
}
}
};
} // namespace stx
#endif // _STX_BTREE_H_
|