db.c 85 KB

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