[C#/COMMON] B+ 트리 파일 사용하기
■ B+ 트리 파일을 사용하는 방법을 보여준다. [TestLibrary 프로젝트] ▶ BPlusTree.cs
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 |
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Threading; namespace TestLibrary { /// <summary> /// B+ 트리 /// </summary> /// <typeparam name="TKey">키 타입</typeparam> /// <typeparam name="TValue">값 타입</typeparam> public partial class BPlusTree<TKey, TValue> : IDisposable, ITransactable, IDictionary<TKey, TValue>, IDictionaryEX<TKey, TValue>, IConcurrentDictionary<TKey, TValue> { //////////////////////////////////////////////////////////////////////////////////////////////////// Enumeration ////////////////////////////////////////////////////////////////////////////////////////// Public #region 디버그 포맷 - DebugFormat /// <summary> /// 디버그 포맷 /// </summary> public enum DebugFormat { /// <summary> /// 완전한 정보 /// </summary> /// <remarks>모든 노드에 대한 완전한 정보이다.</remarks> Full, /// <summary> /// 포맷화 /// </summary> /// <remarks> /// 새 줄에 서식이 지정되고 탭이 표시되지만 정보는 줄어든다. /// </remarks> Formatted, /// <summary> /// 컴팩트 /// </summary> /// <remarks>컴팩트 한 줄 형식이다.</remarks> Compact } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 잠금 타입 - LockType /// <summary> /// 잠금 타입 /// </summary> private enum LockType { /// <summary> /// 읽기 /// </summary> Read = 1, /// <summary> /// 추가 /// </summary> Insert = 2, /// <summary> /// 수정 /// </summary> Update = 3, /// <summary> /// 삭제 /// </summary> Delete = 4 } #endregion #region 삽입 결과 - InsertResult /// <summary> /// 삽입 결과 /// </summary> private enum InsertResult { /// <summary> /// 삽입 /// </summary> Inserted = 1, /// <summary> /// 수정 /// </summary> Updated = 2, /// <summary> /// 존재 /// </summary> Exists = 3, /// <summary> /// 미발견 /// </summary> NotFound = 4 } #endregion #region 제거 결과 - RemoveResult /// <summary> /// 제거 결과 /// </summary> private enum RemoveResult { /// <summary> /// 무시 /// </summary> Ignored = 0, /// <summary> /// 제거 /// </summary> Removed = 1, /// <summary> /// 미발견 /// </summary> NotFound = 2 } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 무시 키/값 업데이트 대리자 /// </summary> private static readonly KeyValueUpdate<TKey, TValue> _ignoreKeyValueUpdate = (key, value) => value; #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 비 잠금 타입 /// </summary> private const LockType NO_LOCK_TYPE = 0; /// <summary> /// 옵션 /// </summary> private readonly BPlusTreeOptions<TKey, TValue> options; /// <summary> /// 노드 캐시 베이스 /// </summary> private readonly NodeCacheBase nodeCacheBase; /// <summary> /// 잠금 전략 /// </summary> private readonly ILockStrategy lockStrategy; /// <summary> /// 키 비교자 /// </summary> private readonly IComparer<TKey> keyComparer; /// <summary> /// 엘리먼트 비교자 /// </summary> private readonly IComparer<Element> elementComparer; /// <summary> /// 리소스 해제 여부 /// </summary> private bool disposed; /// <summary> /// 카운트 보유 여부 /// </summary> private bool hasCount; /// <summary> /// 카운트 /// </summary> private int count; /// <summary> /// 키 컬렉션 /// </summary> private KeyCollection keyCollection; /// <summary> /// 값 컬렉션 /// </summary> private ValueCollection valueCollection; /// <summary> /// 무결성 여부 /// </summary> private bool validated; /// <summary> /// 디버그 텍스트 라이터 /// </summary> private TextWriter debugTextWriter; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 레벨 잠금 호출 - CallLevelLock /// <summary> /// 레벨 잠금 호출 /// </summary> /// <remarks> /// 트리 수준 단독 작업을 제공하는 데 사용되는 잠금을 정의한다. /// 이 값을 설정하기 전에 시작된 작업이 아직 처리 중인 경우 /// 이에 의존하는 작업(Clear, EnableCount 및 UnloadCache)이 제대로 작동하지 않을 수 있으므로 /// 구성 시 설정하거나 전혀 설정하지 않아야 한다. /// 내가 테스트한 잠금 중에서 ReaderWriterLocking 구현은 읽기 집약적인 잠금이므로 여기에서 가장 잘 수행된다. /// 트리 콘텐츠에 액세스하는 모든 공개 API는 트리 독점 작업을 제외하고 리더로서 이 잠금을 획득한다. /// 또한 쓰기 잠금을 획득하여 독점 액세스 권한을 얻고 대량 업데이트, 원자 열거 등을 수행할 수 있다. /// </remarks> public ILockStrategy CallLevelLock { get { CheckNotDisposed(); return this.lockStrategy; } } #endregion #region 카운트 - Count /// <summary> /// 카운트 /// </summary> public int Count { get { return this.hasCount ? this.count : int.MinValue; } } #endregion #region 잠금 타임아웃 - LockTimeout /// <summary> /// 잠금 타임아웃 /// </summary> private int LockTimeout { get { return this.options.LockTimeout; } } #endregion #region 인덱서 - this[key] /// <summary> /// 인덱서 /// </summary> /// <param name="key">키</param> public TValue this[TKey key] { get { TValue result; if(!TryGetValue(key, out result)) { throw new IndexOutOfRangeException(); } return result; } set { InsertValue insertValue = new InsertValue(value, true); AddEntry(key, ref insertValue); } } #endregion #region 키 컬렉션 - Keys /// <summary> /// 키 컬렉션 /// </summary> public ICollection<TKey> Keys { get { return this.keyCollection != null ? this.keyCollection : (this.keyCollection = new KeyCollection(this)); } } #endregion #region 값 컬렉션 - Values /// <summary> /// 값 컬렉션 /// </summary> public ICollection<TValue> Values { get { return this.valueCollection != null ? this.valueCollection : (this.valueCollection = new ValueCollection(this)); } } #endregion #region 읽기 전용 여부 - IsReadOnly /// <summary> /// 읽기 전용 여부 /// </summary> public bool IsReadOnly { get { return this.options.ReadOnly; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - BPlusTree() /// <summary> /// 생성자 /// </summary> public BPlusTree() : this(Comparer<TKey>.Default) { } #endregion #region 생성자 - BPlusTree(comparer) /// <summary> /// 생성자 /// </summary> /// <param name="comparer">비교자</param> public BPlusTree(IComparer<TKey> comparer) : this ( (BPlusTreeOptions<TKey, TValue>)new OptionsV1(InvalidSerializer<TKey>._serializer, InvalidSerializer<TValue>._serializer, comparer) ) { } #endregion #region 생성자 - BPlusTree(optionsV2) /// <summary> /// 생성자 /// </summary> /// <param name="optionsV2">옵션 V2</param> public BPlusTree(OptionsV2 optionsV2) : this((BPlusTreeOptions<TKey, TValue>)optionsV2) { } #endregion #region 생성자 - BPlusTree(options) /// <summary> /// 생성자 /// </summary> /// <param name="options">옵션</param> [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public BPlusTree(OptionsV1 options) : this((BPlusTreeOptions<TKey, TValue>)options) { } #endregion #region 생성자 - BPlusTree(bPlusTreeOptions) /// <summary> /// 생성자 /// </summary> /// <param name="bPlusTreeOptions">B+ 트리 옵션</param> [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public BPlusTree(BPlusTreeOptions<TKey, TValue> bPlusTreeOptions) { bool fileExists = bPlusTreeOptions.StorageType == StorageType.Disk && bPlusTreeOptions.CreatePolicy != CreatePolicy.Always && File.Exists(bPlusTreeOptions.FilePath) && new FileInfo(bPlusTreeOptions.FilePath).Length > 0; this.options = bPlusTreeOptions.Clone(); this.lockStrategy = this.options.LockStrategy; this.keyComparer = this.options.KeyComparer; this.elementComparer = new ElementComparer(this.keyComparer); switch(this.options.CachePolicy) { case CachePolicy.All : this.nodeCacheBase = new FullNodeCache(this.options); break; case CachePolicy.Recent : this.nodeCacheBase = new NormalNodeCache(this.options); break; case CachePolicy.None : this.nodeCacheBase = new NoneNodeCache(this.options); break; default : throw new InvalidConfigurationValueException("CachePolicy"); } try { this.nodeCacheBase.Load(); } catch { this.nodeCacheBase.Dispose(); throw; } if(this.options.LogFile != null && !this.options.ReadOnly) { if(this.options.ExistingLogAction == ExistingLogAction.Truncate || this.options.ExistingLogAction == ExistingLogAction.Default && !fileExists) { this.options.LogFile.TruncateLog(); } else if ( this.options.LogFile.FileSize > 0 && ( this.options.ExistingLogAction == ExistingLogAction.Replay || this.options.ExistingLogAction == ExistingLogAction.ReplayAndCommit || (this.options.ExistingLogAction == ExistingLogAction.Default && fileExists) ) ) { bool commit = this.options.ExistingLogAction == ExistingLogAction.ReplayAndCommit || (this.options.ExistingLogAction == ExistingLogAction.Default && fileExists); bool merge = false; if(this.options.StorageType == StorageType.Disk) { merge = new FileInfo(this.options.FilePath).Length < this.options.LogFile.FileSize; } if(merge) { BulkInsertOptions bulkInsertOptions = new BulkInsertOptions(); bulkInsertOptions.CommitOnCompletion = commit; bulkInsertOptions.DuplicateHandling = DuplicateHandling.LastValueWins; bulkInsertOptions.IsInputSorted = true; bulkInsertOptions.ReplaceContents = true; BulkInsert ( this.options.LogFile.MergeLog ( this.options.KeyComparer, File.Exists(bPlusTreeOptions.FilePath) ? EnumerateFile(bPlusTreeOptions) : new KeyValuePair<TKey, TValue>[0] ), bulkInsertOptions ); } else { this.options.LogFile.ReplayLog(this); if(commit) { Commit(); } } } } INodeStorageWithCount nodeStoreWithCount = this.nodeCacheBase.NodeStorage as INodeStorageWithCount; if(nodeStoreWithCount != null) { this.count = nodeStoreWithCount.Count; this.hasCount = this.count >= 0; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 파일 열거하기 - EnumerateFile(options) /// <summary> /// 파일 열거하기 /// </summary> /// <param name="options">B+ 트리 옵션</param> /// <returns>열거 가능형</returns> public static IEnumerable<KeyValuePair<TKey, TValue>> EnumerateFile(BPlusTreeOptions<TKey, TValue> options) { options = options.Clone(); options.CreatePolicy = CreatePolicy.Never; options.ReadOnly = true; using(INodeStorage nodeStorage = options.CreateNodeStorage()) { bool isnew; Node root; IStorageHandle rootHandle = nodeStorage.OpenRoot(out isnew); if(isnew) { yield break; } NodeSerializer nodeSerializer = new NodeSerializer(options, new NodeHandleSerializer(nodeStorage)); if(isnew || !nodeStorage.TryGetNode(rootHandle, out root, nodeSerializer)) { throw new InvalidDataException(); } Stack<KeyValuePair<Node, int>> todoStack = new Stack<KeyValuePair<Node, int>>(); todoStack.Push(new KeyValuePair<Node, int>(root, 0)); while(todoStack.Count > 0) { KeyValuePair<Node, int> currentItem = todoStack.Pop(); if(currentItem.Value == currentItem.Key.Count) { continue; } todoStack.Push(new KeyValuePair<Node, int>(currentItem.Key, currentItem.Value + 1)); Node childNode; if(!nodeStorage.TryGetNode(currentItem.Key[currentItem.Value].ChildNode.StorageHandle, out childNode, nodeSerializer)) { throw new InvalidDataException(); } if(childNode.IsLeaf) { for(int i = 0; i < childNode.Count; i++) { yield return childNode[i].ToKeyValuePair(); } } else { todoStack.Push(new KeyValuePair<Node, int>(childNode, 0)); } } } } #endregion #region 파일 복구하기 - coverFile(options) /// <summary> /// 파일 복구하기 /// </summary> /// <param name="options">B+ 트리 옵션 V1</param> /// <returns>처리 결과</returns> /// <remarks> /// 새로 생성된 BPlusTree{TKey, TValue}에 최대한 많은 파일 콘텐츠를 복구한다. /// 작업이 0이 아닌 결과를 반환하면 성공한 것이며 파일이 복구된 데이터를 포함하는 새 데이터베이스로 교체된 것이다. /// 원본 파일은 그대로 유지되지만 '.deleted' 확장자로 이름이 변경되었다. /// 파일을 구문 분석하는 동안 예외가 발생하고 하나 이상의 레코드가 복구된 경우 '.recovered' 확장자가 추가된 동일한 이름의 파일에 저장된다. /// 이 복구된 파일은 일반 BPlusTree{TKey, TValue}로 열어 내용을 볼 수 있다. /// 복원하는 동안 단일 키가 여러 번 발견될 수 있으며 이 경우 처음 발견된 키가 사용된다. /// </remarks> public static int RecoverFile(OptionsV1 options) { int recoveredCount = 0; string filePath = options.FilePath; if(string.IsNullOrEmpty(filePath)) { throw new InvalidConfigurationValueException("FilePath", "The FilePath property was not specified."); } if(!File.Exists(filePath)) { throw new InvalidConfigurationValueException("FilePath", "The FilePath specified does not exist."); } if(options.StorageType != StorageType.Disk) { throw new InvalidConfigurationValueException("StorageType", "The storage type is not set to 'Disk'."); } int index = 0; string temporaryFilePath = filePath + ".recovered"; while(File.Exists(temporaryFilePath)) { temporaryFilePath = filePath + ".recovered" + index++; } try { BPlusTreeOptions<TKey, TValue> temporaryOptions = options.Clone(); temporaryOptions.CreatePolicy = CreatePolicy.Always; temporaryOptions.FilePath = temporaryFilePath; temporaryOptions.LockingFactory = new LockFactory<IgnoreLockingStrategy>(); using(BPlusTree<TKey, TValue> temporaryTree = new BPlusTree<TKey, TValue>(temporaryOptions)) { BulkInsertOptions bulkInsertOptions = new BulkInsertOptions(); bulkInsertOptions.DuplicateHandling = DuplicateHandling.LastValueWins; recoveredCount = temporaryTree.BulkInsert(RecoveryScan(options, FileShare.None), bulkInsertOptions); } } finally { if(recoveredCount == 0 && File.Exists(temporaryFilePath)) { File.Delete(temporaryFilePath); } } if(recoveredCount > 0) { index = 0; string backupFilePath = filePath + ".deleted"; while(File.Exists(backupFilePath)) { backupFilePath = filePath + ".deleted" + index++; } File.Move(filePath, backupFilePath); try { File.Move(temporaryFilePath, filePath); } catch { File.Move(backupFilePath, filePath); throw; } } return recoveredCount; } #endregion #region 스캔 복구하기 - RecoveryScan(options, fileShare) /// <summary> /// 스캔 복구하기 /// </summary> /// <param name="options">B+ 트리 옵션 V1</param> /// <param name="fileShare">파일 공유</param> /// <returns>열거 가능형</returns> /// <remarks> /// 파일에서 읽을 수 있었던 모든 키/값 쌍을 생성하기 위해 저장소 파일의 하위 수준 스캔을 수행한다. /// </remarks> public static IEnumerable<KeyValuePair<TKey, TValue>> RecoveryScan(OptionsV1 options, FileShare fileShare) { options = options.Clone(); options.CreatePolicy = CreatePolicy.Never; string filePath = options.FilePath; if(string.IsNullOrEmpty(filePath)) { throw new InvalidConfigurationValueException("FilePath", "The FilePath property was not specified."); } if(!File.Exists(filePath)) { throw new InvalidConfigurationValueException("FilePath", "The FilePath specified does not exist."); } if(options.StorageType != StorageType.Disk) { throw new InvalidConfigurationValueException("StorageType", "The storage type is not set to 'Disk'."); } using ( FragmentedFile fragmentedFile = new FragmentedFile ( filePath, options.FileBlockSize, 1, 1, FileAccess.Read, fileShare, FileOptions.None ) ) { NodeSerializer nodeSerializer = new NodeSerializer ( options, new NodeHandleSerializer(new BTreeFileStorage.HandleSerializer()) ); foreach(KeyValuePair<long, Stream> block in fragmentedFile.ForeachBlock(true, false, CheckInvalidDataException)) { List<KeyValuePair<TKey, TValue>> entryList = new List<KeyValuePair<TKey, TValue>>(); try { foreach(KeyValuePair<TKey, TValue> entry in nodeSerializer.RecoverLeaf(block.Value)) { entryList.Add(entry); } } catch { } foreach(KeyValuePair<TKey, TValue> entry in entryList) { yield return entry; } } } } #endregion //////////////////////////////////////////////////////////////////////////////// Private #region 체크하기 - Assert(condition) /// <summary> /// 체크하기 /// </summary> /// <param name="condition">조건</param> [DebuggerNonUserCode] private static void Assert(bool condition) { if(!condition) { throw new AssertionFailedException(); } } #endregion #region 체크하기 - Assert(condition, message) /// <summary> /// 체크하기 /// </summary> /// <param name="condition">조건</param> /// <param name="message">메시지</param> [DebuggerNonUserCode] private static void Assert(bool condition, string message) { if(!condition) { throw new AssertionFailedException(message); } } #endregion #region 무효 데이터 예외 여부 구하기 - CheckInvalidDataException(exception) /// <summary> /// 무효 데이터 예외 여부 구하기 /// </summary> /// <param name="exception">예외</param> /// <returns>무효 데이터 예외 여부</returns> private static bool CheckInvalidDataException(Exception exception) { return exception is InvalidDataException; } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Public #region 추가하기 - Add(key, value) /// <summary> /// 추가하기 /// </summary> /// <param name="key">키</param> /// <param name="value">값</param> public void Add(TKey key, TValue value) { InsertValue insertValue = new InsertValue(value, false); AddEntry(key, ref insertValue); } #endregion #region 추가하기 - ICollection<KeyValuePair<TKey,TValue>>.Add(keyValuePair) /// <summary> /// 추가하기 /// </summary> /// <param name="keyValuePair">키/값 쌍</param> void ICollection<KeyValuePair<TKey,TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair) { InsertValue insertValue = new InsertValue(keyValuePair.Value, false); AddEntry(keyValuePair.Key, ref insertValue); } #endregion #region 추가 시도하기 - TryAdd(key, value) /// <summary> /// 추가 시도하기 /// </summary> /// <param name="key">키</param> /// <param name="value">값</param> /// <returns></returns> public bool TryAdd(TKey key, TValue value) { FetchValue fetchValue = new FetchValue(value); return InsertResult.Inserted == AddEntry(key, ref fetchValue); } #endregion #region 추가 시도하기 - TryAdd(key, converter) /// <summary> /// 추가 시도하기 /// </summary> /// <param name="key">키</param> /// <param name="converter">변환자</param> /// <returns>처리 결과</returns> public bool TryAdd(TKey key, Converter<TKey, TValue> converter) { InsertionInfo insertionInfo = new InsertionInfo(converter, _ignoreKeyValueUpdate); return InsertResult.Inserted == AddEntry(key, ref insertionInfo); } #endregion #region 추가 또는 업데이트하기 - AddOrUpdate(key, value) /// <summary> /// 추가 또는 업데이트하기 /// </summary> /// <param name="key">키</param> /// <param name="value">값</param> [Obsolete("Just use this[key] = value instead.")] public void AddOrUpdate(TKey key, TValue value) { InsertValue insertValue = new InsertValue(value, true); AddEntry(key, ref insertValue); } #endregion #region 추가 또는 업데이트하기 - AddOrUpdate(key, addValue, keyValueUpdate) /// <summary> /// 추가 또는 업데이트하기 /// </summary> /// <param name="key">키</param> /// <param name="addValue">추가 값</param> /// <param name="keyValueUpdate">키/값 업데이트 대리자</param> /// <returns>값</returns> public TValue AddOrUpdate(TKey key, TValue addValue, KeyValueUpdate<TKey, TValue> keyValueUpdate) { InsertionInfo insertionInfo = new InsertionInfo(addValue, keyValueUpdate); AddEntry(key, ref insertionInfo); return insertionInfo.Value; } #endregion #region 추가 또는 업데이트하기 - AddOrUpdate(key, converter, keyValueUpdate) /// <summary> /// 추가 또는 업데이트하기 /// </summary> /// <param name="key">키</param> /// <param name="converter">변환자</param> /// <param name="keyValueUpdate">키/값 업데이트 대리자</param> /// <returns>값</returns> public TValue AddOrUpdate(TKey key, Converter<TKey, TValue> converter, KeyValueUpdate<TKey, TValue> keyValueUpdate) { InsertionInfo insertionInfo = new InsertionInfo(converter, keyValueUpdate); AddEntry(key, ref insertionInfo); return insertionInfo.Value; } #endregion #region 추가 또는 업데이트하기 - AddOrUpdate<T>(key, addOrUpdateValue) /// <summary> /// 추가 또는 업데이트하기 /// </summary> /// <typeparam name="T">타입</typeparam> /// <param name="key">키</param> /// <param name="addOrUpdateValue">추가 또는 업데이트 값</param> /// <returns>처리 결과</returns> public bool AddOrUpdate<T>(TKey key, ref T addOrUpdateValue) where T : ICreateOrUpdateValue<TKey, TValue> { InsertResult insertResult = AddEntry(key, ref addOrUpdateValue); return insertResult == InsertResult.Inserted || insertResult == InsertResult.Updated; } #endregion #region 구하기 또는 추가하기 - GetOrAdd(key, value) /// <summary> /// 구하기 또는 추가하기 /// </summary> /// <param name="key">키</param> /// <param name="value">값</param> /// <returns>값</returns> public TValue GetOrAdd(TKey key, TValue value) { FetchValue fetchValue = new FetchValue(value); AddEntry(key, ref fetchValue); return fetchValue.Value; } #endregion #region 구하기 또는 추가하기 - GetOrAdd(key, converter) /// <summary> /// 구하기 또는 추가하기 /// </summary> /// <param name="key">키</param> /// <param name="converter">변환자</param> /// <returns>값</returns> public TValue GetOrAdd(TKey key, Converter<TKey, TValue> converter) { InsertionInfo insertionInfo = new InsertionInfo(converter, _ignoreKeyValueUpdate); AddEntry(key, ref insertionInfo); return insertionInfo.Value; } #endregion #region 범위 추가하기 - AddRange(sourceEnumerable, allowUpdates) /// <summary> /// 범위 추가하기 /// </summary> /// <param name="sourceEnumerable">소스 열거 가능형</param> /// <param name="allowUpdates">업데이트 허용 여부</param> /// <returns>추가 건수</returns> public int AddRange(IEnumerable<KeyValuePair<TKey, TValue>> sourceEnumerable, bool allowUpdates) { int totalCount = 0; int count = 0; KeyValuePair<TKey, TValue>[] keyValuePairArray = new KeyValuePair<TKey, TValue>[2048]; KeyValueComparer<TKey, TValue> keyValueComparer = new KeyValueComparer<TKey, TValue>(this.keyComparer); foreach(KeyValuePair<TKey, TValue> keyValuePair in sourceEnumerable) { if(count == 0x010000) { MergeSort.Sort(keyValuePairArray, keyValueComparer); totalCount += AddRangeSorted(keyValuePairArray, allowUpdates); Array.Clear(keyValuePairArray, 0, keyValuePairArray.Length); count = 0; } if(count == keyValuePairArray.Length) Array.Resize(ref keyValuePairArray, keyValuePairArray.Length * 2); keyValuePairArray[count++] = keyValuePair; } if(count > 0) { if(count != keyValuePairArray.Length) { Array.Resize(ref keyValuePairArray, count); } MergeSort.Sort(keyValuePairArray, keyValueComparer); totalCount += AddRangeSorted(keyValuePairArray, allowUpdates); } return totalCount; } #endregion #region 범위 추가하기 - AddRange(sourceEnumerable) /// <summary> /// 범위 추가하기 /// </summary> /// <param name="sourceEnumerable">소스 열거 가능형</param> public void AddRange(IEnumerable<KeyValuePair<TKey, TValue>> sourceEnumerable) { AddRange(sourceEnumerable, false); } #endregion #region 정렬 범위 추가하기 - AddRangeSorted(sourceEnumerable, allowUpdates) /// <summary> /// 정렬 범위 추가하기 /// </summary> /// <param name="sourceEnumerable">소스 열거 가능형</param> /// <param name="allowUpdates">업데이트 허용 여부</param> /// <returns>추가 건수</returns> public int AddRangeSorted(IEnumerable<KeyValuePair<TKey, TValue>> sourceEnumerable, bool allowUpdates) { int count = 0; using(AddRangeInfo addRangeInfo = new AddRangeInfo(allowUpdates, sourceEnumerable)) { while(!addRangeInfo.IsCompleted) { KeyRange keyRange = new KeyRange(this.keyComparer); using(RootLock rootLock = GetLockRoot(LockType.Insert, "BulkInsert")) { count += AddRange(rootLock.Pin, ref keyRange, addRangeInfo, null, int.MinValue); } } } WriteDebugMessage("AddRange({0} records)", count); return count; } #endregion #region 정렬 범위 추가하기 - AddRangeSorted(sourceEnumerable) /// <summary> /// 정렬 범위 추가하기 /// </summary> /// <remarks> /// 사전 정렬된 키/값 쌍의 최적화된 삽입이다. /// 입력이 미리 정렬되지 않은 경우 대신 AddRange()를 사용한다. /// </remarks> public int AddRangeSorted(IEnumerable<KeyValuePair<TKey, TValue>> sourceEnumerable) { return AddRangeSorted(sourceEnumerable, false); } #endregion #region 업데이트 시도하기 - TryUpdate(key, value) /// <summary> /// 업데이트 시도하기 /// </summary> /// <param name="key">키</param> /// <param name="value">값</param> /// <returns>처리 결과</returns> public bool TryUpdate(TKey key, TValue value) { UpdateInfo updateInfo = new UpdateInfo(value); bool result; using(RootLock rootLock = GetLockRoot(LockType.Update, "Update")) { result = Update(rootLock.Pin, key, ref updateInfo); } WriteDebugMessage("Updated({0}) = {1}", key, result); return updateInfo.Updated; } #endregion #region 업데이트 시도하기 - TryUpdate(key, value, comparisonValue) /// <summary> /// 업데이트 시도하기 /// </summary> /// <param name="key">키</param> /// <param name="value">값</param> /// <param name="comparisonValue">비교 값</param> /// <returns>처리 결과</returns> public bool TryUpdate(TKey key, TValue value, TValue comparisonValue) { UpdateIfValue updageIfValue = new UpdateIfValue(value, comparisonValue); bool result; using(RootLock rootLock = GetLockRoot(LockType.Update, "Update")) { result = Update(rootLock.Pin, key, ref updageIfValue); } WriteDebugMessage("Updated({0}) = {1}", key, result); return updageIfValue.Updated; } #endregion #region 업데이트 시도하기 - TryUpdate(key, keyValueUpdate) /// <summary> /// 업데이트 시도하기 /// </summary> /// <param name="key">키</param> /// <param name="keyValueUpdate">키/값 업데이트</param> /// <returns>처리 결과</returns> public bool TryUpdate(TKey key, KeyValueUpdate<TKey, TValue> keyValueUpdate) { UpdateInfo updateInfo = new UpdateInfo(keyValueUpdate); bool result; using(RootLock rootLock = GetLockRoot(LockType.Update, "Update")) { result = Update(rootLock.Pin, key, ref updateInfo); } WriteDebugMessage("Updated({0}) = {1}", key, result); return updateInfo.Updated; } #endregion #region 제거하기 - Remove(key) /// <summary> /// 제거하기 /// </summary> /// <param name="key">키</param> /// <returns>처리 결과</returns> public bool Remove(TKey key) { RemoveAlways removeAlways = new RemoveAlways(); return RemoveEntry(key, ref removeAlways) == RemoveResult.Removed; } #endregion #region 제거하기 - ICollection<KeyValuePair<TKey, TValue>>.Remove(item) /// <summary> /// 제거하기 /// </summary> /// <param name="item">항목</param> /// <returns>처리 결과</returns> bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) { RemoveIfValue removeIfValue = new RemoveIfValue(item.Key, item.Value); return RemoveEntry(item.Key, ref removeIfValue) == RemoveResult.Removed; } #endregion #region 제거 시도하기 - TryRemove(key, value) /// <summary> /// 제거 시도하기 /// </summary> /// <param name="key">키</param> /// <param name="value">값</param> /// <returns>처리 결과</returns> public bool TryRemove(TKey key, out TValue value) { RemoveAlways removeAlways = new RemoveAlways(); if(RemoveEntry(key, ref removeAlways) == RemoveResult.Removed && removeAlways.TryGetValue(out value)) { return true; } value = default(TValue); return false; } #endregion #region 제거 시도하기 - TryRemove<T>(key, removeValue) /// <summary> /// 제거 시도하기 /// </summary> /// <typeparam name="T">제거 값 타입</typeparam> /// <param name="key">키</param> /// <param name="removeValue">제거 값</param> /// <returns>처리 결과</returns> public bool TryRemove<T>(TKey key, ref T removeValue) where T : IRemoveValue<TKey, TValue> { return RemoveEntry(key, ref removeValue) == RemoveResult.Removed; } #endregion #region 제거 시도하기 - TryRemove(key, keyValuePredicate) /// <summary> /// 제거 시도하기 /// </summary> /// <param name="key">키</param> /// <param name="keyValuePredicate">키/값 서술자</param> /// <returns>처리 결과</returns> public bool TryRemove(TKey key, KeyValuePredicate<TKey, TValue> keyValuePredicate) { RemoveIfPredicate removeIfPredicate = new RemoveIfPredicate(keyValuePredicate); return RemoveEntry(key, ref removeIfPredicate) == RemoveResult.Removed; } #endregion #region 값 구하기 시도하기 - TryGetValue(key, value) /// <summary> /// 값 구하기 시도하기 /// </summary> /// <param name="key">키</param> /// <param name="value">값</param> public bool TryGetValue(TKey key, out TValue value) { bool result; value = default(TValue); using(RootLock root = GetLockRoot(LockType.Read, "TryGetValue")) { result = Search(root.Pin, key, ref value); } WriteDebugMessage("Found({0}) = {1}", key, result); return result; } #endregion #region 포함 여부 구하기 - ContainsKey(key) /// <summary> /// 포함 여부 구하기 /// </summary> /// <param name="key">키</param> /// <returns>포함 여부</returns> public bool ContainsKey(TKey key) { TValue value; return TryGetValue(key, out value); } #endregion #region 포함 여부 구하기 - ICollection<KeyValuePair<TKey, TValue>>.Contains(item) /// <summary> /// 포함 여부 구하기 /// </summary> /// <param name="item">항목</param> /// <returns>포함 여부</returns> bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item) { return ContainsKey(item.Key); } #endregion #region 첫번째 항목 구하기 - GetFirstItem() /// <summary> /// 첫번째 항목 구하기 /// </summary> /// <returns>첫번째 항목</returns> public KeyValuePair<TKey, TValue> GetFirstItem() { KeyValuePair<TKey, TValue> item; if(!TryGetFirstItem(out item)) { throw new InvalidOperationException(); } return item; } #endregion #region 첫번째 항목 구하기 시도하기 - TryGetFirstItem(item) /// <summary> /// 첫번째 항목 구하기 시도하기 /// </summary> /// <param name="item">항목</param> /// <returns>처리 결과</returns> public bool TryGetFirstItem(out KeyValuePair<TKey, TValue> item) { using(RootLock rootLock = GetLockRoot(LockType.Read, "TryGetFirst")) { return TryGetEdge(rootLock.Pin, true, out item); } } #endregion #region 마지막 항목 구하기 - GetLastItem() /// <summary> /// 마지막 항목 구하기 /// </summary> /// <returns>마지막 항목</returns> public KeyValuePair<TKey, TValue> GetLastItem() { KeyValuePair<TKey, TValue> item; if(!TryGetLastItem(out item)) { throw new InvalidOperationException(); } return item; } #endregion #region 마지막 항목 구하기 시도하기 - TryGetLastItem(item) /// <summary> /// 마지막 항목 구하기 시도하기 /// </summary> /// <param name="item">항목</param> /// <returns>처리 결과</returns> public bool TryGetLastItem(out KeyValuePair<TKey, TValue> item) { using(RootLock rootLock = GetLockRoot(LockType.Read, "TryGetLast")) { return TryGetEdge(rootLock.Pin, false, out item); } } #endregion #region 지우기 - Clear() /// <summary> /// 지우기 /// </summary> public void Clear() { CheckNotDisposed(); using(this.lockStrategy.Write(LockTimeout)) { this.nodeCacheBase.DeleteAll(); this.count = 0; CommitChanges(false); } WriteDebugMessage("Clear()"); } #endregion #region 커밋하기 - Commit() /// <summary> /// 커밋하기 /// </summary> /// <remarks> /// TransactionLog를 사용할 때 이 메소드는 현재 인스턴스의 변경 사항을 출력 파일에 커밋하고 로그를 자른다. /// 다른 모든 경우에 메소드는 작동하지 않으며 예외가 발생하지 않는다. /// CallLevelLock 속성이 유효한 판독기/작성기 잠금으로 설정되어 있지 않으면 이 메소드는 스레드로부터 안전하지 않다. /// 작성자가 현재 트리에 액세스하는 동안 이 메서드를 호출해야 하는 경우 CallLevelLock 옵션이 지정되었는지 확인한다. /// </remarks> public void Commit() { CommitChanges(true); } #endregion #region 롤백하기 - Rollback() /// <summary> /// 롤백하기 /// </summary> /// <remarks> /// 버전 2 스토리지를 사용하면 파일이 처음 열렸을 때의 초기 상태 또는 커밋을 위한 마지막 호출로 캡처된 상태로 트리 내용을 되돌릴 것이다. /// 모든 트랜잭션 로그 데이터는 잘린다. /// </remarks> public void Rollback() { CheckNotDisposed(); using(this.lockStrategy.Write(LockTimeout)) { if(this.nodeCacheBase.NodeStorage is ITransactable) { ((ITransactable)this.nodeCacheBase.NodeStorage).Rollback(); } else { throw new InvalidOperationException(); } if(this.options.LogFile != null) { this.options.LogFile.TruncateLog(); } this.nodeCacheBase.ResetCache(); if(this.hasCount) { this.hasCount = false; EnableCount(); } } } #endregion #region 복사하기 - CopyTo(targetArray, targetIndex) /// <summary> /// 복사하기 /// </summary> /// <param name="targetArray">타겟 배열</param> /// <param name="targetIndex">타겟 인덱스</param> public void CopyTo(KeyValuePair<TKey, TValue>[] targetArray, int targetIndex) { foreach(KeyValuePair<TKey, TValue> keyValuePair in this) { targetArray[targetIndex++] = keyValuePair; } } #endregion #region 카운트 활성화하기 - EnableCount() /// <summary> /// 카운트 활성화하기 /// </summary> /// <remarks> /// 유지 비용으로 인해 EnableCount() 호출을 통해 개체가 생성될 때마다 활성화해야 하며 이 작업은 작성기 스레드가 활성화되기 전에 수행되어야 정확하다. /// 이것은 초기 작업 카운트를 구축하기 위해 전체 트리를 (순차적으로) 로드해야 한다. /// 완료되면 Add() 및 Remove()와 같은 멤버는 초기 개수를 정확하게 유지한다. /// </remarks> public void EnableCount() { if(this.hasCount) { return; } this.count = 0; using(RootLock rootLock = GetLockRoot(LockType.Read, "EnableCount", true)) { this.count = CountValues(rootLock.Pin); } this.hasCount = true; } #endregion #region 캐시 언로드하기 - UnloadCache() /// <summary> /// 캐시 언로드하기 /// </summary> /// <remarks> /// 메모리 내 캐시에서 모든 항목을 안전하게 제거한다. /// </remarks> public void UnloadCache() { CheckNotDisposed(); using(this.lockStrategy.Write(LockTimeout)) { this.nodeCacheBase.ResetCache(); } } #endregion #region 벌크 삽입하기 - BulkInsert(sourceEnumerable, options) /// <summary> /// 벌크 삽입하기 /// </summary> /// <param name="sourceEnumerable">소스 열거 가능형</param> /// <param name="options">옵션</param> /// <returns>처리 건수</returns> /// <remarks> /// 제공된 항목을 포함하도록 전체 BTree를 트랜잭션으로 다시 작성한다. /// 이 메서드는 스레드로부터 안전하다. /// 입력이 이미 정렬된 경우 BulkInsertOptions 오버로드를 사용하여 InputIsSorted = true를 지정한다. /// </remarks> public int BulkInsert(IEnumerable<KeyValuePair<TKey, TValue>> sourceEnumerable, BulkInsertOptions options) { NodePin previousRootNodePin = null; if(options.IsInputSorted == false) { KeyValueSerializer<TKey, TValue> keyValueSerializer = new KeyValueSerializer<TKey, TValue> ( this.options.KeySerializer, this.options.ValueSerializer ); sourceEnumerable = new OrderedKeyValuePairs<TKey, TValue>(this.options.KeyComparer, sourceEnumerable, keyValueSerializer) { DuplicateHandling = options.DuplicateHandling }; } List<IStorageHandle> storageHandleList = new List<IStorageHandle>(); try { int counter = 0; using(RootLock rootLock = GetLockRoot(LockType.Insert, "Merge", false)) { if(rootLock.Pin.CurrentNode.Count != 1) { throw new InvalidDataException(); } NodeHandle previousRootNodeHandle = rootLock.Pin.CurrentNode[0].ChildNode; previousRootNodePin = this.nodeCacheBase.Lock(rootLock.Pin, previousRootNodeHandle); if(previousRootNodePin.CurrentNode.Count == 0 || options.ReplaceContents) { sourceEnumerable = OrderedKeyValuePairs<TKey, TValue>.GetDuplicateKeyHandlingEnumerable ( sourceEnumerable, new KeyValueComparer<TKey, TValue>(this.options.KeyComparer), options.DuplicateHandling ); } else { sourceEnumerable = OrderedKeyValuePairs<TKey, TValue>.Merge ( this.options.KeyComparer, options.DuplicateHandling, EnumerateNodeContents(previousRootNodePin), sourceEnumerable ); } Node newTreeNode = BulkWrite(storageHandleList, ref counter, sourceEnumerable); if(newTreeNode == null) { return 0; } using(NodeTransaction transaction = this.nodeCacheBase.BeginTransaction()) { Node rootNode = transaction.BeginUpdate(rootLock.Pin); rootNode.ReplaceChild(0, previousRootNodeHandle, new NodeHandle(newTreeNode.StorageHandle)); transaction.Commit(); } this.count = counter; } storageHandleList.Clear(); DeleteTree(previousRootNodePin); previousRootNodePin = null; if(options.CommitOnCompletion) { Commit(); } return counter; } catch { if(previousRootNodePin != null) { previousRootNodePin.Dispose(); } foreach(IStorageHandle storageHandle in storageHandleList) { try { this.nodeCacheBase.NodeStorage.Destroy(storageHandle); } catch(ThreadAbortException) { throw; } catch { continue; } } throw; } } #endregion #region 벌크 삽입하기 - BulkInsert(sourceEnumerable) /// <summary> /// 벌크 삽입하기 /// </summary> /// <param name="sourceEnumerable">소스 열거 가능형</param> /// <returns>처리 건수</returns> public int BulkInsert(IEnumerable<KeyValuePair<TKey, TValue>> sourceEnumerable) { return BulkInsert(sourceEnumerable, new BulkInsertOptions()); } #endregion #region 리소스 해제하기 - Dispose() /// <summary> /// 리소스 해제하기 /// </summary> public void Dispose() { if(this.disposed) { return; } try { bool locked = false; try { if(!IsReadOnly) { locked = this.lockStrategy.TryWrite(Math.Max(1000, LockTimeout)); if(locked) { CommitChanges(false); } } this.nodeCacheBase.Dispose(); } finally { if(locked) { this.lockStrategy.ReleaseWrite(); } if(this.options.LogFile != null) { this.options.LogFile.Dispose(); } } } finally { this.disposed = true; } } #endregion #region 디버그 텍스트 라이터 설정하기 - SetDebugTextWriter(textWriter) /// <summary> /// 디버그 텍스트 라이터 설정하기 /// </summary> /// <param name="textWriter">텍스트 라이터</param> [Conditional("DEBUG")] public void SetDebugTextWriter(TextWriter textWriter) { this.debugTextWriter = textWriter; } #endregion #region 무결성 여부 설정하기 - SetValidated(validated) /// <summary> /// 무결성 여부 설정하기 /// </summary> /// <param name="validated">무결성 여부</param> [Conditional("DEBUG")] public void SetValidated(bool validated) { this.validated = validated; } #endregion #region 인쇄하기 - Print(textWriter, debugFormat) /// <summary> /// 인쇄하기 /// </summary> /// <param name="textWriter">텍스트 라이터</param> /// <param name="debugFormat">디버그 포맷</param> /// <remarks> /// 전체 트리를 텍스트 작성기에 인쇄한다. /// </remarks> [Conditional("DEBUG")] public void Print(TextWriter textWriter, DebugFormat debugFormat) { using(RootLock rootLock = GetLockRoot(LockType.Read, "Print", true)) { Print(rootLock.Pin, textWriter, 0, debugFormat); } } #endregion #region 무결성 검증하기 - Validate() /// <summary> /// 무결성 검증하기 /// </summary> /// <remarks> /// 모든 노드와 모든 링크 또는 키의 정확성을 검사하는 전체 트리의 하향식, 깊이 우선, 크롤링을 강제 실행한다. /// 오류가 발생하면 던진다. /// </remarks> [Conditional("DEBUG")] public void Validate() { #if DEBUG using(RootLock rootLock = GetLockRoot(LockType.Read, "Validate", true)) { Validate(rootLock.Pin, null, int.MinValue, int.MaxValue); } #endif } #endregion //////////////////////////////////////////////////////////////////////////////// Private #region 열거자 구하기 - GetEnumerator() /// <summary> /// 열거자 구하기 /// </summary> /// <returns>열거자</returns> public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return new Enumerator(this); } #endregion #region 열거자 구하기 - IEnumerable.GetEnumerator() /// <summary> /// 열거자 구하기 /// </summary> /// <returns>열거자</returns> [Obsolete] System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion #region 엔트리 추가하기 - AddEntry<T>(key, info) /// <summary> /// 엔트리 추가하기 /// </summary> /// <typeparam name="T">정보 타입</typeparam> /// <param name="key">키</param> /// <param name="info">정보</param> /// <returns>삽입 결과</returns> private InsertResult AddEntry<T>(TKey key, ref T info) where T : ICreateOrUpdateValue<TKey, TValue> { InsertResult insertResult; using(RootLock rootLock = GetLockRoot(LockType.Insert, "AddOrUpdate")) { insertResult = Insert(rootLock.Pin, key, ref info, null, int.MinValue); } if(insertResult == InsertResult.Inserted && this.hasCount) { Interlocked.Increment(ref this.count); } WriteDebugMessage("Added({0}) = {1}", key, insertResult); return insertResult; } #endregion #region 엔트리 제거하기 - RemoveEntry<T>(key, removeValue) /// <summary> /// 엔트리 제거하기 /// </summary> /// <typeparam name="T">제거 값 타입</typeparam> /// <param name="key">키</param> /// <param name="removeValue">제거 값</param> /// <returns>제거 결과</returns> private RemoveResult RemoveEntry<T>(TKey key, ref T removeValue) where T : IRemoveValue<TKey, TValue> { RemoveResult removeResult; using(RootLock rootLock = GetLockRoot(LockType.Delete, "Remove")) { removeResult = Delete(rootLock.Pin, key, ref removeValue, null, int.MinValue); } if(removeResult == RemoveResult.Removed && this.hasCount) { Interlocked.Decrement(ref this.count); } WriteDebugMessage("Removed({0}) = {1}", key, removeResult); return removeResult; } #endregion #region 범위 추가하기 - AddRange(lockNodePin, keyRange, value, parentNodePin, parentIndex) /// <summary> /// 범위 추가하기 /// </summary> /// <param name="lockNodePin">잠금 노드 핀</param> /// <param name="keyRange">키 범위</param> /// <param name="value">값</param> /// <param name="parentNodePin">부모 노드 핀</param> /// <param name="parentIndex">부모 인덱스</param> /// <returns>처리 결과</returns> private int AddRange(NodePin lockNodePin, ref KeyRange keyRange, AddRangeInfo value, NodePin parentNodePin, int parentIndex) { int counter = 0; Node currentNode = lockNodePin.CurrentNode; if(currentNode.Count == currentNode.Size && parentNodePin != null) { using(NodeTransaction transaction = this.nodeCacheBase.BeginTransaction()) { TKey splitKey; if(parentNodePin.CurrentNode.IsRoot) { Node rootNode = transaction.BeginUpdate(parentNodePin); using(NodePin newRoot = transaction.Create(parentNodePin, false)) { rootNode.ReplaceChild(0, lockNodePin.NodeHandle, newRoot.NodeHandle); newRoot.CurrentNode.Insert(0, new Element(default(TKey), lockNodePin.NodeHandle)); using(NodePin nextNodePin = Split(transaction, ref lockNodePin, newRoot, 0, out splitKey, true)) { using(lockNodePin) { transaction.Commit(); GC.KeepAlive(lockNodePin); GC.KeepAlive(nextNodePin); } } return AddRange(newRoot, ref keyRange, value, parentNodePin, parentIndex); } } transaction.BeginUpdate(parentNodePin); using(NodePin next = Split(transaction, ref lockNodePin, parentNodePin, parentIndex, out splitKey, true)) { using(lockNodePin) { transaction.Commit(); if(this.keyComparer.Compare(value.Current.Key, splitKey) >= 0) { lockNodePin.Dispose(); keyRange.SetMinimumKey(splitKey); return AddRange(next, ref keyRange, value, parentNodePin, parentIndex + 1); } next.Dispose(); keyRange.SetMaximumKey(splitKey); return AddRange(lockNodePin, ref keyRange, value, parentNodePin, parentIndex); } } } } if(parentNodePin != null) { parentNodePin.Dispose(); } if(currentNode.IsLeaf) { using(NodeTransaction transaction = this.nodeCacheBase.BeginTransaction()) { currentNode = transaction.BeginUpdate(lockNodePin); int inserted = 0; while(currentNode.Count < currentNode.Size && !value.IsCompleted && keyRange.IsKeyInRange(value.Current.Key)) { int index; bool exists = currentNode.BinarySearch(this.elementComparer, new Element(value.Current.Key), out index); DuplicateKeyException.Assert(!exists || value.AllowUpdate); if(exists) { currentNode.SetValue(index, value.Current.Key, value.Current.Value, this.keyComparer); transaction.UpdateValue(value.Current.Key, value.Current.Value); } else { currentNode.Insert(index, new Element(value.Current.Key, value.Current.Value)); transaction.AddValue(value.Current.Key, value.Current.Value); inserted++; } counter++; value.MoveNext(); } transaction.Commit(); if(this.hasCount && inserted > 0) { int count = this.count, test; while(count != (test = Interlocked.CompareExchange(ref this.count, count + inserted, count))) { count = test; } } } } else { int index; currentNode.BinarySearch(this.elementComparer, new Element(value.Current.Key), out index); if(index >= currentNode.Count) { index = currentNode.Count - 1; } if(index > 0) { keyRange.SetMinimumKey(currentNode[index - 1].Key); } if(index < (currentNode.Count - 1)) { keyRange.SetMaximumKey(currentNode[index + 1].Key); } using(NodePin childNodePin = this.nodeCacheBase.Lock(lockNodePin, currentNode[index].ChildNode)) { counter += AddRange(childNodePin, ref keyRange, value, lockNodePin, index); } } return counter; } #endregion #region 벌크 쓰기 - BulkWrite(storageHandleCollection, counter, itemEnumerable) /// <summary> /// 벌크 쓰기 /// </summary> /// <param name="storageHandleCollection">저장소 핸들 컬렉션</param> /// <param name="counter">카운터</param> /// <param name="itemEnumerable">항목 열거 가능형</param> /// <returns>노드</returns> private Node BulkWrite ( ICollection<IStorageHandle> storageHandleCollection, ref int counter, IEnumerable<KeyValuePair<TKey, TValue>> itemEnumerable ) { List<Node> workingNodeList = new List<Node>(); Node leafNode = null; using(IEnumerator<KeyValuePair<TKey, TValue>> itemEnumerator = itemEnumerable.GetEnumerator()) { bool hasMoreItem = itemEnumerator.MoveNext(); while(hasMoreItem) { NodeHandle nodeHandle = new NodeHandle(this.nodeCacheBase.NodeStorage.Create()); storageHandleCollection.Add(nodeHandle.StorageHandle); leafNode = new Node(nodeHandle.StorageHandle, this.options.MaximumValueNodeCount); while(leafNode.Count < leafNode.Size && hasMoreItem) { leafNode.Insert(leafNode.Count, new Element(itemEnumerator.Current.Key, itemEnumerator.Current.Value)); counter++; hasMoreItem = itemEnumerator.MoveNext(); } this.nodeCacheBase.NodeStorage.Update(nodeHandle.StorageHandle, this.nodeCacheBase.NodeSerializer, leafNode); leafNode.ToReadOnly(); if(!hasMoreItem && workingNodeList.Count == 0) { return leafNode; } InsertWorkingNode(storageHandleCollection, workingNodeList, workingNodeList.Count - 1, new Element(leafNode[0].Key, nodeHandle)); } } if(leafNode == null) { return null; } if(leafNode.Count < this.options.MinimumValueNodeCount) { workingNodeList.Add(leafNode.CloneForWrite(LockType.Insert)); } for(int i = 1; i < workingNodeList.Count; i++) { Node workingNode = workingNodeList[i]; bool isleaf = workingNode.IsLeaf; int minimumLimit = isleaf ? this.options.MinimumValueNodeCount : this.options.MinimumChildNodeCount; if(workingNode.Count < minimumLimit) { Node parentNode = workingNodeList[i - 1]; int previousIndex = parentNode.Count - 2; Node previousNode; bool success = this.nodeCacheBase.NodeStorage.TryGetNode ( parentNode[previousIndex].ChildNode.StorageHandle, out previousNode, this.nodeCacheBase.NodeSerializer ); AssertionFailedException.Assert(success); previousNode = previousNode.CloneForWrite(LockType.Insert); if(!isleaf) { workingNode.ReplaceKey(0, parentNode[parentNode.Count - 1].Key); } while(workingNode.Count < minimumLimit) { Element element = previousNode[previousNode.Count - 1]; if(workingNode.Count + 1 == minimumLimit) { if(isleaf) { workingNode.Insert(0, element); } else { workingNode.Insert(0, new Element(default(TKey), element.ChildNode)); } parentNode.ReplaceKey(parentNode.Count - 1, element.Key); } else { workingNode.Insert(0, element); } previousNode.Remove(previousNode.Count - 1, element, this.keyComparer); } this.nodeCacheBase.NodeStorage.Update ( previousNode.StorageHandle, this.nodeCacheBase.NodeSerializer, previousNode ); previousNode.ToReadOnly(); } } for(int i = workingNodeList.Count - 1; i >= 0; i--) { this.nodeCacheBase.NodeStorage.Update ( workingNodeList[i].StorageHandle, this.nodeCacheBase.NodeSerializer, workingNodeList[i] ); workingNodeList[i].ToReadOnly(); } return workingNodeList[0]; } #endregion #region 작업 노드 삽입하기 - InsertWorkingNode(storageHandleCollection, workingNodeList, index, childElement) /// <summary> /// 작업 노드 삽입하기 /// </summary> /// <param name="storageHandleCollection">저장소 핸들 컬렉션</param> /// <param name="workingNodeList">작업 노드 리스트</param> /// <param name="index">인덱스</param> /// <param name="childElement">자식 엘리먼트</param> private void InsertWorkingNode ( ICollection<IStorageHandle> storageHandleCollection, List<Node> workingNodeList, int index, Element childElement ) { if(index < 0) { workingNodeList.Insert ( 0, new Node(this.nodeCacheBase.NodeStorage.Create(), this.options.MaximumChildNodeCount) ); storageHandleCollection.Add(workingNodeList[0].StorageHandle); if(workingNodeList.Count > 1) { workingNodeList[0].Insert ( 0, new Element ( default(TKey), new NodeHandle(workingNodeList[1].StorageHandle) ) ); } index++; } Node parentNode = workingNodeList[index]; if(parentNode.Count == parentNode.Size) { this.nodeCacheBase.NodeStorage.Update ( parentNode.StorageHandle, this.nodeCacheBase.NodeSerializer, parentNode ); parentNode.ToReadOnly(); parentNode = new Node ( this.nodeCacheBase.NodeStorage.Create(), this.options.MaximumChildNodeCount ); storageHandleCollection.Add(parentNode.StorageHandle); int count = workingNodeList.Count; InsertWorkingNode ( storageHandleCollection, workingNodeList, index - 1, new Element(childElement.Key, new NodeHandle(parentNode.StorageHandle)) ); if(count < workingNodeList.Count) { index++; } workingNodeList[index] = parentNode; } if(parentNode.Count == 0) { parentNode.Insert(parentNode.Count, new Element(default(TKey), childElement.ChildNode)); } else { parentNode.Insert(parentNode.Count, childElement); } } #endregion #region 삽입하기 - Insert<T>(lockNodePin, key, value, parentNodePin, parentIndex) /// <summary> /// 삽입하기 /// </summary> /// <typeparam name="T">타입</typeparam> /// <param name="lockNodePin">잠금 노드 핀</param> /// <param name="key">키</param> /// <param name="value">값</param> /// <param name="parentNodePin">부모 노드 핀</param> /// <param name="parentIndex">부모 인덱스</param> /// <returns>삽입 결과</returns> private InsertResult Insert<T> ( NodePin lockNodePin, TKey key, ref T value, NodePin parentNodePin, int parentIndex ) where T : ICreateOrUpdateValue<TKey, TValue> { Node currentNode = lockNodePin.CurrentNode; if(currentNode.Count == currentNode.Size && parentNodePin != null) { using(NodeTransaction transaction = this.nodeCacheBase.BeginTransaction()) { TKey splitKey; if(parentNodePin.CurrentNode.IsRoot) { Node rootNode = transaction.BeginUpdate(parentNodePin); using(NodePin newRootNodePin = transaction.Create(parentNodePin, false)) { rootNode.ReplaceChild(0, lockNodePin.NodeHandle, newRootNodePin.NodeHandle); newRootNodePin.CurrentNode.Insert(0, new Element(default(TKey), lockNodePin.NodeHandle)); using(NodePin nextNodePin = Split(transaction, ref lockNodePin, newRootNodePin, 0, out splitKey, false)) { using(lockNodePin) { transaction.Commit(); GC.KeepAlive(lockNodePin); GC.KeepAlive(nextNodePin); } } return Insert(newRootNodePin, key, ref value, parentNodePin, parentIndex); } } transaction.BeginUpdate(parentNodePin); using(NodePin nextNodePin = Split(transaction, ref lockNodePin, parentNodePin, parentIndex, out splitKey, false)) { using(lockNodePin) { transaction.Commit(); if(this.keyComparer.Compare(key, splitKey) >= 0) { lockNodePin.Dispose(); return Insert(nextNodePin, key, ref value, parentNodePin, parentIndex + 1); } nextNodePin.Dispose(); return Insert(lockNodePin, key, ref value, parentNodePin, parentIndex); } } } } if(parentNodePin != null) { parentNodePin.Dispose(); } int index; if(currentNode.BinarySearch(this.elementComparer, new Element(key), out index) && currentNode.IsLeaf) { TValue updatedValue = currentNode[index].Payload; if(value.UpdateValue(key, ref updatedValue)) { using(NodeTransaction transaction = this.nodeCacheBase.BeginTransaction()) { currentNode = transaction.BeginUpdate(lockNodePin); currentNode.SetValue(index, key, updatedValue, this.keyComparer); transaction.UpdateValue(key, updatedValue); transaction.Commit(); return InsertResult.Updated; } } return InsertResult.Exists; } if(currentNode.IsLeaf) { TValue newValue; if(value.CreateValue(key, out newValue)) { using(NodeTransaction transaction = this.nodeCacheBase.BeginTransaction()) { currentNode = transaction.BeginUpdate(lockNodePin); currentNode.Insert(index, new Element(key, newValue)); transaction.AddValue(key, newValue); transaction.Commit(); return InsertResult.Inserted; } } return InsertResult.NotFound; } if(index >= currentNode.Count) { index = currentNode.Count - 1; } using(NodePin childNodePin = this.nodeCacheBase.Lock(lockNodePin, currentNode[index].ChildNode)) { return Insert(childNodePin, key, ref value, lockNodePin, index); } } #endregion #region 업데이트하기 - Update<T>(lockNodePint, key, value) /// <summary> /// 업데이트하기 /// </summary> /// <typeparam name="T">타입</typeparam> /// <param name="lockNodePint">잠금 노드 핀</param> /// <param name="key">키</param> /// <param name="value">값</param> /// <returns>처리 결과</returns> private bool Update<T>(NodePin lockNodePint, TKey key, ref T value) where T : IUpdateValue<TKey, TValue> { NodePin nodePin; int offset; if(Seek(lockNodePint, key, out nodePin, out offset)) { using(nodePin) { TValue newValue = nodePin.CurrentNode[offset].Payload; if(value.UpdateValue(key, ref newValue)) { using(NodeTransaction transaction = this.nodeCacheBase.BeginTransaction()) { transaction.BeginUpdate(nodePin); nodePin.CurrentNode.SetValue(offset, key, newValue, this.keyComparer); transaction.UpdateValue(key, newValue); transaction.Commit(); return true; } } } } return false; } #endregion #region 삭제하기 - Delete<T>(lockNodePin, key, condition, parentNodePin, parentIndex) /// <summary> /// 삭제하기 /// </summary> /// <typeparam name="T">타입</typeparam> /// <param name="lockNodePin">잠금 노드 핀</param> /// <param name="key">키</param> /// <param name="condition">조건</param> /// <param name="parentNodePin">부모 노드 핀</param> /// <param name="parentIndex">부모 인덱스</param> /// <returns>삭제 결과</returns> private RemoveResult Delete<T>(NodePin lockNodePin, TKey key, ref T condition, NodePin parentNodePin, int parentIndex) where T : IRemoveValue<TKey, TValue> { Node currentNode = lockNodePin.CurrentNode; if(currentNode.Count == 0) { return RemoveResult.NotFound; } int minimumKeyCount = currentNode.IsLeaf ? this.options.MinimumValueNodeCount : this.options.MinimumChildNodeCount; if(currentNode.Count <= minimumKeyCount && parentNodePin != null && !parentNodePin.CurrentNode.IsRoot) { if(parentIndex < parentNodePin.CurrentNode.Count - 1) { using(NodePin biggerNodePin = this.nodeCacheBase.Lock(parentNodePin, parentNodePin.CurrentNode[parentIndex + 1].ChildNode)) { Join(lockNodePin, biggerNodePin, false, parentNodePin, parentIndex); } lockNodePin.Dispose(); return Delete(parentNodePin, key, ref condition, null, int.MinValue); } if(parentIndex > 0) { using(NodePin smallerNodePin = this.nodeCacheBase.Lock(parentNodePin, parentNodePin.CurrentNode[parentIndex - 1].ChildNode)) { Join(smallerNodePin, lockNodePin, true, parentNodePin, parentIndex - 1); } lockNodePin.Dispose(); return Delete(parentNodePin, key, ref condition, null, int.MinValue); } Assert(false, "Failed to join node before delete."); } else if(parentNodePin != null && parentNodePin.CurrentNode.IsRoot && currentNode.Count == 1 && !currentNode.IsLeaf) { using(NodePin onlyChildNodePin = this.nodeCacheBase.Lock(lockNodePin, currentNode[0].ChildNode)) { using(NodeTransaction transaction = this.nodeCacheBase.BeginTransaction()) { RootNode rootNode = (RootNode)transaction.BeginUpdate(parentNodePin); rootNode.ReplaceChild(0, lockNodePin.NodeHandle, onlyChildNodePin.NodeHandle); transaction.Destroy(lockNodePin); transaction.Commit(); } return Delete(onlyChildNodePin, key, ref condition, null, int.MinValue); } } if(parentNodePin != null) { parentNodePin.Dispose(); } bool isValueNode = currentNode.IsLeaf; int index; if(currentNode.BinarySearch(this.elementComparer, new Element(key), out index) && isValueNode) { if(condition.RemoveValue(key, currentNode[index].Payload)) { using(NodeTransaction transaction = this.nodeCacheBase.BeginTransaction()) { currentNode = transaction.BeginUpdate(lockNodePin); currentNode.Remove(index, new Element(key), this.keyComparer); transaction.RemoveValue(key); transaction.Commit(); return RemoveResult.Removed; } } return RemoveResult.Ignored; } if(isValueNode) { return RemoveResult.NotFound; } if(index >= currentNode.Count) { index = currentNode.Count - 1; } using(NodePin childNodePin = this.nodeCacheBase.Lock(lockNodePin, currentNode[index].ChildNode)) { return Delete(childNodePin, key, ref condition, lockNodePin, index); } } #endregion #region 트리 삭제하기 - DeleteTree(nodePin) /// <summary> /// 트리 삭제하기 /// </summary> /// <param name="nodePin">노드 핀</param> private void DeleteTree(NodePin nodePin) { List<NodeHandle> childNodeHandleList = new List<NodeHandle>(); if(!nodePin.CurrentNode.IsLeaf) { for(int i = 0; i < nodePin.CurrentNode.Count; i++) { childNodeHandleList.Add(nodePin.CurrentNode[i].ChildNode); } } try { using(NodeTransaction transaction = this.nodeCacheBase.BeginTransaction()) { transaction.Destroy(nodePin); transaction.Commit(); } } finally { if(childNodeHandleList.Count > 0) { foreach(NodeHandle childNoedHandle in childNodeHandleList) { using(NodePin childNodePin = this.nodeCacheBase.Lock(nodePin, childNoedHandle)) { DeleteTree(childNodePin); } } } } } #endregion #region 변경 사항 커밋하기 - CommitChanges(requiresLock) /// <summary> /// 변경 사항 커밋하기 /// </summary> /// <param name="requiresLock">잠금 필요 여부</param> private void CommitChanges(bool requiresLock) { CheckNotDisposed(); bool locked = requiresLock && this.lockStrategy.TryWrite(LockTimeout); try { if(this.nodeCacheBase.NodeStorage is INodeStorageWithCount) { ((INodeStorageWithCount)this.nodeCacheBase.NodeStorage).Count = this.hasCount ? this.count : -1; } if(this.nodeCacheBase.NodeStorage is ITransactable) { ((ITransactable)this.nodeCacheBase.NodeStorage).Commit(); } if(this.options.LogFile != null) { this.options.LogFile.TruncateLog(); } } finally { if(locked) { this.lockStrategy.ReleaseWrite(); } } } #endregion #region 변경시 처리하기 - ProcessOnChanged() /// <summary> /// 변경시 처리하기 /// </summary> private void ProcessOnChanged() { if(this.options.TransactionLogLimit > 0 && this.options.LogFile != null) { if(this.options.LogFile.FileSize > this.options.TransactionLogLimit) { using(this.lockStrategy.Write(LockTimeout)) { if(this.options.LogFile.FileSize > this.options.TransactionLogLimit) { CommitChanges(false); } } } } } #endregion #region 열거 가능형 구하기 - GetEnumerable(startKey) /// <summary> /// 열거 가능형 구하기 /// </summary> /// <param name="startKey">시작 키</param> /// <returns>열거 가능형</returns> public IEnumerable<KeyValuePair<TKey, TValue>> GetEnumerable(TKey startKey) { return new Enumerator(this, startKey); } #endregion #region 열거 가능형 구하기 - GetEnumerable(startKey, endKey) /// <summary> /// 열거 가능형 구하기 /// </summary> /// <param name="startKey">시작 키</param> /// <param name="endKey">종료 키</param> /// <returns>열거 가능형</returns> public IEnumerable<KeyValuePair<TKey, TValue>> GetEnumerable(TKey startKey, TKey endKey) { return new Enumerator(this, startKey, x => (this.keyComparer.Compare(x.Key, endKey) <= 0)); } #endregion #region 노드 컨텐츠 열거하기 - EnumerateNodeContents(rootNodePin) /// <summary> /// 노드 컨텐츠 열거하기 /// </summary> /// <param name="rootNodePin">루트 노드 핀</param> /// <returns>열거 가능형</returns> /// <remarks> /// 독점 액세스, 대량 삽입을 위한 심층 잠금 열거는 본질적으로 열거하는 동시에 기존 작성자를 트리에서 쫓아낸다. /// </remarks> private IEnumerable<KeyValuePair<TKey, TValue>> EnumerateNodeContents(NodePin rootNodePin) { if(rootNodePin.CurrentNode.IsLeaf) { for(int i = 0; i < rootNodePin.CurrentNode.Count; i++) { yield return rootNodePin.CurrentNode[i].ToKeyValuePair(); } yield break; } Stack<KeyValuePair<NodePin, int>> todoStack = new Stack<KeyValuePair<NodePin, int>>(); todoStack.Push(new KeyValuePair<NodePin, int>(rootNodePin, 0)); try { while(todoStack.Count > 0) { KeyValuePair<NodePin, int> current = todoStack.Pop(); if(current.Value == current.Key.CurrentNode.Count) { if(todoStack.Count == 0) { yield break; } current.Key.Dispose(); continue; } todoStack.Push(new KeyValuePair<NodePin, int>(current.Key, current.Value + 1)); NodePin childNodePin = this.nodeCacheBase.Lock(current.Key, current.Key.CurrentNode[current.Value].ChildNode); if(childNodePin.CurrentNode.IsLeaf) { using(childNodePin) { for(int i = 0; i < childNodePin.CurrentNode.Count; i++) { yield return childNodePin.CurrentNode[i].ToKeyValuePair(); } } } else { todoStack.Push(new KeyValuePair<NodePin, int>(childNodePin, 0)); } } } finally { while(todoStack.Count > 1) { todoStack.Pop().Key.Dispose(); } } } #endregion #region 엘리먼트 복사하기 - CopyElements(sourceNode, sourceIndex, targetNode, targetIndex, count, firstSourceKey) /// <summary> /// 엘리먼트 복사하기 /// </summary> /// <param name="sourceNode">소스 노드</param> /// <param name="sourceIndex">소스 인덱스</param> /// <param name="targetNode">타겟 노드</param> /// <param name="targetIndex">타겟 인덱스</param> /// <param name="count">카운트</param> /// <param name="firstSourceKey">첫번째 소스 키</param> private void CopyElements(Node sourceNode, int sourceIndex, Node targetNode, int targetIndex, int count, TKey firstSourceKey) { for(int i = 0; i < count; i++) { Element element = sourceNode[sourceIndex + i]; if((targetIndex + i) == 0 && !sourceNode.IsLeaf) { element = new Element(default(TKey), element.ChildNode); } else if((sourceIndex + i) == 0 && !sourceNode.IsLeaf) { element = new Element(firstSourceKey, element.ChildNode); } targetNode.Insert(targetIndex + i, element); } } #endregion #region 연결하기 - Join(smallNodePin, bigNodePin, moveToBigger, parentNodePin, parentSmallIndex) /// <summary> /// 연결하기 /// </summary> /// <param name="smallNodePin">작은 노드 핀</param> /// <param name="bigNodePin">큰 노드 핀</param> /// <param name="moveToBigger">큰 쪽 이동 여부</param> /// <param name="parentNodePin">부모 노드 핀</param> /// <param name="parentSmallIndex">부모 작은 인덱스</param> private void Join(NodePin smallNodePin, NodePin bigNodePin, bool moveToBigger, NodePin parentNodePin, int parentSmallIndex) { int fillFactor = smallNodePin.CurrentNode.IsLeaf ? this.options.FillValueNodeCount : this.options.FillChildNodeCount; int minimumKeyCount = smallNodePin.CurrentNode.IsLeaf ? this.options.MinimumValueNodeCount : this.options.MinimumChildNodeCount; using(NodeTransaction transaction = this.nodeCacheBase.BeginTransaction()) { int parentBigIndex = parentSmallIndex + 1; Assert ( smallNodePin.NodeHandle.Equals(parentNodePin.CurrentNode[parentSmallIndex].ChildNode), "Incorrect parent ordinal for left." ); Assert ( bigNodePin.NodeHandle.Equals(parentNodePin.CurrentNode[parentBigIndex ].ChildNode), "Incorrect parent ordinal for right." ); TKey bigZeroKey = parentNodePin.CurrentNode[parentBigIndex].Key; transaction.BeginUpdate(parentNodePin); if ( smallNodePin.CurrentNode.Count + bigNodePin.CurrentNode.Count <= fillFactor || (smallNodePin.CurrentNode.Count + bigNodePin.CurrentNode.Count) <= (minimumKeyCount * 2) ) { using(NodePin joinNode = transaction.Create(parentNodePin, smallNodePin.CurrentNode.IsLeaf)) { Element removeElement = parentNodePin.CurrentNode[parentBigIndex]; Assert ( removeElement.IsNode && removeElement.ChildNode.Equals(bigNodePin.NodeHandle), "Invalid parent index in join." ); parentNodePin.CurrentNode.Remove(parentBigIndex, removeElement, this.keyComparer); CopyElements ( smallNodePin.CurrentNode, 0, joinNode.CurrentNode, 0, smallNodePin.CurrentNode.Count, smallNodePin.CurrentNode[0].Key ); CopyElements ( bigNodePin.CurrentNode, 0, joinNode.CurrentNode, joinNode.CurrentNode.Count, bigNodePin.CurrentNode.Count, bigZeroKey ); parentNodePin.CurrentNode.ReplaceChild(parentSmallIndex, smallNodePin.NodeHandle, joinNode.NodeHandle); transaction.Destroy(bigNodePin); transaction.Destroy(smallNodePin); transaction.Commit(); } } else { using(NodePin newSmallNodePin = transaction.Create(parentNodePin, smallNodePin.CurrentNode.IsLeaf)) { using(NodePin newBigNodePin = transaction.Create(parentNodePin, bigNodePin.CurrentNode.IsLeaf)) { int totalCount = smallNodePin.CurrentNode.Count + bigNodePin.CurrentNode.Count; int borrowing = ((moveToBigger ? 0 : 1) + totalCount) / 2; TKey breakKey = borrowing < smallNodePin.CurrentNode.Count ? smallNodePin.CurrentNode[borrowing].Key : bigNodePin.CurrentNode[borrowing - smallNodePin.CurrentNode.Count].Key; CopyElements ( smallNodePin.CurrentNode, 0, newSmallNodePin.CurrentNode, 0, Math.Min(borrowing, smallNodePin.CurrentNode.Count), smallNodePin.CurrentNode[0].Key ); CopyElements ( bigNodePin.CurrentNode, 0, newSmallNodePin.CurrentNode, newSmallNodePin.CurrentNode.Count, borrowing - smallNodePin.CurrentNode.Count, bigZeroKey ); CopyElements ( smallNodePin.CurrentNode, borrowing, newBigNodePin.CurrentNode, newBigNodePin.CurrentNode.Count, smallNodePin.CurrentNode.Count - borrowing, default(TKey) ); CopyElements ( bigNodePin.CurrentNode, Math.Max(0, borrowing - smallNodePin.CurrentNode.Count), newBigNodePin.CurrentNode, newBigNodePin.CurrentNode.Count, Math.Min(bigNodePin.CurrentNode.Count, totalCount - borrowing), bigZeroKey ); parentNodePin.CurrentNode.ReplaceChild(parentSmallIndex, smallNodePin.NodeHandle, newSmallNodePin.NodeHandle); parentNodePin.CurrentNode.ReplaceKey(parentBigIndex, breakKey, this.keyComparer); parentNodePin.CurrentNode.ReplaceChild(parentBigIndex, bigNodePin.NodeHandle, newBigNodePin.NodeHandle); transaction.Destroy(bigNodePin); transaction.Destroy(smallNodePin); transaction.Commit(); } } } } } #endregion #region 분리하기 - Split(transaction, lockNodePin, parentNodePin, parentIndex, splitKey, leftHeavy) /// <summary> /// 분리하기 /// </summary> /// <param name="transaction">트랜잭션</param> /// <param name="lockNodePin">잠금 노드 핀</param> /// <param name="parentNodePin">부모 노드 핀</param> /// <param name="parentIndex">부모 인덱스</param> /// <param name="splitKey">분리 키</param> /// <param name="leftHeavy">왼쪽 헤비 여부</param> /// <returns>노드 핀</returns> private NodePin Split ( NodeTransaction transaction, ref NodePin lockNodePin, NodePin parentNodePin, int parentIndex, out TKey splitKey, bool leftHeavy ) { Node currentNode = lockNodePin.CurrentNode; NodePin previousNodePin = transaction.Create(parentNodePin, lockNodePin.CurrentNode.IsLeaf); NodePin nextNodePin = transaction.Create(parentNodePin, lockNodePin.CurrentNode.IsLeaf); try { int index; int count = currentNode.Count >> 1; if(leftHeavy) { int minimumSize = lockNodePin.CurrentNode.IsLeaf ? this.options.MinimumValueNodeCount : this.options.MinimumChildNodeCount; count = currentNode.Count - minimumSize; } for(index = 0; index < count; index++) { previousNodePin.CurrentNode.Insert(previousNodePin.CurrentNode.Count, currentNode[index]); } splitKey = currentNode[count].Key; if(!lockNodePin.CurrentNode.IsLeaf) { nextNodePin.CurrentNode.Insert(nextNodePin.CurrentNode.Count, new Element(default(TKey), currentNode[index++].ChildNode)); } for(; index < currentNode.Count; index++) { nextNodePin.CurrentNode.Insert(nextNodePin.CurrentNode.Count, currentNode[index]); } parentNodePin.CurrentNode.ReplaceChild(parentIndex, lockNodePin.NodeHandle, previousNodePin.NodeHandle); parentNodePin.CurrentNode.Insert(parentIndex + 1, new Element(splitKey, nextNodePin.NodeHandle)); transaction.Destroy(lockNodePin); lockNodePin = previousNodePin; return nextNodePin; } catch { previousNodePin.Dispose(); nextNodePin.Dispose(); throw; } } #endregion #region 탐색하기 - Seek(lockNodePin, key, nodePin, offset) /// <summary> /// 탐색하기 /// </summary> /// <param name="lockNodePin">잠금 노드 핀</param> /// <param name="key">키</param> /// <param name="nodePin">노드 핀</param> /// <param name="offset">오프셋</param> /// <returns>처리 결과</returns> private bool Seek(NodePin lockNodePin, TKey key, out NodePin nodePin, out int offset) { NodePin currentNodePin = lockNodePin; NodePin nextNodePin = null; try { while(currentNodePin != null) { Node currentNode = currentNodePin.CurrentNode; bool isValueNode = currentNode.IsLeaf; int index; if(currentNode.BinarySearch(this.elementComparer, new Element(key), out index) && isValueNode) { nodePin = currentNodePin; currentNodePin = null; offset = index; return true; } if(isValueNode) { break; } nextNodePin = this.nodeCacheBase.Lock(currentNodePin, currentNode[index].ChildNode); currentNodePin.Dispose(); currentNodePin = nextNodePin; nextNodePin = null; } } finally { if(currentNodePin != null) { currentNodePin.Dispose(); } if(nextNodePin != null) { nextNodePin.Dispose(); } } nodePin = null; offset = -1; return false; } #endregion #region 에지 탐색하기 - SeekToEdge(lockNodePin, first, nodePin, offset) /// <summary> /// 에지 탐색하기 /// </summary> /// <param name="lockNodePin">잠금 노드 핀</param> /// <param name="first">첫번째 여부</param> /// <param name="nodePin">노드 핀</param> /// <param name="offset">오프셋</param> /// <returns>처리 결과</returns> private bool SeekToEdge(NodePin lockNodePin, bool first, out NodePin nodePin, out int offset) { NodePin currentNodePin = lockNodePin; NodePin nextNodePin = null; try { while(currentNodePin != null) { Node currentNode = currentNodePin.CurrentNode; int index = first ? 0 : currentNode.Count - 1; if(currentNode.IsLeaf) { if(index < 0 || index >= currentNode.Count) { break; } nodePin = currentNodePin; currentNodePin = null; offset = index; return true; } nextNodePin = this.nodeCacheBase.Lock(currentNodePin, currentNode[index].ChildNode); currentNodePin.Dispose(); currentNodePin = nextNodePin; nextNodePin = null; } } finally { if(currentNodePin != null) { currentNodePin.Dispose(); } if(nextNodePin != null) { nextNodePin.Dispose(); } } nodePin = null; offset = -1; return false; } #endregion #region 에지 구하기 시도하기 - TryGetEdge(lockNodePin, first, item) /// <summary> /// 에지 구하기 시도하기 /// </summary> /// <param name="lockNodePin">잠금 노드 핀</param> /// <param name="first">첫번째 여부</param> /// <param name="item">항목</param> /// <returns>처리 결과</returns> private bool TryGetEdge(NodePin lockNodePin, bool first, out KeyValuePair<TKey, TValue> item) { NodePin nodePin; int offset; if(SeekToEdge(lockNodePin, first, out nodePin, out offset)) { using(nodePin) { item = new KeyValuePair<TKey, TValue> ( nodePin.CurrentNode[offset].Key, nodePin.CurrentNode[offset].Payload ); return true; } } item = default(KeyValuePair<TKey, TValue>); return false; } #endregion #region 조회하기 - Search(lockNodePin, key, value) /// <summary> /// 조회하기 /// </summary> /// <param name="lockNodePin">잠금 노드 핀</param> /// <param name="key">키</param> /// <param name="value">값</param> /// <returns>처리 결과</returns> private bool Search(NodePin lockNodePin, TKey key, ref TValue value) { NodePin nodePin; int offset; if(Seek(lockNodePin, key, out nodePin, out offset)) { using(nodePin) { value = nodePin.CurrentNode[offset].Payload; return true; } } return false; } #endregion #region 루트 잠금 구하기 - GetLockRoot(lockType, methodName) /// <summary> /// 루트 잠금 구하기 /// </summary> /// <param name="lockType">잠금 타입</param> /// <param name="methodName">메소드명</param> /// <returns>루트 잠금</returns> private RootLock GetLockRoot(LockType lockType, string methodName) { return new RootLock(this, lockType, false, methodName); } #endregion #region 루트 잠금 구하기 - GetLockRoot(lockType, methodName, exclusiveTreeAccess) /// <summary> /// 루트 잠금 구하기 /// </summary> /// <param name="lockType">잠금 타입</param> /// <param name="methodName">메소드명</param> /// <param name="exclusiveTreeAccess">배타적 트리 액세스 여부</param> /// <returns>루트 잠금</returns> private RootLock GetLockRoot(LockType lockType, string methodName, bool exclusiveTreeAccess) { return new RootLock(this, lockType, exclusiveTreeAccess, methodName); } #endregion #region 리소스 미해제 여부 체크하기 - CheckNotDisposed() /// <summary> /// 리소스 미해제 여부 체크하기 /// </summary> private void CheckNotDisposed() { if(this.disposed) { throw new ObjectDisposedException(GetType().FullName); } } #endregion #region 값 카운트하기 - CountValues(lockNodePin) /// <summary> /// 값 카운트하기 /// </summary> /// <param name="lockNodePin">잠금 노드 핀</param> /// <returns>값 카운트</returns> private int CountValues(NodePin lockNodePin) { if(lockNodePin.CurrentNode.IsLeaf) { return lockNodePin.CurrentNode.Count; } int count = 0; for(int i = 0; i < lockNodePin.CurrentNode.Count; i++) { using(NodePin childNodePin = this.nodeCacheBase.Lock(lockNodePin, lockNodePin.CurrentNode[i].ChildNode)) { count += CountValues(childNodePin); } } return count; } #endregion #region 인쇄하기 - Print(nodePin, textWriter, depth, debugFormat) /// <summary> /// 인쇄하기 /// </summary> /// <param name="nodePin">노드 핀</param> /// <param name="textWriter">텍스트 라이터</param> /// <param name="depth">깊이</param> /// <param name="debugFormat">디버그 포맷</param> [Conditional("DEBUG")] private void Print(NodePin nodePin, TextWriter textWriter, int depth, DebugFormat debugFormat) { bool formatted = debugFormat != DebugFormat.Compact; string prefix = formatted ? Environment.NewLine + new String(' ', depth << 1) : ""; textWriter.Write("{0}{{", formatted ? " " : ""); if(formatted) { prefix += " "; } for(int i = 0; i < nodePin.CurrentNode.Count; i++) { if(i > 0 || nodePin.CurrentNode[i].IsValue) { textWriter.Write("{0}{1}", prefix, nodePin.CurrentNode[i].Key); } if(formatted && nodePin.CurrentNode.IsLeaf) { textWriter.Write(" = {0}", nodePin.CurrentNode[i].Payload); } if(debugFormat == DebugFormat.Full) { textWriter.Write(" (IsLeaf={0})", nodePin.CurrentNode.IsLeaf); textWriter.Write(" (Count={0})" , nodePin.CurrentNode.Count ); } if(nodePin.CurrentNode[i].IsNode) { using(NodePin childPin = this.nodeCacheBase.Lock(nodePin, nodePin.CurrentNode[i].ChildNode)) { Print(childPin, textWriter, depth + 1, debugFormat); #if DEBUG if(debugFormat == DebugFormat.Full) { try { Validate(childPin, nodePin, i, 1); } catch(Exception exception) { textWriter.WriteLine(); textWriter.WriteLine("{0} Error = {1}", prefix, exception.Message); } } #endif } } else if(formatted) { textWriter.Write("={0}", nodePin.CurrentNode[i].Payload); } if(i + 1 < nodePin.CurrentNode.Count) { textWriter.Write(','); } } if(formatted) { prefix = prefix.Substring(0, prefix.Length - 2); } textWriter.Write("{0}}}", prefix); } #endregion #region 디버그 메시지 쓰기 - WriteDebugMessage(format, argumentArray) /// <summary> /// 디버그 메시지 쓰기 /// </summary> /// <param name="format">포맷 문자열</param> /// <param name="argumentArray">인자 배열</param> [Conditional("DEBUG")] private void WriteDebugMessage(string format, params object[] argumentArray) { if(this.debugTextWriter != null) { using(StringWriter stringWriter = new StringWriter()) { Print(stringWriter, DebugFormat.Compact); stringWriter.Write(" - " + format, argumentArray); this.debugTextWriter.WriteLine(stringWriter.ToString()); } } if(this.validated) { Validate(); } } #endregion #region 무결성 검증하기 - Validate(lockNodePin, parentNodePin, parentIndex, depthToValidate) #if DEBUG /// <summary> /// 무결성 검증하기 /// </summary> /// <param name="lockNodePin">잠금 노드 핀</param> /// <param name="parentNodePin">부모 노드 핀</param> /// <param name="parentIndex">부모 인덱스</param> /// <param name="depthToValidate">검증 깊이</param> /// <returns>처리 결과</returns> private int Validate(NodePin lockNodePin, NodePin parentNodePin, int parentIndex, int depthToValidate) { Assert(lockNodePin != null, "Null node lock encountered."); Node currentNode = lockNodePin.CurrentNode; Assert(currentNode != null, "Null node reference encountered."); if(parentNodePin == null || parentNodePin.CurrentNode.IsRoot) { } else { if(currentNode.IsLeaf) { Assert(currentNode.Count >= this.options.MinimumValueNodeCount, "Not enough child nodes."); Assert(currentNode.Count <= this.options.MaximumValueNodeCount, "Too many child nodes." ); } else { Assert(currentNode.Count >= this.options.MinimumChildNodeCount, "Not enough child nodes."); Assert(currentNode.Count <= this.options.MaximumChildNodeCount, "Too many child nodes." ); } Assert(parentNodePin.CurrentNode[parentIndex].ChildNode.Equals(lockNodePin.NodeHandle), "Parent index is incorrect."); } int depth = 0; for(int i = 0; i < currentNode.Count; i++) { if(parentNodePin != null) { int ordinal; if(currentNode.IsLeaf || i > 0) { parentNodePin.CurrentNode.BinarySearch(this.elementComparer, currentNode[i], out ordinal); Assert(ordinal == parentIndex, "My child is not within parent range."); } else { Assert(this.keyComparer.Compare(currentNode[i].Key, default(TKey)) == 0, "First key non-empty?"); } } Assert(currentNode.IsLeaf == !currentNode[i].IsNode , "Child container in leaf node."); Assert(currentNode.IsLeaf == currentNode[i].IsValue, "Leaf child is not a value." ); if(!currentNode.IsLeaf && depthToValidate > 0) { int testDepth; using(NodePin node = this.nodeCacheBase.Lock(lockNodePin, currentNode[i].ChildNode)) { testDepth = Validate(node, lockNodePin, i, depthToValidate - 1); } if(i == 0) { depth = testDepth; } else { Assert(depth == testDepth, "Expected each node to have the same depth"); } } } for(int i = currentNode.Count; i < currentNode.Size && !currentNode.IsRoot; i++) { Assert(currentNode[i].IsEmpty, "Non-cleared element value."); bool isKeyClass = ReferenceEquals(default(TKey), null); Assert ( isKeyClass ? ReferenceEquals(currentNode[i].Key, null) : this.keyComparer.Compare(currentNode[i].Key, default(TKey)) == 0, "Non-cleared element key." ); } return depth + 1; } #endif #endregion } } |
▶ BPlusTree.AddRangeInfo.cs
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 |
using System; using System.Collections.Generic; namespace TestLibrary { /// <summary> /// B+ 트리 /// </summary> public partial class BPlusTree<TKey, TValue> { //////////////////////////////////////////////////////////////////////////////////////////////////// Class ////////////////////////////////////////////////////////////////////////////////////////// Private #region 범위 추가 정보 - AddRangeInfo /// <summary> /// 범위 추가 정보 /// </summary> private class AddRangeInfo : IDisposable { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Public #region Field /// <summary> /// 업데이트 허용 여부 /// </summary> public readonly bool AllowUpdate; #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 계속 여부 /// </summary> private bool isContinue; /// <summary> /// 항목 열거자 /// </summary> private readonly IEnumerator<KeyValuePair<TKey, TValue>> itemEnumerator; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 현재 항목 - Current /// <summary> /// 현재 항목 /// </summary> public KeyValuePair<TKey, TValue> Current { get { return this.itemEnumerator.Current; } } #endregion #region 완료 여부 - IsCompleted /// <summary> /// 완료 여부 /// </summary> public bool IsCompleted { get { return this.isContinue == false; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - AddRangeInfo(allowUpdate, sourceEnumerable) /// <summary> /// 생성자 /// </summary> /// <param name="allowUpdate">업데이트 허용 여부</param> /// <param name="sourceEnumerable">소스 열거 가능형</param> public AddRangeInfo(bool allowUpdate, IEnumerable<KeyValuePair<TKey, TValue>> sourceEnumerable) { AllowUpdate = allowUpdate; this.itemEnumerator = sourceEnumerable.GetEnumerator(); MoveNext(); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 다음 항목으로 이동하기 - MoveNext() /// <summary> /// 다음 항목으로 이동하기 /// </summary> public void MoveNext() { this.isContinue = this.itemEnumerator.MoveNext(); } #endregion #region 리소스 해제하기 - Dispose() /// <summary> /// 리소스 해제하기 /// </summary> public void Dispose() { this.isContinue = false; this.itemEnumerator.Dispose(); } #endregion } #endregion } } |
▶ BPlusTree.Element.cs
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 |
using System.Collections.Generic; using System.Diagnostics; namespace TestLibrary { /// <summary> /// B+ 트리 /// </summary> public partial class BPlusTree<TKey, TValue> { //////////////////////////////////////////////////////////////////////////////////////////////////// Structure ////////////////////////////////////////////////////////////////////////////////////////// Private #region 엘리먼트 - Element /// <summary> /// 엘리먼트 /// </summary> [DebuggerDisplay("{Key} = {child}")] private struct Element { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Public #region Field /// <summary> /// 키 /// </summary> public readonly TKey Key; #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 자식 /// </summary> private readonly object child; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 노드 여부 - IsNode /// <summary> /// 노드 여부 /// </summary> public bool IsNode { get { return this.child is NodeHandle; } } #endregion #region 값 여부 - IsValue /// <summary> /// 값 여부 /// </summary> public bool IsValue { get { return !(this.child is NodeHandle); } } #endregion #region 비움 여부 - IsEmpty /// <summary> /// 비움 여부 /// </summary> public bool IsEmpty { get { return ReferenceEquals(null, this.child); } } #endregion #region 자식 노드 - ChildNode /// <summary> /// 자식 노드 /// </summary> public NodeHandle ChildNode { get { return (NodeHandle)this.child; } } #endregion #region 페이로드 - Payload /// <summary> /// 페이로드 /// </summary> public TValue Payload { get { return (TValue)this.child; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - Element(key) /// <summary> /// 생성자 /// </summary> /// <param name="key">키</param> public Element(TKey key) { Key = key; this.child = null; } #endregion #region 생성자 - Element(key, nodeHandle) /// <summary> /// 생성자 /// </summary> /// <param name="key">키</param> /// <param name="nodeHandle">노드 핸들</param> public Element(TKey key, NodeHandle nodeHandle) { Key = key; this.child = nodeHandle; } #endregion #region 생성자 - Element(key, value) /// <summary> /// 생성자 /// </summary> /// <param name="key">키</param> /// <param name="value">값</param> public Element(TKey key, TValue value) { Key = key; this.child = value; } #endregion #region 생성자 - Element(key, element) /// <summary> /// 생성자 /// </summary> /// <param name="key">키</param> /// <param name="element">엘리먼트</param> public Element(TKey key, Element element) { Key = key; this.child = element.child; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 키/값 쌍 구하기 - ToKeyValuePair() /// <summary> /// 키/값 쌍 구하기 /// </summary> /// <returns>키/값 쌍</returns> public KeyValuePair<TKey, TValue> ToKeyValuePair() { return new KeyValuePair<TKey, TValue>(Key, Payload); } #endregion } #endregion } } |
▶ BPlusTree.ElementComparer.cs
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 |
using System.Collections.Generic; namespace TestLibrary { /// <summary> /// B+ 트리 /// </summary> public partial class BPlusTree<TKey, TValue> { //////////////////////////////////////////////////////////////////////////////////////////////////// Class ////////////////////////////////////////////////////////////////////////////////////////// Private #region 엘리먼트 비교자 - ElementComparer /// <summary> /// 엘리먼트 비교자 /// </summary> private class ElementComparer : IComparer<Element> { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 키 비교자 /// </summary> private readonly IComparer<TKey> keyComparer; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - ElementComparer(keyComparer) /// <summary> /// 생성자 /// </summary> /// <param name="keyComparer">키 비교자</param> public ElementComparer(IComparer<TKey> keyComparer) { this.keyComparer = keyComparer; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 비교하기 - Compare(x, y) /// <summary> /// 비교하기 /// </summary> /// <param name="x">엘리먼트 X</param> /// <param name="y">엘리먼트 Y</param> /// <returns>비교 결과</returns> public int Compare(Element x, Element y) { return this.keyComparer.Compare(x.Key, y.Key); } #endregion } #endregion } } |
▶