db.c 79 KB

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