db.h 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646
  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 two sections: *
  6. * (1) public typedefs, enums, unions, structures and defines *
  7. * (2) public functions *
  8. * *
  9. * <B>Notes on the release system:</B> *
  10. * Whenever an entry is removed from the database both the key and the *
  11. * data are requested to be released. *
  12. * At least one entry is removed when replacing an entry, removing an *
  13. * entry, clearing the database or destroying the database. *
  14. * What is actually released is defined by the release function, the *
  15. * functions of the database only ask for the key and/or data to be *
  16. * released. *
  17. * *
  18. * TODO: *
  19. * - create a custom database allocator *
  20. * - see what functions need or should be added to the database interface *
  21. * *
  22. * HISTORY: *
  23. * 2013/08/25 - Added int64/uint64 support for keys *
  24. * 2012/03/09 - Added enum for data types (int, uint, void*) *
  25. * 2007/11/09 - Added an iterator to the database. *
  26. * 2.1 (Athena build #???#) - Portability fix *
  27. * - Fixed the portability of casting to union and added the functions *
  28. * {@link DBMap#ensure(DBMap,DBKey,DBCreateData,...)} and *
  29. * {@link DBMap#clear(DBMap,DBApply,...)}. *
  30. * 2.0 (Athena build 4859) - Transition version *
  31. * - Almost everything recoded with a strategy similar to objects, *
  32. * database structure is maintained. *
  33. * 1.0 (up to Athena build 4706) *
  34. * - Previous database system. *
  35. * *
  36. * @version 2.1 (Athena build #???#) - Portability fix *
  37. * @author (Athena build 4859) Flavio @ Amazon Project *
  38. * @author (up to Athena build 4706) Athena Dev Teams *
  39. * @encoding US-ASCII *
  40. * @see common#db.c *
  41. \*****************************************************************************/
  42. #ifndef _DB_H_
  43. #define _DB_H_
  44. #include "cbasetypes.h"
  45. #include <stdarg.h>
  46. /*****************************************************************************\
  47. * (1) Section with public typedefs, enums, unions, structures and defines. *
  48. * DBRelease - Enumeration of release options. *
  49. * DBType - Enumeration of database types. *
  50. * DBOptions - Bitfield enumeration of database options. *
  51. * DBKey - Union of used key types. *
  52. * DBDataType - Enumeration of data types. *
  53. * DBData - Struct for used data types. *
  54. * DBApply - Format of functions applied to the databases. *
  55. * DBMatcher - Format of matchers used in DBMap::getall. *
  56. * DBComparator - Format of the comparators used by the databases. *
  57. * DBHasher - Format of the hashers used by the databases. *
  58. * DBReleaser - Format of the releasers used by the databases. *
  59. * DBIterator - Database iterator. *
  60. * DBMap - Database interface. *
  61. \*****************************************************************************/
  62. /**
  63. * Bitfield with what should be released by the releaser function (if the
  64. * function supports it).
  65. * @public
  66. * @see #DBReleaser
  67. * @see #db_custom_release(DBRelease)
  68. */
  69. typedef enum DBRelease {
  70. DB_RELEASE_NOTHING = 0x0,
  71. DB_RELEASE_KEY = 0x1,
  72. DB_RELEASE_DATA = 0x2,
  73. DB_RELEASE_BOTH = DB_RELEASE_KEY|DB_RELEASE_DATA,
  74. } DBRelease;
  75. /**
  76. * Supported types of database.
  77. * See {@link #db_fix_options(DBType,DBOptions)} for restrictions of the
  78. * types of databases.
  79. * @param DB_INT Uses int's for keys
  80. * @param DB_UINT Uses unsigned int's for keys
  81. * @param DB_STRING Uses strings for keys.
  82. * @param DB_ISTRING Uses case insensitive strings for keys.
  83. * @param DB_INT64 Uses int64's for keys
  84. * @param DB_UINT64 Uses uint64's for keys
  85. * @public
  86. * @see #DBOptions
  87. * @see #DBKey
  88. * @see #db_fix_options(DBType,DBOptions)
  89. * @see #db_default_cmp(DBType)
  90. * @see #db_default_hash(DBType)
  91. * @see #db_default_release(DBType,DBOptions)
  92. * @see #db_alloc(const char *,int,DBType,DBOptions,unsigned short)
  93. */
  94. typedef enum DBType {
  95. DB_INT,
  96. DB_UINT,
  97. DB_STRING,
  98. DB_ISTRING,
  99. DB_INT64,
  100. DB_UINT64,
  101. } DBType;
  102. /**
  103. * Bitfield of options that define the behavior of the database.
  104. * See {@link #db_fix_options(DBType,DBOptions)} for restrictions of the
  105. * types of databases.
  106. * @param DB_OPT_BASE Base options: does not duplicate keys, releases nothing
  107. * and does not allow NULL keys or NULL data.
  108. * @param DB_OPT_DUP_KEY Duplicates the keys internally. If DB_OPT_RELEASE_KEY
  109. * is defined, the real key is freed as soon as the entry is added.
  110. * @param DB_OPT_RELEASE_KEY Releases the key.
  111. * @param DB_OPT_RELEASE_DATA Releases the data whenever an entry is removed
  112. * from the database.
  113. * WARNING: for functions that return the data (like DBMap::remove),
  114. * a dangling pointer will be returned.
  115. * @param DB_OPT_RELEASE_BOTH Releases both key and data.
  116. * @param DB_OPT_ALLOW_NULL_KEY Allow NULL keys in the database.
  117. * @param DB_OPT_ALLOW_NULL_DATA Allow NULL data in the database.
  118. * @public
  119. * @see #db_fix_options(DBType,DBOptions)
  120. * @see #db_default_release(DBType,DBOptions)
  121. * @see #db_alloc(const char *,int,DBType,DBOptions,unsigned short)
  122. */
  123. typedef enum DBOptions {
  124. DB_OPT_BASE = 0x00,
  125. DB_OPT_DUP_KEY = 0x01,
  126. DB_OPT_RELEASE_KEY = 0x02,
  127. DB_OPT_RELEASE_DATA = 0x04,
  128. DB_OPT_RELEASE_BOTH = DB_OPT_RELEASE_KEY|DB_OPT_RELEASE_DATA,
  129. DB_OPT_ALLOW_NULL_KEY = 0x08,
  130. DB_OPT_ALLOW_NULL_DATA = 0x10,
  131. } DBOptions;
  132. /**
  133. * Union of key types used by the database.
  134. * @param i Type of key for DB_INT databases
  135. * @param ui Type of key for DB_UINT databases
  136. * @param str Type of key for DB_STRING and DB_ISTRING databases
  137. * @public
  138. * @see #DBType
  139. * @see DBMap#get
  140. * @see DBMap#put
  141. * @see DBMap#remove
  142. */
  143. typedef union DBKey {
  144. int i;
  145. unsigned int ui;
  146. const char *str;
  147. int64 i64;
  148. uint64 ui64;
  149. } DBKey;
  150. /**
  151. * Supported types of database data.
  152. * @param DB_DATA_INT Uses ints for data.
  153. * @param DB_DATA_UINT Uses unsigned ints for data.
  154. * @param DB_DATA_PTR Uses void pointers for data.
  155. * @public
  156. * @see #DBData
  157. */
  158. typedef enum DBDataType {
  159. DB_DATA_INT,
  160. DB_DATA_UINT,
  161. DB_DATA_PTR,
  162. } DBDataType;
  163. /**
  164. * Struct for data types used by the database.
  165. * @param type Type of data
  166. * @param u Union of available data types
  167. * @param u.i Data of int type
  168. * @param u.ui Data of unsigned int type
  169. * @param u.ptr Data of void* type
  170. * @public
  171. */
  172. typedef struct DBData {
  173. DBDataType type;
  174. union {
  175. int i;
  176. unsigned int ui;
  177. void *ptr;
  178. } u;
  179. } DBData;
  180. /**
  181. * Format of functions that create the data for the key when the entry doesn't
  182. * exist in the database yet.
  183. * @param key Key of the database entry
  184. * @param args Extra arguments of the function
  185. * @return Data identified by the key to be put in the database
  186. * @public
  187. * @see DBMap#vensure
  188. * @see DBMap#ensure
  189. */
  190. typedef DBData (*DBCreateData)(DBKey key, va_list args);
  191. /**
  192. * Format of functions to be applied to an unspecified quantity of entries of
  193. * a database.
  194. * Any function that applies this function to the database will return the sum
  195. * of values returned by this function.
  196. * @param key Key of the database entry
  197. * @param data Data of the database entry
  198. * @param args Extra arguments of the function
  199. * @return Value to be added up by the function that is applying this
  200. * @public
  201. * @see DBMap#vforeach
  202. * @see DBMap#foreach
  203. * @see DBMap#vdestroy
  204. * @see DBMap#destroy
  205. */
  206. typedef int (*DBApply)(DBKey key, DBData *data, va_list args);
  207. /**
  208. * Format of functions that match database entries.
  209. * The purpose of the match depends on the function that is calling the matcher.
  210. * Returns 0 if it is a match, another number otherwise.
  211. * @param key Key of the database entry
  212. * @param data Data of the database entry
  213. * @param args Extra arguments of the function
  214. * @return 0 if a match, another number otherwise
  215. * @public
  216. * @see DBMap#getall
  217. */
  218. typedef int (*DBMatcher)(DBKey key, DBData data, va_list args);
  219. /**
  220. * Format of the comparators used internally by the database system.
  221. * Compares key1 to key2.
  222. * Returns 0 is equal, negative if lower and positive is higher.
  223. * @param key1 Key being compared
  224. * @param key2 Key we are comparing to
  225. * @param maxlen Maximum number of characters used in DB_STRING and DB_ISTRING
  226. * databases.
  227. * @return 0 if equal, negative if lower and positive if higher
  228. * @public
  229. * @see #db_default_cmp(DBType)
  230. */
  231. typedef int (*DBComparator)(DBKey key1, DBKey key2, unsigned short maxlen);
  232. /**
  233. * Format of the hashers used internally by the database system.
  234. * Creates the hash of the key.
  235. * @param key Key being hashed
  236. * @param maxlen Maximum number of characters used in DB_STRING and DB_ISTRING
  237. * databases.
  238. * @return Hash of the key
  239. * @public
  240. * @see #db_default_hash(DBType)
  241. */
  242. typedef uint64 (*DBHasher)(DBKey key, unsigned short maxlen);
  243. /**
  244. * Format of the releaser used by the database system.
  245. * Releases nothing, the key, the data or both.
  246. * All standard releasers use aFree to release.
  247. * @param key Key of the database entry
  248. * @param data Data of the database entry
  249. * @param which What is being requested to be released
  250. * @public
  251. * @see #DBRelease
  252. * @see #db_default_releaser(DBType,DBOptions)
  253. * @see #db_custom_release(DBRelease)
  254. */
  255. typedef void (*DBReleaser)(DBKey key, DBData data, DBRelease which);
  256. typedef struct DBIterator DBIterator;
  257. typedef struct DBMap DBMap;
  258. /**
  259. * Database iterator.
  260. * Supports forward iteration, backward iteration and removing entries from the database.
  261. * The iterator is initially positioned before the first entry of the database.
  262. * While the iterator exists the database is locked internally, so invoke
  263. * {@link DBIterator#destroy} as soon as possible.
  264. * @public
  265. * @see #DBMap
  266. */
  267. struct DBIterator
  268. {
  269. /**
  270. * Fetches the first entry in the database.
  271. * Returns the data of the entry.
  272. * Puts the key in out_key, if out_key is not NULL.
  273. * @param self Iterator
  274. * @param out_key Key of the entry
  275. * @return Data of the entry
  276. * @protected
  277. */
  278. DBData* (*first)(DBIterator* self, DBKey* out_key);
  279. /**
  280. * Fetches the last entry in the database.
  281. * Returns the data of the entry.
  282. * Puts the key in out_key, if out_key is not NULL.
  283. * @param self Iterator
  284. * @param out_key Key of the entry
  285. * @return Data of the entry
  286. * @protected
  287. */
  288. DBData* (*last)(DBIterator* self, DBKey* out_key);
  289. /**
  290. * Fetches the next entry in the database.
  291. * Returns the data of the entry.
  292. * Puts the key in out_key, if out_key is not NULL.
  293. * @param self Iterator
  294. * @param out_key Key of the entry
  295. * @return Data of the entry
  296. * @protected
  297. */
  298. DBData* (*next)(DBIterator* self, DBKey* out_key);
  299. /**
  300. * Fetches the previous entry in the database.
  301. * Returns the data of the entry.
  302. * Puts the key in out_key, if out_key is not NULL.
  303. * @param self Iterator
  304. * @param out_key Key of the entry
  305. * @return Data of the entry
  306. * @protected
  307. */
  308. DBData* (*prev)(DBIterator* self, DBKey* out_key);
  309. /**
  310. * Returns true if the fetched entry exists.
  311. * The databases entries might have NULL data, so use this to to test if
  312. * the iterator is done.
  313. * @param self Iterator
  314. * @return true is the entry exists
  315. * @protected
  316. */
  317. bool (*exists)(DBIterator* self);
  318. /**
  319. * Removes the current entry from the database.
  320. * NOTE: {@link DBIterator#exists} will return false until another entry
  321. * is fetched
  322. * Puts data of the removed entry in out_data, if out_data is not NULL.
  323. * @param self Iterator
  324. * @param out_data Data of the removed entry.
  325. * @return 1 if entry was removed, 0 otherwise
  326. * @protected
  327. * @see DBMap#remove
  328. */
  329. int (*remove)(DBIterator* self, DBData *out_data);
  330. /**
  331. * Destroys this iterator and unlocks the database.
  332. * @param self Iterator
  333. * @protected
  334. */
  335. void (*destroy)(DBIterator* self);
  336. };
  337. /**
  338. * Public interface of a database. Only contains functions.
  339. * All the functions take the interface as the first argument.
  340. * @public
  341. * @see #db_alloc(const char*,int,DBType,DBOptions,unsigned short)
  342. */
  343. struct DBMap {
  344. /**
  345. * Returns a new iterator for this database.
  346. * The iterator keeps the database locked until it is destroyed.
  347. * The database will keep functioning normally but will only free internal
  348. * memory when unlocked, so destroy the iterator as soon as possible.
  349. * @param self Database
  350. * @return New iterator
  351. * @protected
  352. */
  353. DBIterator* (*iterator)(DBMap* self);
  354. /**
  355. * Returns true if the entry exists.
  356. * @param self Database
  357. * @param key Key that identifies the entry
  358. * @return true is the entry exists
  359. * @protected
  360. */
  361. bool (*exists)(DBMap* self, DBKey key);
  362. /**
  363. * Get the data of the entry identified by the key.
  364. * @param self Database
  365. * @param key Key that identifies the entry
  366. * @return Data of the entry or NULL if not found
  367. * @protected
  368. */
  369. DBData* (*get)(DBMap* self, DBKey key);
  370. /**
  371. * Just calls {@link DBMap#vgetall}.
  372. * Get the data of the entries matched by <code>match</code>.
  373. * It puts a maximum of <code>max</code> entries into <code>buf</code>.
  374. * If <code>buf</code> is NULL, it only counts the matches.
  375. * Returns the number of entries that matched.
  376. * NOTE: if the value returned is greater than <code>max</code>, only the
  377. * first <code>max</code> entries found are put into the buffer.
  378. * @param self Database
  379. * @param buf Buffer to put the data of the matched entries
  380. * @param max Maximum number of data entries to be put into buf
  381. * @param match Function that matches the database entries
  382. * @param ... Extra arguments for match
  383. * @return The number of entries that matched
  384. * @protected
  385. * @see DBMap#vgetall(DBMap*,void **,unsigned int,DBMatcher,va_list)
  386. */
  387. unsigned int (*getall)(DBMap* self, DBData** buf, unsigned int max, DBMatcher match, ...);
  388. /**
  389. * Get the data of the entries matched by <code>match</code>.
  390. * It puts a maximum of <code>max</code> entries into <code>buf</code>.
  391. * If <code>buf</code> is NULL, it only counts the matches.
  392. * Returns the number of entries that matched.
  393. * NOTE: if the value returned is greater than <code>max</code>, only the
  394. * first <code>max</code> entries found are put into the buffer.
  395. * @param self Database
  396. * @param buf Buffer to put the data of the matched entries
  397. * @param max Maximum number of data entries to be put into buf
  398. * @param match Function that matches the database entries
  399. * @param ... Extra arguments for match
  400. * @return The number of entries that matched
  401. * @protected
  402. * @see DBMap#getall(DBMap*,void **,unsigned int,DBMatcher,...)
  403. */
  404. unsigned int (*vgetall)(DBMap* self, DBData** buf, unsigned int max, DBMatcher match, va_list args);
  405. /**
  406. * Just calls {@link DBMap#vensure}.
  407. * Get the data of the entry identified by the key.
  408. * If the entry does not exist, an entry is added with the data returned by
  409. * <code>create</code>.
  410. * @param self Database
  411. * @param key Key that identifies the entry
  412. * @param create Function used to create the data if the entry doesn't exist
  413. * @param ... Extra arguments for create
  414. * @return Data of the entry
  415. * @protected
  416. * @see DBMap#vensure(DBMap*,DBKey,DBCreateData,va_list)
  417. */
  418. DBData* (*ensure)(DBMap* self, DBKey key, DBCreateData create, ...);
  419. /**
  420. * Get the data of the entry identified by the key.
  421. * If the entry does not exist, an entry is added with the data returned by
  422. * <code>create</code>.
  423. * @param self Database
  424. * @param key Key that identifies the entry
  425. * @param create Function used to create the data if the entry doesn't exist
  426. * @param args Extra arguments for create
  427. * @return Data of the entry
  428. * @protected
  429. * @see DBMap#ensure(DBMap*,DBKey,DBCreateData,...)
  430. */
  431. DBData* (*vensure)(DBMap* self, DBKey key, DBCreateData create, va_list args);
  432. /**
  433. * Put the data identified by the key in the database.
  434. * Puts the previous data in out_data, if out_data is not NULL.
  435. * NOTE: Uses the new key, the old one is released.
  436. * @param self Database
  437. * @param key Key that identifies the data
  438. * @param data Data to be put in the database
  439. * @param out_data Previous data if the entry exists
  440. * @return 1 if if the entry already exists, 0 otherwise
  441. * @protected
  442. */
  443. int (*put)(DBMap* self, DBKey key, DBData data, DBData *out_data);
  444. /**
  445. * Remove an entry from the database.
  446. * Puts the previous data in out_data, if out_data is not NULL.
  447. * NOTE: The key (of the database) is released.
  448. * @param self Database
  449. * @param key Key that identifies the entry
  450. * @param out_data Previous data if the entry exists
  451. * @return 1 if if the entry already exists, 0 otherwise
  452. * @protected
  453. */
  454. int (*remove)(DBMap* self, DBKey key, DBData *out_data);
  455. /**
  456. * Just calls {@link DBMap#vforeach}.
  457. * Apply <code>func</code> to every entry in the database.
  458. * Returns the sum of values returned by func.
  459. * @param self Database
  460. * @param func Function to be applied
  461. * @param ... Extra arguments for func
  462. * @return Sum of the values returned by func
  463. * @protected
  464. * @see DBMap#vforeach(DBMap*,DBApply,va_list)
  465. */
  466. int (*foreach)(DBMap* self, DBApply func, ...);
  467. /**
  468. * Apply <code>func</code> to every entry in the database.
  469. * Returns the sum of values returned by func.
  470. * @param self Database
  471. * @param func Function to be applied
  472. * @param args Extra arguments for func
  473. * @return Sum of the values returned by func
  474. * @protected
  475. * @see DBMap#foreach(DBMap*,DBApply,...)
  476. */
  477. int (*vforeach)(DBMap* self, DBApply func, va_list args);
  478. /**
  479. * Just calls {@link DBMap#vclear}.
  480. * Removes all entries from the database.
  481. * Before deleting an entry, func is applied to it.
  482. * Releases the key and the data.
  483. * Returns the sum of values returned by func, if it exists.
  484. * @param self Database
  485. * @param func Function to be applied to every entry before deleting
  486. * @param ... Extra arguments for func
  487. * @return Sum of values returned by func
  488. * @protected
  489. * @see DBMap#vclear(DBMap*,DBApply,va_list)
  490. */
  491. int (*clear)(DBMap* self, DBApply func, ...);
  492. /**
  493. * Removes all entries from the database.
  494. * Before deleting an entry, func is applied to it.
  495. * Releases the key and the data.
  496. * Returns the sum of values returned by func, if it exists.
  497. * @param self Database
  498. * @param func Function to be applied to every entry before deleting
  499. * @param args Extra arguments for func
  500. * @return Sum of values returned by func
  501. * @protected
  502. * @see DBMap#clear(DBMap*,DBApply,...)
  503. */
  504. int (*vclear)(DBMap* self, DBApply func, va_list args);
  505. /**
  506. * Just calls {@link DBMap#vdestroy}.
  507. * Finalize the database, feeing all the memory it uses.
  508. * Before deleting an entry, func is applied to it.
  509. * Releases the key and the data.
  510. * Returns the sum of values returned by func, if it exists.
  511. * NOTE: This locks the database globally. Any attempt to insert or remove
  512. * a database entry will give an error and be aborted (except for clearing).
  513. * @param self Database
  514. * @param func Function to be applied to every entry before deleting
  515. * @param ... Extra arguments for func
  516. * @return Sum of values returned by func
  517. * @protected
  518. * @see DBMap#vdestroy(DBMap*,DBApply,va_list)
  519. */
  520. int (*destroy)(DBMap* self, DBApply func, ...);
  521. /**
  522. * Finalize the database, feeing all the memory it uses.
  523. * Before deleting an entry, func is applied to it.
  524. * Returns the sum of values returned by func, if it exists.
  525. * NOTE: This locks the database globally. Any attempt to insert or remove
  526. * a database entry will give an error and be aborted (except for clearing).
  527. * @param self Database
  528. * @param func Function to be applied to every entry before deleting
  529. * @param args Extra arguments for func
  530. * @return Sum of values returned by func
  531. * @protected
  532. * @see DBMap#destroy(DBMap*,DBApply,...)
  533. */
  534. int (*vdestroy)(DBMap* self, DBApply func, va_list args);
  535. /**
  536. * Return the size of the database (number of items in the database).
  537. * @param self Database
  538. * @return Size of the database
  539. * @protected
  540. */
  541. unsigned int (*size)(DBMap* self);
  542. /**
  543. * Return the type of the database.
  544. * @param self Database
  545. * @return Type of the database
  546. * @protected
  547. */
  548. DBType (*type)(DBMap* self);
  549. /**
  550. * Return the options of the database.
  551. * @param self Database
  552. * @return Options of the database
  553. * @protected
  554. */
  555. DBOptions (*options)(DBMap* self);
  556. };
  557. // For easy access to the common functions.
  558. #define db_exists(db,k) ( (db)->exists((db),(k)) )
  559. #define idb_exists(db,k) ( (db)->exists((db),db_i2key(k)) )
  560. #define uidb_exists(db,k) ( (db)->exists((db),db_ui2key(k)) )
  561. #define strdb_exists(db,k) ( (db)->exists((db),db_str2key(k)) )
  562. #define i64db_exists(db,k) ( (db)->exists((db),db_i642key(k)) )
  563. #define ui64db_exists(db,k) ( (db)->exists((db),db_ui642key(k)) )
  564. // Get pointer-type data from DBMaps of various key types
  565. #define db_get(db,k) ( db_data2ptr((db)->get((db),(k))) )
  566. #define idb_get(db,k) ( db_data2ptr((db)->get((db),db_i2key(k))) )
  567. #define uidb_get(db,k) ( db_data2ptr((db)->get((db),db_ui2key(k))) )
  568. #define strdb_get(db,k) ( db_data2ptr((db)->get((db),db_str2key(k))) )
  569. #define i64db_get(db,k) ( db_data2ptr((db)->get((db),db_i642key(k))) )
  570. #define ui64db_get(db,k) ( db_data2ptr((db)->get((db),db_ui642key(k))) )
  571. // Get int-type data from DBMaps of various key types
  572. #define db_iget(db,k) ( db_data2i((db)->get((db),(k))) )
  573. #define idb_iget(db,k) ( db_data2i((db)->get((db),db_i2key(k))) )
  574. #define uidb_iget(db,k) ( db_data2i((db)->get((db),db_ui2key(k))) )
  575. #define strdb_iget(db,k) ( db_data2i((db)->get((db),db_str2key(k))) )
  576. #define i64db_iget(db,k) ( db_data2i((db)->get((db),db_i642key(k))) )
  577. #define ui64db_iget(db,k) ( db_data2i((db)->get((db),db_ui642key(k))) )
  578. // Get uint-type data from DBMaps of various key types
  579. #define db_uiget(db,k) ( db_data2ui((db)->get((db),(k))) )
  580. #define idb_uiget(db,k) ( db_data2ui((db)->get((db),db_i2key(k))) )
  581. #define uidb_uiget(db,k) ( db_data2ui((db)->get((db),db_ui2key(k))) )
  582. #define strdb_uiget(db,k) ( db_data2ui((db)->get((db),db_str2key(k))) )
  583. #define i64db_uiget(db,k) ( db_data2ui((db)->get((db),db_i642key(k))) )
  584. #define ui64db_uiget(db,k) ( db_data2ui((db)->get((db),db_ui642key(k))) )
  585. // Put pointer-type data into DBMaps of various key types
  586. #define db_put(db,k,d) ( (db)->put((db),(k),db_ptr2data(d),NULL) )
  587. #define idb_put(db,k,d) ( (db)->put((db),db_i2key(k),db_ptr2data(d),NULL) )
  588. #define uidb_put(db,k,d) ( (db)->put((db),db_ui2key(k),db_ptr2data(d),NULL) )
  589. #define strdb_put(db,k,d) ( (db)->put((db),db_str2key(k),db_ptr2data(d),NULL) )
  590. #define i64db_put(db,k,d) ( (db)->put((db),db_i642key(k),db_ptr2data(d),NULL) )
  591. #define ui64db_put(db,k,d) ( (db)->put((db),db_ui642key(k),db_ptr2data(d),NULL) )
  592. // Put int-type data into DBMaps of various key types
  593. #define db_iput(db,k,d) ( (db)->put((db),(k),db_i2data(d),NULL) )
  594. #define idb_iput(db,k,d) ( (db)->put((db),db_i2key(k),db_i2data(d),NULL) )
  595. #define uidb_iput(db,k,d) ( (db)->put((db),db_ui2key(k),db_i2data(d),NULL) )
  596. #define strdb_iput(db,k,d) ( (db)->put((db),db_str2key(k),db_i2data(d),NULL) )
  597. #define i64db_iput(db,k,d) ( (db)->put((db),db_i642key(k),db_i2data(d),NULL) )
  598. #define ui64db_iput(db,k,d) ( (db)->put((db),db_ui642key(k),db_i2data(d),NULL) )
  599. // Put uint-type data into DBMaps of various key types
  600. #define db_uiput(db,k,d) ( (db)->put((db),(k),db_ui2data(d),NULL) )
  601. #define idb_uiput(db,k,d) ( (db)->put((db),db_i2key(k),db_ui2data(d),NULL) )
  602. #define uidb_uiput(db,k,d) ( (db)->put((db),db_ui2key(k),db_ui2data(d),NULL) )
  603. #define strdb_uiput(db,k,d) ( (db)->put((db),db_str2key(k),db_ui2data(d),NULL) )
  604. #define i64db_uiput(db,k,d) ( (db)->put((db),db_i642key(k),db_ui2data(d),NULL) )
  605. #define ui64db_uiput(db,k,d) ( (db)->put((db),db_ui642key(k),db_ui2data(d),NULL) )
  606. // Remove entry from DBMaps of various key types
  607. #define db_remove(db,k) ( (db)->remove((db),(k),NULL) )
  608. #define idb_remove(db,k) ( (db)->remove((db),db_i2key(k),NULL) )
  609. #define uidb_remove(db,k) ( (db)->remove((db),db_ui2key(k),NULL) )
  610. #define strdb_remove(db,k) ( (db)->remove((db),db_str2key(k),NULL) )
  611. #define i64db_remove(db,k) ( (db)->remove((db),db_i642key(k),NULL) )
  612. #define ui64db_remove(db,k) ( (db)->remove((db),db_ui642key(k),NULL) )
  613. //These are discarding the possible vargs you could send to the function, so those
  614. //that require vargs must not use these defines.
  615. #define db_ensure(db,k,f) ( db_data2ptr((db)->ensure((db),(k),(f))) )
  616. #define idb_ensure(db,k,f) ( db_data2ptr((db)->ensure((db),db_i2key(k),(f))) )
  617. #define uidb_ensure(db,k,f) ( db_data2ptr((db)->ensure((db),db_ui2key(k),(f))) )
  618. #define strdb_ensure(db,k,f) ( db_data2ptr((db)->ensure((db),db_str2key(k),(f))) )
  619. #define i64db_ensure(db,k,f) ( db_data2ptr((db)->ensure((db),db_i642key(k),(f))) )
  620. #define ui64db_ensure(db,k,f) ( db_data2ptr((db)->ensure((db),db_ui642key(k),(f))) )
  621. // Database creation and destruction macros
  622. #define idb_alloc(opt) db_alloc(__FILE__,__func__,__LINE__,DB_INT,(opt),sizeof(int))
  623. #define uidb_alloc(opt) db_alloc(__FILE__,__func__,__LINE__,DB_UINT,(opt),sizeof(unsigned int))
  624. #define strdb_alloc(opt,maxlen) db_alloc(__FILE__,__func__,__LINE__,DB_STRING,(opt),(maxlen))
  625. #define stridb_alloc(opt,maxlen) db_alloc(__FILE__,__func__,__LINE__,DB_ISTRING,(opt),(maxlen))
  626. #define i64db_alloc(opt) db_alloc(__FILE__,__func__,__LINE__,DB_INT64,(opt),sizeof(int64))
  627. #define ui64db_alloc(opt) db_alloc(__FILE__,__func__,__LINE__,DB_UINT64,(opt),sizeof(uint64))
  628. #define db_destroy(db) ( (db)->destroy((db),NULL) )
  629. // Other macros
  630. #define db_clear(db) ( (db)->clear((db),NULL) )
  631. #define db_size(db) ( (db)->size(db) )
  632. #define db_iterator(db) ( (db)->iterator(db) )
  633. #define dbi_first(dbi) ( db_data2ptr((dbi)->first((dbi),NULL)) )
  634. #define dbi_last(dbi) ( db_data2ptr((dbi)->last((dbi),NULL)) )
  635. #define dbi_next(dbi) ( db_data2ptr((dbi)->next((dbi),NULL)) )
  636. #define dbi_prev(dbi) ( db_data2ptr((dbi)->prev((dbi),NULL)) )
  637. #define dbi_remove(dbi) ( (dbi)->remove((dbi),NULL) )
  638. #define dbi_exists(dbi) ( (dbi)->exists(dbi) )
  639. #define dbi_destroy(dbi) ( (dbi)->destroy(dbi) )
  640. /*****************************************************************************\
  641. * (2) Section with public functions. *
  642. * db_fix_options - Fix the options for a type of database. *
  643. * db_default_cmp - Get the default comparator for a type of database. *
  644. * db_default_hash - Get the default hasher for a type of database. *
  645. * db_default_release - Get the default releaser for a type of database *
  646. * with the fixed options. *
  647. * db_custom_release - Get the releaser that behaves as specified. *
  648. * db_alloc - Allocate a new database. *
  649. * db_i2key - Manual cast from 'int' to 'DBKey'. *
  650. * db_ui2key - Manual cast from 'unsigned int' to 'DBKey'. *
  651. * db_str2key - Manual cast from 'unsigned char *' to 'DBKey'. *
  652. * db_i642key - Manual cast from 'int64' to 'DBKey'. *
  653. * db_ui642key - Manual cast from 'uint64' to 'DBKey'. *
  654. * db_i2data - Manual cast from 'int' to 'DBData'. *
  655. * db_ui2data - Manual cast from 'unsigned int' to 'DBData'. *
  656. * db_ptr2data - Manual cast from 'void*' to 'DBData'. *
  657. * db_data2i - Gets 'int' value from 'DBData'. *
  658. * db_data2ui - Gets 'unsigned int' value from 'DBData'. *
  659. * db_data2ptr - Gets 'void*' value from 'DBData'. *
  660. * db_init - Initializes the database system. *
  661. * db_final - Finalizes the database system. *
  662. \*****************************************************************************/
  663. /**
  664. * Returns the fixed options according to the database type.
  665. * Sets required options and unsets unsupported options.
  666. * For numeric databases DB_OPT_DUP_KEY and DB_OPT_RELEASE_KEY are unset.
  667. * @param type Type of the database
  668. * @param options Original options of the database
  669. * @return Fixed options of the database
  670. * @private
  671. * @see #DBType
  672. * @see #DBOptions
  673. * @see #db_default_release(DBType,DBOptions)
  674. */
  675. DBOptions db_fix_options(DBType type, DBOptions options);
  676. /**
  677. * Returns the default comparator for the type of database.
  678. * @param type Type of database
  679. * @return Comparator for the type of database or NULL if unknown database
  680. * @public
  681. * @see #DBType
  682. * @see #DBComparator
  683. */
  684. DBComparator db_default_cmp(DBType type);
  685. /**
  686. * Returns the default hasher for the specified type of database.
  687. * @param type Type of database
  688. * @return Hasher of the type of database or NULL if unknown database
  689. * @public
  690. * @see #DBType
  691. * @see #DBHasher
  692. */
  693. DBHasher db_default_hash(DBType type);
  694. /**
  695. * Returns the default releaser for the specified type of database with the
  696. * specified options.
  697. * NOTE: the options are fixed by {@link #db_fix_options(DBType,DBOptions)}
  698. * before choosing the releaser
  699. * @param type Type of database
  700. * @param options Options of the database
  701. * @return Default releaser for the type of database with the fixed options
  702. * @public
  703. * @see #DBType
  704. * @see #DBOptions
  705. * @see #DBReleaser
  706. * @see #db_fix_options(DBType,DBOptions)
  707. * @see #db_custom_release(DBRelease)
  708. */
  709. DBReleaser db_default_release(DBType type, DBOptions options);
  710. /**
  711. * Returns the releaser that behaves as <code>which</code> specifies.
  712. * @param which Defines what the releaser releases
  713. * @return Releaser for the specified release options
  714. * @public
  715. * @see #DBRelease
  716. * @see #DBReleaser
  717. * @see #db_default_release(DBType,DBOptions)
  718. */
  719. DBReleaser db_custom_release(DBRelease which);
  720. /**
  721. * Allocate a new database of the specified type.
  722. * It uses the default comparator, hasher and releaser of the specified
  723. * database type and fixed options.
  724. * NOTE: the options are fixed by {@link #db_fix_options(DBType,DBOptions)}
  725. * before creating the database.
  726. * @param file File where the database is being allocated
  727. * @param line Line of the file where the database is being allocated
  728. * @param type Type of database
  729. * @param options Options of the database
  730. * @param maxlen Maximum length of the string to be used as key in string
  731. * databases. If 0, the maximum number of maxlen is used (64K).
  732. * @return The interface of the database
  733. * @public
  734. * @see #DBType
  735. * @see #DBMap
  736. * @see #db_default_cmp(DBType)
  737. * @see #db_default_hash(DBType)
  738. * @see #db_default_release(DBType,DBOptions)
  739. * @see #db_fix_options(DBType,DBOptions)
  740. */
  741. DBMap* db_alloc(const char *file, const char *func, int line, DBType type, DBOptions options, unsigned short maxlen);
  742. /**
  743. * Manual cast from 'int' to the union DBKey.
  744. * @param key Key to be casted
  745. * @return The key as a DBKey union
  746. * @public
  747. */
  748. DBKey db_i2key(int key);
  749. /**
  750. * Manual cast from 'unsigned int' to the union DBKey.
  751. * @param key Key to be casted
  752. * @return The key as a DBKey union
  753. * @public
  754. */
  755. DBKey db_ui2key(unsigned int key);
  756. /**
  757. * Manual cast from 'unsigned char *' to the union DBKey.
  758. * @param key Key to be casted
  759. * @return The key as a DBKey union
  760. * @public
  761. */
  762. DBKey db_str2key(const char *key);
  763. /**
  764. * Manual cast from 'int64' to the union DBKey.
  765. * @param key Key to be casted
  766. * @return The key as a DBKey union
  767. * @public
  768. */
  769. DBKey db_i642key(int64 key);
  770. /**
  771. * Manual cast from 'uint64' to the union DBKey.
  772. * @param key Key to be casted
  773. * @return The key as a DBKey union
  774. * @public
  775. */
  776. DBKey db_ui642key(uint64 key);
  777. /**
  778. * Manual cast from 'int' to the struct DBData.
  779. * @param data Data to be casted
  780. * @return The data as a DBData struct
  781. * @public
  782. */
  783. DBData db_i2data(int data);
  784. /**
  785. * Manual cast from 'unsigned int' to the struct DBData.
  786. * @param data Data to be casted
  787. * @return The data as a DBData struct
  788. * @public
  789. */
  790. DBData db_ui2data(unsigned int data);
  791. /**
  792. * Manual cast from 'void *' to the struct DBData.
  793. * @param data Data to be casted
  794. * @return The data as a DBData struct
  795. * @public
  796. */
  797. DBData db_ptr2data(void *data);
  798. /**
  799. * Gets int type data from struct DBData.
  800. * If data is not int type, returns 0.
  801. * @param data Data
  802. * @return Integer value of the data.
  803. * @public
  804. */
  805. int db_data2i(DBData *data);
  806. /**
  807. * Gets unsigned int type data from struct DBData.
  808. * If data is not unsigned int type, returns 0.
  809. * @param data Data
  810. * @return Unsigned int value of the data.
  811. * @public
  812. */
  813. unsigned int db_data2ui(DBData *data);
  814. /**
  815. * Gets void* type data from struct DBData.
  816. * If data is not void* type, returns NULL.
  817. * @param data Data
  818. * @return Void* value of the data.
  819. * @public
  820. */
  821. void* db_data2ptr(DBData *data);
  822. /**
  823. * Initialize the database system.
  824. * @public
  825. * @see #db_final(void)
  826. */
  827. void db_init(void);
  828. /**
  829. * Finalize the database system.
  830. * Frees the memory used by the block reusage system.
  831. * @public
  832. * @see #db_init(void)
  833. */
  834. void db_final(void);
  835. // Link DB System - From jAthena
  836. struct linkdb_node {
  837. struct linkdb_node *next;
  838. struct linkdb_node *prev;
  839. void *key;
  840. void *data;
  841. };
  842. typedef void (*LinkDBFunc)(void* key, void* data, va_list args);
  843. void linkdb_insert (struct linkdb_node** head, void *key, void* data); // Doesn't take into account duplicate keys
  844. void linkdb_replace (struct linkdb_node** head, void *key, void* data); // Takes into account duplicate keys
  845. void* linkdb_search (struct linkdb_node** head, void *key);
  846. void* linkdb_erase (struct linkdb_node** head, void *key);
  847. void linkdb_final (struct linkdb_node** head);
  848. void linkdb_vforeach(struct linkdb_node** head, LinkDBFunc func, va_list ap);
  849. void linkdb_foreach (struct linkdb_node** head, LinkDBFunc func, ...);
  850. /// Finds an entry in an array.
  851. /// ex: ARR_FIND(0, size, i, list[i] == target);
  852. ///
  853. /// @param __start Starting index (ex: 0)
  854. /// @param __end End index (ex: size of the array)
  855. /// @param __var Index variable
  856. /// @param __cmp Expression that returns true when the target entry is found
  857. #define ARR_FIND(__start, __end, __var, __cmp) \
  858. do{ \
  859. for( (__var) = (__start); (__var) < (__end); ++(__var) ) \
  860. if( __cmp ) \
  861. break; \
  862. }while(0)
  863. /// Moves an entry of the array.
  864. /// Use ARR_MOVERIGHT/ARR_MOVELEFT if __from and __to are direct numbers.
  865. /// ex: ARR_MOVE(i, 0, list, int);// move index i to index 0
  866. ///
  867. ///
  868. /// @param __from Initial index of the entry
  869. /// @param __to Target index of the entry
  870. /// @param __arr Array
  871. /// @param __type Type of entry
  872. #define ARR_MOVE(__from, __to, __arr, __type) \
  873. do{ \
  874. if( (__from) != (__to) ) \
  875. { \
  876. __type __backup__; \
  877. memmove(&__backup__, (__arr)+(__from), sizeof(__type)); \
  878. if( (__from) < (__to) ) \
  879. memmove((__arr)+(__from), (__arr)+(__from)+1, ((__to)-(__from))*sizeof(__type)); \
  880. else if( (__from) > (__to) ) \
  881. memmove((__arr)+(__to)+1, (__arr)+(__to), ((__from)-(__to))*sizeof(__type)); \
  882. memmove((__arr)+(__to), &__backup__, sizeof(__type)); \
  883. } \
  884. }while(0)
  885. /// Moves an entry of the array to the right.
  886. /// ex: ARR_MOVERIGHT(1, 4, list, int);// move index 1 to index 4
  887. ///
  888. /// @param __from Initial index of the entry
  889. /// @param __to Target index of the entry
  890. /// @param __arr Array
  891. /// @param __type Type of entry
  892. #define ARR_MOVERIGHT(__from, __to, __arr, __type) \
  893. do{ \
  894. __type __backup__; \
  895. memmove(&__backup__, (__arr)+(__from), sizeof(__type)); \
  896. memmove((__arr)+(__from), (__arr)+(__from)+1, ((__to)-(__from))*sizeof(__type)); \
  897. memmove((__arr)+(__to), &__backup__, sizeof(__type)); \
  898. }while(0)
  899. /// Moves an entry of the array to the left.
  900. /// ex: ARR_MOVELEFT(3, 0, list, int);// move index 3 to index 0
  901. ///
  902. /// @param __from Initial index of the entry
  903. /// @param __end Target index of the entry
  904. /// @param __arr Array
  905. /// @param __type Type of entry
  906. #define ARR_MOVELEFT(__from, __to, __arr, __type) \
  907. do{ \
  908. __type __backup__; \
  909. memmove(&__backup__, (__arr)+(__from), sizeof(__type)); \
  910. memmove((__arr)+(__to)+1, (__arr)+(__to), ((__from)-(__to))*sizeof(__type)); \
  911. memmove((__arr)+(__to), &__backup__, sizeof(__type)); \
  912. }while(0)
  913. /////////////////////////////////////////////////////////////////////
  914. // Vector library based on defines. (dynamic array)
  915. // uses aMalloc, aRealloc, aFree
  916. /// Declares an anonymous vector struct.
  917. ///
  918. /// @param __type Type of data
  919. #define VECTOR_DECL(__type) \
  920. struct { \
  921. size_t _max_; \
  922. size_t _len_; \
  923. __type* _data_; \
  924. }
  925. /// Declares a named vector struct.
  926. ///
  927. /// @param __name Structure name
  928. /// @param __type Type of data
  929. #define VECTOR_STRUCT_DECL(__name,__type) \
  930. struct __name { \
  931. size_t _max_; \
  932. size_t _len_; \
  933. __type* _data_; \
  934. }
  935. /// Declares and initializes an anonymous vector variable.
  936. ///
  937. /// @param __type Type of data
  938. /// @param __var Variable name
  939. #define VECTOR_VAR(__type,__var) \
  940. VECTOR_DECL(__type) __var = {0,0,NULL}
  941. /// Declares and initializes a named vector variable.
  942. ///
  943. /// @param __name Structure name
  944. /// @param __var Variable name
  945. #define VECTOR_STRUCT_VAR(__name,__var) \
  946. struct __name __var = {0,0,NULL}
  947. /// Initializes a vector.
  948. ///
  949. /// @param __vec Vector
  950. #define VECTOR_INIT(__vec) \
  951. memset(&(__vec), 0, sizeof(__vec))
  952. /// Returns the internal array of values.
  953. ///
  954. /// @param __vec Vector
  955. /// @return Array of values
  956. #define VECTOR_DATA(__vec) \
  957. ( (__vec)._data_ )
  958. /// Returns the length of the vector.
  959. ///
  960. /// @param __vec Vector
  961. /// @return Length
  962. #define VECTOR_LENGTH(__vec) \
  963. ( (__vec)._len_ )
  964. /// Returns the capacity of the vector.
  965. ///
  966. /// @param __vec Vector
  967. /// @return Capacity
  968. #define VECTOR_CAPACITY(__vec) \
  969. ( (__vec)._max_ )
  970. /// Returns the value at the target index.
  971. /// Assumes the index exists.
  972. ///
  973. /// @param __vec Vector
  974. /// @param __idx Index
  975. /// @return Value
  976. #define VECTOR_INDEX(__vec,__idx) \
  977. ( VECTOR_DATA(__vec)[__idx] )
  978. /// Returns the first value of the vector.
  979. /// Assumes the array is not empty.
  980. ///
  981. /// @param __vec Vector
  982. /// @return First value
  983. #define VECTOR_FIRST(__vec) \
  984. ( VECTOR_INDEX(__vec,0) )
  985. /// Returns the last value of the vector.
  986. /// Assumes the array is not empty.
  987. ///
  988. /// @param __vec Vector
  989. /// @return Last value
  990. #define VECTOR_LAST(__vec) \
  991. ( VECTOR_INDEX(__vec,VECTOR_LENGTH(__vec)-1) )
  992. /// Resizes the vector.
  993. /// Excess values are discarded, new positions are zeroed.
  994. ///
  995. /// @param __vec Vector
  996. /// @param __n Size
  997. #define VECTOR_RESIZE(__vec,__n) \
  998. do{ \
  999. if( (__n) > VECTOR_CAPACITY(__vec) ) \
  1000. { /* increase size */ \
  1001. if( VECTOR_CAPACITY(__vec) == 0 ) VECTOR_DATA(__vec) = aMalloc((__n)*sizeof(VECTOR_FIRST(__vec))); /* allocate new */ \
  1002. else VECTOR_DATA(__vec) = aRealloc(VECTOR_DATA(__vec),(__n)*sizeof(VECTOR_FIRST(__vec))); /* reallocate */ \
  1003. memset(VECTOR_DATA(__vec)+VECTOR_LENGTH(__vec), 0, (VECTOR_CAPACITY(__vec)-VECTOR_LENGTH(__vec))*sizeof(VECTOR_FIRST(__vec))); /* clear new data */ \
  1004. VECTOR_CAPACITY(__vec) = (__n); /* update capacity */ \
  1005. } \
  1006. else if( (__n) == 0 && VECTOR_CAPACITY(__vec) ) \
  1007. { /* clear vector */ \
  1008. aFree(VECTOR_DATA(__vec)); VECTOR_DATA(__vec) = NULL; /* free data */ \
  1009. VECTOR_CAPACITY(__vec) = 0; /* clear capacity */ \
  1010. VECTOR_LENGTH(__vec) = 0; /* clear length */ \
  1011. } \
  1012. else if( (__n) < VECTOR_CAPACITY(__vec) ) \
  1013. { /* reduce size */ \
  1014. VECTOR_DATA(__vec) = aRealloc(VECTOR_DATA(__vec),(__n)*sizeof(VECTOR_FIRST(__vec))); /* reallocate */ \
  1015. VECTOR_CAPACITY(__vec) = (__n); /* update capacity */ \
  1016. if( VECTOR_LENGTH(__vec) > (__n) ) VECTOR_LENGTH(__vec) = (__n); /* update length */ \
  1017. } \
  1018. }while(0)
  1019. /// Ensures that the array has the target number of empty positions.
  1020. /// Increases the capacity in multiples of __step.
  1021. ///
  1022. /// @param __vec Vector
  1023. /// @param __n Empty positions
  1024. /// @param __step Increase
  1025. #define VECTOR_ENSURE(__vec,__n,__step) \
  1026. do{ \
  1027. size_t _empty_ = VECTOR_CAPACITY(__vec)-VECTOR_LENGTH(__vec); \
  1028. if( (__n) > _empty_ ) { \
  1029. while( (__n) > _empty_ ) _empty_ += (__step); \
  1030. VECTOR_RESIZE(__vec,_empty_+VECTOR_LENGTH(__vec)); \
  1031. } \
  1032. }while(0)
  1033. /// Inserts a zeroed value in the target index.
  1034. /// Assumes the index is valid and there is enough capacity.
  1035. ///
  1036. /// @param __vec Vector
  1037. /// @param __idx Index
  1038. #define VECTOR_INSERTZEROED(__vec,__idx) \
  1039. do{ \
  1040. if( (__idx) < VECTOR_LENGTH(__vec) ) /* move data */ \
  1041. memmove(&VECTOR_INDEX(__vec,(__idx)+1),&VECTOR_INDEX(__vec,__idx),(VECTOR_LENGTH(__vec)-(__idx))*sizeof(VECTOR_FIRST(__vec))); \
  1042. memset(&VECTOR_INDEX(__vec,__idx), 0, sizeof(VECTOR_INDEX(__vec,__idx))); /* set zeroed value */ \
  1043. ++VECTOR_LENGTH(__vec); /* increase length */ \
  1044. }while(0)
  1045. /// Inserts a value in the target index. (using the '=' operator)
  1046. /// Assumes the index is valid and there is enough capacity.
  1047. ///
  1048. /// @param __vec Vector
  1049. /// @param __idx Index
  1050. /// @param __val Value
  1051. #define VECTOR_INSERT(__vec,__idx,__val) \
  1052. do{ \
  1053. if( (__idx) < VECTOR_LENGTH(__vec) ) /* move data */ \
  1054. memmove(&VECTOR_INDEX(__vec,(__idx)+1),&VECTOR_INDEX(__vec,__idx),(VECTOR_LENGTH(__vec)-(__idx))*sizeof(VECTOR_FIRST(__vec))); \
  1055. VECTOR_INDEX(__vec,__idx) = (__val); /* set value */ \
  1056. ++VECTOR_LENGTH(__vec); /* increase length */ \
  1057. }while(0)
  1058. /// Inserts a value in the target index. (using memcpy)
  1059. /// Assumes the index is valid and there is enough capacity.
  1060. ///
  1061. /// @param __vec Vector
  1062. /// @param __idx Index
  1063. /// @param __val Value
  1064. #define VECTOR_INSERTCOPY(__vec,__idx,__val) \
  1065. VECTOR_INSERTARRAY(__vec,__idx,&(__val),1)
  1066. /// Inserts the values of the array in the target index. (using memcpy)
  1067. /// Assumes the index is valid and there is enough capacity.
  1068. ///
  1069. /// @param __vec Vector
  1070. /// @param __idx Index
  1071. /// @param __pval Array of values
  1072. /// @param __n Number of values
  1073. #define VECTOR_INSERTARRAY(__vec,__idx,__pval,__n) \
  1074. do{ \
  1075. if( (__idx) < VECTOR_LENGTH(__vec) ) /* move data */ \
  1076. memmove(&VECTOR_INDEX(__vec,(__idx)+(__n)),&VECTOR_INDEX(__vec,__idx),(VECTOR_LENGTH(__vec)-(__idx))*sizeof(VECTOR_FIRST(__vec))); \
  1077. memcpy(&VECTOR_INDEX(__vec,__idx), (__pval), (__n)*sizeof(VECTOR_FIRST(__vec))); /* set values */ \
  1078. VECTOR_LENGTH(__vec) += (__n); /* increase length */ \
  1079. }while(0)
  1080. /// Inserts a zeroed value in the end of the vector.
  1081. /// Assumes there is enough capacity.
  1082. ///
  1083. /// @param __vec Vector
  1084. #define VECTOR_PUSHZEROED(__vec) \
  1085. do{ \
  1086. memset(&VECTOR_INDEX(__vec,VECTOR_LENGTH(__vec)), 0, sizeof(VECTOR_INDEX(__vec,VECTOR_LENGTH(__vec)))); /* set zeroed value */ \
  1087. ++VECTOR_LENGTH(__vec); /* increase length */ \
  1088. }while(0)
  1089. /// Inserts a value in the end of the vector. (using the '=' operator)
  1090. /// Assumes there is enough capacity.
  1091. ///
  1092. /// @param __vec Vector
  1093. /// @param __val Value
  1094. #define VECTOR_PUSH(__vec,__val) \
  1095. do{ \
  1096. VECTOR_INDEX(__vec,VECTOR_LENGTH(__vec)) = (__val); /* set value */ \
  1097. ++VECTOR_LENGTH(__vec); /* increase length */ \
  1098. }while(0)
  1099. /// Inserts a value in the end of the vector. (using memcpy)
  1100. /// Assumes there is enough capacity.
  1101. ///
  1102. /// @param __vec Vector
  1103. /// @param __val Value
  1104. #define VECTOR_PUSHCOPY(__vec,__val) \
  1105. VECTOR_PUSHARRAY(__vec,&(__val),1)
  1106. /// Inserts the values of the array in the end of the vector. (using memcpy)
  1107. /// Assumes there is enough capacity.
  1108. ///
  1109. /// @param __vec Vector
  1110. /// @param __pval Array of values
  1111. /// @param __n Number of values
  1112. #define VECTOR_PUSHARRAY(__vec,__pval,__n) \
  1113. do{ \
  1114. memcpy(&VECTOR_INDEX(__vec,VECTOR_LENGTH(__vec)), (__pval), (__n)*sizeof(VECTOR_FIRST(__vec))); /* set values */ \
  1115. VECTOR_LENGTH(__vec) += (__n); /* increase length */ \
  1116. }while(0)
  1117. /// Removes and returns the last value of the vector.
  1118. /// Assumes the array is not empty.
  1119. ///
  1120. /// @param __vec Vector
  1121. /// @return Removed value
  1122. #define VECTOR_POP(__vec) \
  1123. ( VECTOR_INDEX(__vec,--VECTOR_LENGTH(__vec)) )
  1124. /// Removes the last N values of the vector and returns the value of the last pop.
  1125. /// Assumes there are enough values.
  1126. ///
  1127. /// @param __vec Vector
  1128. /// @param __n Number of pops
  1129. /// @return Last removed value
  1130. #define VECTOR_POPN(__vec,__n) \
  1131. ( VECTOR_INDEX(__vec,(VECTOR_LENGTH(__vec)-=(__n))) )
  1132. /// Removes the target index from the vector.
  1133. /// Assumes the index is valid and there are enough values.
  1134. ///
  1135. /// @param __vec Vector
  1136. /// @param __idx Index
  1137. #define VECTOR_ERASE(__vec,__idx) \
  1138. VECTOR_ERASEN(__vec,__idx,1)
  1139. /// Removes N values from the target index of the vector.
  1140. /// Assumes the index is valid and there are enough values.
  1141. ///
  1142. /// @param __vec Vector
  1143. /// @param __idx Index
  1144. /// @param __n Number of values
  1145. #define VECTOR_ERASEN(__vec,__idx,__n) \
  1146. do{ \
  1147. if( (__idx) < VECTOR_LENGTH(__vec)-(__n) ) /* move data */ \
  1148. memmove(&VECTOR_INDEX(__vec,__idx),&VECTOR_INDEX(__vec,(__idx)+(__n)),(VECTOR_LENGTH(__vec)-((__idx)+(__n)))*sizeof(VECTOR_FIRST(__vec))); \
  1149. VECTOR_LENGTH(__vec) -= (__n); /* decrease length */ \
  1150. }while(0)
  1151. /// Clears the vector, freeing allocated data.
  1152. ///
  1153. /// @param __vec Vector
  1154. #define VECTOR_CLEAR(__vec) \
  1155. do{ \
  1156. if( VECTOR_CAPACITY(__vec) ) \
  1157. { \
  1158. aFree(VECTOR_DATA(__vec)); VECTOR_DATA(__vec) = NULL; /* clear allocated array */ \
  1159. VECTOR_CAPACITY(__vec) = 0; /* clear capacity */ \
  1160. VECTOR_LENGTH(__vec) = 0; /* clear length */ \
  1161. } \
  1162. }while(0)
  1163. /////////////////////////////////////////////////////////////////////
  1164. // Binary heap library based on defines. (uses the vector defines above)
  1165. // uses aMalloc, aRealloc, aFree
  1166. // WARNING: BHEAP implementation details affect behaviour of A* pathfinding
  1167. /// Declares an anonymous binary heap struct.
  1168. ///
  1169. /// @param __type Type of data
  1170. #define BHEAP_DECL(__type) VECTOR_DECL(__type)
  1171. /// Declares a named binary heap struct.
  1172. ///
  1173. /// @param __name Structure name
  1174. /// @param __type Type of data
  1175. #define BHEAP_STRUCT_DECL(__name,__type) VECTOR_STRUCT_DECL(__name,__type)
  1176. /// Declares and initializes an anonymous binary heap variable.
  1177. ///
  1178. /// @param __type Type of data
  1179. /// @param __var Variable name
  1180. #define BHEAP_VAR(__type,__var) VECTOR_VAR(__type,__var)
  1181. /// Declares and initializes a named binary heap variable.
  1182. ///
  1183. /// @param __name Structure name
  1184. /// @param __var Variable name
  1185. #define BHEAP_STRUCT_VAR(__name,__var) VECTOR_STRUCT_VAR(__name,__var)
  1186. /// Initializes a heap.
  1187. ///
  1188. /// @param __heap Binary heap
  1189. #define BHEAP_INIT(__heap) VECTOR_INIT(__heap)
  1190. /// Returns the internal array of values.
  1191. ///
  1192. /// @param __heap Binary heap
  1193. /// @return Array of values
  1194. #define BHEAP_DATA(__heap) VECTOR_DATA(__heap)
  1195. /// Returns the length of the heap.
  1196. ///
  1197. /// @param __heap Binary heap
  1198. /// @return Length
  1199. #define BHEAP_LENGTH(__heap) VECTOR_LENGTH(__heap)
  1200. /// Returns the capacity of the heap.
  1201. ///
  1202. /// @param __heap Binary heap
  1203. /// @return Capacity
  1204. #define BHEAP_CAPACITY(__heap) VECTOR_CAPACITY(__heap)
  1205. /// Ensures that the heap has the target number of empty positions.
  1206. /// Increases the capacity in multiples of __step.
  1207. ///
  1208. /// @param __heap Binary heap
  1209. /// @param __n Empty positions
  1210. /// @param __step Increase
  1211. #define BHEAP_ENSURE(__heap,__n,__step) VECTOR_ENSURE(__heap,__n,__step)
  1212. /// Returns the top value of the heap.
  1213. /// Assumes the heap is not empty.
  1214. ///
  1215. /// @param __heap Binary heap
  1216. /// @return Value at the top
  1217. #define BHEAP_PEEK(__heap) VECTOR_INDEX(__heap,0)
  1218. /// Inserts a value in the heap. (using the '=' operator)
  1219. /// Assumes there is enough capacity.
  1220. ///
  1221. /// The comparator takes two values as arguments, returns:
  1222. /// - negative if the first value is on the top
  1223. /// - positive if the second value is on the top
  1224. /// - 0 if they are equal
  1225. ///
  1226. /// @param __heap Binary heap
  1227. /// @param __val Value
  1228. /// @param __topcmp Comparator
  1229. /// @param __swp Swapper
  1230. #define BHEAP_PUSH(__heap,__val,__topcmp,__swp) \
  1231. do{ \
  1232. size_t _i_ = VECTOR_LENGTH(__heap); \
  1233. VECTOR_PUSH(__heap,__val); /* insert at end */ \
  1234. while( _i_ ) \
  1235. { /* restore heap property in parents */ \
  1236. size_t _parent_ = (_i_-1)/2; \
  1237. if( __topcmp(VECTOR_INDEX(__heap,_parent_),VECTOR_INDEX(__heap,_i_)) < 0 ) \
  1238. break; /* done */ \
  1239. __swp(VECTOR_INDEX(__heap,_parent_),VECTOR_INDEX(__heap,_i_)); \
  1240. _i_ = _parent_; \
  1241. } \
  1242. }while(0)
  1243. /// See BHEAP_PUSH. Version used by A* implementation, matching client bheap.
  1244. ///
  1245. /// @param __heap Binary heap
  1246. /// @param __val Value
  1247. /// @param __topcmp Comparator
  1248. /// @param __swp Swapper
  1249. #define BHEAP_PUSH2(__heap,__val,__topcmp,__swp) \
  1250. do{ \
  1251. size_t _i_ = VECTOR_LENGTH(__heap); \
  1252. VECTOR_PUSH(__heap,__val); /* insert at end */ \
  1253. BHEAP_SIFTDOWN(__heap,0,_i_,__topcmp,__swp); \
  1254. }while(0)
  1255. /// Removes the top value of the heap. (using the '=' operator)
  1256. /// Assumes the heap is not empty.
  1257. ///
  1258. /// The comparator takes two values as arguments, returns:
  1259. /// - negative if the first value is on the top
  1260. /// - positive if the second value is on the top
  1261. /// - 0 if they are equal
  1262. ///
  1263. /// @param __heap Binary heap
  1264. /// @param __topcmp Comparator
  1265. /// @param __swp Swapper
  1266. #define BHEAP_POP(__heap,__topcmp,__swp) BHEAP_POPINDEX(__heap,0,__topcmp,__swp)
  1267. /// See BHEAP_POP. Version used by A* implementation, matching client bheap.
  1268. ///
  1269. /// @param __heap Binary heap
  1270. /// @param __topcmp Comparator
  1271. /// @param __swp Swapper
  1272. #define BHEAP_POP2(__heap,__topcmp,__swp) \
  1273. do{ \
  1274. VECTOR_INDEX(__heap,0) = VECTOR_POP(__heap); /* put last at index */ \
  1275. if( !VECTOR_LENGTH(__heap) ) /* removed last, nothing to do */ \
  1276. break; \
  1277. BHEAP_SIFTUP(__heap,0,__topcmp,__swp); \
  1278. }while(0)
  1279. /// Removes the target value of the heap. (using the '=' operator)
  1280. /// Assumes the index exists.
  1281. ///
  1282. /// The comparator takes two values as arguments, returns:
  1283. /// - negative if the first value is on the top
  1284. /// - positive if the second value is on the top
  1285. /// - 0 if they are equal
  1286. ///
  1287. /// @param __heap Binary heap
  1288. /// @param __idx Index
  1289. /// @param __topcmp Comparator
  1290. /// @param __swp Swapper
  1291. #define BHEAP_POPINDEX(__heap,__idx,__topcmp,__swp) \
  1292. do{ \
  1293. size_t _i_ = __idx; \
  1294. VECTOR_INDEX(__heap,__idx) = VECTOR_POP(__heap); /* put last at index */ \
  1295. if( _i_ >= VECTOR_LENGTH(__heap)) /* removed last, nothing to do */ \
  1296. break; \
  1297. while( _i_ ) \
  1298. { /* restore heap property in parents */ \
  1299. size_t _parent_ = (_i_-1)/2; \
  1300. if( __topcmp(VECTOR_INDEX(__heap,_parent_),VECTOR_INDEX(__heap,_i_)) < 0 ) \
  1301. break; /* done */ \
  1302. __swp(VECTOR_INDEX(__heap,_parent_),VECTOR_INDEX(__heap,_i_)); \
  1303. _i_ = _parent_; \
  1304. } \
  1305. while( _i_ < VECTOR_LENGTH(__heap) ) \
  1306. { /* restore heap property in childs */ \
  1307. size_t _lchild_ = _i_*2 + 1; \
  1308. size_t _rchild_ = _i_*2 + 2; \
  1309. if( (_lchild_ >= VECTOR_LENGTH(__heap) || __topcmp(VECTOR_INDEX(__heap,_i_),VECTOR_INDEX(__heap,_lchild_)) <= 0) && \
  1310. (_rchild_ >= VECTOR_LENGTH(__heap) || __topcmp(VECTOR_INDEX(__heap,_i_),VECTOR_INDEX(__heap,_rchild_)) <= 0) ) \
  1311. break; /* done */ \
  1312. else if( _rchild_ >= VECTOR_LENGTH(__heap) || __topcmp(VECTOR_INDEX(__heap,_lchild_),VECTOR_INDEX(__heap,_rchild_)) <= 0 ) \
  1313. { /* left child */ \
  1314. __swp(VECTOR_INDEX(__heap,_i_),VECTOR_INDEX(__heap,_lchild_)); \
  1315. _i_ = _lchild_; \
  1316. } \
  1317. else \
  1318. { /* right child */ \
  1319. __swp(VECTOR_INDEX(__heap,_i_),VECTOR_INDEX(__heap,_rchild_)); \
  1320. _i_ = _rchild_; \
  1321. } \
  1322. } \
  1323. }while(0)
  1324. /// Follow path up towards (but not all the way to) the root, swapping nodes until finding
  1325. /// a place where the new item that was placed at __idx fits.
  1326. /// Only goes as high as __startidx (usually 0).
  1327. ///
  1328. /// @param __heap Binary heap
  1329. /// @param __startidx Index of an ancestor of __idx
  1330. /// @param __idx Index of an inserted element
  1331. /// @param __topcmp Comparator
  1332. /// @param __swp Swapper
  1333. #define BHEAP_SIFTDOWN(__heap,__startidx,__idx,__topcmp,__swp) \
  1334. do{ \
  1335. size_t _i2_ = __idx; \
  1336. while( _i2_ > __startidx ) \
  1337. { /* restore heap property in parents */ \
  1338. size_t _parent_ = (_i2_-1)/2; \
  1339. if( __topcmp(VECTOR_INDEX(__heap,_parent_),VECTOR_INDEX(__heap,_i2_)) <= 0 ) \
  1340. break; /* done */ \
  1341. __swp(VECTOR_INDEX(__heap,_parent_),VECTOR_INDEX(__heap,_i2_)); \
  1342. _i2_ = _parent_; \
  1343. } \
  1344. }while(0)
  1345. /// Repeatedly swap the smaller child with parent, after placing a new item at __idx.
  1346. ///
  1347. /// @param __heap Binary heap
  1348. /// @param __idx Index of an inserted element
  1349. /// @param __topcmp Comparator
  1350. /// @param __swp Swapper
  1351. #define BHEAP_SIFTUP(__heap,__idx,__topcmp,__swp) \
  1352. do{ \
  1353. size_t _i_ = __idx; \
  1354. size_t _lchild_ = _i_*2 + 1; \
  1355. while( _lchild_ < VECTOR_LENGTH(__heap) ) \
  1356. { /* restore heap property in childs */ \
  1357. size_t _rchild_ = _i_*2 + 2; \
  1358. if( _rchild_ >= VECTOR_LENGTH(__heap) || __topcmp(VECTOR_INDEX(__heap,_lchild_),VECTOR_INDEX(__heap,_rchild_)) < 0 ) \
  1359. { /* left child */ \
  1360. __swp(VECTOR_INDEX(__heap,_i_),VECTOR_INDEX(__heap,_lchild_)); \
  1361. _i_ = _lchild_; \
  1362. } \
  1363. else \
  1364. { /* right child */ \
  1365. __swp(VECTOR_INDEX(__heap,_i_),VECTOR_INDEX(__heap,_rchild_)); \
  1366. _i_ = _rchild_; \
  1367. } \
  1368. _lchild_ = _i_*2 + 1; \
  1369. } \
  1370. BHEAP_SIFTDOWN(__heap,__idx,_i_,__topcmp,__swp); \
  1371. }while(0)
  1372. /// Call this after modifying the item at __idx__ to restore the heap
  1373. ///
  1374. /// @param __heap Binary heap
  1375. /// @param __idx Index
  1376. /// @param __topcmp Comparator
  1377. /// @param __swp Swapper
  1378. #define BHEAP_UPDATE(__heap,__idx,__topcmp,__swp) \
  1379. do{ \
  1380. BHEAP_SIFTDOWN(__heap,0,__idx,__topcmp,__swp); \
  1381. BHEAP_SIFTUP(__heap,__idx,__topcmp,__swp); \
  1382. }while(0)
  1383. /// Clears the binary heap, freeing allocated data.
  1384. ///
  1385. /// @param __heap Binary heap
  1386. #define BHEAP_CLEAR(__heap) VECTOR_CLEAR(__heap)
  1387. /// Generic comparator for a min-heap. (minimum value at top)
  1388. /// Returns -1 if v1 is smaller, 1 if v2 is smaller, 0 if equal.
  1389. ///
  1390. /// @param v1 First value
  1391. /// @param v2 Second value
  1392. /// @return negative if v1 is top, positive if v2 is top, 0 if equal
  1393. #define BHEAP_MINTOPCMP(v1,v2) ( v1 == v2 ? 0 : v1 < v2 ? -1 : 1 )
  1394. /// Generic comparator for a max-heap. (maximum value at top)
  1395. /// Returns -1 if v1 is bigger, 1 if v2 is bigger, 0 if equal.
  1396. ///
  1397. /// @param v1 First value
  1398. /// @param v2 Second value
  1399. /// @return negative if v1 is top, positive if v2 is top, 0 if equal
  1400. #define BHEAP_MAXTOPCMP(v1,v2) ( v1 == v2 ? 0 : v1 > v2 ? -1 : 1 )
  1401. #endif /* _DB_H_ */