db.c 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396
  1. /*****************************************************************************\
  2. * Copyright (c) Athena Dev Teams - Licensed under GNU GPL
  3. * For more information, see LICENCE in the main folder
  4. *
  5. * This file is separated in five sections:
  6. * (1) Private typedefs, enums, structures, defines and gblobal variables
  7. * (2) Private functions
  8. * (3) Protected functions used internally
  9. * (4) Protected functions used in the interface of the database
  10. * (5) Public functions
  11. *
  12. * The databases are structured as a hashtable of RED-BLACK trees.
  13. *
  14. * <B>Properties of the RED-BLACK trees being used:</B>
  15. * 1. The value of any node is greater than the value of its left child and
  16. * less than the value of its right child.
  17. * 2. Every node is colored either RED or BLACK.
  18. * 3. Every red node that is not a leaf has only black children.
  19. * 4. Every path from the root to a leaf contains the same number of black
  20. * nodes.
  21. * 5. The root node is black.
  22. * An <code>n</code> node in a RED-BLACK tree has the property that its
  23. * height is <code>O(lg(n))</code>.
  24. * Another important property is that after adding a node to a RED-BLACK
  25. * tree, the tree can be readjusted in <code>O(lg(n))</code> time.
  26. * Similarly, after deleting a node from a RED-BLACK tree, the tree can be
  27. * readjusted in <code>O(lg(n))</code> time.
  28. * {@link http://www.cs.mcgill.ca/~cs251/OldCourses/1997/topic18/}
  29. *
  30. * <B>How to add new database types:</B>
  31. * 1. Add the identifier of the new database type to the enum DBType
  32. * 2. If not already there, add the data type of the key to the union DBKey
  33. * 3. If the key can be considered NULL, update the function db_is_key_null
  34. * 4. If the key can be duplicated, update the functions db_dup_key and
  35. * db_dup_key_free
  36. * 5. Create a comparator and update the function db_default_cmp
  37. * 6. Create a hasher and update the function db_default_hash
  38. * 7. If the new database type requires or does not support some options,
  39. * update the function db_fix_options
  40. *
  41. * TODO:
  42. * - create test cases to test the database system thoroughly
  43. * - make data an enumeration
  44. * - finish this header describing the database system
  45. * - create custom database allocator
  46. * - make the system thread friendly
  47. * - change the structure of the database to T-Trees
  48. * - create a db that organizes itself by splaying
  49. *
  50. * HISTORY:
  51. * 2006/12/21 - Added 1-node cache to the database.
  52. * 2.1 (Athena build #???#) - Portability fix
  53. * - Fixed the portability of casting to union and added the functions
  54. * {@link DB#ensure(DB,DBKey,DBCreateData,...)} and
  55. * {@link DB#clear(DB,DBApply,...)}.
  56. * 2.0 (Athena build 4859) - Transition version
  57. * - Almost everything recoded with a strategy similar to objects,
  58. * database structure is maintained.
  59. * 1.0 (up to Athena build 4706)
  60. * - Previous database system.
  61. *
  62. * @version 2006/12/21
  63. * @author Athena Dev team
  64. * @encoding US-ASCII
  65. * @see #db.h
  66. \*****************************************************************************/
  67. #include <stdio.h>
  68. #include <stdlib.h>
  69. #include <string.h>
  70. #include "db.h"
  71. #include "../common/mmo.h"
  72. #include "../common/utils.h"
  73. #include "../common/malloc.h"
  74. #include "../common/showmsg.h"
  75. #include "../common/ers.h"
  76. //TODO: get rid of this
  77. #define LOWER(c) (((c)>='A' && (c) <= 'Z') ? ((c)+('a'-'A')) : (c))
  78. #define UPPER(c) (((c)>='a' && (c) <= 'z') ? ((c)+('A'-'a')) : (c))
  79. /*****************************************************************************\
  80. * (1) Private typedefs, enums, structures, defines and global variables of *
  81. * the database system. *
  82. * DB_ENABLE_STATS - Define to enable database statistics. *
  83. * HASH_SIZE - Define with the size of the hashtable. *
  84. * DBNColor - Enumeration of colors of the nodes. *
  85. * DBNode - Structure of a node in RED-BLACK trees. *
  86. * struct db_free - Structure that holds a deleted node to be freed. *
  87. * DB_impl - Struture of the database. *
  88. * stats - Statistics about the database system. *
  89. \*****************************************************************************/
  90. /**
  91. * If defined statistics about database nodes, database creating/destruction
  92. * and function usage are keept and displayed when finalizing the database
  93. * system.
  94. * WARNING: This adds overhead to every database operation (not shure how much).
  95. * @private
  96. * @see #DBStats
  97. * @see #stats
  98. * @see #db_final(void)
  99. */
  100. //#define DB_ENABLE_STATS
  101. /**
  102. * Size of the hashtable in the database.
  103. * @private
  104. * @see DB_impl#ht
  105. */
  106. #define HASH_SIZE (256+27)
  107. /**
  108. * A node in a RED-BLACK tree of the database.
  109. * @param parent Parent node
  110. * @param left Left child node
  111. * @param right Right child node
  112. * @param key Key of this database entry
  113. * @param data Data of this database entry
  114. * @param deleted If the node is deleted
  115. * @param color Color of the node
  116. * @private
  117. * @see DB_impl#ht
  118. */
  119. typedef struct dbn {
  120. // Tree structure
  121. struct dbn *parent;
  122. struct dbn *left;
  123. struct dbn *right;
  124. // Node data
  125. DBKey key;
  126. void *data;
  127. // Other
  128. enum {RED, BLACK} color;
  129. unsigned deleted : 1;
  130. } *DBNode;
  131. /**
  132. * Structure that holds a deleted node.
  133. * @param node Deleted node
  134. * @param root Address to the root of the tree
  135. * @private
  136. * @see DB_impl#free_list
  137. */
  138. struct db_free {
  139. DBNode node;
  140. DBNode *root;
  141. };
  142. /**
  143. * Complete database structure.
  144. * @param dbi Interface of the database
  145. * @param alloc_file File where the database was allocated
  146. * @param alloc_line Line in the file where the database was allocated
  147. * @param free_list Array of deleted nodes to be freed
  148. * @param free_count Number of deleted nodes in free_list
  149. * @param free_max Current maximum capacity of free_list
  150. * @param free_lock Lock for freeing the nodes
  151. * @param nodes Manager of reusable tree nodes
  152. * @param cmp Comparator of the database
  153. * @param hash Hasher of the database
  154. * @param release Releaser of the database
  155. * @param ht Hashtable of RED-BLACK trees
  156. * @param type Type of the database
  157. * @param options Options of the database
  158. * @param item_count Number of items in the database
  159. * @param maxlen Maximum length of strings in DB_STRING and DB_ISTRING databases
  160. * @param global_lock Global lock of the database
  161. * @private
  162. * @see #db_alloc(const char *,int,DBOptions,DBType,...)
  163. */
  164. typedef struct db {
  165. // Database interface
  166. struct dbt vtable;
  167. // File and line of allocation
  168. const char *alloc_file;
  169. int alloc_line;
  170. // Lock system
  171. struct db_free *free_list;
  172. unsigned int free_count;
  173. unsigned int free_max;
  174. unsigned int free_lock;
  175. // Other
  176. ERS nodes;
  177. DBComparator cmp;
  178. DBHasher hash;
  179. DBReleaser release;
  180. DBNode ht[HASH_SIZE];
  181. DBNode cache;
  182. DBType type;
  183. DBOptions options;
  184. uint32 item_count;
  185. unsigned short maxlen;
  186. unsigned global_lock : 1;
  187. } *DB_impl;
  188. #ifdef DB_ENABLE_STATS
  189. /**
  190. * Structure with what is counted when the database estatistics are enabled.
  191. * @private
  192. * @see #DB_ENABLE_STATS
  193. * @see #stats
  194. */
  195. static struct db_stats {
  196. // Node alloc/free
  197. uint32 db_node_alloc;
  198. uint32 db_node_free;
  199. // Database creating/destruction counters
  200. uint32 db_int_alloc;
  201. uint32 db_uint_alloc;
  202. uint32 db_string_alloc;
  203. uint32 db_istring_alloc;
  204. uint32 db_int_destroy;
  205. uint32 db_uint_destroy;
  206. uint32 db_string_destroy;
  207. uint32 db_istring_destroy;
  208. // Function usage counters
  209. uint32 db_rotate_left;
  210. uint32 db_rotate_right;
  211. uint32 db_rebalance;
  212. uint32 db_rebalance_erase;
  213. uint32 db_is_key_null;
  214. uint32 db_dup_key;
  215. uint32 db_dup_key_free;
  216. uint32 db_free_add;
  217. uint32 db_free_remove;
  218. uint32 db_free_lock;
  219. uint32 db_free_unlock;
  220. uint32 db_int_cmp;
  221. uint32 db_uint_cmp;
  222. uint32 db_string_cmp;
  223. uint32 db_istring_cmp;
  224. uint32 db_int_hash;
  225. uint32 db_uint_hash;
  226. uint32 db_string_hash;
  227. uint32 db_istring_hash;
  228. uint32 db_release_nothing;
  229. uint32 db_release_key;
  230. uint32 db_release_data;
  231. uint32 db_release_both;
  232. uint32 db_get;
  233. uint32 db_getall;
  234. uint32 db_vgetall;
  235. uint32 db_ensure;
  236. uint32 db_vensure;
  237. uint32 db_put;
  238. uint32 db_remove;
  239. uint32 db_foreach;
  240. uint32 db_vforeach;
  241. uint32 db_clear;
  242. uint32 db_vclear;
  243. uint32 db_destroy;
  244. uint32 db_vdestroy;
  245. uint32 db_size;
  246. uint32 db_type;
  247. uint32 db_options;
  248. uint32 db_fix_options;
  249. uint32 db_default_cmp;
  250. uint32 db_default_hash;
  251. uint32 db_default_release;
  252. uint32 db_custom_release;
  253. uint32 db_alloc;
  254. uint32 db_i2key;
  255. uint32 db_ui2key;
  256. uint32 db_str2key;
  257. uint32 db_init;
  258. uint32 db_final;
  259. } stats = {
  260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  265. 0, 0, 0, 0, 0, 0, 0, 0
  266. };
  267. #define COUNT(func) if (stats. ## func != UINT32_MAX) ++stats. ## func
  268. #endif /* DB_ENABLE_STATS */
  269. /*****************************************************************************\
  270. * (2) Section of private functions used by the database system. *
  271. * db_rotate_left - Rotate a tree node to the left. *
  272. * db_rotate_right - Rotate a tree node to the right. *
  273. * db_rebalance - Rebalance the tree. *
  274. * db_rebalance_erase - Rebalance the tree after a BLACK node was erased. *
  275. * db_is_key_null - Returns not 0 if the key is considered NULL. *
  276. * db_dup_key - Duplicate a key for internal use. *
  277. * db_dup_key_free - Free the duplicated key. *
  278. * db_free_add - Add a node to the free_list of a database. *
  279. * db_free_remove - Remove a node from the free_list of a database. *
  280. * db_free_lock - Increment the free_lock of a database. *
  281. * db_free_unlock - Decrement the free_lock of a database. *
  282. * If it was the last lock, frees the nodes in free_list. *
  283. * NOTE: Keeps the database trees balanced. *
  284. \*****************************************************************************/
  285. /**
  286. * Rotate a node to the left.
  287. * @param node Node to be rotated
  288. * @param root Pointer to the root of the tree
  289. * @private
  290. * @see #db_rebalance(DBNode,DBNode *)
  291. * @see #db_rebalance_erase(DBNode,DBNode *)
  292. */
  293. static void db_rotate_left(DBNode node, DBNode *root)
  294. {
  295. DBNode y = node->right;
  296. #ifdef DB_ENABLE_STATS
  297. COUNT(db_rotate_left);
  298. #endif /* DB_ENABLE_STATS */
  299. // put the left of y at the right of node
  300. node->right = y->left;
  301. if (y->left)
  302. y->left->parent = node;
  303. y->parent = node->parent;
  304. // link y and node's parent
  305. if (node == *root) {
  306. *root = y; // node was root
  307. } else if (node == node->parent->left) {
  308. node->parent->left = y; // node was at the left
  309. } else {
  310. node->parent->right = y; // node was at the right
  311. }
  312. // put node at the left of y
  313. y->left = node;
  314. node->parent = y;
  315. }
  316. /**
  317. * Rotate a node to the right
  318. * @param node Node to be rotated
  319. * @param root Pointer to the root of the tree
  320. * @private
  321. * @see #db_rebalance(DBNode,DBNode *)
  322. * @see #db_rebalance_erase(DBNode,DBNode *)
  323. */
  324. static void db_rotate_right(DBNode node, DBNode *root)
  325. {
  326. DBNode y = node->left;
  327. #ifdef DB_ENABLE_STATS
  328. COUNT(db_rotate_right);
  329. #endif /* DB_ENABLE_STATS */
  330. // put the right of y at the left of node
  331. node->left = y->right;
  332. if (y->right != 0)
  333. y->right->parent = node;
  334. y->parent = node->parent;
  335. // link y and node's parent
  336. if (node == *root) {
  337. *root = y; // node was root
  338. } else if (node == node->parent->right) {
  339. node->parent->right = y; // node was at the right
  340. } else {
  341. node->parent->left = y; // node was at the left
  342. }
  343. // put node at the right of y
  344. y->right = node;
  345. node->parent = y;
  346. }
  347. /**
  348. * Rebalance the RED-BLACK tree.
  349. * Called when the node and it's parent are both RED.
  350. * @param node Node to be rebalanced
  351. * @param root Pointer to the root of the tree
  352. * @private
  353. * @see #db_rotate_left(DBNode,DBNode *)
  354. * @see #db_rotate_right(DBNode,DBNode *)
  355. * @see #db_put(DB,DBKey,void *)
  356. */
  357. static void db_rebalance(DBNode node, DBNode *root)
  358. {
  359. DBNode y;
  360. #ifdef DB_ENABLE_STATS
  361. COUNT(db_rebalance);
  362. #endif /* DB_ENABLE_STATS */
  363. // Restore the RED-BLACK properties
  364. node->color = RED;
  365. while (node != *root && node->parent->color == RED) {
  366. if (node->parent == node->parent->parent->left) {
  367. // If node's parent is a left, y is node's right 'uncle'
  368. y = node->parent->parent->right;
  369. if (y && y->color == RED) { // case 1
  370. // change the colors and move up the tree
  371. node->parent->color = BLACK;
  372. y->color = BLACK;
  373. node->parent->parent->color = RED;
  374. node = node->parent->parent;
  375. } else {
  376. if (node == node->parent->right) { // case 2
  377. // move up and rotate
  378. node = node->parent;
  379. db_rotate_left(node, root);
  380. }
  381. // case 3
  382. node->parent->color = BLACK;
  383. node->parent->parent->color = RED;
  384. db_rotate_right(node->parent->parent, root);
  385. }
  386. } else {
  387. // If node's parent is a right, y is node's left 'uncle'
  388. y = node->parent->parent->left;
  389. if (y && y->color == RED) { // case 1
  390. // change the colors and move up the tree
  391. node->parent->color = BLACK;
  392. y->color = BLACK;
  393. node->parent->parent->color = RED;
  394. node = node->parent->parent;
  395. } else {
  396. if (node == node->parent->left) { // case 2
  397. // move up and rotate
  398. node = node->parent;
  399. db_rotate_right(node, root);
  400. }
  401. // case 3
  402. node->parent->color = BLACK;
  403. node->parent->parent->color = RED;
  404. db_rotate_left(node->parent->parent, root);
  405. }
  406. }
  407. }
  408. (*root)->color = BLACK; // the root can and should always be black
  409. }
  410. /**
  411. * Erase a node from the RED-BLACK tree, keeping the tree balanced.
  412. * @param node Node to be erased from the tree
  413. * @param root Root of the tree
  414. * @private
  415. * @see #db_rotate_left(DBNode,DBNode *)
  416. * @see #db_rotate_right(DBNode,DBNode *)
  417. * @see #db_free_unlock(DB_impl)
  418. */
  419. static void db_rebalance_erase(DBNode node, DBNode *root)
  420. {
  421. DBNode y = node;
  422. DBNode x = NULL;
  423. DBNode x_parent = NULL;
  424. DBNode w;
  425. #ifdef DB_ENABLE_STATS
  426. COUNT(db_rebalance_erase);
  427. #endif /* DB_ENABLE_STATS */
  428. // Select where to change the tree
  429. if (y->left == NULL) { // no left
  430. x = y->right;
  431. } else if (y->right == NULL) { // no right
  432. x = y->left;
  433. } else { // both exist, go to the leftmost node of the right sub-tree
  434. y = y->right;
  435. while (y->left != NULL)
  436. y = y->left;
  437. x = y->right;
  438. }
  439. // Remove the node from the tree
  440. if (y != node) { // both childs existed
  441. // put the left of 'node' in the left of 'y'
  442. node->left->parent = y;
  443. y->left = node->left;
  444. // 'y' is not the direct child of 'node'
  445. if (y != node->right) {
  446. // put 'x' in the old position of 'y'
  447. x_parent = y->parent;
  448. if (x) x->parent = y->parent;
  449. y->parent->left = x;
  450. // put the right of 'node' in 'y'
  451. y->right = node->right;
  452. node->right->parent = y;
  453. // 'y' is a direct child of 'node'
  454. } else {
  455. x_parent = y;
  456. }
  457. // link 'y' and the parent of 'node'
  458. if (*root == node) {
  459. *root = y; // 'node' was the root
  460. } else if (node->parent->left == node) {
  461. node->parent->left = y; // 'node' was at the left
  462. } else {
  463. node->parent->right = y; // 'node' was at the right
  464. }
  465. y->parent = node->parent;
  466. // switch colors
  467. {
  468. int tmp = y->color;
  469. y->color = node->color;
  470. node->color = tmp;
  471. }
  472. y = node;
  473. } else { // one child did not exist
  474. // put x in node's position
  475. x_parent = y->parent;
  476. if (x) x->parent = y->parent;
  477. // link x and node's parent
  478. if (*root == node) {
  479. *root = x; // node was the root
  480. } else if (node->parent->left == node) {
  481. node->parent->left = x; // node was at the left
  482. } else {
  483. node->parent->right = x; // node was at the right
  484. }
  485. }
  486. // Restore the RED-BLACK properties
  487. if (y->color != RED) {
  488. while (x != *root && (x == NULL || x->color == BLACK)) {
  489. if (x == x_parent->left) {
  490. w = x_parent->right;
  491. if (w->color == RED) {
  492. w->color = BLACK;
  493. x_parent->color = RED;
  494. db_rotate_left(x_parent, root);
  495. w = x_parent->right;
  496. }
  497. if ((w->left == NULL || w->left->color == BLACK) &&
  498. (w->right == NULL || w->right->color == BLACK)) {
  499. w->color = RED;
  500. x = x_parent;
  501. x_parent = x_parent->parent;
  502. } else {
  503. if (w->right == NULL || w->right->color == BLACK) {
  504. if (w->left) w->left->color = BLACK;
  505. w->color = RED;
  506. db_rotate_right(w, root);
  507. w = x_parent->right;
  508. }
  509. w->color = x_parent->color;
  510. x_parent->color = BLACK;
  511. if (w->right) w->right->color = BLACK;
  512. db_rotate_left(x_parent, root);
  513. break;
  514. }
  515. } else {
  516. w = x_parent->left;
  517. if (w->color == RED) {
  518. w->color = BLACK;
  519. x_parent->color = RED;
  520. db_rotate_right(x_parent, root);
  521. w = x_parent->left;
  522. }
  523. if ((w->right == NULL || w->right->color == BLACK) &&
  524. (w->left == NULL || w->left->color == BLACK)) {
  525. w->color = RED;
  526. x = x_parent;
  527. x_parent = x_parent->parent;
  528. } else {
  529. if (w->left == NULL || w->left->color == BLACK) {
  530. if (w->right) w->right->color = BLACK;
  531. w->color = RED;
  532. db_rotate_left(w, root);
  533. w = x_parent->left;
  534. }
  535. w->color = x_parent->color;
  536. x_parent->color = BLACK;
  537. if (w->left) w->left->color = BLACK;
  538. db_rotate_right(x_parent, root);
  539. break;
  540. }
  541. }
  542. }
  543. if (x) x->color = BLACK;
  544. }
  545. }
  546. /**
  547. * Returns not 0 if the key is considerd to be NULL.
  548. * @param type Type of database
  549. * @param key Key being tested
  550. * @return not 0 if considered NULL, 0 otherwise
  551. * @private
  552. * @see #db_get(DB,DBKey)
  553. * @see #db_put(DB,DBKey,void *)
  554. * @see #db_remove(DB,DBKey)
  555. */
  556. static int db_is_key_null(DBType type, DBKey key)
  557. {
  558. #ifdef DB_ENABLE_STATS
  559. COUNT(db_is_key_null);
  560. #endif /* DB_ENABLE_STATS */
  561. switch (type) {
  562. case DB_STRING:
  563. case DB_ISTRING:
  564. return (key.str == NULL);
  565. default: // Not a pointer
  566. return 0;
  567. }
  568. }
  569. /**
  570. * Duplicate the key used in the database.
  571. * @param db Database the key is being used in
  572. * @param key Key to be duplicated
  573. * @param Duplicated key
  574. * @private
  575. * @see #db_free_add(DB_impl,DBNode,DBNode *)
  576. * @see #db_free_remove(DB_impl,DBNode)
  577. * @see #db_put(DB,DBKey,void *)
  578. * @see #db_dup_key_free(DB_impl,DBKey)
  579. */
  580. static DBKey db_dup_key(DB_impl db, DBKey key)
  581. {
  582. unsigned char *str;
  583. #ifdef DB_ENABLE_STATS
  584. COUNT(db_dup_key);
  585. #endif /* DB_ENABLE_STATS */
  586. switch (db->type) {
  587. case DB_STRING:
  588. case DB_ISTRING:
  589. if (db->maxlen) {
  590. CREATE(str, unsigned char, db->maxlen +1);
  591. memcpy(str, key.str, db->maxlen);
  592. str[db->maxlen] = '\0';
  593. key.str = str;
  594. } else {
  595. key.str = (unsigned char *)aStrdup((const char *)key.str);
  596. }
  597. return key;
  598. default:
  599. return key;
  600. }
  601. }
  602. /**
  603. * Free a key duplicated by db_dup_key.
  604. * @param db Database the key is being used in
  605. * @param key Key to be freed
  606. * @private
  607. * @see #db_dup_key(DB_impl,DBKey)
  608. */
  609. static void db_dup_key_free(DB_impl db, DBKey key)
  610. {
  611. #ifdef DB_ENABLE_STATS
  612. COUNT(db_dup_key_free);
  613. #endif /* DB_ENABLE_STATS */
  614. switch (db->type) {
  615. case DB_STRING:
  616. case DB_ISTRING:
  617. aFree(key.str);
  618. return;
  619. default:
  620. return;
  621. }
  622. }
  623. /**
  624. * Add a node to the free_list of the database.
  625. * Marks the node as deleted.
  626. * If the key isn't duplicated, the key is duplicated and released.
  627. * @param db Target database
  628. * @param root Root of the tree from the node
  629. * @param node Target node
  630. * @private
  631. * @see #struct db_free
  632. * @see DB_impl#free_list
  633. * @see DB_impl#free_count
  634. * @see DB_impl#free_max
  635. * @see #db_remove(DB,DBKey)
  636. * @see #db_free_remove(DB_impl,DBNode)
  637. */
  638. static void db_free_add(DB_impl db, DBNode node, DBNode *root)
  639. {
  640. DBKey old_key;
  641. #ifdef DB_ENABLE_STATS
  642. COUNT(db_free_add);
  643. #endif /* DB_ENABLE_STATS */
  644. if (db->free_lock == (unsigned int)~0) {
  645. ShowFatalError("db_free_add: free_lock overflow\n"
  646. "Database allocated at %s:%d\n",
  647. db->alloc_file, db->alloc_line);
  648. exit(EXIT_FAILURE);
  649. }
  650. if (!(db->options&DB_OPT_DUP_KEY)) { // Make shure we have a key until the node is freed
  651. old_key = node->key;
  652. node->key = db_dup_key(db, node->key);
  653. db->release(old_key, node->data, DB_RELEASE_KEY);
  654. }
  655. if (db->free_count == db->free_max) { // No more space, expand free_list
  656. db->free_max = (db->free_max<<2) +3; // = db->free_max*4 +3
  657. if (db->free_max <= db->free_count) {
  658. if (db->free_count == (unsigned int)~0) {
  659. ShowFatalError("db_free_add: free_count overflow\n"
  660. "Database allocated at %s:%d\n",
  661. db->alloc_file, db->alloc_line);
  662. exit(EXIT_FAILURE);
  663. }
  664. db->free_max = (unsigned int)~0;
  665. }
  666. RECREATE(db->free_list, struct db_free, db->free_max);
  667. }
  668. node->deleted = 1;
  669. db->free_list[db->free_count].node = node;
  670. db->free_list[db->free_count].root = root;
  671. db->free_count++;
  672. db->item_count--;
  673. }
  674. /**
  675. * Remove a node from the free_list of the database.
  676. * Marks the node as not deleted.
  677. * NOTE: Frees the duplicated key of the node.
  678. * @param db Target database
  679. * @param node Node being removed from free_list
  680. * @private
  681. * @see #struct db_free
  682. * @see DB_impl#free_list
  683. * @see DB_impl#free_count
  684. * @see #db_put(DB,DBKey,void *)
  685. * @see #db_free_add(DB_impl,DBNode *,DBNode)
  686. */
  687. static void db_free_remove(DB_impl db, DBNode node)
  688. {
  689. unsigned int i;
  690. #ifdef DB_ENABLE_STATS
  691. COUNT(db_free_remove);
  692. #endif /* DB_ENABLE_STATS */
  693. for (i = 0; i < db->free_count; i++) {
  694. if (db->free_list[i].node == node) {
  695. if (i < db->free_count -1) // copy the last item to where the removed one was
  696. memcpy(&db->free_list[i], &db->free_list[db->free_count -1], sizeof(struct db_free));
  697. db_dup_key_free(db, node->key);
  698. break;
  699. }
  700. }
  701. node->deleted = 0;
  702. if (i == db->free_count) {
  703. ShowWarning("db_free_remove: node was not found - database allocated at %s:%d\n", db->alloc_file, db->alloc_line);
  704. } else {
  705. db->free_count--;
  706. }
  707. db->item_count++;
  708. }
  709. /**
  710. * Increment the free_lock of the database.
  711. * @param db Target database
  712. * @private
  713. * @see DB_impl#free_lock
  714. * @see #db_unlock(DB_impl)
  715. */
  716. static void db_free_lock(DB_impl db)
  717. {
  718. #ifdef DB_ENABLE_STATS
  719. COUNT(db_free_lock);
  720. #endif /* DB_ENABLE_STATS */
  721. if (db->free_lock == (unsigned int)~0) {
  722. ShowFatalError("db_free_lock: free_lock overflow\n"
  723. "Database allocated at %s:%d\n",
  724. db->alloc_file, db->alloc_line);
  725. exit(EXIT_FAILURE);
  726. }
  727. db->free_lock++;
  728. }
  729. /**
  730. * Decrement the free_lock of the database.
  731. * If it was the last lock, frees the nodes of the database.
  732. * Keeps the tree balanced.
  733. * NOTE: Frees the duplicated keys of the nodes
  734. * @param db Target database
  735. * @private
  736. * @see DB_impl#free_lock
  737. * @see #db_free_dbn(DBNode)
  738. * @see #db_lock(DB_impl)
  739. */
  740. static void db_free_unlock(DB_impl db)
  741. {
  742. unsigned int i;
  743. #ifdef DB_ENABLE_STATS
  744. COUNT(db_free_unlock);
  745. #endif /* DB_ENABLE_STATS */
  746. if (db->free_lock == 0) {
  747. ShowWarning("db_free_unlock: free_lock was already 0\n"
  748. "Database allocated at %s:%d\n",
  749. db->alloc_file, db->alloc_line);
  750. } else {
  751. db->free_lock--;
  752. }
  753. if (db->free_lock)
  754. return; // Not last lock
  755. for (i = 0; i < db->free_count ; i++) {
  756. db_rebalance_erase(db->free_list[i].node, db->free_list[i].root);
  757. db_dup_key_free(db, db->free_list[i].node->key);
  758. #ifdef DB_ENABLE_STATS
  759. if (stats.db_node_free != (unsigned int)~0) stats.db_node_free++;
  760. #endif /* DB_ENABLE_STATS */
  761. ers_free(db->nodes, db->free_list[i].node);
  762. }
  763. db->free_count = 0;
  764. }
  765. /*****************************************************************************\
  766. * (3) Section of protected functions used internally. *
  767. * NOTE: the protected functions used in the database interface are in the *
  768. * next section. *
  769. * db_int_cmp - Default comparator for DB_INT databases. *
  770. * db_uint_cmp - Default comparator for DB_UINT databases. *
  771. * db_string_cmp - Default comparator for DB_STRING databases. *
  772. * db_istring_cmp - Default comparator for DB_ISTRING databases. *
  773. * db_int_hash - Default hasher for DB_INT databases. *
  774. * db_uint_hash - Default hasher for DB_UINT databases. *
  775. * db_string_hash - Default hasher for DB_STRING databases. *
  776. * db_istring_hash - Default hasher for DB_ISTRING databases. *
  777. * db_release_nothing - Releaser that releases nothing. *
  778. * db_release_key - Releaser that only releases the key. *
  779. * db_release_data - Releaser that only releases the data. *
  780. * db_release_both - Releaser that releases key and data. *
  781. \*****************************************************************************/
  782. /**
  783. * Default comparator for DB_INT databases.
  784. * Compares key1 to key2.
  785. * Return 0 if equal, negative if lower and positive if higher.
  786. * <code>maxlen</code> is ignored.
  787. * @param key1 Key to be compared
  788. * @param key2 Key being compared to
  789. * @param maxlen Maximum length of the key to hash
  790. * @return 0 if equal, negative if lower and positive if higher
  791. * @see DBType#DB_INT
  792. * @see #DBComparator
  793. * @see #db_default_cmp(DBType)
  794. */
  795. static int db_int_cmp(DBKey key1, DBKey key2, unsigned short maxlen)
  796. {
  797. (void)maxlen;//not used
  798. #ifdef DB_ENABLE_STATS
  799. COUNT(db_int_cmp);
  800. #endif /* DB_ENABLE_STATS */
  801. if (key1.i < key2.i) return -1;
  802. if (key1.i > key2.i) return 1;
  803. return 0;
  804. }
  805. /**
  806. * Default comparator for DB_UINT databases.
  807. * Compares key1 to key2.
  808. * Return 0 if equal, negative if lower and positive if higher.
  809. * <code>maxlen</code> is ignored.
  810. * @param key1 Key to be compared
  811. * @param key2 Key being compared to
  812. * @param maxlen Maximum length of the key to hash
  813. * @return 0 if equal, negative if lower and positive if higher
  814. * @see DBType#DB_UINT
  815. * @see #DBComparator
  816. * @see #db_default_cmp(DBType)
  817. */
  818. static int db_uint_cmp(DBKey key1, DBKey key2, unsigned short maxlen)
  819. {
  820. (void)maxlen;//not used
  821. #ifdef DB_ENABLE_STATS
  822. COUNT(db_uint_cmp);
  823. #endif /* DB_ENABLE_STATS */
  824. if (key1.ui < key2.ui) return -1;
  825. if (key1.ui > key2.ui) return 1;
  826. return 0;
  827. }
  828. /**
  829. * Default comparator for DB_STRING databases.
  830. * Compares key1 to key2.
  831. * Return 0 if equal, negative if lower and positive if higher.
  832. * @param key1 Key to be compared
  833. * @param key2 Key being compared to
  834. * @param maxlen Maximum length of the key to hash
  835. * @return 0 if equal, negative if lower and positive if higher
  836. * @see DBType#DB_STRING
  837. * @see #DBComparator
  838. * @see #db_default_cmp(DBType)
  839. */
  840. static int db_string_cmp(DBKey key1, DBKey key2, unsigned short maxlen)
  841. {
  842. #ifdef DB_ENABLE_STATS
  843. COUNT(db_string_cmp);
  844. #endif /* DB_ENABLE_STATS */
  845. if (maxlen == 0)
  846. maxlen = UINT16_MAX;
  847. return strncmp((const char *)key1.str, (const char *)key2.str, maxlen);
  848. }
  849. /**
  850. * Default comparator for DB_ISTRING databases.
  851. * Compares key1 to key2 case insensitively.
  852. * Return 0 if equal, negative if lower and positive if higher.
  853. * @param key1 Key to be compared
  854. * @param key2 Key being compared to
  855. * @param maxlen Maximum length of the key to hash
  856. * @return 0 if equal, negative if lower and positive if higher
  857. * @see DBType#DB_ISTRING
  858. * @see #DBComparator
  859. * @see #db_default_cmp(DBType)
  860. */
  861. static int db_istring_cmp(DBKey key1, DBKey key2, unsigned short maxlen)
  862. {
  863. #ifdef DB_ENABLE_STATS
  864. COUNT(db_istring_cmp);
  865. #endif /* DB_ENABLE_STATS */
  866. if (maxlen == 0)
  867. maxlen = UINT16_MAX;
  868. return strncasecmp((const char *)key1.str, (const char *)key2.str, maxlen);
  869. }
  870. /**
  871. * Default hasher for DB_INT databases.
  872. * Returns the value of the key as an unsigned int.
  873. * <code>maxlen</code> is ignored.
  874. * @param key Key to be hashed
  875. * @param maxlen Maximum length of the key to hash
  876. * @return hash of the key
  877. * @see DBType#DB_INT
  878. * @see #DBHasher
  879. * @see #db_default_hash(DBType)
  880. */
  881. static unsigned int db_int_hash(DBKey key, unsigned short maxlen)
  882. {
  883. (void)maxlen;//not used
  884. #ifdef DB_ENABLE_STATS
  885. COUNT(db_int_hash);
  886. #endif /* DB_ENABLE_STATS */
  887. return (unsigned int)key.i;
  888. }
  889. /**
  890. * Default hasher for DB_UINT databases.
  891. * Just returns the value of the key.
  892. * <code>maxlen</code> is ignored.
  893. * @param key Key to be hashed
  894. * @param maxlen Maximum length of the key to hash
  895. * @return hash of the key
  896. * @see DBType#DB_UINT
  897. * @see #DBHasher
  898. * @see #db_default_hash(DBType)
  899. */
  900. static unsigned int db_uint_hash(DBKey key, unsigned short maxlen)
  901. {
  902. (void)maxlen;//not used
  903. #ifdef DB_ENABLE_STATS
  904. COUNT(db_uint_hash);
  905. #endif /* DB_ENABLE_STATS */
  906. return key.ui;
  907. }
  908. /**
  909. * Default hasher for DB_STRING databases.
  910. * If maxlen if 0, the maximum number of maxlen is used instead.
  911. * @param key Key to be hashed
  912. * @param maxlen Maximum length of the key to hash
  913. * @return hash of the key
  914. * @see DBType#DB_STRING
  915. * @see #DBHasher
  916. * @see #db_default_hash(DBType)
  917. */
  918. static unsigned int db_string_hash(DBKey key, unsigned short maxlen)
  919. {
  920. unsigned char *k = key.str;
  921. unsigned int hash = 0;
  922. unsigned short i;
  923. #ifdef DB_ENABLE_STATS
  924. COUNT(db_string_hash);
  925. #endif /* DB_ENABLE_STATS */
  926. if (maxlen == 0)
  927. maxlen = UINT16_MAX;
  928. for (i = 0; *k; i++) {
  929. hash = (hash*33 + *k++)^(hash>>24);
  930. if (i == maxlen)
  931. break;
  932. }
  933. return hash;
  934. }
  935. /**
  936. * Default hasher for DB_ISTRING databases.
  937. * If maxlen if 0, the maximum number of maxlen is used instead.
  938. * @param key Key to be hashed
  939. * @param maxlen Maximum length of the key to hash
  940. * @return hash of the key
  941. * @see DBType#DB_ISTRING
  942. * @see #db_default_hash(DBType)
  943. */
  944. static unsigned int db_istring_hash(DBKey key, unsigned short maxlen)
  945. {
  946. unsigned char *k = key.str;
  947. unsigned int hash = 0;
  948. unsigned short i;
  949. #ifdef DB_ENABLE_STATS
  950. COUNT(db_istring_hash);
  951. #endif /* DB_ENABLE_STATS */
  952. if (maxlen == 0)
  953. maxlen = UINT16_MAX;
  954. for (i = 0; *k; i++) {
  955. hash = (hash*33 + LOWER(*k))^(hash>>24);
  956. k++;
  957. if (i == maxlen)
  958. break;
  959. }
  960. return hash;
  961. }
  962. /**
  963. * Releaser that releases nothing.
  964. * @param key Key of the database entry
  965. * @param data Data of the database entry
  966. * @param which What is being requested to be released
  967. * @protected
  968. * @see #DBReleaser
  969. * @see #db_default_releaser(DBType,DBOptions)
  970. */
  971. static void db_release_nothing(DBKey key, void *data, DBRelease which)
  972. {
  973. (void)key;(void)data;(void)which;//not used
  974. #ifdef DB_ENABLE_STATS
  975. COUNT(db_release_nothing);
  976. #endif /* DB_ENABLE_STATS */
  977. }
  978. /**
  979. * Releaser that only releases the key.
  980. * @param key Key of the database entry
  981. * @param data Data of the database entry
  982. * @param which What is being requested to be released
  983. * @protected
  984. * @see #DBReleaser
  985. * @see #db_default_release(DBType,DBOptions)
  986. */
  987. static void db_release_key(DBKey key, void *data, DBRelease which)
  988. {
  989. (void)data;//not used
  990. #ifdef DB_ENABLE_STATS
  991. COUNT(db_release_key);
  992. #endif /* DB_ENABLE_STATS */
  993. if (which&DB_RELEASE_KEY) aFree(key.str); // needs to be a pointer
  994. }
  995. /**
  996. * Releaser that only releases the data.
  997. * @param key Key of the database entry
  998. * @param data Data of the database entry
  999. * @param which What is being requested to be released
  1000. * @protected
  1001. * @see common\db.h#DBKey
  1002. * @see common\db.h#DBRelease
  1003. * @see common\db.h#DBReleaser
  1004. * @see #db_default_release(DBType,DBOptions)
  1005. */
  1006. static void db_release_data(DBKey key, void *data, DBRelease which)
  1007. {
  1008. (void)key;//not used
  1009. #ifdef DB_ENABLE_STATS
  1010. COUNT(db_release_data);
  1011. #endif /* DB_ENABLE_STATS */
  1012. if (which&DB_RELEASE_DATA) aFree(data);
  1013. }
  1014. /**
  1015. * Releaser that releases both key and data.
  1016. * @param key Key of the database entry
  1017. * @param data Data of the database entry
  1018. * @param which What is being requested to be released
  1019. * @protected
  1020. * @see common\db.h#DBKey
  1021. * @see common\db.h#DBRelease
  1022. * @see common\db.h#DBReleaser
  1023. * @see #db_default_release(DBType,DBOptions)
  1024. */
  1025. static void db_release_both(DBKey key, void *data, DBRelease which)
  1026. {
  1027. #ifdef DB_ENABLE_STATS
  1028. COUNT(db_release_both);
  1029. #endif /* DB_ENABLE_STATS */
  1030. if (which&DB_RELEASE_KEY) aFree(key.str); // needs to be a pointer
  1031. if (which&DB_RELEASE_DATA) aFree(data);
  1032. }
  1033. /*****************************************************************************\
  1034. * (4) Section with protected functions used in the interface of the *
  1035. * database. *
  1036. * db_obj_get - Get the data identified by the key. *
  1037. * db_obj_vgetall - Get the data of the matched entries. *
  1038. * db_obj_getall - Get the data of the matched entries. *
  1039. * db_obj_vensure - Get the data identified by the key, creating if it *
  1040. * doesn't exist yet. *
  1041. * db_obj_ensure - Get the data identified by the key, creating if it *
  1042. * doesn't exist yet. *
  1043. * db_obj_put - Put data identified by the key in the database. *
  1044. * db_obj_remove - Remove an entry from the database. *
  1045. * db_obj_vforeach - Apply a function to every entry in the database. *
  1046. * db_obj_foreach - Apply a function to every entry in the database. *
  1047. * db_obj_vclear - Remove all entries from the database. *
  1048. * db_obj_clear - Remove all entries from the database. *
  1049. * db_obj_vdestroy - Destroy the database, freeing all the used memory. *
  1050. * db_obj_destroy - Destroy the database, freeing all the used memory. *
  1051. * db_obj_size - Return the size of the database. *
  1052. * db_obj_type - Return the type of the database. *
  1053. * db_obj_options - Return the options of the database. *
  1054. \*****************************************************************************/
  1055. /**
  1056. * Get the data of the entry identifid by the key.
  1057. * @param self Interface of the database
  1058. * @param key Key that identifies the entry
  1059. * @return Data of the entry or NULL if not found
  1060. * @protected
  1061. * @see DB_impl::vtable#get
  1062. */
  1063. static void *db_obj_get(DB self, DBKey key)
  1064. {
  1065. DB_impl db = (DB_impl)self;
  1066. DBNode node;
  1067. int c;
  1068. void *data = NULL;
  1069. #ifdef DB_ENABLE_STATS
  1070. COUNT(db_get);
  1071. #endif /* DB_ENABLE_STATS */
  1072. if (db == NULL) return NULL; // nullpo candidate
  1073. if (!(db->options&DB_OPT_ALLOW_NULL_KEY) && db_is_key_null(db->type, key)) {
  1074. ShowError("db_get: Attempted to retrieve non-allowed NULL key for db allocated at %s:%d\n",db->alloc_file, db->alloc_line);
  1075. return NULL; // nullpo candidate
  1076. }
  1077. if (db->cache && db->cmp(key, db->cache->key, db->maxlen) == 0)
  1078. return db->cache->data; // cache hit
  1079. db_free_lock(db);
  1080. node = db->ht[db->hash(key, db->maxlen)%HASH_SIZE];
  1081. while (node) {
  1082. c = db->cmp(key, node->key, db->maxlen);
  1083. if (c == 0) {
  1084. data = node->data;
  1085. break;
  1086. }
  1087. if (c < 0)
  1088. node = node->left;
  1089. else
  1090. node = node->right;
  1091. }
  1092. db->cache = node;
  1093. db_free_unlock(db);
  1094. return data;
  1095. }
  1096. /**
  1097. * Get the data of the entries matched by <code>match</code>.
  1098. * It puts a maximum of <code>max</code> entries into <code>buf</code>.
  1099. * If <code>buf</code> is NULL, it only counts the matches.
  1100. * Returns the number of entries that matched.
  1101. * NOTE: if the value returned is greater than <code>max</code>, only the
  1102. * first <code>max</code> entries found are put into the buffer.
  1103. * @param self Interface of the database
  1104. * @param buf Buffer to put the data of the matched entries
  1105. * @param max Maximum number of data entries to be put into buf
  1106. * @param match Function that matches the database entries
  1107. * @param ... Extra arguments for match
  1108. * @return The number of entries that matched
  1109. * @protected
  1110. * @see DB_impl::vtable#vgetall
  1111. */
  1112. static unsigned int db_obj_vgetall(DB self, void **buf, unsigned int max, DBMatcher match, va_list args)
  1113. {
  1114. DB_impl db = (DB_impl)self;
  1115. unsigned int i;
  1116. DBNode node;
  1117. DBNode parent;
  1118. unsigned int ret = 0;
  1119. #ifdef DB_ENABLE_STATS
  1120. COUNT(db_vgetall);
  1121. #endif /* DB_ENABLE_STATS */
  1122. if (db == NULL) return 0; // nullpo candidate
  1123. if (match == NULL) return 0; // nullpo candidate
  1124. db_free_lock(db);
  1125. for (i = 0; i < HASH_SIZE; i++) {
  1126. // Match in the order: current node, left tree, right tree
  1127. node = db->ht[i];
  1128. while (node) {
  1129. parent = node->parent;
  1130. if (!(node->deleted) && match(node->key, node->data, args) == 0) {
  1131. if (buf && ret < max)
  1132. buf[ret] = node->data;
  1133. ret++;
  1134. }
  1135. if (node->left) {
  1136. node = node->left;
  1137. continue;
  1138. }
  1139. if (node->right) {
  1140. node = node->right;
  1141. continue;
  1142. }
  1143. while (node) {
  1144. parent = node->parent;
  1145. if (parent && parent->right && parent->left == node) {
  1146. node = parent->right;
  1147. break;
  1148. }
  1149. node = parent;
  1150. }
  1151. }
  1152. }
  1153. db_free_unlock(db);
  1154. return ret;
  1155. }
  1156. /**
  1157. * Just calls {@link DB#vgetall(DB,void **,unsigned int,DBMatch,va_list)}.
  1158. * Get the data of the entries matched by <code>match</code>.
  1159. * It puts a maximum of <code>max</code> entries into <code>buf</code>.
  1160. * If <code>buf</code> is NULL, it only counts the matches.
  1161. * Returns the number of entries that matched.
  1162. * NOTE: if the value returned is greater than <code>max</code>, only the
  1163. * first <code>max</code> entries found are put into the buffer.
  1164. * @param self Interface of the database
  1165. * @param buf Buffer to put the data of the matched entries
  1166. * @param max Maximum number of data entries to be put into buf
  1167. * @param match Function that matches the database entries
  1168. * @param ... Extra arguments for match
  1169. * @return The number of entries that matched
  1170. * @protected
  1171. * @see DB_impl::vtable#vgetall
  1172. * @see DB_impl::vtable#getall
  1173. */
  1174. static unsigned int db_obj_getall(DB self, void **buf, unsigned int max, DBMatcher match, ...)
  1175. {
  1176. va_list args;
  1177. unsigned int ret;
  1178. #ifdef DB_ENABLE_STATS
  1179. COUNT(db_getall);
  1180. #endif /* DB_ENABLE_STATS */
  1181. if (self == NULL) return 0; // nullpo candidate
  1182. va_start(args, match);
  1183. ret = self->vgetall(self, buf, max, match, args);
  1184. va_end(args);
  1185. return ret;
  1186. }
  1187. /**
  1188. * Get the data of the entry identified by the key.
  1189. * If the entry does not exist, an entry is added with the data returned by
  1190. * <code>create</code>.
  1191. * @param self Interface of the database
  1192. * @param key Key that identifies the entry
  1193. * @param create Function used to create the data if the entry doesn't exist
  1194. * @param args Extra arguments for create
  1195. * @return Data of the entry
  1196. * @protected
  1197. * @see DB_impl::vtable#vensure
  1198. */
  1199. static void *db_obj_vensure(DB self, DBKey key, DBCreateData create, va_list args)
  1200. {
  1201. DB_impl db = (DB_impl)self;
  1202. DBNode node;
  1203. DBNode parent = NULL;
  1204. unsigned int hash;
  1205. int c = 0;
  1206. void *data = NULL;
  1207. #ifdef DB_ENABLE_STATS
  1208. COUNT(db_vensure);
  1209. #endif /* DB_ENABLE_STATS */
  1210. if (db == NULL) return NULL; // nullpo candidate
  1211. if (create == NULL) {
  1212. ShowError("db_ensure: Create function is NULL for db allocated at %s:%d\n",db->alloc_file, db->alloc_line);
  1213. return NULL; // nullpo candidate
  1214. }
  1215. if (!(db->options&DB_OPT_ALLOW_NULL_KEY) && db_is_key_null(db->type, key)) {
  1216. ShowError("db_ensure: Attempted to use non-allowed NULL key for db allocated at %s:%d\n",db->alloc_file, db->alloc_line);
  1217. return NULL; // nullpo candidate
  1218. }
  1219. if (db->cache && db->cmp(key, db->cache->key, db->maxlen) == 0)
  1220. return db->cache->data; // cache hit
  1221. db_free_lock(db);
  1222. hash = db->hash(key, db->maxlen)%HASH_SIZE;
  1223. node = db->ht[hash];
  1224. while (node) {
  1225. c = db->cmp(key, node->key, db->maxlen);
  1226. if (c == 0) {
  1227. break;
  1228. }
  1229. parent = node;
  1230. if (c < 0)
  1231. node = node->left;
  1232. else
  1233. node = node->right;
  1234. }
  1235. // Create node if necessary
  1236. if (node == NULL) {
  1237. if (db->item_count == UINT32_MAX) {
  1238. ShowError("db_vensure: item_count overflow, aborting item insertion.\n"
  1239. "Database allocated at %s:%d",
  1240. db->alloc_file, db->alloc_line);
  1241. return NULL;
  1242. }
  1243. #ifdef DB_ENABLE_STATS
  1244. COUNT(db_node_alloc);
  1245. #endif /* DB_ENABLE_STATS */
  1246. node = ers_alloc(db->nodes, struct dbn);
  1247. node->left = NULL;
  1248. node->right = NULL;
  1249. node->deleted = 0;
  1250. db->item_count++;
  1251. if (c == 0) { // hash entry is empty
  1252. node->color = BLACK;
  1253. node->parent = NULL;
  1254. db->ht[hash] = node;
  1255. } else {
  1256. node->color = RED;
  1257. if (c < 0) { // put at the left
  1258. parent->left = node;
  1259. node->parent = parent;
  1260. } else { // put at the right
  1261. parent->right = node;
  1262. node->parent = parent;
  1263. }
  1264. if (parent->color == RED) // two consecutive RED nodes, must rebalance
  1265. db_rebalance(node, &db->ht[hash]);
  1266. }
  1267. // put key and data in the node
  1268. if (db->options&DB_OPT_DUP_KEY) {
  1269. node->key = db_dup_key(db, key);
  1270. if (db->options&DB_OPT_RELEASE_KEY)
  1271. db->release(key, data, DB_RELEASE_KEY);
  1272. } else {
  1273. node->key = key;
  1274. }
  1275. node->data = create(key, args);
  1276. }
  1277. data = node->data;
  1278. db->cache = node;
  1279. db_free_unlock(db);
  1280. return data;
  1281. }
  1282. /**
  1283. * Just calls {@link DB#vensure(DB,DBKey,DBCreateData,va_list)}.
  1284. * Get the data of the entry identified by the key.
  1285. * If the entry does not exist, an entry is added with the data returned by
  1286. * <code>create</code>.
  1287. * @param self Interface of the database
  1288. * @param key Key that identifies the entry
  1289. * @param create Function used to create the data if the entry doesn't exist
  1290. * @param ... Extra arguments for create
  1291. * @return Data of the entry
  1292. * @protected
  1293. * @see DB_impl::vtable#vensure
  1294. * @see DB_impl::vtable#ensure
  1295. */
  1296. static void *db_obj_ensure(DB self, DBKey key, DBCreateData create, ...)
  1297. {
  1298. va_list args;
  1299. void *ret;
  1300. #ifdef DB_ENABLE_STATS
  1301. COUNT(db_ensure);
  1302. #endif /* DB_ENABLE_STATS */
  1303. if (self == NULL) return 0; // nullpo candidate
  1304. va_start(args, create);
  1305. ret = self->vensure(self, key, create, args);
  1306. va_end(args);
  1307. return ret;
  1308. }
  1309. /**
  1310. * Put the data identified by the key in the database.
  1311. * Returns the previous data if the entry exists or NULL.
  1312. * NOTE: Uses the new key, the old one is released.
  1313. * @param self Interface of the database
  1314. * @param key Key that identifies the data
  1315. * @param data Data to be put in the database
  1316. * @return The previous data if the entry exists or NULL
  1317. * @protected
  1318. * @see #db_malloc_dbn(void)
  1319. * @see DB_impl::vtable#put
  1320. */
  1321. static void *db_obj_put(DB self, DBKey key, void *data)
  1322. {
  1323. DB_impl db = (DB_impl)self;
  1324. DBNode node;
  1325. DBNode parent = NULL;
  1326. int c = 0;
  1327. unsigned int hash;
  1328. void *old_data = NULL;
  1329. #ifdef DB_ENABLE_STATS
  1330. COUNT(db_put);
  1331. #endif /* DB_ENABLE_STATS */
  1332. if (db == NULL) return NULL; // nullpo candidate
  1333. if (db->global_lock) {
  1334. ShowError("db_put: Database is being destroyed, aborting entry insertion.\n"
  1335. "Database allocated at %s:%d\n",
  1336. db->alloc_file, db->alloc_line);
  1337. return NULL; // nullpo candidate
  1338. }
  1339. if (!(db->options&DB_OPT_ALLOW_NULL_KEY) && db_is_key_null(db->type, key)) {
  1340. ShowError("db_put: Attempted to use non-allowed NULL key for db allocated at %s:%d\n",db->alloc_file, db->alloc_line);
  1341. return NULL; // nullpo candidate
  1342. }
  1343. if (!(data || db->options&DB_OPT_ALLOW_NULL_DATA)) {
  1344. ShowError("db_put: Attempted to use non-allowed NULL data for db allocated at %s:%d\n",db->alloc_file, db->alloc_line);
  1345. return NULL; // nullpo candidate
  1346. }
  1347. if (db->item_count == UINT32_MAX) {
  1348. ShowError("db_put: item_count overflow, aborting item insertion.\n"
  1349. "Database allocated at %s:%d",
  1350. db->alloc_file, db->alloc_line);
  1351. return NULL;
  1352. }
  1353. // search for an equal node
  1354. db_free_lock(db);
  1355. hash = db->hash(key, db->maxlen)%HASH_SIZE;
  1356. for (node = db->ht[hash]; node; ) {
  1357. c = db->cmp(key, node->key, db->maxlen);
  1358. if (c == 0) { // equal entry, replace
  1359. if (node->deleted) {
  1360. db_free_remove(db, node);
  1361. } else {
  1362. db->release(node->key, node->data, DB_RELEASE_BOTH);
  1363. }
  1364. old_data = node->data;
  1365. break;
  1366. }
  1367. parent = node;
  1368. if (c < 0) {
  1369. node = node->left;
  1370. } else {
  1371. node = node->right;
  1372. }
  1373. }
  1374. // allocate a new node if necessary
  1375. if (node == NULL) {
  1376. #ifdef DB_ENABLE_STATS
  1377. COUNT(db_node_alloc);
  1378. #endif /* DB_ENABLE_STATS */
  1379. node = ers_alloc(db->nodes, struct dbn);
  1380. node->left = NULL;
  1381. node->right = NULL;
  1382. node->deleted = 0;
  1383. db->item_count++;
  1384. if (c == 0) { // hash entry is empty
  1385. node->color = BLACK;
  1386. node->parent = NULL;
  1387. db->ht[hash] = node;
  1388. } else {
  1389. node->color = RED;
  1390. if (c < 0) { // put at the left
  1391. parent->left = node;
  1392. node->parent = parent;
  1393. } else { // put at the right
  1394. parent->right = node;
  1395. node->parent = parent;
  1396. }
  1397. if (parent->color == RED) // two consecutive RED nodes, must rebalance
  1398. db_rebalance(node, &db->ht[hash]);
  1399. }
  1400. }
  1401. // put key and data in the node
  1402. if (db->options&DB_OPT_DUP_KEY) {
  1403. node->key = db_dup_key(db, key);
  1404. if (db->options&DB_OPT_RELEASE_KEY)
  1405. db->release(key, data, DB_RELEASE_KEY);
  1406. } else {
  1407. node->key = key;
  1408. }
  1409. node->data = data;
  1410. db->cache = node;
  1411. db_free_unlock(db);
  1412. return old_data;
  1413. }
  1414. /**
  1415. * Remove an entry from the database.
  1416. * Returns the data of the entry.
  1417. * NOTE: The key (of the database) is released in {@link #db_free_add(DB_impl,DBNode,DBNode *)}.
  1418. * @param self Interface of the database
  1419. * @param key Key that identifies the entry
  1420. * @return The data of the entry or NULL if not found
  1421. * @protected
  1422. * @see #db_free_add(DB_impl,DBNode,DBNode *)
  1423. * @see DB_impl::vtable#remove
  1424. */
  1425. static void *db_obj_remove(DB self, DBKey key)
  1426. {
  1427. DB_impl db = (DB_impl)self;
  1428. void *data = NULL;
  1429. DBNode node;
  1430. unsigned int hash;
  1431. int c = 0;
  1432. #ifdef DB_ENABLE_STATS
  1433. COUNT(db_remove);
  1434. #endif /* DB_ENABLE_STATS */
  1435. if (db == NULL) return NULL; // nullpo candidate
  1436. if (db->global_lock) {
  1437. ShowError("db_remove: Database is being destroyed. Aborting entry deletion.\n"
  1438. "Database allocated at %s:%d\n",
  1439. db->alloc_file, db->alloc_line);
  1440. return NULL; // nullpo candidate
  1441. }
  1442. if (!(db->options&DB_OPT_ALLOW_NULL_KEY) && db_is_key_null(db->type, key)) {
  1443. ShowError("db_remove: Attempted to use non-allowed NULL key for db allocated at %s:%d\n",db->alloc_file, db->alloc_line);
  1444. return NULL; // nullpo candidate
  1445. }
  1446. db_free_lock(db);
  1447. hash = db->hash(key, db->maxlen)%HASH_SIZE;
  1448. for(node = db->ht[hash]; node; ){
  1449. c = db->cmp(key, node->key, db->maxlen);
  1450. if (c == 0) {
  1451. if (!(node->deleted)) {
  1452. if (db->cache == node)
  1453. db->cache = NULL;
  1454. data = node->data;
  1455. db->release(node->key, node->data, DB_RELEASE_DATA);
  1456. db_free_add(db, node, &db->ht[hash]);
  1457. }
  1458. break;
  1459. }
  1460. if (c < 0)
  1461. node = node->left;
  1462. else
  1463. node = node->right;
  1464. }
  1465. db_free_unlock(db);
  1466. return data;
  1467. }
  1468. /**
  1469. * Apply <code>func</code> to every entry in the database.
  1470. * Returns the sum of values returned by func.
  1471. * @param self Interface of the database
  1472. * @param func Function to be applyed
  1473. * @param args Extra arguments for func
  1474. * @return Sum of the values returned by func
  1475. * @protected
  1476. * @see DB_impl::vtable#vforeach
  1477. */
  1478. static int db_obj_vforeach(DB self, DBApply func, va_list args)
  1479. {
  1480. DB_impl db = (DB_impl)self;
  1481. unsigned int i;
  1482. int sum = 0;
  1483. DBNode node;
  1484. DBNode parent;
  1485. #ifdef DB_ENABLE_STATS
  1486. COUNT(db_vforeach);
  1487. #endif /* DB_ENABLE_STATS */
  1488. if (db == NULL) return 0; // nullpo candidate
  1489. if (func == NULL) {
  1490. ShowError("db_foreach: Passed function is NULL for db allocated at %s:%d\n",db->alloc_file, db->alloc_line);
  1491. return 0; // nullpo candidate
  1492. }
  1493. db_free_lock(db);
  1494. for (i = 0; i < HASH_SIZE; i++) {
  1495. // Apply func in the order: current node, left node, right node
  1496. node = db->ht[i];
  1497. while (node) {
  1498. parent = node->parent;
  1499. if (!(node->deleted))
  1500. sum += func(node->key, node->data, args);
  1501. if (node->left) {
  1502. node = node->left;
  1503. continue;
  1504. }
  1505. if (node->right) {
  1506. node = node->right;
  1507. continue;
  1508. }
  1509. while (node) {
  1510. parent = node->parent;
  1511. if (parent && parent->right && parent->left == node) {
  1512. node = parent->right;
  1513. break;
  1514. }
  1515. node = parent;
  1516. }
  1517. }
  1518. }
  1519. db_free_unlock(db);
  1520. return sum;
  1521. }
  1522. /**
  1523. * Just calls {@link common\db.h\DB#vforeach(DB,DBApply,va_list)}.
  1524. * Apply <code>func</code> to every entry in the database.
  1525. * Returns the sum of values returned by func.
  1526. * @param self Interface of the database
  1527. * @param func Function to be applyed
  1528. * @param ... Extra arguments for func
  1529. * @return Sum of the values returned by func
  1530. * @protected
  1531. * @see DB_impl::vtable#vforeach
  1532. * @see DB_impl::vtable#foreach
  1533. */
  1534. static int db_obj_foreach(DB self, DBApply func, ...)
  1535. {
  1536. va_list args;
  1537. int ret;
  1538. #ifdef DB_ENABLE_STATS
  1539. COUNT(db_foreach);
  1540. #endif /* DB_ENABLE_STATS */
  1541. if (self == NULL) return 0; // nullpo candidate
  1542. va_start(args, func);
  1543. ret = self->vforeach(self, func, args);
  1544. va_end(args);
  1545. return ret;
  1546. }
  1547. /**
  1548. * Removes all entries from the database.
  1549. * Before deleting an entry, func is applyed to it.
  1550. * Releases the key and the data.
  1551. * Returns the sum of values returned by func, if it exists.
  1552. * @param self Interface of the database
  1553. * @param func Function to be applyed to every entry before deleting
  1554. * @param args Extra arguments for func
  1555. * @return Sum of values returned by func
  1556. * @protected
  1557. * @see DB_impl::vtable#vclear
  1558. */
  1559. static int db_obj_vclear(DB self, DBApply func, va_list args)
  1560. {
  1561. DB_impl db = (DB_impl)self;
  1562. int sum = 0;
  1563. unsigned int i;
  1564. DBNode node;
  1565. DBNode parent;
  1566. #ifdef DB_ENABLE_STATS
  1567. COUNT(db_vclear);
  1568. #endif /* DB_ENABLE_STATS */
  1569. if (db == NULL) return 0; // nullpo candidate
  1570. db_free_lock(db);
  1571. db->cache = NULL;
  1572. for (i = 0; i < HASH_SIZE; i++) {
  1573. // Apply the func and delete in the order: left tree, right tree, current node
  1574. node = db->ht[i];
  1575. db->ht[i] = NULL;
  1576. while (node) {
  1577. parent = node->parent;
  1578. if (node->left) {
  1579. node = node->left;
  1580. continue;
  1581. }
  1582. if (node->right) {
  1583. node = node->right;
  1584. continue;
  1585. }
  1586. if (node->deleted) {
  1587. db_dup_key_free(db, node->key);
  1588. } else {
  1589. if (func)
  1590. sum += func(node->key, node->data, args);
  1591. db->release(node->key, node->data, DB_RELEASE_BOTH);
  1592. node->deleted = 1;
  1593. }
  1594. #ifdef DB_ENABLE_STATS
  1595. COUNT(db_node_free);
  1596. #endif /* DB_ENABLE_STATS */
  1597. ers_free(db->nodes, node);
  1598. if (parent) {
  1599. if (parent->left == node)
  1600. parent->left = NULL;
  1601. else
  1602. parent->right = NULL;
  1603. }
  1604. node = parent;
  1605. }
  1606. db->ht[i] = NULL;
  1607. }
  1608. db->free_count = 0;
  1609. db->item_count = 0;
  1610. db_free_unlock(db);
  1611. return sum;
  1612. }
  1613. /**
  1614. * Just calls {@link common\db.h\DB#vclear(DB,DBApply,va_list)}.
  1615. * Removes all entries from the database.
  1616. * Before deleting an entry, func is applyed to it.
  1617. * Releases the key and the data.
  1618. * Returns the sum of values returned by func, if it exists.
  1619. * NOTE: This locks the database globally. Any attempt to insert or remove
  1620. * a database entry will give an error and be aborted (except for clearing).
  1621. * @param self Interface of the database
  1622. * @param func Function to be applyed to every entry before deleting
  1623. * @param ... Extra arguments for func
  1624. * @return Sum of values returned by func
  1625. * @protected
  1626. * @see DB_impl::vtable#vclear
  1627. * @see DB_impl::vtable#clear
  1628. */
  1629. static int db_obj_clear(DB self, DBApply func, ...)
  1630. {
  1631. va_list args;
  1632. int ret;
  1633. #ifdef DB_ENABLE_STATS
  1634. COUNT(db_clear);
  1635. #endif /* DB_ENABLE_STATS */
  1636. if (self == NULL) return 0; // nullpo candidate
  1637. va_start(args, func);
  1638. ret = self->vclear(self, func, args);
  1639. va_end(args);
  1640. return ret;
  1641. }
  1642. /**
  1643. * Finalize the database, feeing all the memory it uses.
  1644. * Before deleting an entry, func is applyed to it.
  1645. * Returns the sum of values returned by func, if it exists.
  1646. * NOTE: This locks the database globally. Any attempt to insert or remove
  1647. * a database entry will give an error and be aborted (except for clearing).
  1648. * @param self Interface of the database
  1649. * @param func Function to be applyed to every entry before deleting
  1650. * @param args Extra arguments for func
  1651. * @return Sum of values returned by func
  1652. * @protected
  1653. * @see DB_impl::vtable#vdestroy
  1654. */
  1655. static int db_obj_vdestroy(DB self, DBApply func, va_list args)
  1656. {
  1657. DB_impl db = (DB_impl)self;
  1658. int sum;
  1659. #ifdef DB_ENABLE_STATS
  1660. COUNT(db_vdestroy);
  1661. #endif /* DB_ENABLE_STATS */
  1662. if (db == NULL) return 0; // nullpo candidate
  1663. if (db->global_lock) {
  1664. ShowError("db_vdestroy: Database is already locked for destruction. Aborting second database destruction.\n"
  1665. "Database allocated at %s:%d\n",
  1666. db->alloc_file, db->alloc_line);
  1667. return 0;
  1668. }
  1669. if (db->free_lock)
  1670. ShowWarning("db_vdestroy: Database is still in use, %u lock(s) left. Continuing database destruction.\n"
  1671. "Database allocated at %s:%d\n",
  1672. db->alloc_file, db->alloc_line, db->free_lock);
  1673. #ifdef DB_ENABLE_STATS
  1674. switch (db->type) {
  1675. case DB_INT: COUNT(db_int_destroy); break;
  1676. case DB_UINT: COUNT(db_uint_destroy); break;
  1677. case DB_STRING: COUNT(db_string_destroy); break;
  1678. case DB_ISTRING: COUNT(db_istring_destroy); break;
  1679. }
  1680. #endif /* DB_ENABLE_STATS */
  1681. db_free_lock(db);
  1682. db->global_lock = 1;
  1683. sum = self->vclear(self, func, args);
  1684. aFree(db->free_list);
  1685. db->free_list = NULL;
  1686. db->free_max = 0;
  1687. ers_destroy(db->nodes);
  1688. db_free_unlock(db);
  1689. aFree(db);
  1690. return sum;
  1691. }
  1692. /**
  1693. * Just calls {@link DB#db_vdestroy(DB,DBApply,va_list)}.
  1694. * Finalize the database, feeing all the memory it uses.
  1695. * Before deleting an entry, func is applyed to it.
  1696. * Releases the key and the data.
  1697. * Returns the sum of values returned by func, if it exists.
  1698. * NOTE: This locks the database globally. Any attempt to insert or remove
  1699. * a database entry will give an error and be aborted.
  1700. * @param self Interface of the database
  1701. * @param func Function to be applyed to every entry before deleting
  1702. * @param ... Extra arguments for func
  1703. * @return Sum of values returned by func
  1704. * @protected
  1705. * @see DB_impl::vtable#vdestroy
  1706. * @see DB_impl::vtable#destroy
  1707. */
  1708. static int db_obj_destroy(DB self, DBApply func, ...)
  1709. {
  1710. va_list args;
  1711. int ret;
  1712. #ifdef DB_ENABLE_STATS
  1713. COUNT(db_destroy);
  1714. #endif /* DB_ENABLE_STATS */
  1715. if (self == NULL) return 0; // nullpo candidate
  1716. va_start(args, func);
  1717. ret = self->vdestroy(self, func, args);
  1718. va_end(args);
  1719. return ret;
  1720. }
  1721. /**
  1722. * Return the size of the database (number of items in the database).
  1723. * @param self Interface of the database
  1724. * @return Size of the database
  1725. * @protected
  1726. * @see DB_impl#item_count
  1727. * @see DB_impl::vtable#size
  1728. */
  1729. static unsigned int db_obj_size(DB self)
  1730. {
  1731. DB_impl db = (DB_impl)self;
  1732. unsigned int item_count;
  1733. #ifdef DB_ENABLE_STATS
  1734. COUNT(db_size);
  1735. #endif /* DB_ENABLE_STATS */
  1736. if (db == NULL) return 0; // nullpo candidate
  1737. db_free_lock(db);
  1738. item_count = db->item_count;
  1739. db_free_unlock(db);
  1740. return item_count;
  1741. }
  1742. /**
  1743. * Return the type of database.
  1744. * @param self Interface of the database
  1745. * @return Type of the database
  1746. * @protected
  1747. * @see DB_impl#type
  1748. * @see DB_impl::vtable#type
  1749. */
  1750. static DBType db_obj_type(DB self)
  1751. {
  1752. DB_impl db = (DB_impl)self;
  1753. DBType type;
  1754. #ifdef DB_ENABLE_STATS
  1755. COUNT(db_type);
  1756. #endif /* DB_ENABLE_STATS */
  1757. if (db == NULL) return -1; // nullpo candidate - TODO what should this return?
  1758. db_free_lock(db);
  1759. type = db->type;
  1760. db_free_unlock(db);
  1761. return type;
  1762. }
  1763. /**
  1764. * Return the options of the database.
  1765. * @param self Interface of the database
  1766. * @return Options of the database
  1767. * @protected
  1768. * @see DB_impl#options
  1769. * @see DB_impl::vtable#options
  1770. */
  1771. static DBOptions db_obj_options(DB self)
  1772. {
  1773. DB_impl db = (DB_impl)self;
  1774. DBOptions options;
  1775. #ifdef DB_ENABLE_STATS
  1776. COUNT(db_options);
  1777. #endif /* DB_ENABLE_STATS */
  1778. if (db == NULL) return DB_OPT_BASE; // nullpo candidate - TODO what should this return?
  1779. db_free_lock(db);
  1780. options = db->options;
  1781. db_free_unlock(db);
  1782. return options;
  1783. }
  1784. /*****************************************************************************\
  1785. * (5) Section with public functions. *
  1786. * db_fix_options - Apply database type restrictions to the options. *
  1787. * db_default_cmp - Get the default comparator for a type of database. *
  1788. * db_default_hash - Get the default hasher for a type of database. *
  1789. * db_default_release - Get the default releaser for a type of database *
  1790. * with the specified options. *
  1791. * db_custom_release - Get a releaser that behaves a certains way. *
  1792. * db_alloc - Allocate a new database. *
  1793. * db_i2key - Manual cast from 'int' to 'DBKey'. *
  1794. * db_ui2key - Manual cast from 'unsigned int' to 'DBKey'. *
  1795. * db_str2key - Manual cast from 'unsigned char *' to 'DBKey'. *
  1796. * db_init - Initialize the database system. *
  1797. * db_final - Finalize the database system. *
  1798. \*****************************************************************************/
  1799. /**
  1800. * Returns the fixed options according to the database type.
  1801. * Sets required options and unsets unsupported options.
  1802. * For numeric databases DB_OPT_DUP_KEY and DB_OPT_RELEASE_KEY are unset.
  1803. * @param type Type of the database
  1804. * @param options Original options of the database
  1805. * @return Fixed options of the database
  1806. * @private
  1807. * @see #db_default_release(DBType,DBOptions)
  1808. * @see #db_alloc(const char *,int,DBType,DBOptions,unsigned short)
  1809. */
  1810. DBOptions db_fix_options(DBType type, DBOptions options)
  1811. {
  1812. #ifdef DB_ENABLE_STATS
  1813. COUNT(db_fix_options);
  1814. #endif /* DB_ENABLE_STATS */
  1815. switch (type) {
  1816. case DB_INT:
  1817. case DB_UINT: // Numeric database, do nothing with the keys
  1818. return options&~(DB_OPT_DUP_KEY|DB_OPT_RELEASE_KEY);
  1819. default:
  1820. ShowError("db_fix_options: Unknown database type %u with options %x\n", type, options);
  1821. case DB_STRING:
  1822. case DB_ISTRING: // String databases, no fix required
  1823. return options;
  1824. }
  1825. }
  1826. /**
  1827. * Returns the default comparator for the specified type of database.
  1828. * @param type Type of database
  1829. * @return Comparator for the type of database or NULL if unknown database
  1830. * @public
  1831. * @see #db_int_cmp(DBKey,DBKey,unsigned short)
  1832. * @see #db_uint_cmp(DBKey,DBKey,unsigned short)
  1833. * @see #db_string_cmp(DBKey,DBKey,unsigned short)
  1834. * @see #db_istring_cmp(DBKey,DBKey,unsigned short)
  1835. */
  1836. DBComparator db_default_cmp(DBType type)
  1837. {
  1838. #ifdef DB_ENABLE_STATS
  1839. COUNT(db_default_cmp);
  1840. #endif /* DB_ENABLE_STATS */
  1841. switch (type) {
  1842. case DB_INT: return db_int_cmp;
  1843. case DB_UINT: return db_uint_cmp;
  1844. case DB_STRING: return db_string_cmp;
  1845. case DB_ISTRING: return db_istring_cmp;
  1846. default:
  1847. ShowError("db_default_cmp: Unknown database type %u\n", type);
  1848. return NULL;
  1849. }
  1850. }
  1851. /**
  1852. * Returns the default hasher for the specified type of database.
  1853. * @param type Type of database
  1854. * @return Hasher of the type of database or NULL if unknown database
  1855. * @public
  1856. * @see #db_int_hash(DBKey,unsigned short)
  1857. * @see #db_uint_hash(DBKey,unsigned short)
  1858. * @see #db_string_hash(DBKey,unsigned short)
  1859. * @see #db_istring_hash(DBKey,unsigned short)
  1860. */
  1861. DBHasher db_default_hash(DBType type)
  1862. {
  1863. #ifdef DB_ENABLE_STATS
  1864. COUNT(db_default_hash);
  1865. #endif /* DB_ENABLE_STATS */
  1866. switch (type) {
  1867. case DB_INT: return db_int_hash;
  1868. case DB_UINT: return db_uint_hash;
  1869. case DB_STRING: return db_string_hash;
  1870. case DB_ISTRING: return db_istring_hash;
  1871. default:
  1872. ShowError("db_default_hash: Unknown database type %u\n", type);
  1873. return NULL;
  1874. }
  1875. }
  1876. /**
  1877. * Returns the default releaser for the specified type of database with the
  1878. * specified options.
  1879. * NOTE: the options are fixed with {@link #db_fix_options(DBType,DBOptions)}
  1880. * before choosing the releaser.
  1881. * @param type Type of database
  1882. * @param options Options of the database
  1883. * @return Default releaser for the type of database with the specified options
  1884. * @public
  1885. * @see #db_release_nothing(DBKey,void *,DBRelease)
  1886. * @see #db_release_key(DBKey,void *,DBRelease)
  1887. * @see #db_release_data(DBKey,void *,DBRelease)
  1888. * @see #db_release_both(DBKey,void *,DBRelease)
  1889. * @see #db_custom_release(DBRelease)
  1890. */
  1891. DBReleaser db_default_release(DBType type, DBOptions options)
  1892. {
  1893. #ifdef DB_ENABLE_STATS
  1894. COUNT(db_default_release);
  1895. #endif /* DB_ENABLE_STATS */
  1896. options = db_fix_options(type, options);
  1897. if (options&DB_OPT_RELEASE_DATA) { // Release data, what about the key?
  1898. if (options&(DB_OPT_DUP_KEY|DB_OPT_RELEASE_KEY))
  1899. return db_release_both; // Release both key and data
  1900. return db_release_data; // Only release data
  1901. }
  1902. if (options&(DB_OPT_DUP_KEY|DB_OPT_RELEASE_KEY))
  1903. return db_release_key; // Only release key
  1904. return db_release_nothing; // Release nothing
  1905. }
  1906. /**
  1907. * Returns the releaser that releases the specified release options.
  1908. * @param which Options that specified what the releaser releases
  1909. * @return Releaser for the specified release options
  1910. * @public
  1911. * @see #db_release_nothing(DBKey,void *,DBRelease)
  1912. * @see #db_release_key(DBKey,void *,DBRelease)
  1913. * @see #db_release_data(DBKey,void *,DBRelease)
  1914. * @see #db_release_both(DBKey,void *,DBRelease)
  1915. * @see #db_default_release(DBType,DBOptions)
  1916. */
  1917. DBReleaser db_custom_release(DBRelease which)
  1918. {
  1919. #ifdef DB_ENABLE_STATS
  1920. COUNT(db_custom_release);
  1921. #endif /* DB_ENABLE_STATS */
  1922. switch (which) {
  1923. case DB_RELEASE_NOTHING: return db_release_nothing;
  1924. case DB_RELEASE_KEY: return db_release_key;
  1925. case DB_RELEASE_DATA: return db_release_data;
  1926. case DB_RELEASE_BOTH: return db_release_both;
  1927. default:
  1928. ShowError("db_custom_release: Unknown release options %u\n", which);
  1929. return NULL;
  1930. }
  1931. }
  1932. /**
  1933. * Allocate a new database of the specified type.
  1934. * NOTE: the options are fixed by {@link #db_fix_options(DBType,DBOptions)}
  1935. * before creating the database.
  1936. * @param file File where the database is being allocated
  1937. * @param line Line of the file where the database is being allocated
  1938. * @param type Type of database
  1939. * @param options Options of the database
  1940. * @param maxlen Maximum length of the string to be used as key in string
  1941. * databases
  1942. * @return The interface of the database
  1943. * @public
  1944. * @see #DB_impl
  1945. * @see #db_fix_options(DBType,DBOptions)
  1946. */
  1947. DB db_alloc(const char *file, int line, DBType type, DBOptions options, unsigned short maxlen)
  1948. {
  1949. DB_impl db;
  1950. unsigned int i;
  1951. #ifdef DB_ENABLE_STATS
  1952. if (stats.db_alloc != (unsigned int)~0) stats.db_alloc++;
  1953. switch (type) {
  1954. case DB_INT:
  1955. COUNT(db_int_alloc);
  1956. break;
  1957. case DB_UINT:
  1958. COUNT(db_uint_alloc);
  1959. break;
  1960. case DB_STRING:
  1961. COUNT(db_string_alloc);
  1962. break;
  1963. case DB_ISTRING:
  1964. COUNT(db_istring_alloc);
  1965. break;
  1966. }
  1967. #endif /* DB_ENABLE_STATS */
  1968. CREATE(db, struct db, 1);
  1969. options = db_fix_options(type, options);
  1970. /* Interface of the database */
  1971. db->vtable.get = db_obj_get;
  1972. db->vtable.getall = db_obj_getall;
  1973. db->vtable.vgetall = db_obj_vgetall;
  1974. db->vtable.ensure = db_obj_ensure;
  1975. db->vtable.vensure = db_obj_vensure;
  1976. db->vtable.put = db_obj_put;
  1977. db->vtable.remove = db_obj_remove;
  1978. db->vtable.foreach = db_obj_foreach;
  1979. db->vtable.vforeach = db_obj_vforeach;
  1980. db->vtable.clear = db_obj_clear;
  1981. db->vtable.vclear = db_obj_vclear;
  1982. db->vtable.destroy = db_obj_destroy;
  1983. db->vtable.vdestroy = db_obj_vdestroy;
  1984. db->vtable.size = db_obj_size;
  1985. db->vtable.type = db_obj_type;
  1986. db->vtable.options = db_obj_options;
  1987. /* File and line of allocation */
  1988. db->alloc_file = file;
  1989. db->alloc_line = line;
  1990. /* Lock system */
  1991. db->free_list = NULL;
  1992. db->free_count = 0;
  1993. db->free_max = 0;
  1994. db->free_lock = 0;
  1995. /* Other */
  1996. db->nodes = ers_new(sizeof(struct dbn));
  1997. db->cmp = db_default_cmp(type);
  1998. db->hash = db_default_hash(type);
  1999. db->release = db_default_release(type, options);
  2000. for (i = 0; i < HASH_SIZE; i++)
  2001. db->ht[i] = NULL;
  2002. db->cache = NULL;
  2003. db->type = type;
  2004. db->options = options;
  2005. db->item_count = 0;
  2006. db->maxlen = maxlen;
  2007. db->global_lock = 0;
  2008. return &db->vtable;
  2009. }
  2010. #ifdef DB_MANUAL_CAST_TO_UNION
  2011. /**
  2012. * Manual cast from 'int' to the union DBKey.
  2013. * Created for compilers that don't support casting to unions.
  2014. * @param key Key to be casted
  2015. * @return The key as a DBKey union
  2016. * @public
  2017. * @see #DB_MANUAL_CAST_TO_UNION
  2018. * @see #db_ui2key(unsigned int)
  2019. * @see #db_str2key(unsigned char *)
  2020. */
  2021. DBKey db_i2key(int key)
  2022. {
  2023. DBKey ret;
  2024. #ifdef DB_ENABLE_STATS
  2025. COUNT(db_i2key);
  2026. #endif /* DB_ENABLE_STATS */
  2027. ret.i = key;
  2028. return ret;
  2029. }
  2030. /**
  2031. * Manual cast from 'unsigned int' to the union DBKey.
  2032. * Created for compilers that don't support casting to unions.
  2033. * @param key Key to be casted
  2034. * @return The key as a DBKey union
  2035. * @public
  2036. * @see common\db.h#DB_MANUAL_CAST_TO_UNION
  2037. * @see #db_i2key(int)
  2038. * @see #db_str2key(unsigned char *)
  2039. * @see common\db.h#db_ui2key(unsigned int)
  2040. */
  2041. DBKey db_ui2key(unsigned int key)
  2042. {
  2043. DBKey ret;
  2044. #ifdef DB_ENABLE_STATS
  2045. COUNT(db_ui2key);
  2046. #endif /* DB_ENABLE_STATS */
  2047. ret.ui = key;
  2048. return ret;
  2049. }
  2050. /**
  2051. * Manual cast from 'unsigned char *' to the union DBKey.
  2052. * Created for compilers that don't support casting to unions.
  2053. * @param key Key to be casted
  2054. * @return The key as a DBKey union
  2055. * @public
  2056. * @see common\db.h#DB_MANUAL_CAST_TO_UNION
  2057. * @see #db_i2key(int)
  2058. * @see #db_ui2key(unsigned int)
  2059. * @see common\db.h#db_str2key(unsigned char *)
  2060. */
  2061. DBKey db_str2key(unsigned char *key)
  2062. {
  2063. DBKey ret;
  2064. #ifdef DB_ENABLE_STATS
  2065. COUNT(db_str2key);
  2066. #endif /* DB_ENABLE_STATS */
  2067. ret.str = key;
  2068. return ret;
  2069. }
  2070. #endif /* DB_MANUAL_CAST_TO_UNION */
  2071. /**
  2072. * Initialize the database system.
  2073. * @public
  2074. * @see #db_final(void)
  2075. * @see common\db.h#db_init(void)
  2076. */
  2077. void db_init(void)
  2078. {
  2079. #ifdef DB_ENABLE_STATS
  2080. COUNT(db_init);
  2081. #endif /* DB_ENABLE_STATS */
  2082. }
  2083. /**
  2084. * Finalize the database system.
  2085. * Frees the memory used by the block reusage system.
  2086. * @public
  2087. * @see common\db.h#DB_FINAL_NODE_CHECK
  2088. * @see #db_init(void)
  2089. * @see common\db.h#db_final(void)
  2090. */
  2091. void db_final(void)
  2092. {
  2093. #ifdef DB_ENABLE_STATS
  2094. if (stats.db_final != (unsigned int)~0)
  2095. stats.db_final++;
  2096. ShowInfo(CL_WHITE"Database nodes"CL_RESET":\n"
  2097. "allocated %u, freed %u\n",
  2098. stats.db_node_alloc, stats.db_node_free);
  2099. ShowInfo(CL_WHITE"Database types"CL_RESET":\n"
  2100. "DB_INT : allocated %10u, destroyed %10u\n"
  2101. "DB_UINT : allocated %10u, destroyed %10u\n"
  2102. "DB_STRING : allocated %10u, destroyed %10u\n"
  2103. "DB_ISTRING : allocated %10u, destroyed %10u\n",
  2104. stats.db_int_alloc, stats.db_int_destroy,
  2105. stats.db_uint_alloc, stats.db_uint_destroy,
  2106. stats.db_string_alloc, stats.db_string_destroy,
  2107. stats.db_istring_alloc, stats.db_istring_destroy);
  2108. ShowInfo(CL_WHITE"Database function counters"CL_RESET":\n"
  2109. "db_rotate_left %10u, db_rotate_right %10u,\n"
  2110. "db_rebalance %10u, db_rebalance_erase %10u,\n"
  2111. "db_is_key_null %10u,\n"
  2112. "db_dup_key %10u, db_dup_key_free %10u,\n"
  2113. "db_free_add %10u, db_free_remove %10u,\n"
  2114. "db_free_lock %10u, db_free_unlock %10u,\n"
  2115. "db_int_cmp %10u, db_uint_cmp %10u,\n"
  2116. "db_string_cmp %10u, db_istring_cmp %10u,\n"
  2117. "db_int_hash %10u, db_uint_hash %10u,\n"
  2118. "db_string_hash %10u, db_istring_hash %10u,\n"
  2119. "db_release_nothing %10u, db_release_key %10u,\n"
  2120. "db_release_data %10u, db_release_both %10u,\n"
  2121. "db_get %10u,\n"
  2122. "db_getall %10u, db_vgetall %10u,\n"
  2123. "db_ensure %10u, db_vensure %10u,\n"
  2124. "db_put %10u, db_remove %10u,\n"
  2125. "db_foreach %10u, db_vforeach %10u,\n"
  2126. "db_clear %10u, db_vclear %10u,\n"
  2127. "db_destroy %10u, db_vdestroy %10u,\n"
  2128. "db_size %10u, db_type %10u,\n"
  2129. "db_options %10u, db_fix_options %10u,\n"
  2130. "db_default_cmp %10u, db_default_hash %10u,\n"
  2131. "db_default_release %10u, db_custom_release %10u,\n"
  2132. "db_alloc %10u, db_i2key %10u,\n"
  2133. "db_ui2key %10u, db_str2key %10u,\n"
  2134. "db_init %10u, db_final %10u\n",
  2135. stats.db_rotate_left, stats.db_rotate_right,
  2136. stats.db_rebalance, stats.db_rebalance_erase,
  2137. stats.db_is_key_null,
  2138. stats.db_dup_key, stats.db_dup_key_free,
  2139. stats.db_free_add, stats.db_free_remove,
  2140. stats.db_free_lock, stats.db_free_unlock,
  2141. stats.db_int_cmp, stats.db_uint_cmp,
  2142. stats.db_string_cmp, stats.db_istring_cmp,
  2143. stats.db_int_hash, stats.db_uint_hash,
  2144. stats.db_string_hash, stats.db_istring_hash,
  2145. stats.db_release_nothing, stats.db_release_key,
  2146. stats.db_release_data, stats.db_release_both,
  2147. stats.db_get,
  2148. stats.db_getall, stats.db_vgetall,
  2149. stats.db_ensure, stats.db_vensure,
  2150. stats.db_put, stats.db_remove,
  2151. stats.db_foreach, stats.db_vforeach,
  2152. stats.db_clear, stats.db_vclear,
  2153. stats.db_destroy, stats.db_vdestroy,
  2154. stats.db_size, stats.db_type,
  2155. stats.db_options, stats.db_fix_options,
  2156. stats.db_default_cmp, stats.db_default_hash,
  2157. stats.db_default_release, stats.db_custom_release,
  2158. stats.db_alloc, stats.db_i2key,
  2159. stats.db_ui2key, stats.db_str2key,
  2160. stats.db_init, stats.db_final);
  2161. #endif /* DB_ENABLE_STATS */
  2162. }
  2163. // Link DB System - jAthena
  2164. void linkdb_insert( struct linkdb_node** head, void *key, void* data) {
  2165. struct linkdb_node *node;
  2166. if( head == NULL ) return ;
  2167. node = aMalloc( sizeof(struct linkdb_node) );
  2168. if( *head == NULL ) {
  2169. // first node
  2170. *head = node;
  2171. node->prev = NULL;
  2172. node->next = NULL;
  2173. } else {
  2174. // link nodes
  2175. node->next = *head;
  2176. node->prev = (*head)->prev;
  2177. (*head)->prev = node;
  2178. (*head) = node;
  2179. }
  2180. node->key = key;
  2181. node->data = data;
  2182. }
  2183. void* linkdb_search( struct linkdb_node** head, void *key) {
  2184. int n = 0;
  2185. struct linkdb_node *node;
  2186. if( head == NULL ) return NULL;
  2187. node = *head;
  2188. while( node ) {
  2189. if( node->key == key ) {
  2190. if( node->prev && n > 5 ) {
  2191. // 処理効率改善の為にheadに移動させる
  2192. if(node->prev) node->prev->next = node->next;
  2193. if(node->next) node->next->prev = node->prev;
  2194. node->next = *head;
  2195. node->prev = (*head)->prev;
  2196. (*head)->prev = node;
  2197. (*head) = node;
  2198. }
  2199. return node->data;
  2200. }
  2201. node = node->next;
  2202. n++;
  2203. }
  2204. return NULL;
  2205. }
  2206. void* linkdb_erase( struct linkdb_node** head, void *key) {
  2207. struct linkdb_node *node;
  2208. if( head == NULL ) return NULL;
  2209. node = *head;
  2210. while( node ) {
  2211. if( node->key == key ) {
  2212. void *data = node->data;
  2213. if( node->prev == NULL )
  2214. *head = node->next;
  2215. else
  2216. node->prev->next = node->next;
  2217. if( node->next )
  2218. node->next->prev = node->prev;
  2219. aFree( node );
  2220. return data;
  2221. }
  2222. node = node->next;
  2223. }
  2224. return NULL;
  2225. }
  2226. void linkdb_replace( struct linkdb_node** head, void *key, void *data ) {
  2227. int n = 0;
  2228. struct linkdb_node *node;
  2229. if( head == NULL ) return ;
  2230. node = *head;
  2231. while( node ) {
  2232. if( node->key == key ) {
  2233. if( node->prev && n > 5 ) {
  2234. // 処理効率改善の為にheadに移動させる
  2235. if(node->prev) node->prev->next = node->next;
  2236. if(node->next) node->next->prev = node->prev;
  2237. node->next = *head;
  2238. node->prev = (*head)->prev;
  2239. (*head)->prev = node;
  2240. (*head) = node;
  2241. }
  2242. node->data = data;
  2243. return ;
  2244. }
  2245. node = node->next;
  2246. n++;
  2247. }
  2248. // 見つからないので挿入
  2249. linkdb_insert( head, key, data );
  2250. }
  2251. void linkdb_final( struct linkdb_node** head ) {
  2252. struct linkdb_node *node, *node2;
  2253. if( head == NULL ) return ;
  2254. node = *head;
  2255. while( node ) {
  2256. node2 = node->next;
  2257. aFree( node );
  2258. node = node2;
  2259. }
  2260. *head = NULL;
  2261. }