db.h 46 KB

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