jgc.h 58.1 KB
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
/***************************************************************************
 *   Copyright (C) 2005 <still unknown>                                    *
 *   root@sat                                                              *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#ifndef J_GC_H
#define J_GC_H

#include "jruntimeexception.h"

#ifdef _MSC_VER
#pragma warning(disable : 4786)
#endif

#if _MSC_VER >= 1000
#pragma once
#endif

#if defined(_MSC_VER) && (_MSC_VER >= 1000)
#pragma once
#endif

#ifndef _SMGC_POOR_STL
#include <cstdlib>
#include <memory>
#include <climits>
#include <cstring>
#include <limits>
#else
#include <stdlib.h>
#include <limits.h>
#include <memory.h>
#include <string.h>
#endif

#include <set>
#include <map>
#include <vector>
#include <deque>
#include <utility>
#include <algorithm>
#include <exception>
#include <stdexcept>
#include <iostream>
#include <functional>
#include <new>

#ifndef _SMGC_POOR_STL
#include <cstdlib>
#include <cstddef>
#else
#include <stdlib.h>
#include <stddef.h>
#endif

#ifndef _SMGC_POOR_STL
#include <cstdlib>
#include <cstddef>
#include <climits>
#include <cassert>
#else
#include <stdlib.h>
#include <stddef.h>
#include <limits.h>
#include <assert.h>
#endif

#if defined(_MSC_VER) && (_MSVC <= 1200)
#define _SMGC_NO_FRIEND_TEMPLATES
#define _SMGC_NO_ARRAY_NEW
#define _SMGC_POOR_TEMPLATES
#endif

#if defined(_SMGC_POOR_TEMPLATES) && !defined(_SMGC_NO_FRIEND_TEMPLATES)
#define _SMGC_NO_FRIEND_TEMPLATES
#endif

#define ASSERT_VALID if(0){}else
#define ASSERT_SUPER_VALID if(0){}else
#define ASSERT_PTR_VALID(_p_)  if(0){}else
#ifndef NDEBUG
# ifdef DEBUG_COMPILER
#  undef ASSERT_VALID
#  undef ASSERT_SUPER_VALID
#  undef ASSERT_PTR_VALID
#  define ASSERT_VALID assert(!destroyed)
#  define ASSERT_SUPER_VALID assert(!super::destroyed)
#  define ASSERT_PTR_VALID(_p_) assert(!(_p_).destroyed)
# endif
#endif

namespace jcommon {

template<typename T> class gc_ptr;
template<typename T> class const_gc_ptr;
template<typename T> class gc_arr;
template<typename T> class const_gc_arr;
template<typename T> class wk_ptr;
template<typename T> class const_wk_ptr;
template<typename T> class wk_arr;
template<typename T> class const_wk_arr;

void collect();
void set_threshold(size_t bytes);
size_t get_threshold();
size_t get_dynamic_threshold();

extern const size_t no_threshold;
extern const size_t default_threshold;

struct gc_t {
};

struct gc_null_t {
	operator void* () const
	{
		return 0;
	}
};

template <typename T>struct destructor {
	static void destroy(void* obj, void* base, size_t)
	{
		T* ptr = static_cast<T*>(obj);
		ptr->~T();
		::operator delete(base);
	}

	static void destroy_array(void* obj, void* base, size_t size)
	{
		T* arr = static_cast<T*>(obj);
		for(size_t i = 0; i < size/sizeof(T); ++i)
		{
			arr[i].~T();
		}
		::operator delete[](base);
	}
};

struct node_base {
};

struct pointer_base {
	int pos;
#ifndef NDEBUG
	bool destroyed;
#ifdef DEBUG_COMPILER
	char *trash;
	//void assert_valid()
	//{ ASSERT_VALID; }
#endif
#endif

	protected:
	pointer_base();
	pointer_base(const pointer_base& pb);
	virtual ~pointer_base();

	void operator= (const pointer_base& pb) 
	{
	}

	void reset_node(const void* obj, void (*destroy)(void*, void*, size_t));

	void swap(pointer_base &pb)
	{ 
		ASSERT_VALID; 
	}
};

struct weak_base {
	int pos;
#ifndef NDEBUG
	bool destroyed;
#ifdef DEBUG_COMPILER
	char *trash;
#endif
#endif

	protected:
	weak_base();
	weak_base(const weak_base& pb);
	virtual ~weak_base();

	void operator= (const weak_base& pb) 
	{
	}
};

void reg(void *obj, size_t size, void (*destroy)(void*, void*, size_t));

struct dynamic_cast_t {
};

struct static_cast_t {
};

struct const_cast_t {
};

struct light_cons_t {
};

// Pointer registation function, allocated memory must be freeable using supplied destroy function
template<typename T>T* reg(T *ptr, void (*destroy)(void*, void*, size_t))
{
	reg(static_cast<void*>(ptr), sizeof(T), destroy);
	return ptr;
}

// Array pointer registation function, allocated memory must be freeable using supplied destroy function
template<typename T>T* reg(T arr[], size_t len, void (*destroy)(void*, void*, size_t))
{
	reg(static_cast<void*>(arr), sizeof(T)*len, destroy);
	return arr;
}

/* Implicit cast operation */
template<typename T, typename U> T implicit_cast(U u) 
{
   	return u; 
}

// Managed pointer class template 
template<typename T>class const_gc_ptr: public pointer_base {
#ifdef _SMGC_NO_FRIEND_TEMPLATES
	public:
#else
	protected:
		template<typename U> friend class const_gc_ptr;
		template<typename U> friend class gc_ptr;
		template<typename U> friend class const_wk_ptr;
		template<typename U> friend class wk_ptr;
		friend struct std::less<const_gc_ptr<T> >;
		friend struct std::less<gc_ptr<T> >;
#endif
		friend void collect();

		T* ptr;

	public:
		typedef T element_type;

	private:
		typedef pointer_base super;

	protected:
		template <typename U>void reset_node(const U* obj)
		{
			super::reset_node(obj, destructor<U>::destroy);
		}

		const_gc_ptr(const light_cons_t&) 
		{
		}

	public:
		const_gc_ptr(): ptr(0) 
		{
		}

		const_gc_ptr(const gc_null_t&): ptr(0) 
		{
		}

		template<typename U>explicit const_gc_ptr(const U *p)//: ptr(0)
		{
			reset(p);
		}

		template<typename U>const_gc_ptr(const U *p, const dynamic_cast_t*)//: ptr(0)
		{
			reset(dynamic_cast<T*>(p));
		}

		template<typename U>const_gc_ptr(const U *p, const static_cast_t*)//: ptr(0)
		{
			reset(static_cast<T*>(p));
		}

		const_gc_ptr(const T *p)//: ptr(0)
		{
			reset(p);
		}

		template<typename U>const_gc_ptr(const const_gc_ptr<U> &p): super(p), ptr(implicit_cast<T*>(p.ptr)) 
		{
		}

		template<typename U>const_gc_ptr(const const_gc_ptr<U> &p, const dynamic_cast_t*):
				super(p), ptr(dynamic_cast<T*>(p.ptr)) 
		{
		}

		template<typename U>const_gc_ptr(const const_gc_ptr<U> &p, const static_cast_t*):
				super(p), ptr(static_cast<T*>(p.ptr)) 
		{
		}

#ifndef NDEBUG
		virtual ~const_gc_ptr()
		{
			ptr=0;
		}
#endif

		const_gc_ptr<T>& operator = (const gc_null_t&)
		{
			ASSERT_VALID;
			ptr = 0;
			return *this;
		}

		template<typename U>const_gc_ptr<T>& operator = (const U *p)
		{
			ASSERT_VALID;
			reset(p);
			return *this;
		}

		template<typename U>const_gc_ptr<T>& operator = (const const_gc_ptr<U> &p)
		{
			ASSERT_VALID;
			ptr = p.ptr;
			return *this;
		}

		const T& operator * () const
		{
			ASSERT_VALID;
			return *ptr;
		}

		const T* operator -> () const
		{
			ASSERT_VALID;
			return ptr;
		}

		const T* get() const
		{
			ASSERT_VALID;
			return ptr;
		}

		bool operator ! () const
		{
			ASSERT_VALID;
			return ptr==0;
		}

		operator bool () const
		{
			ASSERT_VALID;
			return ptr!=0;
		}

		bool operator ==(const gc_null_t&) const
		{
			ASSERT_VALID;
			return ptr == 0;
		}

		bool operator !=(const gc_null_t&) const
		{
			ASSERT_VALID;
			return ptr != 0;
		}

		template<typename U>bool operator ==(const const_gc_ptr<U> &p) const
		{
			ASSERT_VALID;
			return ptr == p.ptr;
		}

		template<typename U>bool operator !=(const const_gc_ptr<U> &p) const
		{
			ASSERT_VALID;
			return ptr != p.ptr;
		}

		template<typename U>bool operator <=(const const_gc_ptr<U> &p) const
		{
			ASSERT_VALID;
			return ptr <= p.ptr;
		}

		template<typename U>bool operator >=(const const_gc_ptr<U> &p) const
		{
			ASSERT_VALID;
			return ptr >= p.ptr;
		}

		template<typename U>bool operator <(const const_gc_ptr<U> &p) const
		{
			ASSERT_VALID;
			return ptr < p.ptr;
		}

		template<typename U>bool operator >(const const_gc_ptr<U> &p) const
		{
			ASSERT_VALID;
			return ptr > p.ptr;
		}


		template<typename U>bool operator ==(const U *p) const
		{
			ASSERT_VALID;
			return ptr == p;
		}

		template<typename U>bool operator !=(const U *p) const
		{
			ASSERT_VALID;
			return ptr != p;
		}

#ifdef _SMGC_PTR_COMPARABLE
		template<typename U>bool operator <=(const U *p) const
		{
			ASSERT_VALID;
			return ptr <= p;
		}

		template<typename U>bool operator >=(const U *p) const
		{
			ASSERT_VALID;
			return ptr >= p;
		}

		template<typename U>bool operator <(const U *p) const
		{
			ASSERT_VALID;
			return ptr < p;
		}

		template<typename U>bool operator >(const U *p) const
		{
			ASSERT_VALID;
			return ptr > p;
		}
#endif

		void reset(const T* p=0)
		{
			ASSERT_VALID;
			reset_node(p);
			ptr = const_cast<T*>(p);
		}

		void swap(const_gc_ptr &p)
		{
			ASSERT_VALID;
			T* tmp = ptr;
			ptr = p.ptr;
			p.ptr = tmp;
			super::swap(p);
		}
};


// Managed pointer class template 
template<typename T>class gc_ptr: public const_gc_ptr<T> {
	public:
		typedef T element_type;

	private:
		typedef const_gc_ptr<T> super;

	public:
		gc_ptr() 
		{
		}

		gc_ptr(const gc_null_t&) 
		{
		}

		template<typename U>explicit gc_ptr(U *p): super(light_cons_t())
		{
			reset(p);
		}

		template<typename U>gc_ptr(U *p, const dynamic_cast_t*): super(light_cons_t())
		{
			reset(dynamic_cast<T*>(p));
		}

		template<typename U>gc_ptr(U *p, const static_cast_t*): super(light_cons_t())
		{
			reset(static_cast<T*>(p));
		}

		template<typename U>gc_ptr(const U *p, const const_cast_t*): super(light_cons_t())
		{
			reset(const_cast<T*>(p));
		}

		gc_ptr(T *p): super(light_cons_t())
		{
			reset(p);
		}

		template<typename U>gc_ptr(const gc_ptr<U> &p): super(p) 
		{
		}

		template<typename U>gc_ptr(const gc_ptr<U> &p, const dynamic_cast_t*):
				super(p, static_cast<dynamic_cast_t*>(0)) 
		{
		}

		template<typename U>gc_ptr(const gc_ptr<U> &p, const static_cast_t*):
				super(p, static_cast<static_cast_t*>(0)) 
		{
		}

		template<typename U>gc_ptr(const const_gc_ptr<U> &p, const const_cast_t*):
				super(p) 
		{
		}

#ifndef NDEBUG
		virtual ~gc_ptr()
		{
			ASSERT_SUPER_VALID;
			super::ptr=0;
		}
#endif

		gc_ptr<T>& operator = (const gc_null_t&)
		{
			ASSERT_SUPER_VALID;
			super::ptr = 0;
			return *this;
		}

		template<typename U>gc_ptr<T>& operator = (U *p)
		{
			ASSERT_SUPER_VALID;
			reset(p);
			return *this;
		}

		template<typename U>gc_ptr<T>& operator = (const gc_ptr<U> &p)
		{
			ASSERT_SUPER_VALID;
			super::ptr = const_cast<U*>(p.ptr);
			return *this;
		}

		T& operator * () const
		{
			ASSERT_SUPER_VALID;
			return *super::ptr;
		}

		T* operator -> () const
		{
			ASSERT_SUPER_VALID;
			return super::ptr;
		}

		T* get() const
		{
			ASSERT_SUPER_VALID;
			return super::ptr;
		}

		void reset(T* p=0)
		{
			ASSERT_SUPER_VALID;
			reset_node(p);
			super::ptr = p;
		}

		void swap(gc_ptr &p)
		{
			ASSERT_SUPER_VALID;
			T* tmp = super::ptr;
			super::ptr = p.ptr;
			p.ptr = tmp;
			super::swap(p);
		}
};

template<typename U>bool operator ==(const gc_null_t &l, const const_gc_ptr<U> &p)
{
	return p.operator ==(l);
}

template<typename U>bool operator !=(const gc_null_t &l, const const_gc_ptr<U> &p)
{
	return p.operator !=(l);
}

template<typename T, typename U>bool operator ==(const T *l, const const_gc_ptr<U> &p)
{
	return p.operator ==(l);
}

template<typename T, typename U>bool operator !=(const T *l, const const_gc_ptr<U> &p)
{
	return p.operator !=(l);
}

#ifdef _SMGC_PTR_COMPARABLE
template<typename T, typename U>bool operator <=(const T *l, const const_gc_ptr<U> &p)
{
	return p.operator >=(l);
}

template<typename T, typename U>bool operator >=(const T *l, const const_gc_ptr<U> &p)
{
	return p.operator <=(l);
}

template<typename T, typename U>bool operator <(const T *l, const const_gc_ptr<U> &p)
{
	return p.operator >(l);
}

template<typename T, typename U>bool operator >(const T *l, const const_gc_ptr<U> &p)
{
	return p.operator <(l);
}
#endif

/* Smartpointer cast operations */
template<typename T, typename U>gc_ptr<T> dynamic_cast_gc_ptr(U *u)
{
	return gc_ptr<T>(u, static_cast<dynamic_cast_t*>(0));
}

template<typename T, typename U>const_gc_ptr<T> dynamic_cast_gc_ptr(const U *u)
{
	return const_gc_ptr<T>(u, static_cast<dynamic_cast_t*>(0));
}

template<typename T, typename U>gc_ptr<T> dynamic_cast_gc_ptr(const gc_ptr<U> &u)
{
	return gc_ptr<T>(u, static_cast<dynamic_cast_t*>(0));
}

template<typename T, typename U>const_gc_ptr<T> dynamic_cast_gc_ptr(const const_gc_ptr<U> &u)
{
	return const_gc_ptr<T>(u, static_cast<dynamic_cast_t*>(0));
}

template<typename T, typename U>gc_ptr<T> static_cast_gc_ptr(U *u)
{
	return gc_ptr<T>(u, static_cast<static_cast_t*>(0));
}

template<typename T, typename U>const_gc_ptr<T> static_cast_gc_ptr(const U *u)
{
	return const_gc_ptr<T>(u, static_cast<static_cast_t*>(0));
}

template<typename T, typename U>gc_ptr<T> static_cast_gc_ptr(const gc_ptr<U> &u)
{
	return gc_ptr<T>(u, static_cast<static_cast_t*>(0));
}

template<typename T, typename U>const_gc_ptr<T> static_cast_gc_ptr(const const_gc_ptr<U> &u)
{
	return const_gc_ptr<T>(u, static_cast<static_cast_t*>(0));
}

template<typename T, typename U>gc_ptr<T> const_cast_gc_ptr(const U *u)
{
	return gc_ptr<T>(u, static_cast<const_cast_t*>(0));
}

template<typename T, typename U>gc_ptr<T> const_cast_gc_ptr(const const_gc_ptr<U> &u)
{
	return gc_ptr<T>(u, static_cast<const_cast_t*>(0));
}

/* Managed const array class template */
template<typename T>class const_gc_arr: public pointer_base
{
	protected:
		friend class gc_arr<T>;
		friend class const_wk_arr<T>;
		friend class wk_arr<T>;
#ifndef _SMGC_POOR_TEMPLATES
		friend struct std::less<const_gc_arr<T> >;
		friend struct std::less<gc_arr<T> >;
#endif
		T* ptr;

	public:
		typedef T element_type;

	private:
		typedef pointer_base super;

	protected:
		void reset_node(const T* obj)
		{
			super::reset_node(obj, destructor<T>::destroy_array);
		}

		const_gc_arr(const light_cons_t&) 
		{
		}

	public:
		const_gc_arr(): ptr(0)
		{
		}

		const_gc_arr(const gc_null_t&): ptr(0)
		{
		}

		/*explicit*/ const_gc_arr(const T p[])//: ptr(0)
		{
			reset(p);
		}

#ifndef NDEBUG
		virtual ~const_gc_arr()
		{
			ptr = 0;
		}
#endif

		const_gc_arr& operator = (const gc_null_t&)
		{
			ptr = 0;
			return *this;
		}

		const_gc_arr& operator = (const T p[])
		{
			reset(p);
			return *this;
		}

		const T& operator [] (size_t i) const
		{
			return ptr[i];
		}

		const T* get() const
		{
			return ptr;
		}

		bool operator ! () const
		{
			return ptr == 0;
		}

		operator bool () const
		{
			return ptr != 0;
		}

		bool operator ==(const gc_null_t&) const
		{
			return ptr == 0;
		}

		bool operator !=(const gc_null_t&) const
		{
			return ptr != 0;
		}

		template<typename U>bool operator ==(const const_gc_arr<U> &p) const
		{
			return ptr == p.ptr;
		}

		template<typename U>bool operator !=(const const_gc_arr<U> &p) const
		{
			return ptr != p.ptr;
		}

		template<typename U>bool operator <=(const const_gc_arr<U> &p) const
		{
			return ptr <= p.ptr;
		}

		template<typename U>bool operator >=(const const_gc_arr<U> &p) const
		{
			return ptr >= p.ptr;
		}

		template<typename U>bool operator <(const const_gc_arr<U> &p) const
		{
			return ptr < p.ptr;
		}

		template<typename U>bool operator >(const const_gc_arr<U> &p) const
		{
			return ptr > p.ptr;
		}

		template<typename U>bool operator ==(const U *p) const
		{
			return ptr == p;
		}

		template<typename U>bool operator !=(const U *p) const
		{
			return ptr != p;
		}

		template<typename U>bool operator <=(const U *p) const
		{
			return ptr <= p;
		}

		template<typename U>bool operator >=(const U *p) const
		{
			return ptr >= p;
		}

		template<typename U>bool operator <(const U *p) const
		{
			return ptr < p;
		}

		template<typename U>bool operator >(const U *p) const
		{
			return ptr > p;
		}

		const_gc_arr& operator += (ptrdiff_t d)
		{
			ptr += d;
			return *this;
		}

		const_gc_arr& operator -= (ptrdiff_t d)
		{
			ptr -= d;
			return *this;
		}

		const_gc_arr& operator ++ ()
		{
			++ptr;
			return *this;
		}

		const_gc_arr& operator -- ()
		{
			--ptr;
			return *this;
		}

		const_gc_arr operator ++ (int)
		{
			const_gc_arr<T> old(*this);
			++ptr;
			return old;
		}

		const_gc_arr operator -- (int)
		{
			const_gc_arr<T> old(*this);
			--ptr;
			return old;
		}

		const_gc_arr operator + (ptrdiff_t d) const
		{
			const_gc_arr<T> res(*this);
			res += d;
			return res;
		}

		const_gc_arr operator - (ptrdiff_t d) const
		{
			const_gc_arr<T> res(*this);
			res -= d;
			return res;
		}

		void reset(const T* p=0)
		{
			reset_node(p);
			ptr = const_cast<T*>(p);
		}

		void swap(const_gc_arr &p)
		{
			T* tmp = ptr;
			ptr = p.ptr;
			p.ptr = tmp;
			super::swap(p);
		}
};

/* Managed array class template */
template<typename T>class gc_arr: public const_gc_arr<T>
{
	public:
		typedef T element_type;

	private:
		typedef const_gc_arr<T> super;

	public:
		gc_arr()
		{
		}

		gc_arr(const gc_null_t&)
		{
		}

		/*explicit*/ gc_arr(T p[]): super(light_cons_t())
		{
			reset(p);
		}

#ifndef NDEBUG
		virtual ~gc_arr()
		{
			super::ptr = 0;
		}
#endif

		gc_arr& operator = (const gc_null_t&)
		{
			super::ptr = 0;
			return *this;
		}

		gc_arr& operator = (T p[])
		{
			reset(p);
			return *this;
		}

		T& operator [] (size_t i) const
		{
			return super::ptr[i];
		}

		T* get() const
		{
			return super::ptr;
		}

		gc_arr& operator += (ptrdiff_t d)
		{
			super::ptr += d;
			return *this;
		}

		gc_arr& operator -= (ptrdiff_t d)
		{
			super::ptr -= d;
			return *this;
		}

		gc_arr& operator ++ ()
		{
			++super::ptr;
			return *this;
		}

		gc_arr& operator -- ()
		{
			--super::ptr;
			return *this;
		}

		gc_arr operator ++ (int)
		{
			gc_arr<T> old(*this);
			++super::ptr;
			return old;
		}

		gc_arr operator -- (int)
		{
			gc_arr<T> old(*this);
			--super::ptr;
			return old;
		}

		gc_arr operator + (ptrdiff_t d) const
		{
			gc_arr<T> res(*this);
			res += d;
			return res;
		}

		gc_arr operator - (ptrdiff_t d) const
		{
			gc_arr<T> res(*this);
			res -= d;
			return res;
		}

		void reset(T* p=0)
		{
			reset_node(p);
			super::ptr = /*const_cast<T*>*/(p);
		}

		void swap(gc_arr &p)
		{
			T* tmp = super::ptr;
			super::ptr = p.ptr;
			p.ptr = tmp;
			super::swap(p);
		}
};

template<typename U>bool operator ==(const gc_null_t &l, const const_gc_arr<U> &p)
{
	return p.operator ==(l);
}

template<typename U>
bool operator !=(const gc_null_t &l, const const_gc_arr<U> &p)
{
	return p.operator !=(l);
}

template<typename T, typename U>bool operator ==(const T *l, const const_gc_arr<U> &p)
{
	return p.operator ==(l);
}

template<typename T, typename U>bool operator !=(const T *l, const const_gc_arr<U> &p)
{
	return p.operator !=(l);
}

template<typename T, typename U>bool operator <=(const T *l, const const_gc_arr<U> &p)
{
	return p.operator >=(l);
}

template<typename T, typename U>bool operator >=(const T *l, const const_gc_arr<U> &p)
{
	return p.operator <=(l);
}

template<typename T, typename U>bool operator <(const T *l, const const_gc_arr<U> &p)
{
	return p.operator >(l);
}

template<typename T, typename U>bool operator >(const T *l, const const_gc_arr<U> &p)
{
	return p.operator <(l);
}

template<typename T>const_gc_arr<T> operator +(ptrdiff_t l, const const_gc_arr<T> &p)
{
	return p+l;
}

template<typename T>gc_arr<T> operator +(ptrdiff_t l, const gc_arr<T> &p)
{
	return p+l;
}

/* Const weak pointer template */
template<typename T>class const_wk_ptr: public weak_base
{
#ifdef _SMGC_NO_FRIEND_TEMPLATES
	public:
#else
	protected:
		template<typename U> friend class const_wk_ptr;
		template<typename U> friend class wk_ptr;
#endif
		friend void collect();

		T *ptr;

	public:
		const_wk_ptr(): ptr(0) 
		{
		}

		const_wk_ptr(const gc_null_t&): ptr(0) 
		{
		}

		template<typename U>const_wk_ptr(const const_wk_ptr<U> &p): ptr(implicit_cast<T*>(p.ptr)) 
		{
		}

		template<typename U>const_wk_ptr(const const_gc_ptr<U> &p): ptr(implicit_cast<T*>(p.ptr)) 
		{
		}

		template<typename U>const_wk_ptr(const const_gc_ptr<U> &p, const dynamic_cast_t*):
				ptr(dynamic_cast<T*>(p.ptr)) 
		{
		}

		template<typename U>const_wk_ptr(const const_gc_ptr<U> &p, const static_cast_t*):
				ptr(static_cast<T*>(p.ptr)) 
		{
		}

#ifndef NDEBUG
		virtual ~const_wk_ptr()
		{
			ptr=0;
		}
#endif

		const_wk_ptr<T>& operator = (const gc_null_t&)
		{
			ptr = 0;
			return *this;
		}

		template<typename U>const_wk_ptr<T>& operator = (const const_gc_ptr<U> &p)
		{
			ptr = const_cast<U*>(p.ptr);
			return *this;
		}

		const_gc_ptr<T> get() const
		{
			return const_gc_ptr<T>(ptr);
		}
};

template<typename T>class wk_ptr: public const_wk_ptr<T>
{
	typedef const_wk_ptr<T> super;

	public:
	wk_ptr(const gc_null_t&) 
	{
	}

	template<typename U>
		wk_ptr(const wk_ptr<U> &p): super(p) 
	{
	}

	template<typename U>
		wk_ptr(const gc_ptr<U> &p): super(p) 
	{
	}

	template<typename U>
		wk_ptr(const gc_ptr<U> &p, const dynamic_cast_t*):
			super(p, static_cast<dynamic_cast_t*>(0)) 
	{
	}

	template<typename U>
		wk_ptr(const gc_ptr<U> &p, const static_cast_t*):
			super(p, static_cast<static_cast_t*>(0)) 
	{
	}

	template<typename U>
		wk_ptr(const const_gc_ptr<U> &p, const const_cast_t*):
			super(p) 
	{
	}

	wk_ptr<T>& operator = (const gc_null_t &nt)
	{
		return super::operator=(nt);
	}

	template<typename U>wk_ptr<T>& operator = (const gc_ptr<U> &p)
	{
		super::ptr = const_cast<U*>(p.ptr);
		return *this;
	}

	//using super::get;

	gc_ptr<T> get() const
	{
		return gc_ptr<T>(super::ptr);
	}
};

/* Const weak array template */
template<typename T>class const_wk_arr: public weak_base
{
	protected:
		friend class wk_arr<T>;
		friend void collect();

		T *ptr;

	public:
		const_wk_arr(): ptr(0) 
		{
		}

		const_wk_arr(const gc_null_t&): ptr(0) 
		{
		}

		const_wk_arr(const const_gc_arr<T> &p): ptr(p.ptr) 
		{
		}

#ifndef NDEBUG
		virtual ~const_wk_arr()
		{
			ptr=0;
		}
#endif

		const_wk_arr<T>& operator = (const gc_null_t&)
		{
			ptr = 0;
			return *this;
		}

		const_wk_arr<T>& operator = (const const_gc_arr<T> &p)
		{
			ptr = const_cast<T*>(p.ptr);
			return *this;
		}

		const_gc_arr<T> get() const
		{
			return const_gc_arr<T>(ptr);
		}
};

template<typename T>class wk_arr: public const_wk_arr<T>
{
	typedef const_wk_arr<T> super;

	public:
		wk_arr(const gc_null_t&) 
		{
		}

		template<typename U>wk_arr(const wk_arr<U> &p): super(p) 
		{
		}

		template<typename U>wk_arr(const gc_arr<U> &p): super(p) 
		{
		}

		template<typename U>wk_arr(const const_gc_arr<U> &p, const const_cast_t*):
				super(p) 
		{
		}

		wk_arr<T>& operator = (const gc_null_t &nt)
		{
			return super::operator=(nt);
		}

		wk_arr<T>& operator = (const gc_arr<T> &p)
		{
			super::ptr = const_cast<T*>(p.ptr);
			return *this;
		}

		//using super::get;

		gc_arr<T> get() const
		{
			return gc_arr<T>(super::ptr);
		}
};

gc_null_t NIL;
gc_t GC;
gc_null_t GC_NIL;

template<typename P>struct ptr_rev {
	P *ptr;
	ptr_rev(P *p=0): ptr(p) {}

	ptr_rev& operator=(P *p)
	{
		ptr = p;
		return *this;
	}

	P& operator*() 
	{
	   	return *ptr; 
	}
	
	const P& operator*() const 
	{
	   	return *ptr; 
	}
	
	P* operator->() 
	{
	   	return ptr; 
	}
	
	const P* operator->() const
   	{ 
		return ptr; 
	}

	ptr_rev& operator--() 
	{
	   	++ptr; return *this; 
	}
	
	ptr_rev& operator++() 
	{
	   	--ptr; return *this; 
	}

	ptr_rev operator--(int) 
	{
	   	ptr_rev<P> p=*this; ++ptr; return p; 
	}
	
	ptr_rev operator++(int) 
	{
	   	ptr_rev<P> p=*this; --ptr; return p; 
	}

	ptr_rev& operator-=(ptrdiff_t d) 
	{
	   	ptr+=d; return *this; 
	}
	
	ptr_rev& operator+=(ptrdiff_t d) 
	{
	   	ptr-=d; return *this; 
	}
	
	ptrdiff_t operator-(ptr_rev& p) 
	{
	   	return p.ptr-ptr; 
	}

	bool operator<(const ptr_rev& p) 
	{
	   	return p.ptr < ptr; 
	}
	
	bool operator<=(const ptr_rev& p) 
	{
	   	return p.ptr <= ptr; 
	}
	
	bool operator>(const ptr_rev& p) 
	{
	   	return p.ptr > ptr; 
	}
	
	bool operator>=(const ptr_rev& p) 
	{
	   	return p.ptr >= ptr; 
	}
	
	bool operator==(const ptr_rev& p) 
	{
	   	return p.ptr == ptr; 
	}
	
	bool operator!=(const ptr_rev& p) 
	{
	   	return p.ptr != ptr; 
	}
	
	bool operator==(P *p) 
	{
	   	return p == ptr; 
	}
	
	bool operator!=(P *p) 
	{
	   	return p != ptr; 
	}

};

template<typename P>inline ptr_rev<P> operator+(const ptr_rev<P> &p, ptrdiff_t d)
{
	ptr_rev<P> r = p.ptr-d;
	return r;
}

template<typename P>inline ptr_rev<P> operator+(ptrdiff_t d, const ptr_rev<P> &p)
{
	ptr_rev<P> r = d-p.ptr;
	return r;
}

template<typename P>inline ptr_rev<P> operator-(const ptr_rev<P> &p, ptrdiff_t d)
{
	ptr_rev<P> r = p.ptr+d;
	return r;
}

template<typename P>inline ptr_rev<P> operator-(ptrdiff_t d, const ptr_rev<P> &p)
{
	ptr_rev<P> r = d+p.ptr;
	return r;
}

template<typename P>inline bool operator==(P *l, const ptr_rev<P> &p)
{
	return p.ptr == l;
}

template<typename P>inline bool operator!=(P *l, const ptr_rev<P> &p)
{
	return p.ptr != l;
}


template<typename T>class fastvec {
	size_t len;
	size_t reserved;
	T* data;

	public:
		typedef T& reference;
		typedef const T& const_reference;
		typedef T* pointer;
		typedef const T* const_pointer;
		typedef T value_type;
		typedef size_t size_type;
		typedef ptrdiff_t difference_type;
		typedef T* iterator;
		typedef const T* const_iterator;
		typedef ptr_rev<T> reverse_iterator;
		typedef ptr_rev<const T> const_reverse_iterator;


		fastvec(): 
			len(0)
		{
			reserved = 64;
			data = (static_cast<T*>(malloc(sizeof(T)*(reserved+1))))+1;
		}

		fastvec(size_t r): reserved(r+1024), len(r)
		{
			data = (static_cast<T*>(malloc(sizeof(T)*(reserved+1))))+1;
		}

		fastvec(size_t r, size_t res): reserved(res), len(r)
		{
			data = (static_cast<T*>(malloc(sizeof(T)*(reserved+1))))+1;
		}

		fastvec(const fastvec &f): reserved(f.reserved), len(f.len)
		{
			data = (static_cast<T*>(malloc(sizeof(T)*(reserved+1))))+1;
			memcpy(data, f.data, sizeof(T)*len);
		}

		virtual ~fastvec() 
		{
			free(data-1); 
		}

		fastvec& operator =(const fastvec &f)
		{
			reserved = f.reserved;
			len = f.len;
			data = (static_cast<T*>(realloc(data-1, sizeof(T)*(reserved+1))))+1;
			memcpy(data, f.data, sizeof(T)*(reserved-1));
			return *this;
		}

		void reserve(size_t r)
		{
			reserved = r;
			data = (static_cast<T*>(realloc(data-1, sizeof(T)*(reserved+1))))+1;
		}

		void erase(iterator w)
		{
			iterator e = data+len;//-1;
			if(w == e/*+1*/)
			{
				return;
			}
			//else if(w == e)
			//{
			//  len--;
			//  return;
			//}
			for(;w!=e; ++w)
			{
				*w = *(w+1);
			}
			if(len*4+4096 < reserved)
				reserve(len*2+2048);
			len--;
		}

		void erase(iterator f, iterator l)
		{
			if(f == l)
				return;
			ptrdiff_t d = l-f;
			iterator e = data+len;
			for(;l!=e; ++l)
			{
				*f++ = *l;
			}
			len -= d;
			if(len*4+4096 < reserved)
				reserve(len*2+2048);
		}

		void push_back(const_reference val)
		{
			if(len >= reserved)
				reserve(len*2+2048);
			data[len++] = val;
		}

		void pop_back()
		{
			if(len*4+4096 < reserved)
				reserve(len*2+2048);
			--len;
		}

		void resize(size_t r)
		{
			len = r;
			if(len >= reserved)
				reserve(len*2+2048);
		}

		void clear() 
		{
		   	len = 0; 
		}

		operator pointer() 
		{
		   	return data; 
		}
		
		operator const_pointer() const 
		{
		   	return data; 
		}

		size_t size() const 
		{
		   	return len; 
		}
		
		size_t capacity() const 
		{
		   	return reserved; 
		}
		
		bool empty() const 
		{
		   	return len == 0; 
		}

		reference front() 
		{
		   	return *data; 
		}
		
		const_reference front() const 
		{
		   	return *data; 
		}
		
		reference back() 
		{
		   	return data[len-1]; 
		}
		
		const_reference back() const 
		{
		   	return data[len-1]; 
		}

		iterator begin() 
		{
		   	return data; 
		}
		
		const_iterator begin() const 
		{
		   	return data; 
		}
		
		reverse_iterator rbegin() 
		{
		   	return data+len-1; 
		}
		
		const_reverse_iterator rbegin() const 
		{
		   	return data+len-1; 
		}

		iterator end() 
		{
		   	return data+len; 
		}
		
		const_iterator end() const 
		{
		   	return data+len; 
		}
	
		reverse_iterator rend() 
		{
		   	return data-1; 
		}
	
		const_reverse_iterator rend() const 
		{
		   	return data-1; 
		}

};

struct node_t: public node_base {
	node_t(const void* obj, size_t n, bool intern);

	virtual ~node_t() 
	{
	}

	bool contains(const void* obj);

	const void* base;
	size_t size;
	bool mark;
	bool internal;
	void* object;
	void (*destroy)(void*, void*, size_t);

	static void kill(node_t *node);
	static void* operator new(size_t s);
	static void* operator new(size_t s, void *place);
	static void operator delete(void *n);
	static void operator delete(void *n, void *place) {}
};

struct node_less {
	bool operator()(const node_t* x, const node_t* y) const
	{
		//return (static_cast<const char*>(x->base) + x->size) <= static_cast<const char*>(y->base);
		static const std::less<const void*> cmp = std::less<const void*>();
		return !cmp(static_cast<const char*>(y->base), static_cast<const char*>(x->base) + x->size);
	}
} node_cmp;

typedef std::pair<pointer_base*, node_t*> ptr_pair;
typedef std::pair<weak_base*, node_t*> weak_pair;
typedef fastvec<ptr_pair> ptr_vector;
typedef fastvec<node_t*> node_vector;
typedef fastvec<weak_pair> weak_vector;
typedef std::deque<ptr_vector::iterator> ptr_queue;

struct data_t {
	data_t(): 
		threshold(default_threshold), 
		dynamic_threshold(default_threshold), 
		allocated(0), 
		collecting(false), 
		current_mark(false)
	{ 
		// InitializeCriticalSection(&cs);
		// cs=false;
	}

	virtual ~data_t()
	{
		// If there is something to collect, then we do collections until
		// nothing could be freed anymore
		size_t pre = old_nodes.size() + new_nodes.size() + born_nodes.size();
		if(pre)
		{
			size_t post = pre;
			do
			{
				pre = post;
				collect();
				post = old_nodes.size() + new_nodes.size() + born_nodes.size();
			} while(post < pre && post != 0);
			pre = post;
		}

		// After final collection we clean up remaining undeleted nodes,
		// but do not call destructors of objects belonging to them
		if(pre) {
			node_vector::iterator end = old_nodes.end();
			for(node_vector::iterator i=old_nodes.begin(); i<end; ++i)
			{
				(*i)->destroy = 0;
				node_t::kill(*i);
			}
			end = new_nodes.end();
			for(node_vector::iterator j=new_nodes.begin(); j<end; ++j)
			{
				(*j)->destroy = 0;
				node_t::kill(*j);
			}
			end = born_nodes.end();
			for(node_vector::iterator k=born_nodes.begin(); k<end; ++k)
			{
				(*k)->destroy = 0;
				node_t::kill(*k);
			}
		}
		/*DeleteCriticalSection(&cs);*/
	}

	ptr_vector old_pointers;
	ptr_vector new_pointers;
	weak_vector weak_pointers;
	//node_set nodes;
	node_vector old_nodes;
	node_vector new_nodes;
	node_vector born_nodes;
	size_t threshold;
	size_t dynamic_threshold;
	size_t allocated;
	bool collecting;
	bool current_mark;
	//CRITICAL_SECTION cs;
	/*bool cs;*/
};

data_t& data() 
{
   	static data_t instance; return instance; 
}

struct data_lock {
	data_lock() 
	{ 
		/*EnterCriticalSection(&data().cs);*//*if(data().cs) throw "double lock"; data().cs=true;*/ 
	}
	
	virtual ~data_lock() 
	{
		// LeaveCriticalSection(&data().cs);
		// data().cs=false;
	}
};

node_t::node_t(const void* obj, /*int*/size_t node, bool intern=false): 
	base(obj), size(node), /*mark(data().current_mark),*/ internal(intern), object(0), destroy(0)
{
}

void node_t::kill(node_t *node)
{
	bool internal = node->internal;
	if(node->object && node->destroy)
		node->destroy(node->object, const_cast<void*>(node->base), node->size);
	if(!internal)
		free(static_cast<void*>(node));
}

bool node_t::contains(const void* obj)
{
	static const std::less<const void*> cmp = std::less<const void*>();
	if(cmp(obj, base))
		return false;
	return cmp(obj, static_cast<const char*>(base) + size);
}

void * node_t::operator new(size_t s)
{
	void *res = malloc(s);
	if(res == 0)
		throw std::bad_alloc();
	return res;
}

void * node_t::operator new(size_t s, void *place)
{
	return place;
}

void node_t::operator delete(void *n)
{
#ifndef NDEBUG
	std::cerr << "Internal error -- badly written software" << std::endl;
	abort();
#endif
}

node_t* find_node(const void* obj)
{
	// Construct a temporary node in order to search for the object's node.
	node_t temp(obj, 0);

	// Use lower_bound to search for the "insertion point" and determine
	// if the node at this point contains the specified object.  If the
	// insertion point is at the end or does not contain the object then
	// we've failed to find the node and return an iterator to the end.
	node_vector::iterator i = std::lower_bound(data().new_nodes.begin(), data().new_nodes.end(), &temp, node_cmp);
	if(i == data().new_nodes.end() || !(*i)->contains(obj))
	{
		i = std::lower_bound(data().old_nodes.begin(), data().old_nodes.end(), &temp, node_cmp);
		if (i == data().old_nodes.end() || !(*i)->contains(obj))
			return NULL;
	}
	// Return the found iterator.
	return *i;
}

node_t* find_new_node(const void* obj)
{
	// Construct a temporary node in order to search for the object's node.
	node_t temp(obj, 0);

	// Use lower_bound to search for the "insertion point" and determine
	// if the node at this point contains the specified object.  If the
	// insertion point is at the end or does not contain the object then
	// we've failed to find the node and return an iterator to the end.
	node_vector::iterator i = std::lower_bound(data().new_nodes.begin(), data().new_nodes.end(), &temp, node_cmp);
	if(i == data().new_nodes.end() || !(*i)->contains(obj))
		return NULL;

	// Return the found iterator.
	return *i;
}

node_vector::iterator find_born_node(const void* obj)
{
	node_vector::iterator e = data().born_nodes.end();
	for(node_vector::iterator i = data().born_nodes.begin(); i!=e; ++i)
	{
		if((*i)->contains(obj))
			return i;
	}
	return e;
}

void get_node(const void* obj, void (*destroy)(void*, void*, size_t))
{
	if(!obj)
		return;

	//data_lock lock; -- podwójny lock -- po co???

	node_vector::iterator i = find_born_node(obj);
	if(i != data().born_nodes.end())
	{
		node_t* node = *i;

		data().new_nodes.push_back(node);
		data().born_nodes.erase(i);
		node->mark = data().current_mark;
		node->destroy = destroy;
		node->object = const_cast<void*>(obj);
	}
}

void mark(ptr_vector::iterator i, ptr_queue &que)
{
	// Mark the node associated with the pointer and then iterate
	// through all pointers contained by the object pointed to and
	// add them to the queue for later marking.
	node_t* node = i->second;
	if(node && node->mark != data().current_mark)
	{
		node->mark = data().current_mark;
		ptr_vector::iterator j = lower_bound(data().old_pointers.begin(),
				data().old_pointers.end(),
				ptr_pair(static_cast<pointer_base*>(const_cast<void*>(node->base)),0));
		ptr_vector::iterator end = data().old_pointers.end();
		for(; j != end; ++j)
		{
			if (node->contains(j->first))
				que.push_back(j);
			else
				break;
		}
	}
}

void presort_ptr_vect(ptr_vector::iterator begin, ptr_vector::iterator end)
{
	static const std::less<pointer_base*> cmp = std::less<pointer_base*>();
	if(end-begin < 16)
		return;

	ptr_vector::iterator i = begin+((end-begin)>>1);
	ptr_pair pivot = *i;
	*i = *begin;
	*begin = pivot;
	i = begin;

	ptr_vector::iterator j = end;
	register pointer_base* piv = pivot.first;
	ptr_pair p;

	while(i<j)
	{
		do
		{
			++i;
		} while(i<end && cmp(i->first, piv));
		do
		{
			--j;
		} while(cmp(piv, j->first)/* j>begin && ... -- this is not needed as piv==*begin */);

		if(i<j)
		{
			p = *i;
			*i = *j;
			*j = p;
		}
	}
	*begin = *j;
	*j = pivot;

	presort_ptr_vect(begin, j);
	presort_ptr_vect(j+1, end);
}

void sort_ptr_vect(ptr_vector &v)
{
	static const std::less<pointer_base*> cmp = std::less<pointer_base*>();

	ptr_vector::iterator begin = v.begin();
	ptr_vector::iterator end = v.end();

	if(end-begin < 32)
	{
		sort(begin, end);
		return;
	}

	presort_ptr_vect(begin, end);

	ptr_vector::iterator i = begin+1;
	ptr_vector::iterator j;
	ptr_pair p = *begin;
	for(j=i; j<begin+17; ++j)
	{
		if(cmp(j->first, p.first))
			p = *j;
	}
	*(begin-1) = p; // this is perfectly legal with fastvect

	while(i<end)
	{
		if(cmp(i->first, (i-1)->first))
		{
			j = i-1;
			p = *i;
			while(cmp(p.first, j->first))
			{
				*(j+1) = *j;
				--j;
			}
			*(j+1) = p;
		}
		++i;
	}

#ifndef NDEBUG
	p = *begin;
	for(i=begin+1; i<end; ++i)
	{
		//if(cmp(i->first, p.first))
		if(i->first <= p.first && p.first)
		{
			throw jcommon::RuntimeException("smartpointer order lost");
			//cerr << "Order lost at " << (i-begin) << endl;
			//abort();
		}
		p = *i;
	}
#endif
}

void presort_node_vect(node_vector::iterator begin, node_vector::iterator end)
{
	if(end-begin < 16)
		return;

	node_vector::iterator i = begin+((end-begin)>>1);
	node_t *pivot = *i;
	*i = *begin;
	*begin = pivot;
	i = begin;

	node_vector::iterator j = end;
	node_t *p;

	while(i<j)
	{
		do
		{
			++i;
		} while(i<end && node_cmp(*i, pivot));
		do
		{
			--j;
		} while(node_cmp(pivot, *j)/* j>begin && ... -- this is not needed as piv==*begin */);

		if(i<j)
		{
			p = *i;
			*i = *j;
			*j = p;
		}
	}
	*begin = *j;
	*j = pivot;

	presort_node_vect(begin, j);
	presort_node_vect(j+1, end);
}

void sort_node_vect(node_vector &v)
{
	node_vector::iterator begin = v.begin();
	node_vector::iterator end = v.end();

	if(end-begin < 32)
	{
		std::sort(begin, end, node_cmp);
		return;
	}

	presort_node_vect(begin, end);

	node_vector::iterator i = begin+1;
	node_vector::iterator j;
	node_t *p = *begin;
	for(j=i; j<begin+17; ++j)
	{
		if(node_cmp(*j, p))
			p = *j;
	}
	*(begin-1) = p; // this is perfectly legal with fastvect

	while(i<end)
	{
		if(node_cmp(*i, *(i-1)))
		{
			j = i-1;
			p = *i;
			while(node_cmp(p, *j))
			{
				*(j+1) = *j;
				--j;
			}
			*(j+1) = p;
		}
		++i;
	}
}

void clean_merge_ptr()
{
	// Clean old_pointers pulling off null references then
	// sort new_pointers and merge it into old_pointers

	ptr_vector &ops = data().old_pointers;
	ptr_vector &nps = data().new_pointers;

	sort_ptr_vect(nps);

	ptr_vector::iterator o = ops.begin();
	ptr_vector::iterator end = ops.end();
	for(ptr_vector::iterator i = o; i != end; ++i)
	{
		if(i->first != 0)
			*o++ = *i;
	}
	ops.erase(o, ops.end());
	ops.resize(ops.size()+nps.size()/*, ptr_pair(0,0)*/);

	// We do our own merge, not merge algorithm, because
	// we don't want to create new old_pointers vector
	// everytime, nor we want to go for inplace_merge, as
	// it'd be slow.
	ptr_vector::reverse_iterator r = ops.rbegin()+nps.size();
	ptr_vector::reverse_iterator n = nps.rbegin();
	size_t os = ops.size();

#ifdef _WIN32
	if (os > INT_MAX)
#else
	if ((int)os > std::numeric_limits<int>::max())
#endif
		throw jcommon::RuntimeException("No space exception");

	int s = (int)os;
	while(r != ops.rend() && n != nps.rend()) {
		--s;
		if(*r > *n)
			ops[s] = *r++;
		else
			ops[s] = *n++;
		ops[s].first->pos = -1-s;
	}

	while(r != ops.rend()) {
		--s;
		ops[s] = *r++;
		ops[s].first->pos = -1-s;
	}

	while(n != nps.rend()) {
		--s;
		ops[s] = *n++;
		ops[s].first->pos = -1-s;
	}
#ifndef NDEBUG
	if(s != 0)
		throw jcommon::RuntimeException("internal error in ptr_vectors merge");
	void *old = 0;
	end = ops.end();
	for(ptr_vector::iterator c = ops.begin(); c != end; ++c)
	{
		ASSERT_PTR_VALID(*(c->first));
		if(c->first == old)
			throw jcommon::RuntimeException("duplicated pointer");
		else if(c->first < old)
			throw jcommon::RuntimeException("pointer order lost");
		old = c->first;
	}
#endif
	nps.clear();
}

void clean_merge_nodes(size_t new_sweeped_out)
{
	// Clean old_nodes pulling off null references then
	// merge old_nodes into new_nodes

	node_vector &onv = data().old_nodes;
	node_vector &nnv = data().new_nodes;

	node_vector::iterator o = onv.begin();
	node_vector::iterator end = onv.end();
	for(node_vector::iterator i = o; i != end; ++i)
	{
		if(*i != 0)
			*o++ = *i;
	}
	onv.erase(o, onv.end());
	onv.resize(onv.size()+nnv.size()-new_sweeped_out);

	// We do our own merge, not merge algorithm, because
	// we don't want to create new old_pointers vector
	// everytime, nor we want to go for inplace_merge, as
	// it'd be slow.
	node_vector::reverse_iterator r = onv.rbegin()+(nnv.size()-new_sweeped_out);
	node_vector::reverse_iterator n = nnv.rbegin();
	size_t s = onv.size();
	while(r != onv.rend() && n != nnv.rend())
	{
		if(*n == 0)
		{
			n++;
			continue;
		}
		--s;
		if(node_cmp(*n, *r))
			onv[s] = *r++;
		else
			onv[s] = *n++;
	}
	while(r != onv.rend())
	{
		--s;
		onv[s] = *r++;
	}
	while(n != nnv.rend())
	{
		if(*n == 0)
		{
			n++;
			continue;
		}
		--s;
		onv[s] = *n++;
	}
#ifndef NDEBUG
	if(s != 0)
		throw jcommon::RuntimeException("internal error in node_sets merge");
	node_t *old = 0;
	end = onv.end();
	for(node_vector::iterator c = onv.begin(); c != end; ++c)
	{
		if(*c == old)
			throw jcommon::RuntimeException("duplicated node");
		else if(old && !node_cmp(old, *c))
			throw jcommon::RuntimeException("node order lost");
		old = *c;
	}
#endif
	nnv.clear();
}

template<class A>void* gnew(size_t size, const A& a)
{
	data_lock lock;

	bool collected = false;

	if (data().threshold != no_threshold) {
		// Determine if we've exceeded the threshold and so should collect.
		data().allocated += size;
		if (data().allocated > data().dynamic_threshold)
		{
			collect();
			collected = true;
		}
	}

	// Attempt the first allocation.  The standard requires new to throw
	// on failure but user code may change this behavior and VC++ by default
	// only returns 0.  We'll catch exceptions and if we've already collected
	// re-throw the exception.
	void* obj = 0;
	try {
	   	obj = a.alloc(size); 
	} catch(std::bad_alloc&) { 
		if (collected) throw; 
	}

	// If we've failed to allocate but new didn't throw an exception and we've
	// not collected yet we'll collect and then re-try calling new.  If new
	// throws at this point we'll ignore it and let the caller handle it.
	if (obj == 0 && !collected) {
		collect();
		obj = a.alloc(size);
	}

	// If we actually allocated memory then we need to add it to the node map.
	try {
		if (obj != 0) {
			node_t *node;
			if(a.internal_node())
				node = new(static_cast<void*>(static_cast<char*>(obj)+a.node_offset(size))) node_t(obj, size, true);
			else
				node = new node_t(obj, size);
			if(node == 0) // Dealing with VC++ 6.0 quirk
				throw std::bad_alloc();
			data().born_nodes.push_back(node);
		}
	} catch (...) {
		// If inserting into the map failed clean up and simply throw
		// a bad_alloc exception.
		a.free(obj);
		throw std::bad_alloc();
	}

	return obj;
}

template<class A>void gfree(void* obj, const A &a)
{
	data_lock lock;

	// Theoretically, none of this code will throw an exception.
	// If an exception occurs the best we can do is assume that
	// everything worked any way and ignore the exception.
	try
	{
		node_vector::iterator i = find_born_node(obj);
		node_t* node = *i;
		if (node)
			data().born_nodes.erase(i);

		// This operator really should only be called when
		// construction of an object fails, in which case
		// there won't be a "registered destructor" and the
		// following will only delete the node.
		node_t::kill(node);
	}
	catch (...)
	{
	}

	// Because there was no "registered destructor" we'll still
	// need to delete the memory allocated by operator new(GC).
	a.free(obj);
}

struct alloc_single_t {
	static void *alloc(size_t s)
	{
		return ::operator new(node_offset(s) + sizeof(node_t));
	}

	static void free(void *obj)
	{
		::operator delete(obj);
	}

	static size_t node_offset(size_t s)
	{
		size_t r = ((s+sizeof(void(*)())-1) / sizeof(void(*)())) * sizeof(void(*)());
		if(r>2000000000u) abort();
		return r;
	}

	static bool internal_node()
	{
		return true;
	}
};

alloc_single_t alloc_single;

#ifndef _SMGC_NO_ARRAY_NEW
struct alloc_array_t {
	static void *alloc(size_t s)
	{
		return ::operator new[](s);
	}

	static void free(void *obj)
	{
		::operator delete[](obj);
	}

	static size_t node_offset(size_t s)
	{
		return 0;
	}

	static bool internal_node()
	{
		return false;
	}
};

alloc_array_t alloc_array;
#endif

pointer_base::pointer_base()
{
	data_lock lock;

#ifndef NDEBUG
	destroyed = false;
#ifdef DEBUG_COMPILER
	trash = new char[1];
#endif
#endif
	ptr_vector &ps = data().new_pointers;
	pos = ps.size();
	ps.push_back(ptr_pair(this, 0));
}

pointer_base::pointer_base(const pointer_base &pb)
{
	data_lock lock;

#ifndef NDEBUG
	destroyed = false;
#ifdef DEBUG_COMPILER
	trash = new char[3];
#endif
#endif
	ptr_vector &ps = data().new_pointers;
	pos = ps.size();
	/*if(pb.pos >= 0)
	  ps.push_back(ptr_pair(this, ps[pb.pos].second));
	  else
	  ps.push_back(ptr_pair(this, data().old_pointers[-1-pb.pos].second));
	  */
	ps.push_back(ptr_pair(this, 0));
}

pointer_base::~pointer_base()
{
	data_lock lock;

#ifndef NDEBUG
#ifdef DEBUG_COMPILER
	delete[] trash;
#endif
	destroyed = true;
#endif
	if(pos >= 0)
	{
		ptr_vector &ps = data().new_pointers;
		if (pos == (int)(ps.size()-1)) {
			ps.pop_back();
		} else {
			ps[pos] = ps.back();
#ifndef NDEBUG
			if(ps[pos].first->pos != (int)(ps.size()-1)) {
				//cerr << "GC: memory corrupted; smartpointer lost!" << endl;
				//abort();
				throw jcommon::RuntimeException("smartpointer lost");
			}

			if(ps[pos].first->destroyed) {
				//cerr << "GC: memory corrupted; smartpointer destructed 2 times or overwritten!" << endl;
				//abort();
				throw jcommon::RuntimeException("smartpointer overwritten or double destructed");
			}
#endif
			ps[pos].first->pos = pos;
			ps.pop_back();
		}
	} else {
		data().old_pointers[-1-pos].first = 0;
	}
}

void pointer_base::reset_node(const void* obj, void (*destroy)(void*, void*, size_t))
{
	data_lock lock;
	get_node(obj, destroy);
}

weak_base::weak_base()
{
	data_lock lock;

#ifndef NDEBUG
	destroyed = false;
#ifdef DEBUG_COMPILER
	trash = new char[2];
#endif
#endif
	weak_vector &ps = data().weak_pointers;
	pos = ps.size();
	ps.push_back(weak_pair(this, 0));
}

weak_base::weak_base(const weak_base &pb)
{
	data_lock lock;

#ifndef NDEBUG
	destroyed = false;
#ifdef DEBUG_COMPILER
	trash = new char[4];
#endif
#endif
	weak_vector &ps = data().weak_pointers;
	pos = ps.size();
	ps.push_back(weak_pair(this, 0));
}

weak_base::~weak_base()
{
	data_lock lock;

#ifndef NDEBUG
#ifdef DEBUG_COMPILER
	delete[] trash;
#endif
	destroyed = true;
#endif
	weak_vector &ps = data().weak_pointers;
	if(pos == (int)(ps.size()-1)) {
		ps.pop_back();
	} else {
		ps[pos] = ps.back();
#ifndef NDEBUG
		if(ps[pos].first->pos != (int)(ps.size()-1)) {
			throw jcommon::RuntimeException("weakpointer lost");
		}

		if(ps[pos].first->destroyed) {
			throw jcommon::RuntimeException("weakpointer overwritten or double destructed");
		}
#endif
		ps[pos].first->pos = pos;
		ps.pop_back();
	}
}

// Register memory area in GC. Area must be freeable using supplied destroy function
void reg(void *obj, size_t size, void (*destroy)(void*, void*, size_t))
{
	data_lock lock;

	bool collected = false;

	if (data().threshold != no_threshold)
	{
		// Determine if we've exceeded the threshold and so should collect.
		data().allocated += size;
		if (data().allocated > data().dynamic_threshold)
		{
			collect();
			collected = true;
		}
	}

	// If we actually allocated memory then we need to add it to the node map.
	try
	{
		if (obj != 0)
		{
			node_t *node = new node_t(obj, size);
			if(node == 0)
				throw std::bad_alloc();
			data().new_nodes.push_back(node);
			node->destroy = destroy;
			node->object = const_cast<void*>(obj);
		}
	}
	catch (...)
	{
		// If inserting into the map failed simply throw
		// a bad_reg exception.
		throw jcommon::RuntimeException("Bad reg exception");
	}
}

#if (defined(_MSC_VER) && (_MSVC <= 1200)) || defined(_SMGC_POOR_STL)
const size_t no_threshold = ~((size_t)0);
#else
const size_t no_threshold = std::numeric_limits<size_t>::max();
#endif

const size_t default_threshold = (INT_MAX>=4194304*8)?4194304:(INT_MAX/8);

void collect()
{
	data_lock lock;

	// During the sweep phase we'll be deleting objects that could cause
	// a recursive call to 'collect' which would cause invalid results.  So
	// we prevent recursion here.
	if (data().collecting)
		return;

	data().collecting = true;

#ifndef NDEBUG
	//cerr << "Allocated: " << data().allocated << endl;
#endif

	// Toggle the 'current_mark' so that we can start over.
	data().current_mark = !data().current_mark;
	bool current_mark = data().current_mark;

	{ // Mark phase
		// Loop through all of the pointers looking for 'root' pointers.  A 'root'
		// pointer is a pointer that's not contained within the object pointed
		// to by any other pointer.  When a 'root' pointer is found it is
		// marked, and all the pointers referenced through the 'root' pointer
		// are also marked.
		clean_merge_ptr();
		//sort(data().new_nodes.begin(), data().new_nodes.end(), node_cmp);
		sort_node_vect(data().new_nodes);

		ptr_vector::iterator end = data().old_pointers.end();
		for(ptr_vector::iterator i = data().old_pointers.begin(); i != end; ++i)
		{
			pointer_base* ptr = i->first;
			if(!(reinterpret_cast<gc_ptr<void*>& >(*ptr)).ptr)
			{
				i->second = 0;
				continue;
			}
			node_t* node = i->second;
			if(!node || !node->contains((reinterpret_cast<gc_ptr<void*>& >(*ptr)).ptr))
			{
				node = find_node((reinterpret_cast<gc_ptr<void*>& >(*ptr)).ptr);
				//#ifndef NDEBUG
				//          if(!node)
				//          {
				//            //cerr << "Pointer points to nonsensical address" << endl;
				//            //abort();
				//            throw mem_corrupt("smartpointer points to nonsense address");
				//          }
				//#endif
				i->second = node;
			}
		}
		ptr_queue que;
		for(ptr_vector::iterator ii = data().old_pointers.begin(); ii != end; ++ii)
		{
			node_t* node = ii->second;
			if (!node || node->mark == current_mark)
				continue; // Don't need to check pointers that are marked.

			// If we can't find a node that contains the pointer it's a root pointer
			// and should be marked.
			node = find_node(ii->first);
			if (!node)
				que.push_back(ii);
		}
		while(que.size())
		{
			mark(que.front(), que);
			que.pop_front();
		}
		// Nullify weak pointers pointing to unmarked nodes
		weak_vector::iterator weak_end = data().weak_pointers.end();
		for(weak_vector::iterator j = data().weak_pointers.begin(); j != weak_end; ++j)
		{
			weak_base* ptr = j->first;
			if(!(reinterpret_cast<wk_ptr<void*>& >(*ptr)).ptr)
			{
				j->second = 0;
				continue;
			}
			node_t* node = j->second;
			if(!node || !node->contains((reinterpret_cast<wk_ptr<void*>& >(*ptr)).ptr))
			{
				node = find_node((reinterpret_cast<wk_ptr<void*>& >(*ptr)).ptr);
				j->second = node;
			}
			if(!node || node->mark != current_mark)
				reinterpret_cast<wk_ptr<void*>& >(*ptr).ptr = 0;
		}
	}

	{ // Sweep phase
		// Step through all of the nodes and delete any that are not marked.
		node_vector::iterator i;
		node_vector::iterator end = data().new_nodes.end();
		size_t nnsweep = 0;
		size_t freed = 0;
		size_t remain = 0;
		for (i = data().new_nodes.begin(); i != end; /*nothing*/)
		{
			node_t* node = *i;
			remain += node->size;
			if (node->mark != current_mark)
			{
				if (node->destroy == 0)
				{
					// We must be constructing this object, so we'll just mark it.
					// This prevents premature collection of objects that call
					// gc_collect during the construction phase before any gc_ptr<>'s
					// are assigned to the object.
					node->mark = current_mark;
				}
				else
				{
					++nnsweep;
					freed += node->size;
					*i = 0;
					node_t::kill(node);
				}
			}
			++i;
		}
		end = data().old_nodes.end();
		for (i = data().old_nodes.begin(); i != end; /*nothing*/)
		{
			node_t* node = *i;
			remain += node->size;
			if (node->mark != current_mark)
			{
				if (node->destroy == 0)
				{
					// We must be constructing this object, so we'll just mark it.
					// This prevents premature collection of objects that call
					// gc_collect during the construction phase before any gc_ptr<>'s
					// are assigned to the object.
					node->mark = current_mark;
				}
				else
				{
					freed += node->size;
					*i = 0;
					node_t::kill(node);
				}
			}
			++i;
		}
		remain -= freed;

		clean_merge_nodes(nnsweep);

		if(data().threshold != no_threshold && data().threshold > 0)
		{
			if(data().dynamic_threshold < freed/2 && data().dynamic_threshold > data().threshold/2)
			{
				data().dynamic_threshold /= 2;
			}
			else if(data().dynamic_threshold < freed/2 && data().dynamic_threshold > data().threshold/4)
			{
				data().dynamic_threshold = data().threshold/4;
			}
			else if(data().dynamic_threshold > remain && data().dynamic_threshold > data().threshold)
			{
				data().dynamic_threshold /= 4;
			}
			else if(data().dynamic_threshold > remain && data().dynamic_threshold > data().threshold/4)
			{
				data().dynamic_threshold = data().threshold/4;
			}
			else if(data().dynamic_threshold < remain/4)
			{
				data().dynamic_threshold *= 2;
			}
			else if(data().dynamic_threshold > freed/16)
			{
				data().dynamic_threshold *= 4;
			}
			else if(data().dynamic_threshold > freed/4)
			{
				data().dynamic_threshold *= 2;
			}
		}
	}

	data().collecting = false;
	data().allocated = 0;
}

void set_threshold(size_t bytes)
{
	data_lock lock;
	data().threshold = bytes;
	data().dynamic_threshold = bytes;
}

size_t get_threshold()
{
	data_lock lock;
	return data().threshold;
}

size_t get_dynamic_threshold()
{
	data_lock lock;
	return data().dynamic_threshold;
}

}

namespace std {
#ifdef _SMGC_POOR_TEMPLATES
	struct less<pointer_base>
	{
		bool operator()(const pointer_base &l, const pointer_base &p)
		{
			static less<void**> cmp;
			ASSERT_PTR_VALID(l);
			ASSERT_PTR_VALID(p);
			return cmp((reinterpret_cast<const const_gc_ptr<void*>&>(l)).ptr, (reinterpret_cast<const const_gc_ptr<void*>&>(p)).ptr);
		}
	};
#else

	template<typename T>
		struct less<jcommon::const_gc_ptr<T> >
		{
			bool operator()(const jcommon::const_gc_ptr<T> &l, const jcommon::const_gc_ptr<T> &p)
			{
				static less<T> cmp;
				ASSERT_PTR_VALID(l);
				ASSERT_PTR_VALID(p);
				return cmp(l.ptr, p.ptr);
			}
		};

	template<typename T>
		struct less<jcommon::gc_ptr<T> >
		{
			bool operator()(const jcommon::gc_ptr<T> &l, const jcommon::gc_ptr<T> &p)
			{
				static less<T> cmp;
				ASSERT_PTR_VALID(l);
				ASSERT_PTR_VALID(p);
				return cmp(l.ptr, p.ptr);
			}
		};

	template<typename T>
		struct less<jcommon::const_gc_arr<T> >
		{
			bool operator()(const jcommon::const_gc_arr<T> &l, const jcommon::const_gc_arr<T> &p)
			{
				static less<T> cmp;
				ASSERT_PTR_VALID(l);
				ASSERT_PTR_VALID(p);
				return cmp(l.ptr, p.ptr);
			}
		};

	template<typename T>
		struct less<jcommon::gc_arr<T> >
		{
			bool operator()(const jcommon::gc_arr<T> &l, const jcommon::gc_arr<T> &p)
			{
				static less<T> cmp;
				ASSERT_PTR_VALID(l);
				ASSERT_PTR_VALID(p);
				return cmp(l.ptr, p.ptr);
			}
		};
#endif
}

#ifndef _SMGC_NO_PLACEMENT_NEW
void* operator new(size_t s, const jcommon::gc_t&) throw (std::bad_alloc);
void operator delete(void *obj, const jcommon::gc_t&) throw ();
#ifndef _SMGC_NO_ARRAY_NEW
void* operator new[](size_t s, const jcommon::gc_t&) throw (std::bad_alloc);
void operator delete[](void *obj, const jcommon::gc_t&) throw ();
#endif
#endif

#undef GC_INTERNAL

#ifndef _SMGC_NO_PLACEMENT_NEW
void* operator new(size_t s, const jcommon::gc_t&) throw (std::bad_alloc)
{
	return gnew(s, jcommon::alloc_single);
}

void operator delete(void *obj, const jcommon::gc_t&) throw ()
{
	gfree(obj, jcommon::alloc_single);
}

#ifndef _SMGC_NO_ARRAY_NEW
void* operator new[](size_t s, const jcommon::gc_t&) throw (std::bad_alloc)
{
	return gnew(s, jcommon::alloc_array);
}

void operator delete[](void *obj, const jcommon::gc_t&) throw ()
{
	gfree(obj, jcommon::alloc_array);
}

#endif
#endif

#endif