summaryrefslogtreecommitdiff
path: root/src/common/db.c
blob: c28ad1f7c5e0c5e9a2d8224728e8be7e83c0f803 (plain) (blame)
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
/**
 * This file is part of Hercules.
 * http://herc.ws - http://github.com/HerculesWS/Hercules
 *
 * Copyright (C) 2012-2018  Hercules Dev Team
 * Copyright (C)  Athena Dev Teams
 *
 * Hercules 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 3 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, see <http://www.gnu.org/licenses/>.
 */

/*****************************************************************************\
 *  This file is separated in five sections:
 *  (1) Private enums, structures, defines and global variables
 *  (2) Private functions
 *  (3) Protected functions used internally
 *  (4) Protected functions used in the interface of the database
 *  (5) Public functions
 *
 *  The databases are structured as a hashtable of RED-BLACK trees.
 *
 *  <B>Properties of the RED-BLACK trees being used:</B>
 *  1. The value of any node is greater than the value of its left child and
 *     less than the value of its right child.
 *  2. Every node is colored either RED or BLACK.
 *  3. Every red node that is not a leaf has only black children.
 *  4. Every path from the root to a leaf contains the same number of black
 *     nodes.
 *  5. The root node is black.
 *  An <code>n</code> node in a RED-BLACK tree has the property that its
 *  height is <code>O(lg(n))</code>.
 *  Another important property is that after adding a node to a RED-BLACK
 *  tree, the tree can be readjusted in <code>O(lg(n))</code> time.
 *  Similarly, after deleting a node from a RED-BLACK tree, the tree can be
 *  readjusted in <code>O(lg(n))</code> time.
 *  {@link http://www.cs.mcgill.ca/~cs251/OldCourses/1997/topic18/}
 *
 *  <B>How to add new database types:</B>
 *  1. Add the identifier of the new database type to the enum DBType
 *  2. If not already there, add the data type of the key to the union DBKey
 *  3. If the key can be considered NULL, update the function db_is_key_null
 *  4. If the key can be duplicated, update the functions db_dup_key and
 *     db_dup_key_free
 *  5. Create a comparator and update the function db_default_cmp
 *  6. Create a hasher and update the function db_default_hash
 *  7. If the new database type requires or does not support some options,
 *     update the function db_fix_options
 *
 *  TODO:
 *  - create test cases to test the database system thoroughly
 *  - finish this header describing the database system
 *  - create custom database allocator
 *  - make the system thread friendly
 *  - change the structure of the database to T-Trees
 *  - create a db that organizes itself by splaying
 *
 *  HISTORY:
 *    2013/08/25 - Added int64/uint64 support for keys [Ind/Hercules]
 *    2013/04/27 - Added ERS to speed up iterator memory allocation [Ind/Hercules]
 *    2012/03/09 - Added enum for data types (int, uint, void*)
 *    2008/02/19 - Fixed db_obj_get not handling deleted entries correctly.
 *    2007/11/09 - Added an iterator to the database.
 *    2006/12/21 - Added 1-node cache to the database.
 *    2.1 (Athena build #???#) - Portability fix
 *      - Fixed the portability of casting to union and added the functions
 *        ensure and clear to the database.
 *    2.0 (Athena build 4859) - Transition version
 *      - Almost everything recoded with a strategy similar to objects,
 *        database structure is maintained.
 *    1.0 (up to Athena build 4706)
 *      - Previous database system.
 *
 * @version 2006/12/21
 * @author Athena Dev team
 * @encoding US-ASCII
 * @see #db.h
\*****************************************************************************/

#define HERCULES_CORE

#include "db.h"

#include "common/ers.h"
#include "common/memmgr.h"
#include "common/mmo.h"
#include "common/nullpo.h"
#include "common/showmsg.h"
#include "common/strlib.h"

#include <stdio.h>
#include <stdlib.h>

static struct db_interface DB_s;
struct db_interface *DB;

/*****************************************************************************
 *  (1) Private enums, structures, defines and global variables of the       *
 *      database system.                                                     *
 *  DB_ENABLE_STATS  - Define to enable database statistics.                 *
 *  HASH_SIZE        - Define with the size of the hashtable.                *
 *  enum DBNodeColor - Enumeration of colors of the nodes.                   *
 *  struct DBNode     - Structure of a node in RED-BLACK trees.              *
 *  struct db_free    - Structure that holds a deleted node to be freed.     *
 *  struct DBMap_impl - Structure of the database.                           *
 *  stats             - Statistics about the database system.                *
 *****************************************************************************/

/**
 * If defined statistics about database nodes, database creating/destruction
 * and function usage are kept and displayed when finalizing the database
 * system.
 * WARNING: This adds overhead to every database operation (not sure how much).
 * @private
 * @see #DBStats
 * @see #stats
 * @see #db_final(void)
 */
//#define DB_ENABLE_STATS

/**
 * Size of the hashtable in the database.
 * @private
 * @see struct DBMap_impl#ht
 */
#define HASH_SIZE (256+27)

/**
 * The color of individual nodes.
 * @private
 * @see struct DBNode
 */
enum DBNodeColor {
	RED,
	BLACK,
};

/**
 * A node in a RED-BLACK tree of the database.
 * @param parent Parent node
 * @param left Left child node
 * @param right Right child node
 * @param key Key of this database entry
 * @param data Data of this database entry
 * @param deleted If the node is deleted
 * @param color Color of the node
 * @private
 * @see struct DBMap_impl#ht
 */
struct DBNode {
	// Tree structure
	struct DBNode *parent;
	struct DBNode *left;
	struct DBNode *right;
	// Node data
	union DBKey key;
	struct DBData data;
	// Other
	enum DBNodeColor color;
	unsigned deleted : 1;
};

/**
 * Structure that holds a deleted node.
 * @param node Deleted node
 * @param root Address to the root of the tree
 * @private
 * @see struct DBMap_impl#free_list
 */
struct db_free {
	struct DBNode *node;
	struct DBNode **root;
};

/**
 * Complete database structure.
 * @param vtable Interface of the database
 * @param alloc_file File where the database was allocated
 * @param alloc_line Line in the file where the database was allocated
 * @param free_list Array of deleted nodes to be freed
 * @param free_count Number of deleted nodes in free_list
 * @param free_max Current maximum capacity of free_list
 * @param free_lock Lock for freeing the nodes
 * @param nodes Manager of reusable tree nodes
 * @param cmp Comparator of the database
 * @param hash Hasher of the database
 * @param release Releaser of the database
 * @param ht Hashtable of RED-BLACK trees
 * @param type Type of the database
 * @param options Options of the database
 * @param item_count Number of items in the database
 * @param maxlen Maximum length of strings in DB_STRING and DB_ISTRING databases
 * @param global_lock Global lock of the database
 * @private
 * @see #db_alloc()
 */
struct DBMap_impl {
	// Database interface
	struct DBMap vtable;
	// File and line of allocation
	const char *alloc_file;
	int alloc_line;
	// Lock system
	struct db_free *free_list;
	unsigned int free_count;
	unsigned int free_max;
	unsigned int free_lock;
	// Other
	ERS *nodes;
	DBComparator cmp;
	DBHasher hash;
	DBReleaser release;
	struct DBNode *ht[HASH_SIZE];
	struct DBNode *cache;
	enum DBType type;
	enum DBOptions options;
	uint32 item_count;
	unsigned short maxlen;
	unsigned global_lock : 1;
};

/**
 * Complete iterator structure.
 * @param vtable Interface of the iterator
 * @param db Parent database
 * @param ht_index Current index of the hashtable
 * @param node Current node
 * @private
 * @see struct DBIterator
 * @see struct DBMap_impl
 * @see struct DBNode
 */
struct DBIterator_impl {
	// Iterator interface
	struct DBIterator vtable;
	struct DBMap_impl *db;
	int ht_index;
	struct DBNode *node;
};

#if defined(DB_ENABLE_STATS)
/**
 * Structure with what is counted when the database statistics are enabled.
 * @private
 * @see #DB_ENABLE_STATS
 * @see #stats
 */
static struct db_stats {
	// Node alloc/free
	uint32 db_node_alloc;
	uint32 db_node_free;
	// Database creating/destruction counters
	uint32 db_int_alloc;
	uint32 db_uint_alloc;
	uint32 db_string_alloc;
	uint32 db_istring_alloc;
	uint32 db_int64_alloc;
	uint32 db_uint64_alloc;
	uint32 db_int_destroy;
	uint32 db_uint_destroy;
	uint32 db_string_destroy;
	uint32 db_istring_destroy;
	uint32 db_int64_destroy;
	uint32 db_uint64_destroy;
	// Function usage counters
	uint32 db_rotate_left;
	uint32 db_rotate_right;
	uint32 db_rebalance;
	uint32 db_rebalance_erase;
	uint32 db_is_key_null;
	uint32 db_dup_key;
	uint32 db_dup_key_free;
	uint32 db_free_add;
	uint32 db_free_remove;
	uint32 db_free_lock;
	uint32 db_free_unlock;
	uint32 db_int_cmp;
	uint32 db_uint_cmp;
	uint32 db_string_cmp;
	uint32 db_istring_cmp;
	uint32 db_int64_cmp;
	uint32 db_uint64_cmp;
	uint32 db_int_hash;
	uint32 db_uint_hash;
	uint32 db_string_hash;
	uint32 db_istring_hash;
	uint32 db_int64_hash;
	uint32 db_uint64_hash;
	uint32 db_release_nothing;
	uint32 db_release_key;
	uint32 db_release_data;
	uint32 db_release_both;
	uint32 dbit_first;
	uint32 dbit_last;
	uint32 dbit_next;
	uint32 dbit_prev;
	uint32 dbit_exists;
	uint32 dbit_remove;
	uint32 dbit_destroy;
	uint32 db_iterator;
	uint32 db_exists;
	uint32 db_get;
	uint32 db_getall;
	uint32 db_vgetall;
	uint32 db_ensure;
	uint32 db_vensure;
	uint32 db_put;
	uint32 db_remove;
	uint32 db_foreach;
	uint32 db_vforeach;
	uint32 db_clear;
	uint32 db_vclear;
	uint32 db_destroy;
	uint32 db_vdestroy;
	uint32 db_size;
	uint32 db_type;
	uint32 db_options;
	uint32 db_fix_options;
	uint32 db_default_cmp;
	uint32 db_default_hash;
	uint32 db_default_release;
	uint32 db_custom_release;
	uint32 db_alloc;
	uint32 db_i2key;
	uint32 db_ui2key;
	uint32 db_str2key;
	uint32 db_i642key;
	uint32 db_ui642key;
	uint32 db_i2data;
	uint32 db_ui2data;
	uint32 db_ptr2data;
	uint32 db_data2i;
	uint32 db_data2ui;
	uint32 db_data2ptr;
	uint32 db_init;
	uint32 db_final;
} stats = {
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0
};
#define DB_COUNTSTAT(token) do { if ((stats.token) != UINT32_MAX) ++(stats.token); } while(0)
#else /* !defined(DB_ENABLE_STATS) */
#define DB_COUNTSTAT(token) (void)0
#endif /* !defined(DB_ENABLE_STATS) */

/* [Ind/Hercules] */
static struct eri *db_iterator_ers;
static struct eri *db_alloc_ers;

/*****************************************************************************\
 *  (2) Section of private functions used by the database system.            *
 *  db_rotate_left     - Rotate a tree node to the left.                     *
 *  db_rotate_right    - Rotate a tree node to the right.                    *
 *  db_rebalance       - Rebalance the tree.                                 *
 *  db_rebalance_erase - Rebalance the tree after a BLACK node was erased.   *
 *  db_is_key_null     - Returns not 0 if the key is considered NULL.        *
 *  db_dup_key         - Duplicate a key for internal use.                   *
 *  db_dup_key_free    - Free the duplicated key.                            *
 *  db_free_add        - Add a node to the free_list of a database.          *
 *  db_free_remove     - Remove a node from the free_list of a database.     *
 *  db_free_lock       - Increment the free_lock of a database.              *
 *  db_free_unlock     - Decrement the free_lock of a database.              *
 *         If it was the last lock, frees the nodes in free_list.            *
 *         NOTE: Keeps the database trees balanced.                          *
\*****************************************************************************/

/**
 * Rotate a node to the left.
 * @param node Node to be rotated
 * @param root Pointer to the root of the tree
 * @private
 * @see #db_rebalance()
 * @see #db_rebalance_erase()
 */
static void db_rotate_left(struct DBNode *node, struct DBNode **root)
{
	struct DBNode *y = node->right;

	DB_COUNTSTAT(db_rotate_left);
	// put the left of y at the right of node
	node->right = y->left;
	if (y->left)
		y->left->parent = node;
	y->parent = node->parent;
	// link y and node's parent
	if (node == *root) {
		*root = y; // node was root
	} else if (node == node->parent->left) {
		node->parent->left = y; // node was at the left
	} else {
		node->parent->right = y; // node was at the right
	}
	// put node at the left of y
	y->left = node;
	node->parent = y;
}

/**
 * Rotate a node to the right
 * @param node Node to be rotated
 * @param root Pointer to the root of the tree
 * @private
 * @see #db_rebalance()
 * @see #db_rebalance_erase()
 */
static void db_rotate_right(struct DBNode *node, struct DBNode **root)
{
	struct DBNode *y = node->left;

	DB_COUNTSTAT(db_rotate_right);
	// put the right of y at the left of node
	node->left = y->right;
	if (y->right != 0)
		y->right->parent = node;
	y->parent = node->parent;
	// link y and node's parent
	if (node == *root) {
		*root = y; // node was root
	} else if (node == node->parent->right) {
		node->parent->right = y; // node was at the right
	} else {
		node->parent->left = y; // node was at the left
	}
	// put node at the right of y
	y->right = node;
	node->parent = y;
}

/**
 * Rebalance the RED-BLACK tree.
 * Called when the node and it's parent are both RED.
 * @param node Node to be rebalanced
 * @param root Pointer to the root of the tree
 * @private
 * @see #db_rotate_left()
 * @see #db_rotate_right()
 * @see #db_obj_put()
 */
static void db_rebalance(struct DBNode *node, struct DBNode **root)
{
	struct DBNode *y;

	DB_COUNTSTAT(db_rebalance);
	// Restore the RED-BLACK properties
	node->color = RED;
	while (node != *root && node->parent->color == RED) {
		if (node->parent == node->parent->parent->left) {
			// If node's parent is a left, y is node's right 'uncle'
			y = node->parent->parent->right;
			if (y && y->color == RED) { // case 1
				// change the colors and move up the tree
				node->parent->color = BLACK;
				y->color = BLACK;
				node->parent->parent->color = RED;
				node = node->parent->parent;
			} else {
				if (node == node->parent->right) { // case 2
					// move up and rotate
					node = node->parent;
					db_rotate_left(node, root);
				}
				// case 3
				node->parent->color = BLACK;
				node->parent->parent->color = RED;
				db_rotate_right(node->parent->parent, root);
			}
		} else {
			// If node's parent is a right, y is node's left 'uncle'
			y = node->parent->parent->left;
			if (y && y->color == RED) { // case 1
				// change the colors and move up the tree
				node->parent->color = BLACK;
				y->color = BLACK;
				node->parent->parent->color = RED;
				node = node->parent->parent;
			} else {
				if (node == node->parent->left) { // case 2
					// move up and rotate
					node = node->parent;
					db_rotate_right(node, root);
				}
				// case 3
				node->parent->color = BLACK;
				node->parent->parent->color = RED;
				db_rotate_left(node->parent->parent, root);
			}
		}
	}
	(*root)->color = BLACK; // the root can and should always be black
}

/**
 * Erase a node from the RED-BLACK tree, keeping the tree balanced.
 * @param node Node to be erased from the tree
 * @param root Root of the tree
 * @private
 * @see #db_rotate_left()
 * @see #db_rotate_right()
 * @see #db_free_unlock()
 */
static void db_rebalance_erase(struct DBNode *node, struct DBNode **root)
{
	struct DBNode *y = node;
	struct DBNode *x = NULL;
	struct DBNode *x_parent = NULL;

	DB_COUNTSTAT(db_rebalance_erase);
	// Select where to change the tree
	if (y->left == NULL) { // no left
		x = y->right;
	} else if (y->right == NULL) { // no right
		x = y->left;
	} else { // both exist, go to the leftmost node of the right sub-tree
		y = y->right;
		while (y->left != NULL)
			y = y->left;
		x = y->right;
	}

	// Remove the node from the tree
	if (y != node) { // both child existed
		// put the left of 'node' in the left of 'y'
		node->left->parent = y;
		y->left = node->left;

		// 'y' is not the direct child of 'node'
		if (y != node->right) {
			// put 'x' in the old position of 'y'
			x_parent = y->parent;
			if (x) x->parent = y->parent;
			y->parent->left = x;
			// put the right of 'node' in 'y'
			y->right = node->right;
			node->right->parent = y;
			// 'y' is a direct child of 'node'
		} else {
			x_parent = y;
		}

		// link 'y' and the parent of 'node'
		if (*root == node) {
			*root = y; // 'node' was the root
		} else if (node->parent->left == node) {
			node->parent->left = y; // 'node' was at the left
		} else {
			node->parent->right = y; // 'node' was at the right
		}
		y->parent = node->parent;
		// switch colors
		{
			enum DBNodeColor tmp = y->color;
			y->color = node->color;
			node->color = tmp;
		}
		y = node;
	} else { // one child did not exist
		// put x in node's position
		x_parent = y->parent;
		if (x) x->parent = y->parent;
		// link x and node's parent
		if (*root == node) {
			*root = x; // node was the root
		} else if (node->parent->left == node) {
			node->parent->left = x; // node was at the left
		} else {
			node->parent->right = x;  // node was at the right
		}
	}

	// Restore the RED-BLACK properties
	if (y->color != RED) {
		while (x != *root && (x == NULL || x->color == BLACK)) {
			struct DBNode *w;
			if (x == x_parent->left) {
				w = x_parent->right;
				if (w->color == RED) {
					w->color = BLACK;
					x_parent->color = RED;
					db_rotate_left(x_parent, root);
					w = x_parent->right;
				}
				if ((w->left == NULL || w->left->color == BLACK) &&
					(w->right == NULL || w->right->color == BLACK)) {
					w->color = RED;
					x = x_parent;
					x_parent = x_parent->parent;
				} else {
					if (w->right == NULL || w->right->color == BLACK) {
						if (w->left) w->left->color = BLACK;
						w->color = RED;
						db_rotate_right(w, root);
						w = x_parent->right;
					}
					w->color = x_parent->color;
					x_parent->color = BLACK;
					if (w->right) w->right->color = BLACK;
					db_rotate_left(x_parent, root);
					break;
				}
			} else {
				w = x_parent->left;
				if (w->color == RED) {
					w->color = BLACK;
					x_parent->color = RED;
					db_rotate_right(x_parent, root);
					w = x_parent->left;
				}
				if ((w->right == NULL || w->right->color == BLACK) &&
					(w->left == NULL || w->left->color == BLACK)) {
					w->color = RED;
					x = x_parent;
					x_parent = x_parent->parent;
				} else {
					if (w->left == NULL || w->left->color == BLACK) {
						if (w->right) w->right->color = BLACK;
						w->color = RED;
						db_rotate_left(w, root);
						w = x_parent->left;
					}
					w->color = x_parent->color;
					x_parent->color = BLACK;
					if (w->left) w->left->color = BLACK;
					db_rotate_right(x_parent, root);
					break;
				}
			}
		}
		if (x) x->color = BLACK;
	}
}

/**
 * Returns not 0 if the key is considered to be NULL.
 * @param type Type of database
 * @param key Key being tested
 * @return not 0 if considered NULL, 0 otherwise
 * @private
 * @see #db_obj_get()
 * @see #db_obj_put()
 * @see #db_obj_remove()
 */
static int db_is_key_null(enum DBType type, union DBKey key)
{
	DB_COUNTSTAT(db_is_key_null);
	switch (type) {
		case DB_STRING:
		case DB_ISTRING:
			return (key.str == NULL);

		default: // Not a pointer
			return 0;
	}
}

/**
 * Duplicate the key used in the database.
 * @param db Database the key is being used in
 * @param key Key to be duplicated
 * @param Duplicated key
 * @private
 * @see #db_free_add()
 * @see #db_free_remove()
 * @see #db_obj_put()
 * @see #db_dup_key_free()
 */
static union DBKey db_dup_key(struct DBMap_impl *db, union DBKey key)
{
	DB_COUNTSTAT(db_dup_key);
	switch (db->type) {
		case DB_STRING:
		case DB_ISTRING:
		{
			size_t len = strnlen(key.str, db->maxlen);
			char *str = aMalloc(len + 1);

			memcpy(str, key.str, len);
			str[len] = '\0';
			key.mutstr = str;
			return key;
		}

		default:
			return key;
	}
}

/**
 * Free a key duplicated by db_dup_key.
 * @param db Database the key is being used in
 * @param key Key to be freed
 * @private
 * @see #db_dup_key()
 */
static void db_dup_key_free(struct DBMap_impl *db, union DBKey key)
{
	DB_COUNTSTAT(db_dup_key_free);
	switch (db->type) {
		case DB_STRING:
		case DB_ISTRING:
			aFree(key.mutstr);
			return;

		default:
			return;
	}
}

/**
 * Add a node to the free_list of the database.
 * Marks the node as deleted.
 * If the key isn't duplicated, the key is duplicated and released.
 * @param db Target database
 * @param root Root of the tree from the node
 * @param node Target node
 * @private
 * @see #struct db_free
 * @see struct DBMap_impl#free_list
 * @see struct DBMap_impl#free_count
 * @see struct DBMap_impl#free_max
 * @see #db_obj_remove()
 * @see #db_free_remove()
 */
static void db_free_add(struct DBMap_impl *db, struct DBNode *node, struct DBNode **root)
{
	union DBKey old_key;

	DB_COUNTSTAT(db_free_add);
	if (db->free_lock == (unsigned int)~0) {
		ShowFatalError("db_free_add: free_lock overflow\n"
				"Database allocated at %s:%d\n",
				db->alloc_file, db->alloc_line);
		exit(EXIT_FAILURE);
	}
	if (!(db->options&DB_OPT_DUP_KEY)) { // Make sure we have a key until the node is freed
		old_key = node->key;
		node->key = db_dup_key(db, node->key);
		db->release(old_key, node->data, DB_RELEASE_KEY);
	}
	if (db->free_count == db->free_max) { // No more space, expand free_list
		db->free_max = (db->free_max<<2) +3; // = db->free_max*4 +3
		if (db->free_max <= db->free_count) {
			if (db->free_count == (unsigned int)~0) {
				ShowFatalError("db_free_add: free_count overflow\n"
						"Database allocated at %s:%d\n",
						db->alloc_file, db->alloc_line);
				exit(EXIT_FAILURE);
			}
			db->free_max = (unsigned int)~0;
		}
		RECREATE(db->free_list, struct db_free, db->free_max);
	}
	node->deleted = 1;
	db->free_list[db->free_count].node = node;
	db->free_list[db->free_count].root = root;
	db->free_count++;
	db->item_count--;
}

/**
 * Remove a node from the free_list of the database.
 * Marks the node as not deleted.
 * NOTE: Frees the duplicated key of the node.
 * @param db Target database
 * @param node Node being removed from free_list
 * @private
 * @see #struct db_free
 * @see struct DBMap_impl#free_list
 * @see struct DBMap_impl#free_count
 * @see #db_obj_put()
 * @see #db_free_add()
 */
static void db_free_remove(struct DBMap_impl *db, struct DBNode *node)
{
	unsigned int i;

	DB_COUNTSTAT(db_free_remove);
	for (i = 0; i < db->free_count; i++) {
		if (db->free_list[i].node == node) {
			if (i < db->free_count -1) // copy the last item to where the removed one was
				memcpy(&db->free_list[i], &db->free_list[db->free_count -1], sizeof(struct db_free));
			db_dup_key_free(db, node->key);
			break;
		}
	}
	node->deleted = 0;
	if (i == db->free_count) {
		ShowWarning("db_free_remove: node was not found - database allocated at %s:%d\n", db->alloc_file, db->alloc_line);
	} else {
		db->free_count--;
	}
	db->item_count++;
}

/**
 * Increment the free_lock of the database.
 * @param db Target database
 * @private
 * @see struct DBMap_impl#free_lock
 * @see #db_unlock()
 */
static void db_free_lock(struct DBMap_impl *db)
{
	DB_COUNTSTAT(db_free_lock);
	if (db->free_lock == (unsigned int)~0) {
		ShowFatalError("db_free_lock: free_lock overflow\n"
				"Database allocated at %s:%d\n",
				db->alloc_file, db->alloc_line);
		exit(EXIT_FAILURE);
	}
	db->free_lock++;
}

/**
 * Decrement the free_lock of the database.
 * If it was the last lock, frees the nodes of the database.
 * Keeps the tree balanced.
 * NOTE: Frees the duplicated keys of the nodes
 * @param db Target database
 * @private
 * @see struct DBMap_impl#free_lock
 * @see #db_free_dbn()
 * @see #db_lock()
 */
static void db_free_unlock(struct DBMap_impl *db)
{
	unsigned int i;

	DB_COUNTSTAT(db_free_unlock);
	if (db->free_lock == 0) {
		ShowWarning("db_free_unlock: free_lock was already 0\n"
				"Database allocated at %s:%d\n",
				db->alloc_file, db->alloc_line);
	} else {
		db->free_lock--;
	}
	if (db->free_lock)
		return; // Not last lock

	for (i = 0; i < db->free_count ; i++) {
		db_rebalance_erase(db->free_list[i].node, db->free_list[i].root);
		db_dup_key_free(db, db->free_list[i].node->key);
		DB_COUNTSTAT(db_node_free);
		ers_free(db->nodes, db->free_list[i].node);
	}
	db->free_count = 0;
}

/*****************************************************************************\
 *  (3) Section of protected functions used internally.                      *
 *  NOTE: the protected functions used in the database interface are in the  *
 *           next section.                                                   *
 *  db_int_cmp         - Default comparator for DB_INT databases.            *
 *  db_uint_cmp        - Default comparator for DB_UINT databases.           *
 *  db_string_cmp      - Default comparator for DB_STRING databases.         *
 *  db_istring_cmp     - Default comparator for DB_ISTRING databases.        *
 *  db_int64_cmp       - Default comparator for DB_INT64 databases.          *
 *  db_uint64_cmp      - Default comparator for DB_UINT64 databases.         *
 *  db_int_hash        - Default hasher for DB_INT databases.                *
 *  db_uint_hash       - Default hasher for DB_UINT databases.               *
 *  db_string_hash     - Default hasher for DB_STRING databases.             *
 *  db_istring_hash    - Default hasher for DB_ISTRING databases.            *
 *  db_int64_hash      - Default hasher for DB_INT64 databases.              *
 *  db_uint64_hash     - Default hasher for DB_UINT64 databases.             *
 *  db_release_nothing - Releaser that releases nothing.                     *
 *  db_release_key     - Releaser that only releases the key.                *
 *  db_release_data    - Releaser that only releases the data.               *
 *  db_release_both    - Releaser that releases key and data.                *
\*****************************************************************************/

/**
 * Default comparator for DB_INT databases.
 * Compares key1 to key2.
 * Return 0 if equal, negative if lower and positive if higher.
 * <code>maxlen</code> is ignored.
 * @param key1 Key to be compared
 * @param key2 Key being compared to
 * @param maxlen Maximum length of the key to hash
 * @return 0 if equal, negative if lower and positive if higher
 * @see enum DBType#DB_INT
 * @see #DBComparator
 * @see #db_default_cmp()
 */
static int db_int_cmp(union DBKey key1, union DBKey key2, unsigned short maxlen)
{
	(void)maxlen;//not used
	DB_COUNTSTAT(db_int_cmp);
	if (key1.i < key2.i) return -1;
	if (key1.i > key2.i) return 1;
	return 0;
}

/**
 * Default comparator for DB_UINT databases.
 * Compares key1 to key2.
 * Return 0 if equal, negative if lower and positive if higher.
 * <code>maxlen</code> is ignored.
 * @param key1 Key to be compared
 * @param key2 Key being compared to
 * @param maxlen Maximum length of the key to hash
 * @return 0 if equal, negative if lower and positive if higher
 * @see enum DBType#DB_UINT
 * @see #DBComparator
 * @see #db_default_cmp()
 */
static int db_uint_cmp(union DBKey key1, union DBKey key2, unsigned short maxlen)
{
	(void)maxlen;//not used
	DB_COUNTSTAT(db_uint_cmp);
	if (key1.ui < key2.ui) return -1;
	if (key1.ui > key2.ui) return 1;
	return 0;
}

/**
 * Default comparator for DB_STRING databases.
 * Compares key1 to key2.
 * Return 0 if equal, negative if lower and positive if higher.
 * @param key1 Key to be compared
 * @param key2 Key being compared to
 * @param maxlen Maximum length of the key to hash
 * @return 0 if equal, negative if lower and positive if higher
 * @see enum DBType#DB_STRING
 * @see #DBComparator
 * @see #db_default_cmp()
 */
static int db_string_cmp(union DBKey key1, union DBKey key2, unsigned short maxlen)
{
	DB_COUNTSTAT(db_string_cmp);
	return strncmp((const char *)key1.str, (const char *)key2.str, maxlen);
}

/**
 * Default comparator for DB_ISTRING databases.
 * Compares key1 to key2 case insensitively.
 * Return 0 if equal, negative if lower and positive if higher.
 * @param key1 Key to be compared
 * @param key2 Key being compared to
 * @param maxlen Maximum length of the key to hash
 * @return 0 if equal, negative if lower and positive if higher
 * @see enum DBType#DB_ISTRING
 * @see #DBComparator
 * @see #db_default_cmp()
 */
static int db_istring_cmp(union DBKey key1, union DBKey key2, unsigned short maxlen)
{
	DB_COUNTSTAT(db_istring_cmp);
	return strncasecmp((const char *)key1.str, (const char *)key2.str, maxlen);
}

/**
 * Default comparator for DB_INT64 databases.
 * Compares key1 to key2.
 * Return 0 if equal, negative if lower and positive if higher.
 * <code>maxlen</code> is ignored.
 * @param key1 Key to be compared
 * @param key2 Key being compared to
 * @param maxlen Maximum length of the key to hash
 * @return 0 if equal, negative if lower and positive if higher
 * @see enum DBType#DB_INT64
 * @see #DBComparator
 * @see #db_default_cmp()
 */
static int db_int64_cmp(union DBKey key1, union DBKey key2, unsigned short maxlen)
{
	(void)maxlen;//not used
	DB_COUNTSTAT(db_int64_cmp);
	if (key1.i64 < key2.i64) return -1;
	if (key1.i64 > key2.i64) return 1;
	return 0;
}

/**
 * Default comparator for DB_UINT64 databases.
 * Compares key1 to key2.
 * Return 0 if equal, negative if lower and positive if higher.
 * <code>maxlen</code> is ignored.
 * @param key1 Key to be compared
 * @param key2 Key being compared to
 * @param maxlen Maximum length of the key to hash
 * @return 0 if equal, negative if lower and positive if higher
 * @see enum DBType#DB_UINT64
 * @see #DBComparator
 * @see #db_default_cmp()
 */
static int db_uint64_cmp(union DBKey key1, union DBKey key2, unsigned short maxlen)
{
	(void)maxlen;//not used
	DB_COUNTSTAT(db_uint64_cmp);
	if (key1.ui64 < key2.ui64) return -1;
	if (key1.ui64 > key2.ui64) return 1;
	return 0;
}


/**
 * Default hasher for DB_INT databases.
 * Returns the value of the key as an unsigned int.
 * <code>maxlen</code> is ignored.
 * @param key Key to be hashed
 * @param maxlen Maximum length of the key to hash
 * @return hash of the key
 * @see enum DBType#DB_INT
 * @see #DBHasher
 * @see #db_default_hash()
 */
static uint64 db_int_hash(union DBKey key, unsigned short maxlen)
{
	(void)maxlen;//not used
	DB_COUNTSTAT(db_int_hash);
	return (uint64)key.i;
}

/**
 * Default hasher for DB_UINT databases.
 * Just returns the value of the key.
 * <code>maxlen</code> is ignored.
 * @param key Key to be hashed
 * @param maxlen Maximum length of the key to hash
 * @return hash of the key
 * @see enum DBType#DB_UINT
 * @see #DBHasher
 * @see #db_default_hash()
 */
static uint64 db_uint_hash(union DBKey key, unsigned short maxlen)
{
	(void)maxlen;//not used
	DB_COUNTSTAT(db_uint_hash);
	return (uint64)key.ui;
}

/**
 * Default hasher for DB_STRING databases.
 * @param key Key to be hashed
 * @param maxlen Maximum length of the key to hash
 * @return hash of the key
 * @see enum DBType#DB_STRING
 * @see #DBHasher
 * @see #db_default_hash()
 */
static uint64 db_string_hash(union DBKey key, unsigned short maxlen)
{
	const char *k = key.str;
	unsigned int hash = 0;
	unsigned short i;

	DB_COUNTSTAT(db_string_hash);

	for (i = 0; *k; ++i) {
		hash = (hash*33 + ((unsigned char)*k))^(hash>>24);
		k++;
		if (i == maxlen)
			break;
	}

	return (uint64)hash;
}

/**
 * Default hasher for DB_ISTRING databases.
 * @param key Key to be hashed
 * @param maxlen Maximum length of the key to hash
 * @return hash of the key
 * @see enum DBType#DB_ISTRING
 * @see #db_default_hash()
 */
static uint64 db_istring_hash(union DBKey key, unsigned short maxlen)
{
	const char *k = key.str;
	unsigned int hash = 0;
	unsigned short i;

	DB_COUNTSTAT(db_istring_hash);

	for (i = 0; *k; i++) {
		hash = (hash*33 + ((unsigned char)TOLOWER(*k)))^(hash>>24);
		k++;
		if (i == maxlen)
			break;
	}

	return (uint64)hash;
}

/**
 * Default hasher for DB_INT64 databases.
 * Returns the value of the key as an unsigned int.
 * <code>maxlen</code> is ignored.
 * @param key Key to be hashed
 * @param maxlen Maximum length of the key to hash
 * @return hash of the key
 * @see enum DBType#DB_INT64
 * @see #DBHasher
 * @see #db_default_hash()
 */
static uint64 db_int64_hash(union DBKey key, unsigned short maxlen)
{
	(void)maxlen;//not used
	DB_COUNTSTAT(db_int64_hash);
	return (uint64)key.i64;
}

/**
 * Default hasher for DB_UINT64 databases.
 * Just returns the value of the key.
 * <code>maxlen</code> is ignored.
 * @param key Key to be hashed
 * @param maxlen Maximum length of the key to hash
 * @return hash of the key
 * @see enum DBType#DB_UINT64
 * @see #DBHasher
 * @see #db_default_hash()
 */
static uint64 db_uint64_hash(union DBKey key, unsigned short maxlen)
{
	(void)maxlen;//not used
	DB_COUNTSTAT(db_uint64_hash);
	return key.ui64;
}

/**
 * Releaser that releases nothing.
 * @param key Key of the database entry
 * @param data Data of the database entry
 * @param which What is being requested to be released
 * @protected
 * @see #DBReleaser
 * @see #db_default_releaser()
 */
static void db_release_nothing(union DBKey key, struct DBData data, enum DBReleaseOption which)
{
	(void)key;(void)data;(void)which;//not used
	DB_COUNTSTAT(db_release_nothing);
}

/**
 * Releaser that only releases the key.
 * @param key Key of the database entry
 * @param data Data of the database entry
 * @param which What is being requested to be released
 * @protected
 * @see #DBReleaser
 * @see #db_default_release()
 */
static void db_release_key(union DBKey key, struct DBData data, enum DBReleaseOption which)
{
	(void)data;//not used
	DB_COUNTSTAT(db_release_key);
	if (which&DB_RELEASE_KEY)
		aFree(key.mutstr); // FIXME: Ensure this is the right db type.
}

/**
 * Releaser that only releases the data.
 * @param key Key of the database entry
 * @param data Data of the database entry
 * @param which What is being requested to be released
 * @protected
 * @see struct DBData
 * @see enum DBReleaseOption
 * @see #DBReleaser
 * @see #db_default_release()
 */
static void db_release_data(union DBKey key, struct DBData data, enum DBReleaseOption which)
{
	(void)key;//not used
	DB_COUNTSTAT(db_release_data);
	if (which&DB_RELEASE_DATA && data.type == DB_DATA_PTR) {
		aFree(data.u.ptr);
		data.u.ptr = NULL;
	}
}

/**
 * Releaser that releases both key and data.
 * @param key Key of the database entry
 * @param data Data of the database entry
 * @param which What is being requested to be released
 * @protected
 * @see union DBKey
 * @see struct DBData
 * @see enum DBReleaseOption
 * @see #DBReleaser
 * @see #db_default_release()
 */
static void db_release_both(union DBKey key, struct DBData data, enum DBReleaseOption which)
{
	DB_COUNTSTAT(db_release_both);
	if (which&DB_RELEASE_KEY)
		aFree(key.mutstr); // FIXME: Ensure this is the right db type.
	if (which&DB_RELEASE_DATA && data.type == DB_DATA_PTR) {
		aFree(data.u.ptr);
		data.u.ptr = NULL;
	}
}

/*****************************************************************************\
 *  (4) Section with protected functions used in the interface of the        *
 *  database and interface of the iterator.                                  *
 *  dbit_obj_first   - Fetches the first entry from the database.            *
 *  dbit_obj_last    - Fetches the last entry from the database.             *
 *  dbit_obj_next    - Fetches the next entry from the database.             *
 *  dbit_obj_prev    - Fetches the previous entry from the database.         *
 *  dbit_obj_exists  - Returns true if the current entry exists.             *
 *  dbit_obj_remove  - Remove the current entry from the database.           *
 *  dbit_obj_destroy - Destroys the iterator, unlocking the database and     *
 *           freeing used memory.                                            *
 *  db_obj_iterator - Return a new database iterator.                         *
 *  db_obj_exists   - Checks if an entry exists.                             *
 *  db_obj_get      - Get the data identified by the key.                    *
 *  db_obj_vgetall  - Get the data of the matched entries.                   *
 *  db_obj_getall   - Get the data of the matched entries.                   *
 *  db_obj_vensure  - Get the data identified by the key, creating if it     *
 *           doesn't exist yet.                                              *
 *  db_obj_ensure   - Get the data identified by the key, creating if it     *
 *           doesn't exist yet.                                              *
 *  db_obj_put      - Put data identified by the key in the database.        *
 *  db_obj_remove   - Remove an entry from the database.                     *
 *  db_obj_vforeach - Apply a function to every entry in the database.       *
 *  db_obj_foreach  - Apply a function to every entry in the database.       *
 *  db_obj_vclear   - Remove all entries from the database.                  *
 *  db_obj_clear    - Remove all entries from the database.                  *
 *  db_obj_vdestroy - Destroy the database, freeing all the used memory.     *
 *  db_obj_destroy  - Destroy the database, freeing all the used memory.     *
 *  db_obj_size     - Return the size of the database.                       *
 *  db_obj_type     - Return the type of the database.                       *
 *  db_obj_options  - Return the options of the database.                    *
\*****************************************************************************/

/**
 * Fetches the first entry in the database.
 * Returns the data of the entry.
 * Puts the key in out_key, if out_key is not NULL.
 * @param self Iterator
 * @param out_key Key of the entry
 * @return Data of the entry
 * @protected
 * @see struct DBIterator#first()
 */
static struct DBData *dbit_obj_first(struct DBIterator *self, union DBKey *out_key)
{
	struct DBIterator_impl *it = (struct DBIterator_impl *)self;

	DB_COUNTSTAT(dbit_first);
	// position before the first entry
	it->ht_index = -1;
	it->node = NULL;
	// get next entry
	return self->next(self, out_key);
}

/**
 * Fetches the last entry in the database.
 * Returns the data of the entry.
 * Puts the key in out_key, if out_key is not NULL.
 * @param self Iterator
 * @param out_key Key of the entry
 * @return Data of the entry
 * @protected
 * @see struct DBIterator#last()
 */
static struct DBData *dbit_obj_last(struct DBIterator *self, union DBKey *out_key)
{
	struct DBIterator_impl *it = (struct DBIterator_impl *)self;

	DB_COUNTSTAT(dbit_last);
	// position after the last entry
	it->ht_index = HASH_SIZE;
	it->node = NULL;
	// get previous entry
	return self->prev(self, out_key);
}

/**
 * Fetches the next entry in the database.
 * Returns the data of the entry.
 * Puts the key in out_key, if out_key is not NULL.
 * @param self Iterator
 * @param out_key Key of the entry
 * @return Data of the entry
 * @protected
 * @see struct DBIterator#next()
 */
static struct DBData *dbit_obj_next(struct DBIterator *self, union DBKey *out_key)
{
	struct DBIterator_impl *it = (struct DBIterator_impl *)self;
	struct DBNode *node;
	struct DBNode *parent;
	struct DBNode fake;

	DB_COUNTSTAT(dbit_next);
	if( it->ht_index < 0 )
	{// get first node
		it->ht_index = 0;
		it->node = NULL;
	}
	node = it->node;
	memset(&fake, 0, sizeof(fake));
	for( ; it->ht_index < HASH_SIZE; ++(it->ht_index) )
	{
		// Iterate in the order: left tree, current node, right tree
		if( node == NULL )
		{// prepare initial node of this hash
			node = it->db->ht[it->ht_index];
			if( node == NULL )
				continue;// next hash
			fake.right = node;
			node = &fake;
		}

		while( node )
		{// next node
			if( node->right )
			{// continue in the right subtree
				node = node->right;
				while( node->left )
					node = node->left;// get leftmost node
			}
			else
			{// continue to the next parent (recursive)
				parent = node->parent;
				while( parent )
				{
					if( parent->right != node )
						break;
					node = parent;
					parent = node->parent;
				}
				if( parent == NULL )
				{// next hash
					node = NULL;
					break;
				}
				node = parent;
			}

			if( !node->deleted )
			{// found next entry
				it->node = node;
				if( out_key )
					memcpy(out_key, &node->key, sizeof(union DBKey));
				return &node->data;
			}
		}
	}
	it->node = NULL;
	return NULL;// not found
}

/**
 * Fetches the previous entry in the database.
 * Returns the data of the entry.
 * Puts the key in out_key, if out_key is not NULL.
 * @param self Iterator
 * @param out_key Key of the entry
 * @return Data of the entry
 * @protected
 * @see struct DBIterator#prev()
 */
static struct DBData *dbit_obj_prev(struct DBIterator *self, union DBKey *out_key)
{
	struct DBIterator_impl *it = (struct DBIterator_impl *)self;
	struct DBNode *node;
	struct DBNode *parent;
	struct DBNode fake;

	DB_COUNTSTAT(dbit_prev);
	if( it->ht_index >= HASH_SIZE )
	{// get last node
		it->ht_index = HASH_SIZE-1;
		it->node = NULL;
	}
	node = it->node;
	memset(&fake, 0, sizeof(fake));
	for( ; it->ht_index >= 0; --(it->ht_index) )
	{
		// Iterate in the order: right tree, current node, left tree
		if( node == NULL )
		{// prepare initial node of this hash
			node = it->db->ht[it->ht_index];
			if( node == NULL )
				continue;// next hash
			fake.left = node;
			node = &fake;
		}

		while( node )
		{// next node
			if( node->left )
			{// continue in the left subtree
				node = node->left;
				while( node->right )
					node = node->right;// get rightmost node
			}
			else
			{// continue to the next parent (recursive)
				parent = node->parent;
				while( parent )
				{
					if( parent->left != node )
						break;
					node = parent;
					parent = node->parent;
				}
				if( parent == NULL )
				{// next hash
					node = NULL;
					break;
				}
				node = parent;
			}

			if( !node->deleted )
			{// found previous entry
				it->node = node;
				if( out_key )
					memcpy(out_key, &node->key, sizeof(union DBKey));
				return &node->data;
			}
		}
	}
	it->node = NULL;
	return NULL;// not found
}

/**
 * Returns true if the fetched entry exists.
 * The databases entries might have NULL data, so use this to to test if
 * the iterator is done.
 * @param self Iterator
 * @return true if the entry exists
 * @protected
 * @see struct DBIterator#exists()
 */
static bool dbit_obj_exists(struct DBIterator *self)
{
	struct DBIterator_impl *it = (struct DBIterator_impl *)self;

	DB_COUNTSTAT(dbit_exists);
	return (it->node && !it->node->deleted);
}

/**
 * Removes the current entry from the database.
 *
 * NOTE: struct DBIterator#exists() will return false until another entry is
 * fetched.
 *
 * Puts data of the removed entry in out_data, if out_data is not NULL (unless data has been released)
 * @param self Iterator
 * @param out_data Data of the removed entry.
 * @return 1 if entry was removed, 0 otherwise
 * @protected
 * @see struct DBMap#remove()
 * @see struct DBIterator#remove()
 */
static int dbit_obj_remove(struct DBIterator *self, struct DBData *out_data)
{
	struct DBIterator_impl *it = (struct DBIterator_impl *)self;
	struct DBNode *node;
	int retval = 0;

	DB_COUNTSTAT(dbit_remove);
	node = it->node;
	if( node && !node->deleted )
	{
		struct DBMap_impl *db = it->db;
		if( db->cache == node )
			db->cache = NULL;
		db->release(node->key, node->data, DB_RELEASE_DATA);
		if( out_data )
			memcpy(out_data, &node->data, sizeof(struct DBData));
		retval = 1;
		db_free_add(db, node, &db->ht[it->ht_index]);
	}
	return retval;
}

/**
 * Destroys this iterator and unlocks the database.
 * @param self Iterator
 * @protected
 */
static void dbit_obj_destroy(struct DBIterator *self)
{
	struct DBIterator_impl *it = (struct DBIterator_impl *)self;

	DB_COUNTSTAT(dbit_destroy);
	// unlock the database
	db_free_unlock(it->db);
	// free iterator
	ers_free(db_iterator_ers,self);
}

/**
 * Returns a new iterator for this database.
 * The iterator keeps the database locked until it is destroyed.
 * The database will keep functioning normally but will only free internal
 * memory when unlocked, so destroy the iterator as soon as possible.
 * @param self Database
 * @return New iterator
 * @protected
 */
static struct DBIterator *db_obj_iterator(struct DBMap *self)
{
	struct DBMap_impl *db = (struct DBMap_impl *)self;
	struct DBIterator_impl *it;

	DB_COUNTSTAT(db_iterator);
	it = ers_alloc(db_iterator_ers, struct DBIterator_impl);
	/* Interface of the iterator **/
	it->vtable.first   = dbit_obj_first;
	it->vtable.last    = dbit_obj_last;
	it->vtable.next    = dbit_obj_next;
	it->vtable.prev    = dbit_obj_prev;
	it->vtable.exists  = dbit_obj_exists;
	it->vtable.remove  = dbit_obj_remove;
	it->vtable.destroy = dbit_obj_destroy;
	/* Initial state (before the first entry) */
	it->db = db;
	it->ht_index = -1;
	it->node = NULL;
	/* Lock the database */
	db_free_lock(db);
	return &it->vtable;
}

/**
 * Returns true if the entry exists.
 * @param self Interface of the database
 * @param key Key that identifies the entry
 * @return true is the entry exists
 * @protected
 * @see struct DBMap#exists()
 */
static bool db_obj_exists(struct DBMap *self, union DBKey key)
{
	struct DBMap_impl *db = (struct DBMap_impl *)self;
	struct DBNode *node;
	bool found = false;

	DB_COUNTSTAT(db_exists);
	if (db == NULL) return false; // nullpo candidate
	if (!(db->options&DB_OPT_ALLOW_NULL_KEY) && db_is_key_null(db->type, key)) {
		return false; // nullpo candidate
	}

	if (db->cache && db->cmp(key, db->cache->key, db->maxlen) == 0) {
#if defined(DEBUG)
		if (db->cache->deleted) {
			ShowDebug("db_exists: Cache contains a deleted node. Please report this!!!\n");
			return false;
		}
#endif
		return true; // cache hit
	}

	db_free_lock(db);
	node = db->ht[db->hash(key, db->maxlen)%HASH_SIZE];
	while (node) {
		int c = db->cmp(key, node->key, db->maxlen);
		if (c == 0) {
			if (!(node->deleted)) {
				db->cache = node;
				found = true;
			}
			break;
		}
		if (c < 0)
			node = node->left;
		else
			node = node->right;
	}
	db_free_unlock(db);
	return found;
}

/**
 * Get the data of the entry identified by the key.
 * @param self Interface of the database
 * @param key Key that identifies the entry
 * @return Data of the entry or NULL if not found
 * @protected
 * @see struct DBMap#get()
 */
static struct DBData *db_obj_get(struct DBMap *self, union DBKey key)
{
	struct DBMap_impl *db = (struct DBMap_impl *)self;
	struct DBNode *node;
	struct DBData *data = NULL;

	DB_COUNTSTAT(db_get);
	if (db == NULL) return NULL; // nullpo candidate
	if (!(db->options&DB_OPT_ALLOW_NULL_KEY) && db_is_key_null(db->type, key)) {
		ShowError("db_get: Attempted to retrieve non-allowed NULL key for db allocated at %s:%d\n",db->alloc_file, db->alloc_line);
		return NULL; // nullpo candidate
	}

	if (db->cache && db->cmp(key, db->cache->key, db->maxlen) == 0) {
#if defined(DEBUG)
		if (db->cache->deleted) {
			ShowDebug("db_get: Cache contains a deleted node. Please report this!!!\n");
			return NULL;
		}
#endif
		return &db->cache->data; // cache hit
	}

	db_free_lock(db);
	node = db->ht[db->hash(key, db->maxlen)%HASH_SIZE];
	while (node) {
		int c = db->cmp(key, node->key, db->maxlen);
		if (c == 0) {
			if (!(node->deleted)) {
				data = &node->data;
				db->cache = node;
			}
			break;
		}
		if (c < 0)
			node = node->left;
		else
			node = node->right;
	}
	db_free_unlock(db);
	return data;
}

/**
 * Get the data of the entries matched by <code>match</code>.
 * It puts a maximum of <code>max</code> entries into <code>buf</code>.
 * If <code>buf</code> is NULL, it only counts the matches.
 * Returns the number of entries that matched.
 * NOTE: if the value returned is greater than <code>max</code>, only the
 * first <code>max</code> entries found are put into the buffer.
 * @param self Interface of the database
 * @param buf Buffer to put the data of the matched entries
 * @param max Maximum number of data entries to be put into buf
 * @param match Function that matches the database entries
 * @param ... Extra arguments for match
 * @return The number of entries that matched
 * @protected
 * @see struct DBMap#vgetall()
 */
static unsigned int db_obj_vgetall(struct DBMap *self, struct DBData **buf, unsigned int max, DBMatcher match, va_list args)
{
	struct DBMap_impl *db = (struct DBMap_impl *)self;
	unsigned int i;
	struct DBNode *node;
	struct DBNode *parent;
	unsigned int ret = 0;

	DB_COUNTSTAT(db_vgetall);
	if (db == NULL) return 0; // nullpo candidate
	if (match == NULL) return 0; // nullpo candidate

	db_free_lock(db);
	for (i = 0; i < HASH_SIZE; i++) {
		// Match in the order: current node, left tree, right tree
		node = db->ht[i];
		while (node) {

			if (!(node->deleted)) {
				va_list argscopy;
				va_copy(argscopy, args);
				if (match(node->key, node->data, argscopy) == 0) {
					if (buf && ret < max)
						buf[ret] = &node->data;
					ret++;
				}
				va_end(argscopy);
			}

			if (node->left) {
				node = node->left;
				continue;
			}

			if (node->right) {
				node = node->right;
				continue;
			}

			while (node) {
				parent = node->parent;
				if (parent && parent->right && parent->left == node) {
					node = parent->right;
					break;
				}
				node = parent;
			}

		}
	}
	db_free_unlock(db);
	return ret;
}

/**
 * Just calls struct DBMap#vgetall().
 *
 * Get the data of the entries matched by <code>match</code>.
 * It puts a maximum of <code>max</code> entries into <code>buf</code>.
 * If <code>buf</code> is NULL, it only counts the matches.
 * Returns the number of entries that matched.
 * NOTE: if the value returned is greater than <code>max</code>, only the
 * first <code>max</code> entries found are put into the buffer.
 * @param self Interface of the database
 * @param buf Buffer to put the data of the matched entries
 * @param max Maximum number of data entries to be put into buf
 * @param match Function that matches the database entries
 * @param ... Extra arguments for match
 * @return The number of entries that matched
 * @protected
 * @see struct DBMap#vgetall()
 * @see struct DBMap#getall()
 */
static unsigned int db_obj_getall(struct DBMap *self, struct DBData **buf, unsigned int max, DBMatcher match, ...)
{
	va_list args;
	unsigned int ret;

	DB_COUNTSTAT(db_getall);
	if (self == NULL) return 0; // nullpo candidate

	va_start(args, match);
	ret = self->vgetall(self, buf, max, match, args);
	va_end(args);
	return ret;
}

/**
 * Get the data of the entry identified by the key.
 * If the entry does not exist, an entry is added with the data returned by
 * <code>create</code>.
 * @param self Interface of the database
 * @param key Key that identifies the entry
 * @param create Function used to create the data if the entry doesn't exist
 * @param args Extra arguments for create
 * @return Data of the entry
 * @protected
 * @see struct DBMap#vensure()
 */
static struct DBData *db_obj_vensure(struct DBMap *self, union DBKey key, DBCreateData create, va_list args)
{
	struct DBMap_impl *db = (struct DBMap_impl *)self;
	struct DBNode *node;
	struct DBNode *parent = NULL;
	unsigned int hash;
	int c = 0;
	struct DBData *data = NULL;

	DB_COUNTSTAT(db_vensure);
	if (db == NULL) return NULL; // nullpo candidate
	if (create == NULL) {
		ShowError("db_ensure: Create function is NULL for db allocated at %s:%d\n",db->alloc_file, db->alloc_line);
		return NULL; // nullpo candidate
	}
	if (!(db->options&DB_OPT_ALLOW_NULL_KEY) && db_is_key_null(db->type, key)) {
		ShowError("db_ensure: Attempted to use non-allowed NULL key for db allocated at %s:%d\n",db->alloc_file, db->alloc_line);
		return NULL; // nullpo candidate
	}

	if (db->cache && db->cmp(key, db->cache->key, db->maxlen) == 0)
		return &db->cache->data; // cache hit

	db_free_lock(db);
	hash = db->hash(key, db->maxlen)%HASH_SIZE;
	node = db->ht[hash];
	while (node) {
		c = db->cmp(key, node->key, db->maxlen);
		if (c == 0) {
			break;
		}
		parent = node;
		if (c < 0)
			node = node->left;
		else
			node = node->right;
	}
	// Create node if necessary
	if (node == NULL) {
		va_list argscopy;
		if (db->item_count == UINT32_MAX) {
			ShowError("db_vensure: item_count overflow, aborting item insertion.\n"
					"Database allocated at %s:%d",
					db->alloc_file, db->alloc_line);
				return NULL;
		}
		DB_COUNTSTAT(db_node_alloc);
		node = ers_alloc(db->nodes, struct DBNode);
		node->left = NULL;
		node->right = NULL;
		node->deleted = 0;
		db->item_count++;
		if (c == 0) { // hash entry is empty
			node->color = BLACK;
			node->parent = NULL;
			db->ht[hash] = node;
		} else {
			node->color = RED;
			if (c < 0) { // put at the left
				parent->left = node;
				node->parent = parent;
			} else { // put at the right
				parent->right = node;
				node->parent = parent;
			}
			if (parent->color == RED) // two consecutive RED nodes, must rebalance
				db_rebalance(node, &db->ht[hash]);
		}
		// put key and data in the node
		if (db->options&DB_OPT_DUP_KEY) {
			node->key = db_dup_key(db, key);
			if (db->options&DB_OPT_RELEASE_KEY)
				db->release(key, node->data, DB_RELEASE_KEY);
		} else {
			node->key = key;
		}
		va_copy(argscopy, args);
		node->data = create(key, argscopy);
		va_end(argscopy);
	}
	data = &node->data;
	db->cache = node;
	db_free_unlock(db);
	return data;
}

/**
 * Just calls struct DBMap#vensure().
 *
 * Get the data of the entry identified by the key.
 * If the entry does not exist, an entry is added with the data returned by
 * <code>create</code>.
 * @param self Interface of the database
 * @param key Key that identifies the entry
 * @param create Function used to create the data if the entry doesn't exist
 * @param ... Extra arguments for create
 * @return Data of the entry
 * @protected
 * @see struct DBMap#vensure()
 * @see struct DBMap#ensure()
 */
static struct DBData *db_obj_ensure(struct DBMap *self, union DBKey key, DBCreateData create, ...)
{
	va_list args;
	struct DBData *ret = NULL;

	DB_COUNTSTAT(db_ensure);
	if (self == NULL) return NULL; // nullpo candidate

	va_start(args, create);
	ret = self->vensure(self, key, create, args);
	va_end(args);
	return ret;
}

/**
 * Put the data identified by the key in the database.
 * Puts the previous data in out_data, if out_data is not NULL. (unless data has been released)
 * NOTE: Uses the new key, the old one is released.
 * @param self Interface of the database
 * @param key Key that identifies the data
 * @param data Data to be put in the database
 * @param out_data Previous data if the entry exists
 * @return 1 if if the entry already exists, 0 otherwise
 * @protected
 * @see #db_malloc_dbn(void)
 * @see struct DBMap#put()
 * FIXME: If this method fails shouldn't it return another value?
 *        Other functions rely on this to know if they were able to put something [Panikon]
 */
static int db_obj_put(struct DBMap *self, union DBKey key, struct DBData data, struct DBData *out_data)
{
	struct DBMap_impl *db = (struct DBMap_impl *)self;
	struct DBNode *node;
	struct DBNode *parent = NULL;
	int c = 0, retval = 0;
	unsigned int hash;

	DB_COUNTSTAT(db_put);
	if (db == NULL) return 0; // nullpo candidate
	if (db->global_lock) {
		ShowError("db_put: Database is being destroyed, aborting entry insertion.\n"
				"Database allocated at %s:%d\n",
				db->alloc_file, db->alloc_line);
		return 0; // nullpo candidate
	}
	if (!(db->options&DB_OPT_ALLOW_NULL_KEY) && db_is_key_null(db->type, key)) {
		ShowError("db_put: Attempted to use non-allowed NULL key for db allocated at %s:%d\n",db->alloc_file, db->alloc_line);
		return 0; // nullpo candidate
	}
	if (!(db->options&DB_OPT_ALLOW_NULL_DATA) && (data.type == DB_DATA_PTR && data.u.ptr == NULL)) {
		ShowError("db_put: Attempted to use non-allowed NULL data for db allocated at %s:%d\n",db->alloc_file, db->alloc_line);
		return 0; // nullpo candidate
	}

	if (db->item_count == UINT32_MAX) {
		ShowError("db_put: item_count overflow, aborting item insertion.\n"
				"Database allocated at %s:%d",
				db->alloc_file, db->alloc_line);
		return 0;
	}
	// search for an equal node
	db_free_lock(db);
	hash = db->hash(key, db->maxlen)%HASH_SIZE;
	for (node = db->ht[hash]; node; ) {
		c = db->cmp(key, node->key, db->maxlen);
		if (c == 0) { // equal entry, replace
			if (node->deleted) {
				db_free_remove(db, node);
			} else {
				db->release(node->key, node->data, DB_RELEASE_BOTH);
				if (out_data)
					memcpy(out_data, &node->data, sizeof(*out_data));
				retval = 1;
			}
			break;
		}
		parent = node;
		if (c < 0) {
			node = node->left;
		} else {
			node = node->right;
		}
	}
	// allocate a new node if necessary
	if (node == NULL) {
		DB_COUNTSTAT(db_node_alloc);
		node = ers_alloc(db->nodes, struct DBNode);
		node->left = NULL;
		node->right = NULL;
		node->deleted = 0;
		db->item_count++;
		if (c == 0) { // hash entry is empty
			node->color = BLACK;
			node->parent = NULL;
			db->ht[hash] = node;
		} else {
			node->color = RED;
			if (c < 0) { // put at the left
				parent->left = node;
				node->parent = parent;
			} else { // put at the right
				parent->right = node;
				node->parent = parent;
			}
			if (parent->color == RED) // two consecutive RED nodes, must rebalance
				db_rebalance(node, &db->ht[hash]);
		}
	}
	// put key and data in the node
	if (db->options&DB_OPT_DUP_KEY) {
		node->key = db_dup_key(db, key);
		if (db->options&DB_OPT_RELEASE_KEY)
			db->release(key, data, DB_RELEASE_KEY);
	} else {
		node->key = key;
	}
	node->data = data;
	db->cache = node;
	db_free_unlock(db);
	return retval;
}

/**
 * Remove an entry from the database.
 * Puts the previous data in out_data, if out_data is not NULL. (unless data has been released)
 * NOTE: The key (of the database) is released in #db_free_add().
 * @param self Interface of the database
 * @param key Key that identifies the entry
 * @param out_data Previous data if the entry exists
 * @return 1 if if the entry already exists, 0 otherwise
 * @protected
 * @see #db_free_add()
 * @see struct DBMap#remove()
 */
static int db_obj_remove(struct DBMap *self, union DBKey key, struct DBData *out_data)
{
	struct DBMap_impl *db = (struct DBMap_impl *)self;
	struct DBNode *node;
	unsigned int hash;
	int retval = 0;

	DB_COUNTSTAT(db_remove);
	if (db == NULL) return 0; // nullpo candidate
	if (db->global_lock) {
		ShowError("db_remove: Database is being destroyed. Aborting entry deletion.\n"
				"Database allocated at %s:%d\n",
				db->alloc_file, db->alloc_line);
		return 0; // nullpo candidate
	}
	if (!(db->options&DB_OPT_ALLOW_NULL_KEY) && db_is_key_null(db->type, key)) {
		ShowError("db_remove: Attempted to use non-allowed NULL key for db allocated at %s:%d\n",db->alloc_file, db->alloc_line);
		return 0; // nullpo candidate
	}

	db_free_lock(db);
	hash = db->hash(key, db->maxlen)%HASH_SIZE;
	for(node = db->ht[hash]; node; ){
		int c = db->cmp(key, node->key, db->maxlen);
		if (c == 0) {
			if (!(node->deleted)) {
				if (db->cache == node)
					db->cache = NULL;
				db->release(node->key, node->data, DB_RELEASE_DATA);
				if (out_data)
					memcpy(out_data, &node->data, sizeof(*out_data));
				retval = 1;
				db_free_add(db, node, &db->ht[hash]);
			}
			break;
		}
		if (c < 0)
			node = node->left;
		else
			node = node->right;
	}
	db_free_unlock(db);
	return retval;
}

/**
 * Apply <code>func</code> to every entry in the database.
 * Returns the sum of values returned by func.
 * @param self Interface of the database
 * @param func Function to be applied
 * @param args Extra arguments for func
 * @return Sum of the values returned by func
 * @protected
 * @see struct DBMap#vforeach()
 */
static int db_obj_vforeach(struct DBMap *self, DBApply func, va_list args)
{
	struct DBMap_impl *db = (struct DBMap_impl *)self;
	unsigned int i;
	int sum = 0;
	struct DBNode *node;
	struct DBNode *parent;

	DB_COUNTSTAT(db_vforeach);
	if (db == NULL) return 0; // nullpo candidate
	if (func == NULL) {
		ShowError("db_foreach: Passed function is NULL for db allocated at %s:%d\n",db->alloc_file, db->alloc_line);
		return 0; // nullpo candidate
	}

	db_free_lock(db);
	for (i = 0; i < HASH_SIZE; i++) {
		// Apply func in the order: current node, left node, right node
		node = db->ht[i];
		while (node) {
			if (!(node->deleted)) {
				va_list argscopy;
				va_copy(argscopy, args);
				sum += func(node->key, &node->data, argscopy);
				va_end(argscopy);
			}
			if (node->left) {
				node = node->left;
				continue;
			}
			if (node->right) {
				node = node->right;
				continue;
			}
			while (node) {
				parent = node->parent;
				if (parent && parent->right && parent->left == node) {
					node = parent->right;
					break;
				}
				node = parent;
			}
		}
	}
	db_free_unlock(db);
	return sum;
}

/**
 * Just calls struct DBMap#vforeach().
 *
 * Apply <code>func</code> to every entry in the database.
 * Returns the sum of values returned by func.
 * @param self Interface of the database
 * @param func Function to be applied
 * @param ... Extra arguments for func
 * @return Sum of the values returned by func
 * @protected
 * @see struct DBMap#vforeach()
 * @see struct DBMap#foreach()
 */
static int db_obj_foreach(struct DBMap *self, DBApply func, ...)
{
	va_list args;
	int ret;

	DB_COUNTSTAT(db_foreach);
	if (self == NULL) return 0; // nullpo candidate

	va_start(args, func);
	ret = self->vforeach(self, func, args);
	va_end(args);
	return ret;
}

/**
 * Removes all entries from the database.
 * Before deleting an entry, func is applied to it.
 * Releases the key and the data.
 * Returns the sum of values returned by func, if it exists.
 * @param self Interface of the database
 * @param func Function to be applied to every entry before deleting
 * @param args Extra arguments for func
 * @return Sum of values returned by func
 * @protected
 * @see struct DBMap#vclear()
 */
static int db_obj_vclear(struct DBMap *self, DBApply func, va_list args)
{
	struct DBMap_impl *db = (struct DBMap_impl *)self;
	int sum = 0;
	unsigned int i;
	struct DBNode *node;
	struct DBNode *parent;

	DB_COUNTSTAT(db_vclear);
	if (db == NULL) return 0; // nullpo candidate

	db_free_lock(db);
	db->cache = NULL;
	for (i = 0; i < HASH_SIZE; i++) {
		// Apply the func and delete in the order: left tree, right tree, current node
		node = db->ht[i];
		db->ht[i] = NULL;
		while (node) {
			parent = node->parent;
			if (node->left) {
				node = node->left;
				continue;
			}
			if (node->right) {
				node = node->right;
				continue;
			}
			if (node->deleted) {
				db_dup_key_free(db, node->key);
			} else {
				if (func)
				{
					va_list argscopy;
					va_copy(argscopy, args);
					sum += func(node->key, &node->data, argscopy);
					va_end(argscopy);
				}
				db->release(node->key, node->data, DB_RELEASE_BOTH);
				node->deleted = 1;
			}
			DB_COUNTSTAT(db_node_free);
			if (parent) {
				if (parent->left == node)
					parent->left = NULL;
				else
					parent->right = NULL;
			}
			ers_free(db->nodes, node);
			node = parent;
		}
		db->ht[i] = NULL;
	}
	db->free_count = 0;
	db->item_count = 0;
	db_free_unlock(db);
	return sum;
}

/**
 * Just calls struct DBMap#vclear().
 *
 * Removes all entries from the database.
 * Before deleting an entry, func is applied to it.
 * Releases the key and the data.
 * Returns the sum of values returned by func, if it exists.
 * NOTE: This locks the database globally. Any attempt to insert or remove
 * a database entry will give an error and be aborted (except for clearing).
 * @param self Interface of the database
 * @param func Function to be applied to every entry before deleting
 * @param ... Extra arguments for func
 * @return Sum of values returned by func
 * @protected
 * @see struct DBMap#vclear()
 * @see struct DBMap#clear()
 */
static int db_obj_clear(struct DBMap *self, DBApply func, ...)
{
	va_list args;
	int ret;

	DB_COUNTSTAT(db_clear);
	if (self == NULL) return 0; // nullpo candidate

	va_start(args, func);
	ret = self->vclear(self, func, args);
	va_end(args);
	return ret;
}

/**
 * Finalize the database, feeing all the memory it uses.
 * Before deleting an entry, func is applied to it.
 * Returns the sum of values returned by func, if it exists.
 * NOTE: This locks the database globally. Any attempt to insert or remove
 * a database entry will give an error and be aborted (except for clearing).
 * @param self Interface of the database
 * @param func Function to be applied to every entry before deleting
 * @param args Extra arguments for func
 * @return Sum of values returned by func
 * @protected
 * @see struct DBMap#vdestroy()
 */
static int db_obj_vdestroy(struct DBMap *self, DBApply func, va_list args)
{
	struct DBMap_impl *db = (struct DBMap_impl *)self;
	int sum;

	DB_COUNTSTAT(db_vdestroy);
	if (db == NULL) return 0; // nullpo candidate
	if (db->global_lock) {
		ShowError("db_vdestroy: Database is already locked for destruction. Aborting second database destruction.\n"
				"Database allocated at %s:%d\n",
				db->alloc_file, db->alloc_line);
		return 0;
	}
	if (db->free_lock)
		ShowWarning("db_vdestroy: Database is still in use, %u lock(s) left. Continuing database destruction.\n"
				"Database allocated at %s:%d\n",
				db->free_lock, db->alloc_file, db->alloc_line);

#ifdef DB_ENABLE_STATS
	switch (db->type) {
		case DB_INT: DB_COUNTSTAT(db_int_destroy); break;
		case DB_UINT: DB_COUNTSTAT(db_uint_destroy); break;
		case DB_STRING: DB_COUNTSTAT(db_string_destroy); break;
		case DB_ISTRING: DB_COUNTSTAT(db_istring_destroy); break;
		case DB_INT64: DB_COUNTSTAT(db_int64_destroy); break;
		case DB_UINT64: DB_COUNTSTAT(db_uint64_destroy); break;
	}
#endif /* DB_ENABLE_STATS */
	db_free_lock(db);
	db->global_lock = 1;
	sum = self->vclear(self, func, args);
	aFree(db->free_list);
	db->free_list = NULL;
	db->free_max = 0;
	ers_destroy(db->nodes);
	db_free_unlock(db);
	ers_free(db_alloc_ers, db);
	return sum;
}

/**
 * Just calls struct DBMap#db_vdestroy().
 * Finalize the database, feeing all the memory it uses.
 * Before deleting an entry, func is applied to it.
 * Releases the key and the data.
 * Returns the sum of values returned by func, if it exists.
 * NOTE: This locks the database globally. Any attempt to insert or remove
 * a database entry will give an error and be aborted.
 * @param self Database
 * @param func Function to be applied to every entry before deleting
 * @param ... Extra arguments for func
 * @return Sum of values returned by func
 * @protected
 * @see struct DBMap#vdestroy()
 * @see struct DBMap#destroy()
 */
static int db_obj_destroy(struct DBMap *self, DBApply func, ...)
{
	va_list args;
	int ret;

	DB_COUNTSTAT(db_destroy);
	if (self == NULL) return 0; // nullpo candidate

	va_start(args, func);
	ret = self->vdestroy(self, func, args);
	va_end(args);
	return ret;
}

/**
 * Return the size of the database (number of items in the database).
 * @param self Interface of the database
 * @return Size of the database
 * @protected
 * @see struct DBMap_impl#item_count
 * @see struct DBMap#size()
 */
static unsigned int db_obj_size(struct DBMap *self)
{
	struct DBMap_impl *db = (struct DBMap_impl *)self;
	unsigned int item_count;

	DB_COUNTSTAT(db_size);
	if (db == NULL) return 0; // nullpo candidate

	db_free_lock(db);
	item_count = db->item_count;
	db_free_unlock(db);

	return item_count;
}

/**
 * Return the type of database.
 * @param self Interface of the database
 * @return Type of the database
 * @protected
 * @see struct DBMap_impl#type
 * @see struct DBMap#type()
 */
static enum DBType db_obj_type(struct DBMap *self)
{
	struct DBMap_impl *db = (struct DBMap_impl *)self;
	enum DBType type;

	DB_COUNTSTAT(db_type);
	if (db == NULL)
		return (enum DBType)-1; // nullpo candidate - TODO what should this return?

	db_free_lock(db);
	type = db->type;
	db_free_unlock(db);

	return type;
}

/**
 * Return the options of the database.
 * @param self Interface of the database
 * @return Options of the database
 * @protected
 * @see struct DBMap_impl#options
 * @see struct DBMap#options()
 */
static enum DBOptions db_obj_options(struct DBMap *self)
{
	struct DBMap_impl* db = (struct DBMap_impl *)self;
	enum DBOptions options;

	DB_COUNTSTAT(db_options);
	if (db == NULL) return DB_OPT_BASE; // nullpo candidate - TODO what should this return?

	db_free_lock(db);
	options = db->options;
	db_free_unlock(db);

	return options;
}

/*****************************************************************************\
 *  (5) Section with public functions.
 *  db_fix_options     - Apply database type restrictions to the options.
 *  db_default_cmp     - Get the default comparator for a type of database.
 *  db_default_hash    - Get the default hasher for a type of database.
 *  db_default_release - Get the default releaser for a type of database with the specified options.
 *  db_custom_release  - Get a releaser that behaves a certain way.
 *  db_alloc           - Allocate a new database.
 *  db_i2key           - Manual cast from `int` to `union DBKey`.
 *  db_ui2key          - Manual cast from `unsigned int` to `union DBKey`.
 *  db_str2key         - Manual cast from `unsigned char *` to `union DBKey`.
 *  db_i642key         - Manual cast from `int64` to `union DBKey`.
 *  db_ui642key        - Manual cast from `uin64` to `union DBKey`.
 *  db_i2data          - Manual cast from `int` to `struct DBData`.
 *  db_ui2data         - Manual cast from `unsigned int` to `struct DBData`.
 *  db_ptr2data        - Manual cast from `void*` to `struct DBData`.
 *  db_data2i          - Gets `int` value from `struct DBData`.
 *  db_data2ui         - Gets `unsigned int` value from `struct DBData`.
 *  db_data2ptr        - Gets `void*` value from `struct DBData`.
 *  db_init            - Initializes the database system.
 *  db_final           - Finalizes the database system.
\*****************************************************************************/

/**
 * Returns the fixed options according to the database type.
 * Sets required options and unsets unsupported options.
 * For numeric databases DB_OPT_DUP_KEY and DB_OPT_RELEASE_KEY are unset.
 * @param type Type of the database
 * @param options Original options of the database
 * @return Fixed options of the database
 * @private
 * @see #db_default_release()
 * @see #db_alloc()
 */
static enum DBOptions db_fix_options(enum DBType type, enum DBOptions options)
{
	DB_COUNTSTAT(db_fix_options);
	switch (type) {
		case DB_INT:
		case DB_UINT:
		case DB_INT64:
		case DB_UINT64: // Numeric database, do nothing with the keys
			return (enum DBOptions)(options&~(DB_OPT_DUP_KEY|DB_OPT_RELEASE_KEY));

		default:
			ShowError("db_fix_options: Unknown database type %u with options %x\n", type, options);
			FALLTHROUGH
		case DB_STRING:
		case DB_ISTRING: // String databases, no fix required
			return options;
	}
}

/**
 * Returns the default comparator for the specified type of database.
 * @param type Type of database
 * @return Comparator for the type of database or NULL if unknown database
 * @public
 * @see #db_int_cmp()
 * @see #db_uint_cmp()
 * @see #db_string_cmp()
 * @see #db_istring_cmp()
 * @see #db_int64_cmp()
 * @see #db_uint64_cmp()
 */
static DBComparator db_default_cmp(enum DBType type)
{
	DB_COUNTSTAT(db_default_cmp);
	switch (type) {
		case DB_INT:     return &db_int_cmp;
		case DB_UINT:    return &db_uint_cmp;
		case DB_STRING:  return &db_string_cmp;
		case DB_ISTRING: return &db_istring_cmp;
		case DB_INT64:   return &db_int64_cmp;
		case DB_UINT64:  return &db_uint64_cmp;
		default:
			ShowError("db_default_cmp: Unknown database type %u\n", type);
			return NULL;
	}
}

/**
 * Returns the default hasher for the specified type of database.
 * @param type Type of database
 * @return Hasher of the type of database or NULL if unknown database
 * @public
 * @see #db_int_hash()
 * @see #db_uint_hash()
 * @see #db_string_hash()
 * @see #db_istring_hash()
 * @see #db_int64_hash()
 * @see #db_uint64_hash()
 */
static DBHasher db_default_hash(enum DBType type)
{
	DB_COUNTSTAT(db_default_hash);
	switch (type) {
		case DB_INT:     return &db_int_hash;
		case DB_UINT:    return &db_uint_hash;
		case DB_STRING:  return &db_string_hash;
		case DB_ISTRING: return &db_istring_hash;
		case DB_INT64:   return &db_int64_hash;
		case DB_UINT64:  return &db_uint64_hash;
		default:
			ShowError("db_default_hash: Unknown database type %u\n", type);
			return NULL;
	}
}

/**
 * Returns the default releaser for the specified type of database with the
 * specified options.
 *
 * NOTE: the options are fixed with #db_fix_options() before choosing the
 * releaser.
 *
 * @param type Type of database
 * @param options Options of the database
 * @return Default releaser for the type of database with the specified options
 * @public
 * @see #db_release_nothing()
 * @see #db_release_key()
 * @see #db_release_data()
 * @see #db_release_both()
 * @see #db_custom_release()
 */
static DBReleaser db_default_release(enum DBType type, enum DBOptions options)
{
	DB_COUNTSTAT(db_default_release);
	options = DB->fix_options(type, options);
	if (options&DB_OPT_RELEASE_DATA) { // Release data, what about the key?
		if (options&(DB_OPT_DUP_KEY|DB_OPT_RELEASE_KEY))
			return &db_release_both; // Release both key and data
		return &db_release_data; // Only release data
	}
	if (options&(DB_OPT_DUP_KEY|DB_OPT_RELEASE_KEY))
		return &db_release_key; // Only release key
	return &db_release_nothing; // Release nothing
}

/**
 * Returns the releaser that releases the specified release options.
 * @param which Options that specified what the releaser releases
 * @return Releaser for the specified release options
 * @public
 * @see #db_release_nothing()
 * @see #db_release_key()
 * @see #db_release_data()
 * @see #db_release_both()
 * @see #db_default_release()
 */
static DBReleaser db_custom_release(enum DBReleaseOption which)
{
	DB_COUNTSTAT(db_custom_release);
	switch (which) {
		case DB_RELEASE_NOTHING: return &db_release_nothing;
		case DB_RELEASE_KEY:     return &db_release_key;
		case DB_RELEASE_DATA:    return &db_release_data;
		case DB_RELEASE_BOTH:    return &db_release_both;
		default:
			ShowError("db_custom_release: Unknown release options %u\n", which);
			return NULL;
	}
}

/**
 * Allocate a new database of the specified type.
 *
 * NOTE: the options are fixed by #db_fix_options() before creating the
 * database.
 *
 * @param file File where the database is being allocated
 * @param line Line of the file where the database is being allocated
 * @param type Type of database
 * @param options Options of the database
 * @param maxlen Maximum length of the string to be used as key in string
 *          databases. If 0, the maximum number of maxlen is used (64K).
 * @return The interface of the database
 * @public
 * @see struct DBMap_impl
 * @see #db_fix_options()
 */
static struct DBMap *db_alloc(const char *file, const char *func, int line, enum DBType type, enum DBOptions options, unsigned short maxlen)
{
	struct DBMap_impl *db;
	unsigned int i;
	char ers_name[50];

#ifdef DB_ENABLE_STATS
	DB_COUNTSTAT(db_alloc);
	switch (type) {
		case DB_INT: DB_COUNTSTAT(db_int_alloc); break;
		case DB_UINT: DB_COUNTSTAT(db_uint_alloc); break;
		case DB_STRING: DB_COUNTSTAT(db_string_alloc); break;
		case DB_ISTRING: DB_COUNTSTAT(db_istring_alloc); break;
		case DB_INT64: DB_COUNTSTAT(db_int64_alloc); break;
		case DB_UINT64: DB_COUNTSTAT(db_uint64_alloc); break;
	}
#endif /* DB_ENABLE_STATS */
	db = ers_alloc(db_alloc_ers, struct DBMap_impl);

	options = DB->fix_options(type, options);
	/* Interface of the database */
	db->vtable.iterator = db_obj_iterator;
	db->vtable.exists   = db_obj_exists;
	db->vtable.get      = db_obj_get;
	db->vtable.getall   = db_obj_getall;
	db->vtable.vgetall  = db_obj_vgetall;
	db->vtable.ensure   = db_obj_ensure;
	db->vtable.vensure  = db_obj_vensure;
	db->vtable.put      = db_obj_put;
	db->vtable.remove   = db_obj_remove;
	db->vtable.foreach  = db_obj_foreach;
	db->vtable.vforeach = db_obj_vforeach;
	db->vtable.clear    = db_obj_clear;
	db->vtable.vclear   = db_obj_vclear;
	db->vtable.destroy  = db_obj_destroy;
	db->vtable.vdestroy = db_obj_vdestroy;
	db->vtable.size     = db_obj_size;
	db->vtable.type     = db_obj_type;
	db->vtable.options  = db_obj_options;
	/* File and line of allocation */
	db->alloc_file = file;
	db->alloc_line = line;
	/* Lock system */
	db->free_list = NULL;
	db->free_count = 0;
	db->free_max = 0;
	db->free_lock = 0;
	/* Other */
	snprintf(ers_name, 50, "db_alloc:nodes:%s:%s:%d",func,file,line);
	db->nodes = ers_new(sizeof(struct DBNode),ers_name,ERS_OPT_WAIT|ERS_OPT_FREE_NAME|ERS_OPT_CLEAN);
	db->cmp = DB->default_cmp(type);
	db->hash = DB->default_hash(type);
	db->release = DB->default_release(type, options);
	for (i = 0; i < HASH_SIZE; i++)
		db->ht[i] = NULL;
	db->cache = NULL;
	db->type = type;
	db->options = options;
	db->item_count = 0;
	db->maxlen = maxlen;
	db->global_lock = 0;

	if( db->maxlen == 0 && (type == DB_STRING || type == DB_ISTRING) )
		db->maxlen = UINT16_MAX;

	return &db->vtable;
}

/**
 * Manual cast from 'int' to the union DBKey.
 * @param key Key to be casted
 * @return The key as a DBKey union
 * @public
 */
static union DBKey db_i2key(int key)
{
	union DBKey ret;

	DB_COUNTSTAT(db_i2key);
	ret.i = key;
	return ret;
}

/**
 * Manual cast from 'unsigned int' to the union DBKey.
 * @param key Key to be casted
 * @return The key as a DBKey union
 * @public
 */
static union DBKey db_ui2key(unsigned int key)
{
	union DBKey ret;

	DB_COUNTSTAT(db_ui2key);
	ret.ui = key;
	return ret;
}

/**
 * Manual cast from 'const char *' to the union DBKey.
 * @param key Key to be casted
 * @return The key as a DBKey union
 * @public
 */
static union DBKey db_str2key(const char *key)
{
	union DBKey ret;

	DB_COUNTSTAT(db_str2key);
	ret.str = key;
	return ret;
}

/**
 * Manual cast from 'int64' to the union DBKey.
 * @param key Key to be casted
 * @return The key as a DBKey union
 * @public
 */
static union DBKey db_i642key(int64 key)
{
	union DBKey ret;

	DB_COUNTSTAT(db_i642key);
	ret.i64 = key;
	return ret;
}

/**
 * Manual cast from 'uin64' to the union DBKey.
 * @param key Key to be casted
 * @return The key as a DBKey union
 * @public
 */
static union DBKey db_ui642key(uint64 key)
{
	union DBKey ret;

	DB_COUNTSTAT(db_ui642key);
	ret.ui64 = key;
	return ret;
}

/**
 * Manual cast from 'int' to the struct DBData.
 * @param data Data to be casted
 * @return The data as a DBData struct
 * @public
 */
static struct DBData db_i2data(int data)
{
	struct DBData ret;

	DB_COUNTSTAT(db_i2data);
	ret.type = DB_DATA_INT;
	ret.u.i = data;
	return ret;
}

/**
 * Manual cast from 'unsigned int' to the struct DBData.
 * @param data Data to be casted
 * @return The data as a DBData struct
 * @public
 */
static struct DBData db_ui2data(unsigned int data)
{
	struct DBData ret;

	DB_COUNTSTAT(db_ui2data);
	ret.type = DB_DATA_UINT;
	ret.u.ui = data;
	return ret;
}

/**
 * Manual cast from 'void *' to the struct DBData.
 * @param data Data to be casted
 * @return The data as a DBData struct
 * @public
 */
static struct DBData db_ptr2data(void *data)
{
	struct DBData ret;

	DB_COUNTSTAT(db_ptr2data);
	ret.type = DB_DATA_PTR;
	ret.u.ptr = data;
	return ret;
}

/**
 * Gets int type data from struct DBData.
 * If data is not int type, returns 0.
 * @param data Data
 * @return Integer value of the data.
 * @public
 */
static int db_data2i(struct DBData *data)
{
	DB_COUNTSTAT(db_data2i);
	if (data && DB_DATA_INT == data->type)
		return data->u.i;
	return 0;
}

/**
 * Gets unsigned int type data from struct DBData.
 * If data is not unsigned int type, returns 0.
 * @param data Data
 * @return Unsigned int value of the data.
 * @public
 */
static unsigned int db_data2ui(struct DBData *data)
{
	DB_COUNTSTAT(db_data2ui);
	if (data && DB_DATA_UINT == data->type)
		return data->u.ui;
	return 0;
}

/**
 * Gets void* type data from struct DBData.
 * If data is not void* type, returns NULL.
 * @param data Data
 * @return Void* value of the data.
 * @public
 */
static void *db_data2ptr(struct DBData *data)
{
	DB_COUNTSTAT(db_data2ptr);
	if (data && DB_DATA_PTR == data->type)
		return data->u.ptr;
	return NULL;
}

/**
 * Initializes the database system.
 * @public
 * @see #db_final(void)
 */
static void db_init(void)
{
	db_iterator_ers = ers_new(sizeof(struct DBIterator_impl),"db.c::db_iterator_ers",ERS_OPT_CLEAN|ERS_OPT_FLEX_CHUNK);
	db_alloc_ers = ers_new(sizeof(struct DBMap_impl),"db.c::db_alloc_ers",ERS_OPT_CLEAN|ERS_OPT_FLEX_CHUNK);
	ers_chunk_size(db_alloc_ers, 50);
	ers_chunk_size(db_iterator_ers, 10);
	DB_COUNTSTAT(db_init);
}

/**
 * Finalizes the database system.
 * @public
 * @see #db_init(void)
 */
static void db_final(void)
{
#ifdef DB_ENABLE_STATS
	DB_COUNTSTAT(db_final);
	ShowInfo(CL_WHITE"Database nodes"CL_RESET":\n"
			"allocated %u, freed %u\n",
			stats.db_node_alloc, stats.db_node_free);
	ShowInfo(CL_WHITE"Database types"CL_RESET":\n"
			"DB_INT     : allocated %10u, destroyed %10u\n"
			"DB_UINT    : allocated %10u, destroyed %10u\n"
			"DB_STRING  : allocated %10u, destroyed %10u\n"
			"DB_ISTRING : allocated %10u, destroyed %10u\n"
			"DB_INT64   : allocated %10u, destroyed %10u\n"
			"DB_UINT64  : allocated %10u, destroyed %10u\n",
			stats.db_int_alloc,     stats.db_int_destroy,
			stats.db_uint_alloc,    stats.db_uint_destroy,
			stats.db_string_alloc,  stats.db_string_destroy,
			stats.db_istring_alloc, stats.db_istring_destroy,
			stats.db_int64_alloc,   stats.db_int64_destroy,
			stats.db_uint64_alloc,  stats.db_uint64_destroy);
	ShowInfo(CL_WHITE"Database function counters"CL_RESET":\n"
			"db_rotate_left     %10u, db_rotate_right    %10u,\n"
			"db_rebalance       %10u, db_rebalance_erase %10u,\n"
			"db_is_key_null     %10u,\n"
			"db_dup_key         %10u, db_dup_key_free    %10u,\n"
			"db_free_add        %10u, db_free_remove     %10u,\n"
			"db_free_lock       %10u, db_free_unlock     %10u,\n"
			"db_int_cmp         %10u, db_uint_cmp        %10u,\n"
			"db_string_cmp      %10u, db_istring_cmp     %10u,\n"
			"db_int64_cmp       %10u, db_uint64_cmp      %10u,\n"
			"db_int_hash        %10u, db_uint_hash       %10u,\n"
			"db_string_hash     %10u, db_istring_hash    %10u,\n"
			"db_int64_hash      %10u, db_uint64_hash     %10u,\n"
			"db_release_nothing %10u, db_release_key     %10u,\n"
			"db_release_data    %10u, db_release_both    %10u,\n"
			"dbit_first         %10u, dbit_last          %10u,\n"
			"dbit_next          %10u, dbit_prev          %10u,\n"
			"dbit_exists        %10u, dbit_remove        %10u,\n"
			"dbit_destroy       %10u, db_iterator        %10u,\n"
			"db_exits           %10u, db_get             %10u,\n"
			"db_getall          %10u, db_vgetall         %10u,\n"
			"db_ensure          %10u, db_vensure         %10u,\n"
			"db_put             %10u, db_remove          %10u,\n"
			"db_foreach         %10u, db_vforeach        %10u,\n"
			"db_clear           %10u, db_vclear          %10u,\n"
			"db_destroy         %10u, db_vdestroy        %10u,\n"
			"db_size            %10u, db_type            %10u,\n"
			"db_options         %10u, db_fix_options     %10u,\n"
			"db_default_cmp     %10u, db_default_hash    %10u,\n"
			"db_default_release %10u, db_custom_release  %10u,\n"
			"db_alloc           %10u, db_i2key           %10u,\n"
			"db_ui2key          %10u, db_str2key         %10u,\n"
			"db_i642key         %10u, db_ui642key        %10u,\n"
			"db_i2data          %10u, db_ui2data         %10u,\n"
			"db_ptr2data        %10u, db_data2i          %10u,\n"
			"db_data2ui         %10u, db_data2ptr        %10u,\n"
			"db_init            %10u, db_final           %10u\n",
			stats.db_rotate_left,     stats.db_rotate_right,
			stats.db_rebalance,       stats.db_rebalance_erase,
			stats.db_is_key_null,
			stats.db_dup_key,         stats.db_dup_key_free,
			stats.db_free_add,        stats.db_free_remove,
			stats.db_free_lock,       stats.db_free_unlock,
			stats.db_int_cmp,         stats.db_uint_cmp,
			stats.db_string_cmp,      stats.db_istring_cmp,
			stats.db_int64_cmp,       stats.db_uint64_cmp,
			stats.db_int_hash,        stats.db_uint_hash,
			stats.db_string_hash,     stats.db_istring_hash,
			stats.db_int64_hash,      stats.db_uint64_hash,
			stats.db_release_nothing, stats.db_release_key,
			stats.db_release_data,    stats.db_release_both,
			stats.dbit_first,         stats.dbit_last,
			stats.dbit_next,          stats.dbit_prev,
			stats.dbit_exists,        stats.dbit_remove,
			stats.dbit_destroy,       stats.db_iterator,
			stats.db_exists,          stats.db_get,
			stats.db_getall,          stats.db_vgetall,
			stats.db_ensure,          stats.db_vensure,
			stats.db_put,             stats.db_remove,
			stats.db_foreach,         stats.db_vforeach,
			stats.db_clear,           stats.db_vclear,
			stats.db_destroy,         stats.db_vdestroy,
			stats.db_size,            stats.db_type,
			stats.db_options,         stats.db_fix_options,
			stats.db_default_cmp,     stats.db_default_hash,
			stats.db_default_release, stats.db_custom_release,
			stats.db_alloc,           stats.db_i2key,
			stats.db_ui2key,          stats.db_str2key,
			stats.db_i642key,         stats.db_ui642key,
			stats.db_i2data,          stats.db_ui2data,
			stats.db_ptr2data,        stats.db_data2i,
			stats.db_data2ui,         stats.db_data2ptr,
			stats.db_init,            stats.db_final);
#endif /* DB_ENABLE_STATS */
	ers_destroy(db_iterator_ers);
	ers_destroy(db_alloc_ers);
}

// Link DB System - jAthena
void linkdb_insert(struct linkdb_node **head, void *key, void *data)
{
	struct linkdb_node *node;
	if( head == NULL ) return ;
	node = (struct linkdb_node*)aMalloc( sizeof(struct linkdb_node) );
	if( *head == NULL ) {
		// first node
		*head      = node;
		node->prev = NULL;
		node->next = NULL;
	} else {
		// link nodes
		node->next    = *head;
		node->prev    = (*head)->prev;
		(*head)->prev = node;
		(*head)       = node;
	}
	node->key  = key;
	node->data = data;
}

void linkdb_vforeach(struct linkdb_node **head, LinkDBFunc func, va_list ap)
{
	struct linkdb_node *node;
	if( head == NULL ) return;
	node = *head;
	while ( node ) {
		va_list argscopy;
		va_copy(argscopy, ap);
		func(node->key, node->data, argscopy);
		va_end(argscopy);
		node = node->next;
	}
}

void linkdb_foreach(struct linkdb_node **head, LinkDBFunc func, ...)
{
	va_list ap;
	va_start(ap, func);
	linkdb_vforeach(head, func, ap);
	va_end(ap);
}

void* linkdb_search(struct linkdb_node **head, void *key)
{
	int n = 0;
	struct linkdb_node *node;
	if( head == NULL ) return NULL;
	node = *head;
	while( node ) {
		if( node->key == key ) {
			if( node->prev && n > 5 ) {
				//Moving the head in order to improve processing efficiency
				if(node->prev) node->prev->next = node->next;
				if(node->next) node->next->prev = node->prev;
				node->next = *head;
				node->prev = (*head)->prev;
				(*head)->prev = node;
				(*head)       = node;
			}
			return node->data;
		}
		node = node->next;
		n++;
	}
	return NULL;
}

void* linkdb_erase(struct linkdb_node **head, void *key)
{
	struct linkdb_node *node;
	if( head == NULL ) return NULL;
	node = *head;
	while( node ) {
		if( node->key == key ) {
			void *data = node->data;
			if( node->prev == NULL )
				*head = node->next;
			else
				node->prev->next = node->next;
			if( node->next )
				node->next->prev = node->prev;
			aFree( node );
			return data;
		}
		node = node->next;
	}
	return NULL;
}

void linkdb_replace(struct linkdb_node **head, void *key, void *data)
{
	int n = 0;
	struct linkdb_node *node;
	if( head == NULL ) return ;
	node = *head;
	while( node ) {
		if( node->key == key ) {
			if( node->prev && n > 5 ) {
				//Moving the head in order to improve processing efficiency
				if(node->prev) node->prev->next = node->next;
				if(node->next) node->next->prev = node->prev;
				node->next = *head;
				node->prev = (*head)->prev;
				(*head)->prev = node;
				(*head)       = node;
			}
			node->data = data;
			return ;
		}
		node = node->next;
		n++;
	}
	//Insert because it can not find
	linkdb_insert( head, key, data );
}

void linkdb_final(struct linkdb_node **head)
{
	struct linkdb_node *node, *node2;
	if( head == NULL ) return ;
	node = *head;
	while( node ) {
		node2 = node->next;
		aFree( node );
		node = node2;
	}
	*head = NULL;
}

void db_defaults(void)
{
	DB = &DB_s;
	DB->alloc = db_alloc;
	DB->custom_release = db_custom_release;
	DB->data2i = db_data2i;
	DB->data2ptr = db_data2ptr;
	DB->data2ui = db_data2ui;
	DB->default_cmp = db_default_cmp;
	DB->default_hash = db_default_hash;
	DB->default_release = db_default_release;
	DB->final = db_final;
	DB->fix_options = db_fix_options;
	DB->i2data = db_i2data;
	DB->i2key = db_i2key;
	DB->init = db_init;
	DB->ptr2data = db_ptr2data;
	DB->str2key = db_str2key;
	DB->ui2data = db_ui2data;
	DB->ui2key = db_ui2key;
	DB->i642key = db_i642key;
	DB->ui642key = db_ui642key;
}