simclist.c 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732
  1. /*
  2. * Copyright (c) 2007,2008,2009,2010,2011 Mij <mij@bitchx.it>
  3. *
  4. * Permission to use, copy, modify, and distribute this software for any
  5. * purpose with or without fee is hereby granted, provided that the above
  6. * copyright notice and this permission notice appear in all copies.
  7. *
  8. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. */
  16. /*
  17. * SimCList library. See http://mij.oltrelinux.com/devel/simclist
  18. */
  19. /* SimCList implementation, version 1.6 */
  20. #include "libks/ks.h"
  21. #include <stdlib.h>
  22. #include <string.h>
  23. #include <errno.h> /* for setting errno */
  24. #include <sys/types.h>
  25. #ifndef _WIN32
  26. /* not in Windows! */
  27. # include <unistd.h>
  28. # include <stdint.h>
  29. #endif
  30. #ifndef SIMCLIST_NO_DUMPRESTORE
  31. /* includes for dump/restore */
  32. # include <time.h>
  33. #ifdef KS_PLAT_WIN
  34. #pragma warning( disable : 4996) /* Silence usage of old api warnings */
  35. #else
  36. # include <sys/uio.h> /* for READ_ERRCHECK() and write() */
  37. #endif
  38. # include <fcntl.h> /* for open() etc */
  39. # ifndef _WIN32
  40. # include <arpa/inet.h> /* for htons() on UNIX */
  41. # else
  42. # include <winsock2.h> /* for htons() on Windows */
  43. # endif
  44. #endif
  45. #include <assert.h>
  46. #include <sys/stat.h> /* for open()'s access modes S_IRUSR etc */
  47. #include <limits.h>
  48. #if defined(_MSC_VER) || defined(__MINGW32__)
  49. /* provide gettimeofday() missing in Windows */
  50. #ifdef _MSC_VER
  51. #pragma comment(lib, "Winmm.lib")
  52. #endif
  53. int gettimeofday(struct timeval *tp, void *tzp) {
  54. DWORD t;
  55. /* XSI says: "If tzp is not a null pointer, the behavior is unspecified" */
  56. ks_assert(tzp == NULL);
  57. t = timeGetTime();
  58. tp->tv_sec = t / 1000;
  59. tp->tv_usec = t % 1000;
  60. return 0;
  61. }
  62. #endif
  63. /* work around lack of inttypes.h support in broken Microsoft Visual Studio compilers */
  64. #if !defined(_WIN32) || !defined(_MSC_VER)
  65. # include <inttypes.h> /* (u)int*_t */
  66. #else
  67. # include <basetsd.h>
  68. typedef UINT8 uint8_t;
  69. typedef UINT16 uint16_t;
  70. typedef ULONG32 uint32_t;
  71. typedef UINT64 uint64_t;
  72. typedef INT8 int8_t;
  73. typedef INT16 int16_t;
  74. typedef LONG32 int32_t;
  75. typedef INT64 int64_t;
  76. #endif
  77. /* define some commodity macros for Dump/Restore functionality */
  78. #ifndef SIMCLIST_NO_DUMPRESTORE
  79. /* write() decorated with error checking logic */
  80. #define WRITE_ERRCHECK(fd, msgbuf, msglen) do { \
  81. if (write(fd, msgbuf, msglen) < 0) return -1; \
  82. } while (0);
  83. /* READ_ERRCHECK() decorated with error checking logic */
  84. #define READ_ERRCHECK(fd, msgbuf, msglen) do { \
  85. if (read(fd, msgbuf, msglen) != msglen) { \
  86. /*errno = EPROTO;*/ \
  87. return -1; \
  88. } \
  89. } while (0);
  90. /* convert 64bit integers from host to network format */
  91. #define hton64(x) (\
  92. htons(1) == 1 ? \
  93. (uint64_t)x /* big endian */ \
  94. : /* little endian */ \
  95. ((uint64_t)((((uint64_t)(x) & 0xff00000000000000ULL) >> 56) | \
  96. (((uint64_t)(x) & 0x00ff000000000000ULL) >> 40) | \
  97. (((uint64_t)(x) & 0x0000ff0000000000ULL) >> 24) | \
  98. (((uint64_t)(x) & 0x000000ff00000000ULL) >> 8) | \
  99. (((uint64_t)(x) & 0x00000000ff000000ULL) << 8) | \
  100. (((uint64_t)(x) & 0x0000000000ff0000ULL) << 24) | \
  101. (((uint64_t)(x) & 0x000000000000ff00ULL) << 40) | \
  102. (((uint64_t)(x) & 0x00000000000000ffULL) << 56))) \
  103. )
  104. /* convert 64bit integers from network to host format */
  105. #define ntoh64(x) (hton64(x))
  106. #endif
  107. /* some OSes don't have EPROTO (eg OpenBSD) */
  108. #ifndef EPROTO
  109. #define EPROTO EIO
  110. #endif
  111. #ifdef SIMCLIST_WITH_THREADS
  112. /* limit (approx) to the number of threads running
  113. * for threaded operations. Only meant when
  114. * SIMCLIST_WITH_THREADS is defined */
  115. #define SIMCLIST_MAXTHREADS 2
  116. #endif
  117. /*
  118. * how many elems to keep as spare. During a deletion, an element
  119. * can be saved in a "free-list", not free()d immediately. When
  120. * latter insertions are performed, spare elems can be used instead
  121. * of malloc()ing new elems.
  122. *
  123. * about this param, some values for appending
  124. * 10 million elems into an empty list:
  125. * (#, time[sec], gain[%], gain/no[%])
  126. * 0 2,164 0,00 0,00 <-- feature disabled
  127. * 1 1,815 34,9 34,9
  128. * 2 1,446 71,8 35,9 <-- MAX gain/no
  129. * 3 1,347 81,7 27,23
  130. * 5 1,213 95,1 19,02
  131. * 8 1,064 110,0 13,75
  132. * 10 1,015 114,9 11,49 <-- MAX gain w/ likely sol
  133. * 15 1,019 114,5 7,63
  134. * 25 0,985 117,9 4,72
  135. * 50 1,088 107,6 2,15
  136. * 75 1,016 114,8 1,53
  137. * 100 0,988 117,6 1,18
  138. * 150 1,022 114,2 0,76
  139. * 200 0,939 122,5 0,61 <-- MIN time
  140. */
  141. #ifndef SIMCLIST_MAX_SPARE_ELEMS
  142. #define SIMCLIST_MAX_SPARE_ELEMS 5
  143. #endif
  144. #ifdef SIMCLIST_WITH_THREADS
  145. #include <pthread.h>
  146. #endif
  147. #include "libks/simclist.h"
  148. /* minumum number of elements for sorting with quicksort instead of insertion */
  149. #define SIMCLIST_MINQUICKSORTELS 24
  150. /* list dump declarations */
  151. #define SIMCLIST_DUMPFORMAT_VERSION 1 /* (short integer) version of fileformat managed by _dump* and _restore* functions */
  152. // @todo this is not correct, the header would be padded by default on version for 2 more bytes, and treating the structure as 30 bytes would cut the last 2 bytes off the listhash at the end
  153. #define SIMCLIST_DUMPFORMAT_HEADERLEN 30 /* length of the header */
  154. /* header for a list dump */
  155. struct ks_list_dump_header_s {
  156. uint16_t ver; /* version */
  157. int32_t timestamp_sec; /* dump timestamp, seconds since UNIX Epoch */
  158. int32_t timestamp_usec; /* dump timestamp, microseconds since timestamp_sec */
  159. int32_t rndterm; /* random value terminator -- terminates the data sequence */
  160. uint32_t totlistlen; /* sum of every element' size, bytes */
  161. uint32_t numels; /* number of elements */
  162. uint32_t elemlen; /* bytes length of an element, for constant-size lists, <= 0 otherwise */
  163. int32_t listhash; /* hash of the list at the time of dumping, or 0 if to be ignored */
  164. };
  165. /* deletes tmp from list, with care wrt its position (head, tail, middle) */
  166. static int ks_list_drop_elem(ks_list_t *restrict l, struct ks_list_entry_s *tmp, unsigned int pos);
  167. /* set default values for initialized lists */
  168. static int ks_list_attributes_setdefaults(ks_list_t *restrict l);
  169. /* check whether the list internal REPresentation is valid -- Costs O(n) */
  170. static int ks_list_repOk(const ks_list_t *restrict l);
  171. /* check whether the list attribute set is valid -- Costs O(1) */
  172. static int ks_list_attrOk(const ks_list_t *restrict l);
  173. /* do not inline, this is recursive */
  174. static void ks_list_sort_quicksort(ks_list_t *restrict l, int versus,
  175. unsigned int first, struct ks_list_entry_s *fel,
  176. unsigned int last, struct ks_list_entry_s *lel);
  177. static inline void ks_list_sort_selectionsort(ks_list_t *restrict l, int versus,
  178. unsigned int first, struct ks_list_entry_s *fel,
  179. unsigned int last, struct ks_list_entry_s *lel);
  180. static void *ks_list_get_minmax(const ks_list_t *restrict l, int versus);
  181. static inline struct ks_list_entry_s *ks_list_findpos(const ks_list_t *restrict l, int posstart);
  182. /*
  183. * Random Number Generator
  184. *
  185. * The user is expected to seed the RNG (ie call srand()) if
  186. * SIMCLIST_SYSTEM_RNG is defined.
  187. *
  188. * Otherwise, a self-contained RNG based on LCG is used; see
  189. * http://en.wikipedia.org/wiki/Linear_congruential_generator .
  190. *
  191. * Facts pro local RNG:
  192. * 1. no need for the user to call srand() on his own
  193. * 2. very fast, possibly faster than OS
  194. * 3. avoid interference with user's RNG
  195. *
  196. * Facts pro system RNG:
  197. * 1. may be more accurate (irrelevant for SimCList randno purposes)
  198. * 2. why reinvent the wheel
  199. *
  200. * Default to local RNG for user's ease of use.
  201. */
  202. #ifdef SIMCLIST_SYSTEM_RNG
  203. /* keep track whether we initialized already (non-0) or not (0) */
  204. static unsigned random_seed = 0;
  205. /* use local RNG */
  206. static inline void seed_random(void) {
  207. if (random_seed == 0)
  208. random_seed = (unsigned)getpid() ^ (unsigned)time(NULL);
  209. }
  210. static inline long get_random(void) {
  211. random_seed = (1664525 * random_seed + 1013904223);
  212. return random_seed;
  213. }
  214. #else
  215. /* use OS's random generator */
  216. # define seed_random()
  217. # define get_random() (rand())
  218. #endif
  219. static void ks_list_cleanup(void *ptr, void *arg, ks_pool_cleanup_action_t action, ks_pool_cleanup_type_t type)
  220. {
  221. ks_list_t *l = (ks_list_t *)ptr;
  222. switch (action) {
  223. case KS_MPCL_ANNOUNCE:
  224. break;
  225. case KS_MPCL_TEARDOWN:
  226. ks_list_clear(l);
  227. ks_rwl_write_lock(l->lock);
  228. for (unsigned int i = 0; i < l->spareelsnum; i++) ks_pool_free(&l->spareels[i]);
  229. l->spareelsnum = 0;
  230. ks_pool_free(&l->spareels);
  231. ks_pool_free(&l->head_sentinel);
  232. ks_pool_free(&l->tail_sentinel);
  233. ks_rwl_write_unlock(l->lock);
  234. ks_rwl_destroy(&l->lock);
  235. break;
  236. case KS_MPCL_DESTROY:
  237. break;
  238. }
  239. }
  240. /* list initialization */
  241. KS_DECLARE(ks_status_t) ks_list_create(ks_list_t **list, ks_pool_t *pool) {
  242. ks_list_t *l = NULL;
  243. ks_assert(list);
  244. ks_assert(pool);
  245. seed_random();
  246. l = ks_pool_alloc(pool, sizeof(ks_list_t));
  247. ks_assert(l);
  248. l->numels = 0;
  249. ks_rwl_create(&l->lock, pool);
  250. ks_assert(l->lock);
  251. /* head/tail sentinels and mid pointer */
  252. l->head_sentinel = (struct ks_list_entry_s *)ks_pool_alloc(pool, sizeof(struct ks_list_entry_s));
  253. l->tail_sentinel = (struct ks_list_entry_s *)ks_pool_alloc(pool, sizeof(struct ks_list_entry_s));
  254. l->head_sentinel->next = l->tail_sentinel;
  255. l->tail_sentinel->prev = l->head_sentinel;
  256. l->head_sentinel->prev = l->tail_sentinel->next = l->mid = NULL;
  257. l->head_sentinel->data = l->tail_sentinel->data = NULL;
  258. /* iteration attributes */
  259. l->iter_active = 0;
  260. l->iter_pos = 0;
  261. l->iter_curentry = NULL;
  262. /* free-list attributes */
  263. l->spareels = (struct ks_list_entry_s **)ks_pool_alloc(pool, SIMCLIST_MAX_SPARE_ELEMS * sizeof(struct ks_list_entry_s *));
  264. l->spareelsnum = 0;
  265. #ifdef SIMCLIST_WITH_THREADS
  266. l->threadcount = 0;
  267. #endif
  268. ks_list_attributes_setdefaults(l);
  269. ks_assert(ks_list_repOk(l));
  270. ks_assert(ks_list_attrOk(l));
  271. ks_pool_set_cleanup(l, NULL, ks_list_cleanup);
  272. *list = l;
  273. return KS_STATUS_SUCCESS;
  274. }
  275. KS_DECLARE(ks_status_t) ks_list_destroy(ks_list_t **list) {
  276. ks_list_t *l = NULL;
  277. ks_assert(list);
  278. l = *list;
  279. *list = NULL;
  280. if (!l) return KS_STATUS_FAIL;
  281. ks_pool_free(&l);
  282. return KS_STATUS_SUCCESS;
  283. }
  284. int ks_list_attributes_setdefaults(ks_list_t *restrict l) {
  285. l->attrs.comparator = NULL;
  286. l->attrs.seeker = NULL;
  287. /* also free() element data when removing and element from the list */
  288. l->attrs.meter = NULL;
  289. l->attrs.copy_data = 0;
  290. l->attrs.hasher = NULL;
  291. /* serializer/unserializer */
  292. l->attrs.serializer = NULL;
  293. l->attrs.unserializer = NULL;
  294. ks_assert(ks_list_attrOk(l));
  295. return 0;
  296. }
  297. /* setting list properties */
  298. KS_DECLARE(int) ks_list_attributes_comparator(ks_list_t *restrict l, element_comparator comparator_fun) {
  299. if (l == NULL) return -1;
  300. ks_rwl_write_lock(l->lock);
  301. l->attrs.comparator = comparator_fun;
  302. ks_assert(ks_list_attrOk(l));
  303. ks_rwl_write_unlock(l->lock);
  304. return 0;
  305. }
  306. KS_DECLARE(int) ks_list_attributes_seeker(ks_list_t *restrict l, element_seeker seeker_fun) {
  307. if (l == NULL) return -1;
  308. ks_rwl_write_lock(l->lock);
  309. l->attrs.seeker = seeker_fun;
  310. ks_assert(ks_list_attrOk(l));
  311. ks_rwl_write_unlock(l->lock);
  312. return 0;
  313. }
  314. int ks_list_attributes_copy(ks_list_t *restrict l, element_meter metric_fun, int copy_data) {
  315. if (l == NULL || (metric_fun == NULL && copy_data != 0)) return -1;
  316. ks_rwl_write_lock(l->lock);
  317. l->attrs.meter = metric_fun;
  318. l->attrs.copy_data = copy_data;
  319. ks_assert(ks_list_attrOk(l));
  320. ks_rwl_write_unlock(l->lock);
  321. return 0;
  322. }
  323. int ks_list_attributes_hash_computer(ks_list_t *restrict l, element_hash_computer hash_computer_fun) {
  324. if (l == NULL) return -1;
  325. ks_rwl_write_lock(l->lock);
  326. l->attrs.hasher = hash_computer_fun;
  327. ks_assert(ks_list_attrOk(l));
  328. ks_rwl_write_unlock(l->lock);
  329. return 0;
  330. }
  331. int ks_list_attributes_serializer(ks_list_t *restrict l, element_serializer serializer_fun) {
  332. if (l == NULL) return -1;
  333. ks_rwl_write_lock(l->lock);
  334. l->attrs.serializer = serializer_fun;
  335. ks_assert(ks_list_attrOk(l));
  336. ks_rwl_write_unlock(l->lock);
  337. return 0;
  338. }
  339. int ks_list_attributes_unserializer(ks_list_t *restrict l, element_unserializer unserializer_fun) {
  340. if (l == NULL) return -1;
  341. ks_rwl_write_lock(l->lock);
  342. l->attrs.unserializer = unserializer_fun;
  343. ks_assert(ks_list_attrOk(l));
  344. ks_rwl_write_unlock(l->lock);
  345. return 0;
  346. }
  347. KS_DECLARE(int) ks_list_append(ks_list_t *restrict l, const void *data) {
  348. return ks_list_insert_at(l, data, l->numels);
  349. }
  350. KS_DECLARE(int) ks_list_prepend(ks_list_t *restrict l, const void *data) {
  351. return ks_list_insert_at(l, data, 0);
  352. }
  353. KS_DECLARE(void *) ks_list_fetch(ks_list_t *restrict l) {
  354. return ks_list_extract_at(l, 0);
  355. }
  356. KS_DECLARE(void *) ks_list_get_at(const ks_list_t *restrict l, unsigned int pos) {
  357. struct ks_list_entry_s *tmp;
  358. void *data = NULL;
  359. ks_rwl_read_lock(l->lock);
  360. tmp = ks_list_findpos(l, pos);
  361. data = tmp != NULL ? tmp->data : NULL;
  362. ks_rwl_read_unlock(l->lock);
  363. return data;
  364. }
  365. KS_DECLARE(void *) ks_list_get_max(const ks_list_t *restrict l) {
  366. return ks_list_get_minmax(l, +1);
  367. }
  368. KS_DECLARE(void *) ks_list_get_min(const ks_list_t *restrict l) {
  369. return ks_list_get_minmax(l, -1);
  370. }
  371. /* REQUIRES {list->numels >= 1}
  372. * return the min (versus < 0) or max value (v > 0) in l */
  373. static void *ks_list_get_minmax(const ks_list_t *restrict l, int versus) {
  374. void *curminmax;
  375. struct ks_list_entry_s *s;
  376. if (l->attrs.comparator == NULL || l->numels == 0)
  377. return NULL;
  378. ks_rwl_read_lock(l->lock);
  379. curminmax = l->head_sentinel->next->data;
  380. for (s = l->head_sentinel->next->next; s != l->tail_sentinel; s = s->next) {
  381. if (l->attrs.comparator(curminmax, s->data) * versus > 0)
  382. curminmax = s->data;
  383. }
  384. ks_rwl_read_unlock(l->lock);
  385. return curminmax;
  386. }
  387. /* set tmp to point to element at index posstart in l */
  388. static inline struct ks_list_entry_s *ks_list_findpos(const ks_list_t *restrict l, int posstart) {
  389. struct ks_list_entry_s *ptr;
  390. float x;
  391. int i;
  392. /* accept 1 slot overflow for fetching head and tail sentinels */
  393. if (posstart < -1 || posstart >(int)l->numels) return NULL;
  394. x = (float)(posstart + 1) / l->numels;
  395. if (x <= 0.25) {
  396. /* first quarter: get to posstart from head */
  397. for (i = -1, ptr = l->head_sentinel; i < posstart; ptr = ptr->next, i++);
  398. }
  399. else if (x < 0.5) {
  400. /* second quarter: get to posstart from mid */
  401. for (i = (l->numels - 1) / 2, ptr = l->mid; i > posstart; ptr = ptr->prev, i--);
  402. }
  403. else if (x <= 0.75) {
  404. /* third quarter: get to posstart from mid */
  405. for (i = (l->numels - 1) / 2, ptr = l->mid; i < posstart; ptr = ptr->next, i++);
  406. }
  407. else {
  408. /* fourth quarter: get to posstart from tail */
  409. for (i = l->numels, ptr = l->tail_sentinel; i > posstart; ptr = ptr->prev, i--);
  410. }
  411. return ptr;
  412. }
  413. KS_DECLARE(void *) ks_list_extract_at(ks_list_t *restrict l, unsigned int pos) {
  414. struct ks_list_entry_s *tmp;
  415. void *data;
  416. if (l->iter_active || pos >= l->numels) return NULL;
  417. ks_rwl_write_lock(l->lock);
  418. tmp = ks_list_findpos(l, pos);
  419. data = tmp->data;
  420. tmp->data = NULL; /* save data from ks_list_drop_elem() free() */
  421. ks_list_drop_elem(l, tmp, pos);
  422. l->numels--;
  423. ks_assert(ks_list_repOk(l));
  424. ks_rwl_write_unlock(l->lock);
  425. return data;
  426. }
  427. KS_DECLARE(int) ks_list_insert_at(ks_list_t *restrict l, const void *data, unsigned int pos) {
  428. ks_pool_t *pool = NULL;
  429. struct ks_list_entry_s *lent, *succ, *prec;
  430. if (l->iter_active || pos > l->numels) return -1;
  431. pool = ks_pool_get(l);
  432. ks_rwl_write_lock(l->lock);
  433. /* this code optimizes malloc() with a free-list */
  434. if (l->spareelsnum > 0) {
  435. lent = l->spareels[l->spareelsnum - 1];
  436. l->spareelsnum--;
  437. }
  438. else {
  439. lent = (struct ks_list_entry_s *)ks_pool_alloc(pool, sizeof(struct ks_list_entry_s));
  440. ks_assert(lent);
  441. }
  442. if (l->attrs.copy_data) {
  443. /* make room for user' data (has to be copied) */
  444. ks_size_t datalen = l->attrs.meter(data);
  445. lent->data = (struct ks_list_entry_s *)ks_pool_alloc(pool, datalen);
  446. memcpy(lent->data, data, datalen);
  447. }
  448. else {
  449. lent->data = (void*)data;
  450. }
  451. /* actually append element */
  452. prec = ks_list_findpos(l, pos - 1);
  453. succ = prec->next;
  454. prec->next = lent;
  455. lent->prev = prec;
  456. lent->next = succ;
  457. succ->prev = lent;
  458. l->numels++;
  459. /* fix mid pointer */
  460. if (l->numels == 1) { /* first element, set pointer */
  461. l->mid = lent;
  462. }
  463. else if (l->numels % 2) { /* now odd */
  464. if (pos >= (l->numels - 1) / 2) l->mid = l->mid->next;
  465. }
  466. else { /* now even */
  467. if (pos <= (l->numels - 1) / 2) l->mid = l->mid->prev;
  468. }
  469. ks_assert(ks_list_repOk(l));
  470. ks_rwl_write_unlock(l->lock);
  471. return 1;
  472. }
  473. KS_DECLARE(int) ks_list_delete(ks_list_t *restrict l, const void *data) {
  474. int pos, r;
  475. int ret = 0;
  476. ks_rwl_write_lock(l->lock);
  477. pos = ks_list_locate(l, data, KS_TRUE);
  478. if (pos < 0) {
  479. ret = -1;
  480. goto done;
  481. }
  482. r = ks_list_delete_at(l, pos);
  483. if (r < 0) ret = -1;
  484. done:
  485. ks_assert(ks_list_repOk(l));
  486. ks_rwl_write_unlock(l->lock);
  487. return ret;
  488. }
  489. KS_DECLARE(int) ks_list_delete_at(ks_list_t *restrict l, unsigned int pos) {
  490. struct ks_list_entry_s *delendo;
  491. if (l->iter_active || pos >= l->numels) return -1;
  492. ks_rwl_write_lock(l->lock);
  493. delendo = ks_list_findpos(l, pos);
  494. ks_list_drop_elem(l, delendo, pos);
  495. l->numels--;
  496. ks_assert(ks_list_repOk(l));
  497. ks_rwl_write_unlock(l->lock);
  498. return 0;
  499. }
  500. KS_DECLARE(int) ks_list_delete_iterator(ks_list_t *restrict l) {
  501. struct ks_list_entry_s *delendo;
  502. if (!l->iter_active || l->iter_pos > l->numels) return -1;
  503. ks_rwl_write_lock(l->lock);
  504. delendo = ks_list_findpos(l, l->iter_pos - 1);
  505. ks_list_drop_elem(l, delendo, l->iter_pos - 1);
  506. l->numels--;
  507. ks_assert(ks_list_repOk(l));
  508. ks_rwl_write_unlock(l->lock);
  509. return 0;
  510. }
  511. KS_DECLARE(int) ks_list_delete_range(ks_list_t *restrict l, unsigned int posstart, unsigned int posend) {
  512. struct ks_list_entry_s *lastvalid, *tmp, *tmp2;
  513. unsigned int numdel, midposafter, i;
  514. int movedx;
  515. if (l->iter_active || posend < posstart || posend >= l->numels) return -1;
  516. numdel = posend - posstart + 1;
  517. if (numdel == l->numels) return ks_list_clear(l);
  518. ks_rwl_write_lock(l->lock);
  519. tmp = ks_list_findpos(l, posstart); /* first el to be deleted */
  520. lastvalid = tmp->prev; /* last valid element */
  521. midposafter = (l->numels - 1 - numdel) / 2;
  522. midposafter = midposafter < posstart ? midposafter : midposafter + numdel;
  523. movedx = midposafter - (l->numels - 1) / 2;
  524. if (movedx > 0) { /* move right */
  525. for (i = 0; i < (unsigned int)movedx; l->mid = l->mid->next, i++);
  526. }
  527. else { /* move left */
  528. movedx = -movedx;
  529. for (i = 0; i < (unsigned int)movedx; l->mid = l->mid->prev, i++);
  530. }
  531. ks_assert(posstart == 0 || lastvalid != l->head_sentinel);
  532. i = posstart;
  533. if (l->attrs.copy_data) {
  534. /* also free element data */
  535. for (; i <= posend; i++) {
  536. tmp2 = tmp;
  537. tmp = tmp->next;
  538. if (tmp2->data != NULL) ks_pool_free(&tmp2->data);
  539. if (l->spareelsnum < SIMCLIST_MAX_SPARE_ELEMS) {
  540. l->spareels[l->spareelsnum++] = tmp2;
  541. }
  542. else {
  543. ks_pool_free(&tmp2);
  544. }
  545. }
  546. }
  547. else {
  548. /* only free containers */
  549. for (; i <= posend; i++) {
  550. tmp2 = tmp;
  551. tmp = tmp->next;
  552. if (l->spareelsnum < SIMCLIST_MAX_SPARE_ELEMS) {
  553. l->spareels[l->spareelsnum++] = tmp2;
  554. }
  555. else {
  556. ks_pool_free(&tmp2);
  557. }
  558. }
  559. }
  560. ks_assert(i == posend + 1 && (posend != l->numels || tmp == l->tail_sentinel));
  561. lastvalid->next = tmp;
  562. tmp->prev = lastvalid;
  563. l->numels -= posend - posstart + 1;
  564. ks_assert(ks_list_repOk(l));
  565. ks_rwl_write_unlock(l->lock);
  566. return numdel;
  567. }
  568. KS_DECLARE(int) ks_list_clear(ks_list_t *restrict l) {
  569. struct ks_list_entry_s *s;
  570. int numels;
  571. ks_rwl_write_lock(l->lock);
  572. /* will be returned */
  573. numels = (int)l->numels;
  574. if (l->iter_active) {
  575. numels = -1;
  576. goto done;
  577. }
  578. if (l->attrs.copy_data) { /* also free user data */
  579. /* spare a loop conditional with two loops: spareing elems and freeing elems */
  580. for (s = l->head_sentinel->next; l->spareelsnum < SIMCLIST_MAX_SPARE_ELEMS && s != l->tail_sentinel; s = s->next) {
  581. /* move elements as spares as long as there is room */
  582. if (s->data != NULL) ks_pool_free(&s->data);
  583. l->spareels[l->spareelsnum++] = s;
  584. }
  585. while (s != l->tail_sentinel) {
  586. /* free the remaining elems */
  587. if (s->data != NULL) ks_pool_free(&s->data);
  588. s = s->next;
  589. ks_pool_free(&s->prev);
  590. }
  591. l->head_sentinel->next = l->tail_sentinel;
  592. l->tail_sentinel->prev = l->head_sentinel;
  593. }
  594. else { /* only free element containers */
  595. /* spare a loop conditional with two loops: spareing elems and freeing elems */
  596. for (s = l->head_sentinel->next; l->spareelsnum < SIMCLIST_MAX_SPARE_ELEMS && s != l->tail_sentinel; s = s->next) {
  597. /* move elements as spares as long as there is room */
  598. l->spareels[l->spareelsnum++] = s;
  599. }
  600. while (s != l->tail_sentinel) {
  601. /* free the remaining elems */
  602. s = s->next;
  603. ks_pool_free(&s->prev);
  604. }
  605. l->head_sentinel->next = l->tail_sentinel;
  606. l->tail_sentinel->prev = l->head_sentinel;
  607. }
  608. l->numels = 0;
  609. l->mid = NULL;
  610. done:
  611. ks_assert(ks_list_repOk(l));
  612. ks_rwl_write_unlock(l->lock);
  613. return numels;
  614. }
  615. KS_DECLARE(unsigned int) ks_list_size(const ks_list_t *restrict l) {
  616. return l->numels;
  617. }
  618. KS_DECLARE(int) ks_list_empty(const ks_list_t *restrict l) {
  619. return (l->numels == 0);
  620. }
  621. KS_DECLARE(int) ks_list_locate(const ks_list_t *restrict l, const void *data, ks_bool_t prelocked) {
  622. struct ks_list_entry_s *el;
  623. int pos = 0;
  624. if (!prelocked) ks_rwl_read_lock(l->lock);
  625. if (l->attrs.comparator != NULL) {
  626. /* use comparator */
  627. for (el = l->head_sentinel->next; el != l->tail_sentinel; el = el->next, pos++) {
  628. if (l->attrs.comparator(data, el->data) == 0) break;
  629. }
  630. }
  631. else {
  632. /* compare references */
  633. for (el = l->head_sentinel->next; el != l->tail_sentinel; el = el->next, pos++) {
  634. if (el->data == data) break;
  635. }
  636. }
  637. if (!prelocked) ks_rwl_read_unlock(l->lock);
  638. if (el == l->tail_sentinel) return -1;
  639. return pos;
  640. }
  641. KS_DECLARE(void *) ks_list_seek(ks_list_t *restrict l, const void *indicator) {
  642. const struct ks_list_entry_s *iter;
  643. void *ret = NULL;
  644. if (l->attrs.seeker == NULL) return NULL;
  645. ks_rwl_read_lock(l->lock);
  646. for (iter = l->head_sentinel->next; iter != l->tail_sentinel; iter = iter->next) {
  647. if (l->attrs.seeker(iter->data, indicator) != 0) {
  648. ret = iter->data;
  649. break;
  650. }
  651. }
  652. ks_rwl_read_unlock(l->lock);
  653. return ret;
  654. }
  655. KS_DECLARE(int) ks_list_contains(const ks_list_t *restrict l, const void *data) {
  656. return (ks_list_locate(l, data, KS_FALSE) >= 0);
  657. }
  658. KS_DECLARE(int) ks_list_concat(const ks_list_t *l1, const ks_list_t *l2, ks_list_t *restrict dest) {
  659. ks_pool_t *pool = NULL;
  660. struct ks_list_entry_s *el, *srcel;
  661. unsigned int cnt;
  662. int err;
  663. if (l1 == NULL || l2 == NULL || dest == NULL || l1 == dest || l2 == dest)
  664. return -1;
  665. //ks_list_init(dest);
  666. ks_rwl_read_lock(l1->lock);
  667. ks_rwl_read_lock(l2->lock);
  668. ks_rwl_write_lock(dest->lock);
  669. dest->numels = l1->numels + l2->numels;
  670. if (dest->numels == 0) goto done;
  671. pool = ks_pool_get(dest);
  672. /* copy list1 */
  673. srcel = l1->head_sentinel->next;
  674. el = dest->head_sentinel;
  675. while (srcel != l1->tail_sentinel) {
  676. el->next = (struct ks_list_entry_s *)ks_pool_alloc(pool, sizeof(struct ks_list_entry_s));
  677. el->next->prev = el;
  678. el = el->next;
  679. el->data = srcel->data;
  680. srcel = srcel->next;
  681. }
  682. dest->mid = el; /* approximate position (adjust later) */
  683. /* copy list 2 */
  684. srcel = l2->head_sentinel->next;
  685. while (srcel != l2->tail_sentinel) {
  686. el->next = (struct ks_list_entry_s *)ks_pool_alloc(pool, sizeof(struct ks_list_entry_s));
  687. el->next->prev = el;
  688. el = el->next;
  689. el->data = srcel->data;
  690. srcel = srcel->next;
  691. }
  692. el->next = dest->tail_sentinel;
  693. dest->tail_sentinel->prev = el;
  694. /* fix mid pointer */
  695. err = l2->numels - l1->numels;
  696. if ((err + 1) / 2 > 0) { /* correct pos RIGHT (err-1)/2 moves */
  697. err = (err + 1) / 2;
  698. for (cnt = 0; cnt < (unsigned int)err; cnt++) dest->mid = dest->mid->next;
  699. }
  700. else if (err / 2 < 0) { /* correct pos LEFT (err/2)-1 moves */
  701. err = -err / 2;
  702. for (cnt = 0; cnt < (unsigned int)err; cnt++) dest->mid = dest->mid->prev;
  703. }
  704. done:
  705. ks_assert(!(ks_list_repOk(l1) && ks_list_repOk(l2)) || ks_list_repOk(dest));
  706. ks_rwl_write_unlock(dest->lock);
  707. ks_rwl_read_unlock(l2->lock);
  708. ks_rwl_read_unlock(l1->lock);
  709. return 0;
  710. }
  711. KS_DECLARE(int) ks_list_sort(ks_list_t *restrict l, int versus) {
  712. if (l->iter_active || l->attrs.comparator == NULL) /* cannot modify list in the middle of an iteration */
  713. return -1;
  714. if (l->numels <= 1)
  715. return 0;
  716. ks_rwl_write_lock(l->lock);
  717. ks_list_sort_quicksort(l, versus, 0, l->head_sentinel->next, l->numels - 1, l->tail_sentinel->prev);
  718. ks_assert(ks_list_repOk(l));
  719. ks_rwl_write_unlock(l->lock);
  720. return 0;
  721. }
  722. #ifdef SIMCLIST_WITH_THREADS
  723. struct ks_list_sort_wrappedparams {
  724. ks_list_t *restrict l;
  725. int versus;
  726. unsigned int first, last;
  727. struct ks_list_entry_s *fel, *lel;
  728. };
  729. static void *ks_list_sort_quicksort_threadwrapper(void *wrapped_params) {
  730. struct ks_list_sort_wrappedparams *wp = (struct ks_list_sort_wrappedparams *)wrapped_params;
  731. ks_list_sort_quicksort(wp->l, wp->versus, wp->first, wp->fel, wp->last, wp->lel);
  732. ks_pool_free(&wp);
  733. pthread_exit(NULL);
  734. return NULL;
  735. }
  736. #endif
  737. static inline void ks_list_sort_selectionsort(ks_list_t *restrict l, int versus,
  738. unsigned int first, struct ks_list_entry_s *fel,
  739. unsigned int last, struct ks_list_entry_s *lel) {
  740. struct ks_list_entry_s *cursor, *toswap, *firstunsorted;
  741. void *tmpdata;
  742. if (last <= first) /* <= 1-element lists are always sorted */
  743. return;
  744. for (firstunsorted = fel; firstunsorted != lel; firstunsorted = firstunsorted->next) {
  745. /* find min or max in the remainder of the list */
  746. for (toswap = firstunsorted, cursor = firstunsorted->next; cursor != lel->next; cursor = cursor->next)
  747. if (l->attrs.comparator(toswap->data, cursor->data) * -versus > 0) toswap = cursor;
  748. if (toswap != firstunsorted) { /* swap firstunsorted with toswap */
  749. tmpdata = firstunsorted->data;
  750. firstunsorted->data = toswap->data;
  751. toswap->data = tmpdata;
  752. }
  753. }
  754. }
  755. static void ks_list_sort_quicksort(ks_list_t *restrict l, int versus,
  756. unsigned int first, struct ks_list_entry_s *fel,
  757. unsigned int last, struct ks_list_entry_s *lel) {
  758. unsigned int pivotid;
  759. unsigned int i;
  760. register struct ks_list_entry_s *pivot;
  761. struct ks_list_entry_s *left, *right;
  762. void *tmpdata;
  763. #ifdef SIMCLIST_WITH_THREADS
  764. pthread_t tid;
  765. int traised;
  766. #endif
  767. if (last <= first) /* <= 1-element lists are always sorted */
  768. return;
  769. if (last - first + 1 <= SIMCLIST_MINQUICKSORTELS) {
  770. ks_list_sort_selectionsort(l, versus, first, fel, last, lel);
  771. return;
  772. }
  773. /* base of iteration: one element list */
  774. if (!(last > first)) return;
  775. pivotid = (get_random() % (last - first + 1));
  776. /* pivotid = (last - first + 1) / 2; */
  777. /* find pivot */
  778. if (pivotid < (last - first + 1) / 2) {
  779. for (i = 0, pivot = fel; i < pivotid; pivot = pivot->next, i++);
  780. }
  781. else {
  782. for (i = last - first, pivot = lel; i > pivotid; pivot = pivot->prev, i--);
  783. }
  784. /* smaller PIVOT bigger */
  785. left = fel;
  786. right = lel;
  787. /* iterate --- left ---> PIV <--- right --- */
  788. while (left != pivot && right != pivot) {
  789. for (; left != pivot && (l->attrs.comparator(left->data, pivot->data) * -versus <= 0); left = left->next);
  790. /* left points to a smaller element, or to pivot */
  791. for (; right != pivot && (l->attrs.comparator(right->data, pivot->data) * -versus >= 0); right = right->prev);
  792. /* right points to a bigger element, or to pivot */
  793. if (left != pivot && right != pivot) {
  794. /* swap, then move iterators */
  795. tmpdata = left->data;
  796. left->data = right->data;
  797. right->data = tmpdata;
  798. left = left->next;
  799. right = right->prev;
  800. }
  801. }
  802. /* now either left points to pivot (end run), or right */
  803. if (right == pivot) { /* left part longer */
  804. while (left != pivot) {
  805. if (l->attrs.comparator(left->data, pivot->data) * -versus > 0) {
  806. tmpdata = left->data;
  807. left->data = pivot->prev->data;
  808. pivot->prev->data = pivot->data;
  809. pivot->data = tmpdata;
  810. pivot = pivot->prev;
  811. pivotid--;
  812. if (pivot == left) break;
  813. }
  814. else {
  815. left = left->next;
  816. }
  817. }
  818. }
  819. else { /* right part longer */
  820. while (right != pivot) {
  821. if (l->attrs.comparator(right->data, pivot->data) * -versus < 0) {
  822. /* move current right before pivot */
  823. tmpdata = right->data;
  824. right->data = pivot->next->data;
  825. pivot->next->data = pivot->data;
  826. pivot->data = tmpdata;
  827. pivot = pivot->next;
  828. pivotid++;
  829. if (pivot == right) break;
  830. }
  831. else {
  832. right = right->prev;
  833. }
  834. }
  835. }
  836. /* sort sublists A and B : |---A---| pivot |---B---| */
  837. #ifdef SIMCLIST_WITH_THREADS
  838. traised = 0;
  839. if (pivotid > 0) {
  840. /* prepare wrapped args, then start thread */
  841. if (l->threadcount < SIMCLIST_MAXTHREADS - 1) {
  842. struct ks_list_sort_wrappedparams *wp = (struct ks_list_sort_wrappedparams *)ks_pool_alloc(ks_pool_get(l), sizeof(struct ks_list_sort_wrappedparams));
  843. l->threadcount++;
  844. traised = 1;
  845. wp->l = l;
  846. wp->versus = versus;
  847. wp->first = first;
  848. wp->fel = fel;
  849. wp->last = first + pivotid - 1;
  850. wp->lel = pivot->prev;
  851. if (pthread_create(&tid, NULL, ks_list_sort_quicksort_threadwrapper, wp) != 0) {
  852. ks_pool_free(&wp);
  853. traised = 0;
  854. ks_list_sort_quicksort(l, versus, first, fel, first + pivotid - 1, pivot->prev);
  855. }
  856. }
  857. else {
  858. ks_list_sort_quicksort(l, versus, first, fel, first + pivotid - 1, pivot->prev);
  859. }
  860. }
  861. if (first + pivotid < last) ks_list_sort_quicksort(l, versus, first + pivotid + 1, pivot->next, last, lel);
  862. if (traised) {
  863. pthread_join(tid, (void **)NULL);
  864. l->threadcount--;
  865. }
  866. #else
  867. if (pivotid > 0) ks_list_sort_quicksort(l, versus, first, fel, first + pivotid - 1, pivot->prev);
  868. if (first + pivotid < last) ks_list_sort_quicksort(l, versus, first + pivotid + 1, pivot->next, last, lel);
  869. #endif
  870. }
  871. KS_DECLARE(int) ks_list_iterator_start(ks_list_t *restrict l) {
  872. if (l->iter_active) return 0;
  873. ks_rwl_write_lock(l->lock);
  874. l->iter_pos = 0;
  875. l->iter_active = 1;
  876. l->iter_curentry = l->head_sentinel->next;
  877. ks_rwl_write_unlock(l->lock);
  878. return 1;
  879. }
  880. KS_DECLARE(void *) ks_list_iterator_next(ks_list_t *restrict l) {
  881. void *toret;
  882. if (!l->iter_active) return NULL;
  883. ks_rwl_write_lock(l->lock);
  884. toret = l->iter_curentry->data;
  885. l->iter_curentry = l->iter_curentry->next;
  886. l->iter_pos++;
  887. ks_rwl_write_unlock(l->lock);
  888. return toret;
  889. }
  890. KS_DECLARE(int) ks_list_iterator_hasnext(const ks_list_t *restrict l) {
  891. int ret = 0;
  892. if (!l->iter_active) return 0;
  893. ks_rwl_read_lock(l->lock);
  894. ret = (l->iter_pos < l->numels);
  895. ks_rwl_read_unlock(l->lock);
  896. return ret;
  897. }
  898. KS_DECLARE(int) ks_list_iterator_stop(ks_list_t *restrict l) {
  899. if (!l->iter_active) return 0;
  900. ks_rwl_write_lock(l->lock);
  901. l->iter_pos = 0;
  902. l->iter_active = 0;
  903. ks_rwl_write_unlock(l->lock);
  904. return 1;
  905. }
  906. KS_DECLARE(int) ks_list_hash(const ks_list_t *restrict l, ks_list_hash_t *restrict hash) {
  907. struct ks_list_entry_s *x;
  908. ks_list_hash_t tmphash;
  909. int ret = 0;
  910. ks_assert(hash != NULL);
  911. ks_rwl_read_lock(l->lock);
  912. tmphash = l->numels * 2 + 100;
  913. if (l->attrs.hasher == NULL) {
  914. #ifdef SIMCLIST_ALLOW_LOCATIONBASED_HASHES
  915. /* ENABLE WITH CARE !! */
  916. #warning "Memlocation-based hash is consistent only for testing modification in the same program run."
  917. int i;
  918. /* only use element references */
  919. for (x = l->head_sentinel->next; x != l->tail_sentinel; x = x->next) {
  920. for (i = 0; i < sizeof(x->data); i++) {
  921. tmphash += (tmphash ^ (uintptr_t)x->data);
  922. }
  923. tmphash += tmphash % l->numels;
  924. }
  925. #else
  926. ret = -1;
  927. #endif
  928. }
  929. else {
  930. /* hash each element with the user-given function */
  931. for (x = l->head_sentinel->next; x != l->tail_sentinel; x = x->next) {
  932. tmphash += tmphash ^ l->attrs.hasher(x->data);
  933. tmphash += tmphash % l->numels;
  934. }
  935. }
  936. ks_rwl_read_unlock(l->lock);
  937. *hash = tmphash;
  938. return ret;
  939. }
  940. #ifndef SIMCLIST_NO_DUMPRESTORE
  941. int ks_list_dump_getinfo_filedescriptor(int fd, ks_list_dump_info_t *restrict info) {
  942. int32_t terminator_head, terminator_tail;
  943. uint32_t elemlen;
  944. off_t hop;
  945. /* version */
  946. READ_ERRCHECK(fd, &info->version, sizeof(info->version));
  947. info->version = ntohs(info->version);
  948. if (info->version > SIMCLIST_DUMPFORMAT_VERSION) {
  949. errno = EILSEQ;
  950. return -1;
  951. }
  952. /* timestamp.tv_sec and timestamp.tv_usec */
  953. READ_ERRCHECK(fd, &info->timestamp.tv_sec, sizeof(info->timestamp.tv_sec));
  954. info->timestamp.tv_sec = ntohl(info->timestamp.tv_sec);
  955. READ_ERRCHECK(fd, &info->timestamp.tv_usec, sizeof(info->timestamp.tv_usec));
  956. info->timestamp.tv_usec = ntohl(info->timestamp.tv_usec);
  957. /* list terminator (to check thereafter) */
  958. READ_ERRCHECK(fd, &terminator_head, sizeof(terminator_head));
  959. terminator_head = ntohl(terminator_head);
  960. /* list size */
  961. READ_ERRCHECK(fd, &info->list_size, sizeof(info->list_size));
  962. info->list_size = ntohl(info->list_size);
  963. /* number of elements */
  964. READ_ERRCHECK(fd, &info->list_numels, sizeof(info->list_numels));
  965. info->list_numels = ntohl(info->list_numels);
  966. /* length of each element (for checking for consistency) */
  967. READ_ERRCHECK(fd, &elemlen, sizeof(elemlen));
  968. elemlen = ntohl(elemlen);
  969. /* list hash */
  970. READ_ERRCHECK(fd, &info->list_hash, sizeof(info->list_hash));
  971. info->list_hash = ntohl(info->list_hash);
  972. /* check consistency */
  973. if (elemlen > 0) {
  974. /* constant length, hop by size only */
  975. hop = info->list_size;
  976. }
  977. else {
  978. /* non-constant length, hop by size + all element length blocks */
  979. hop = info->list_size + elemlen*info->list_numels;
  980. }
  981. if (lseek(fd, hop, SEEK_CUR) == -1) {
  982. return -1;
  983. }
  984. /* read the trailing value and compare with terminator_head */
  985. READ_ERRCHECK(fd, &terminator_tail, sizeof(terminator_tail));
  986. terminator_tail = ntohl(terminator_tail);
  987. if (terminator_head == terminator_tail)
  988. info->consistent = 1;
  989. else
  990. info->consistent = 0;
  991. return 0;
  992. }
  993. int ks_list_dump_getinfo_file(const char *restrict filename, ks_list_dump_info_t *restrict info) {
  994. int fd, ret;
  995. fd = open(filename, O_RDONLY, 0);
  996. if (fd < 0) return -1;
  997. ret = ks_list_dump_getinfo_filedescriptor(fd, info);
  998. close(fd);
  999. return ret;
  1000. }
  1001. int ks_list_dump_filedescriptor(const ks_list_t *restrict l, int fd, ks_size_t *restrict len) {
  1002. struct ks_list_entry_s *x;
  1003. void *ser_buf;
  1004. uint32_t bufsize;
  1005. struct timeval timeofday;
  1006. struct ks_list_dump_header_s header;
  1007. if (l->attrs.meter == NULL && l->attrs.serializer == NULL) {
  1008. errno = ENOTTY;
  1009. return -1;
  1010. }
  1011. /**** DUMP FORMAT ****
  1012. [ ver timestamp | totlen numels elemlen hash | DATA ]
  1013. where DATA can be:
  1014. @ for constant-size list (element size is constant; elemlen > 0)
  1015. [ elem elem ... elem ]
  1016. @ for other lists (element size dictated by element_meter each time; elemlen <= 0)
  1017. [ size elem size elem ... size elem ]
  1018. all integers are encoded in NETWORK BYTE FORMAT
  1019. *****/
  1020. /* prepare HEADER */
  1021. /* version */
  1022. header.ver = htons(SIMCLIST_DUMPFORMAT_VERSION);
  1023. /* timestamp */
  1024. gettimeofday(&timeofday, NULL);
  1025. header.timestamp_sec = htonl(timeofday.tv_sec);
  1026. header.timestamp_usec = htonl(timeofday.tv_usec);
  1027. header.rndterm = htonl((int32_t)get_random());
  1028. /* total list size is postprocessed afterwards */
  1029. /* number of elements */
  1030. header.numels = htonl(l->numels);
  1031. /* include an hash, if possible */
  1032. if (l->attrs.hasher != NULL) {
  1033. if (htonl(ks_list_hash(l, &header.listhash)) != 0) {
  1034. /* could not compute list hash! */
  1035. return -1;
  1036. }
  1037. }
  1038. else {
  1039. header.listhash = htonl(0);
  1040. }
  1041. header.totlistlen = header.elemlen = 0;
  1042. /* leave room for the header at the beginning of the file */
  1043. if (lseek(fd, SIMCLIST_DUMPFORMAT_HEADERLEN, SEEK_SET) < 0) {
  1044. /* errno set by lseek() */
  1045. return -1;
  1046. }
  1047. /* write CONTENT */
  1048. if (l->numels > 0) {
  1049. /* SPECULATE that the list has constant element size */
  1050. if (l->attrs.serializer != NULL) { /* user user-specified serializer */
  1051. /* get preliminary length of serialized element in header.elemlen */
  1052. ser_buf = l->attrs.serializer(l->head_sentinel->next->data, &header.elemlen);
  1053. ks_pool_free(&ser_buf);
  1054. /* request custom serialization of each element */
  1055. for (x = l->head_sentinel->next; x != l->tail_sentinel; x = x->next) {
  1056. ser_buf = l->attrs.serializer(x->data, &bufsize);
  1057. header.totlistlen += bufsize;
  1058. if (header.elemlen != 0) { /* continue on speculation */
  1059. if (header.elemlen != bufsize) {
  1060. ks_pool_free(&ser_buf);
  1061. /* constant element length speculation broken! */
  1062. header.elemlen = 0;
  1063. header.totlistlen = 0;
  1064. x = l->head_sentinel;
  1065. if (lseek(fd, SIMCLIST_DUMPFORMAT_HEADERLEN, SEEK_SET) < 0) {
  1066. /* errno set by lseek() */
  1067. return -1;
  1068. }
  1069. /* restart from the beginning */
  1070. continue;
  1071. }
  1072. /* speculation confirmed */
  1073. WRITE_ERRCHECK(fd, ser_buf, bufsize);
  1074. }
  1075. else { /* speculation found broken */
  1076. WRITE_ERRCHECK(fd, &bufsize, sizeof(ks_size_t));
  1077. WRITE_ERRCHECK(fd, ser_buf, bufsize);
  1078. }
  1079. ks_pool_free(&ser_buf);
  1080. }
  1081. }
  1082. else if (l->attrs.meter != NULL) {
  1083. header.elemlen = (uint32_t)l->attrs.meter(l->head_sentinel->next->data);
  1084. /* serialize the element straight from its data */
  1085. for (x = l->head_sentinel->next; x != l->tail_sentinel; x = x->next) {
  1086. bufsize = (uint32_t)l->attrs.meter(x->data);
  1087. header.totlistlen += bufsize;
  1088. if (header.elemlen != 0) {
  1089. if (header.elemlen != bufsize) {
  1090. /* constant element length speculation broken! */
  1091. header.elemlen = 0;
  1092. header.totlistlen = 0;
  1093. x = l->head_sentinel;
  1094. /* restart from the beginning */
  1095. continue;
  1096. }
  1097. WRITE_ERRCHECK(fd, x->data, bufsize);
  1098. }
  1099. else {
  1100. WRITE_ERRCHECK(fd, &bufsize, sizeof(ks_size_t));
  1101. WRITE_ERRCHECK(fd, x->data, bufsize);
  1102. }
  1103. }
  1104. }
  1105. /* adjust endianness */
  1106. header.elemlen = htonl(header.elemlen);
  1107. header.totlistlen = htonl(header.totlistlen);
  1108. }
  1109. /* write random terminator */
  1110. WRITE_ERRCHECK(fd, &header.rndterm, sizeof(header.rndterm)); /* list terminator */
  1111. /* write header */
  1112. lseek(fd, 0, SEEK_SET);
  1113. WRITE_ERRCHECK(fd, &header.ver, sizeof(header.ver)); /* version */
  1114. WRITE_ERRCHECK(fd, &header.timestamp_sec, sizeof(header.timestamp_sec)); /* timestamp seconds */
  1115. WRITE_ERRCHECK(fd, &header.timestamp_usec, sizeof(header.timestamp_usec)); /* timestamp microseconds */
  1116. WRITE_ERRCHECK(fd, &header.rndterm, sizeof(header.rndterm)); /* random terminator */
  1117. WRITE_ERRCHECK(fd, &header.totlistlen, sizeof(header.totlistlen)); /* total length of elements */
  1118. WRITE_ERRCHECK(fd, &header.numels, sizeof(header.numels)); /* number of elements */
  1119. WRITE_ERRCHECK(fd, &header.elemlen, sizeof(header.elemlen)); /* size of each element, or 0 for independent */
  1120. WRITE_ERRCHECK(fd, &header.listhash, sizeof(header.listhash)); /* list hash, or 0 for "ignore" */
  1121. /* possibly store total written length in "len" */
  1122. if (len != NULL) {
  1123. *len = sizeof(header) + ntohl(header.totlistlen);
  1124. }
  1125. return 0;
  1126. }
  1127. int ks_list_restore_filedescriptor(ks_list_t *restrict l, int fd, ks_size_t *restrict len) {
  1128. ks_pool_t *pool = NULL;
  1129. struct ks_list_dump_header_s header;
  1130. unsigned long cnt;
  1131. void *buf;
  1132. uint32_t elsize, totreadlen, totmemorylen;
  1133. memset(&header, 0, sizeof(header));
  1134. /* read header */
  1135. /* version */
  1136. READ_ERRCHECK(fd, &header.ver, sizeof(header.ver));
  1137. header.ver = ntohs(header.ver);
  1138. if (header.ver != SIMCLIST_DUMPFORMAT_VERSION) {
  1139. errno = EILSEQ;
  1140. return -1;
  1141. }
  1142. pool = ks_pool_get(l);
  1143. /* timestamp */
  1144. READ_ERRCHECK(fd, &header.timestamp_sec, sizeof(header.timestamp_sec));
  1145. header.timestamp_sec = ntohl(header.timestamp_sec);
  1146. READ_ERRCHECK(fd, &header.timestamp_usec, sizeof(header.timestamp_usec));
  1147. header.timestamp_usec = ntohl(header.timestamp_usec);
  1148. /* list terminator */
  1149. READ_ERRCHECK(fd, &header.rndterm, sizeof(header.rndterm));
  1150. header.rndterm = ntohl(header.rndterm);
  1151. /* total list size */
  1152. READ_ERRCHECK(fd, &header.totlistlen, sizeof(header.totlistlen));
  1153. header.totlistlen = ntohl(header.totlistlen);
  1154. /* number of elements */
  1155. READ_ERRCHECK(fd, &header.numels, sizeof(header.numels));
  1156. header.numels = ntohl(header.numels);
  1157. /* length of every element, or '0' = variable */
  1158. READ_ERRCHECK(fd, &header.elemlen, sizeof(header.elemlen));
  1159. header.elemlen = ntohl(header.elemlen);
  1160. /* list hash, or 0 = 'ignore' */
  1161. READ_ERRCHECK(fd, &header.listhash, sizeof(header.listhash));
  1162. header.listhash = ntohl(header.listhash);
  1163. /* read content */
  1164. totreadlen = totmemorylen = 0;
  1165. if (header.elemlen > 0) {
  1166. /* elements have constant size = header.elemlen */
  1167. if (l->attrs.unserializer != NULL) {
  1168. /* use unserializer */
  1169. buf = ks_pool_alloc(pool, header.elemlen);
  1170. for (cnt = 0; cnt < header.numels; cnt++) {
  1171. READ_ERRCHECK(fd, buf, header.elemlen);
  1172. ks_list_append(l, l->attrs.unserializer(buf, &elsize));
  1173. totmemorylen += elsize;
  1174. }
  1175. }
  1176. else {
  1177. /* copy verbatim into memory */
  1178. for (cnt = 0; cnt < header.numels; cnt++) {
  1179. buf = ks_pool_alloc(pool, header.elemlen);
  1180. READ_ERRCHECK(fd, buf, header.elemlen);
  1181. ks_list_append(l, buf);
  1182. }
  1183. totmemorylen = header.numels * header.elemlen;
  1184. }
  1185. totreadlen = header.numels * header.elemlen;
  1186. }
  1187. else {
  1188. /* elements have variable size. Each element is preceded by its size */
  1189. if (l->attrs.unserializer != NULL) {
  1190. /* use unserializer */
  1191. for (cnt = 0; cnt < header.numels; cnt++) {
  1192. READ_ERRCHECK(fd, &elsize, sizeof(elsize));
  1193. buf = ks_pool_alloc(pool, (ks_size_t)elsize);
  1194. READ_ERRCHECK(fd, buf, elsize);
  1195. totreadlen += elsize;
  1196. ks_list_append(l, l->attrs.unserializer(buf, &elsize));
  1197. totmemorylen += elsize;
  1198. }
  1199. }
  1200. else {
  1201. /* copy verbatim into memory */
  1202. for (cnt = 0; cnt < header.numels; cnt++) {
  1203. READ_ERRCHECK(fd, &elsize, sizeof(elsize));
  1204. buf = ks_pool_alloc(pool, elsize);
  1205. READ_ERRCHECK(fd, buf, elsize);
  1206. totreadlen += elsize;
  1207. ks_list_append(l, buf);
  1208. }
  1209. totmemorylen = totreadlen;
  1210. }
  1211. }
  1212. READ_ERRCHECK(fd, &elsize, sizeof(elsize)); /* read list terminator */
  1213. elsize = ntohl(elsize);
  1214. /* possibly verify the list consistency */
  1215. /* wrt hash */
  1216. /* don't do that
  1217. if (header.listhash != 0 && header.listhash != ks_list_hash(l)) {
  1218. errno = ECANCELED;
  1219. return -1;
  1220. }
  1221. */
  1222. /* wrt header */
  1223. if (totreadlen != header.totlistlen && (int32_t)elsize == header.rndterm) {
  1224. errno = EPROTO;
  1225. return -1;
  1226. }
  1227. /* wrt file */
  1228. if (lseek(fd, 0, SEEK_CUR) != lseek(fd, 0, SEEK_END)) {
  1229. errno = EPROTO;
  1230. return -1;
  1231. }
  1232. if (len != NULL) {
  1233. *len = totmemorylen;
  1234. }
  1235. return 0;
  1236. }
  1237. int ks_list_dump_file(const ks_list_t *restrict l, const char *restrict filename, ks_size_t *restrict len) {
  1238. int fd, oflag, mode;
  1239. #ifndef _WIN32
  1240. oflag = O_RDWR | O_CREAT | O_TRUNC;
  1241. mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
  1242. #else
  1243. oflag = _O_RDWR | _O_CREAT | _O_TRUNC;
  1244. mode = S_IRUSR | S_IWUSR;
  1245. #endif
  1246. fd = open(filename, oflag, mode);
  1247. if (fd < 0) return -1;
  1248. ks_rwl_write_lock(l->lock);
  1249. ks_list_dump_filedescriptor(l, fd, len);
  1250. ks_rwl_write_unlock(l->lock);
  1251. close(fd);
  1252. return 0;
  1253. }
  1254. int ks_list_restore_file(ks_list_t *restrict l, const char *restrict filename, ks_size_t *restrict len) {
  1255. int fd;
  1256. fd = open(filename, O_RDONLY, 0);
  1257. if (fd < 0) return -1;
  1258. ks_rwl_write_lock(l->lock);
  1259. ks_list_restore_filedescriptor(l, fd, len);
  1260. ks_rwl_write_unlock(l->lock);
  1261. close(fd);
  1262. return 0;
  1263. }
  1264. #endif /* ifndef SIMCLIST_NO_DUMPRESTORE */
  1265. static int ks_list_drop_elem(ks_list_t *restrict l, struct ks_list_entry_s *tmp, unsigned int pos) {
  1266. if (tmp == NULL) return -1;
  1267. /* fix mid pointer. This is wrt the PRE situation */
  1268. if (l->numels % 2) { /* now odd */
  1269. /* sort out the base case by hand */
  1270. if (l->numels == 1) l->mid = NULL;
  1271. else if (pos >= l->numels / 2) l->mid = l->mid->prev;
  1272. }
  1273. else { /* now even */
  1274. if (pos < l->numels / 2) l->mid = l->mid->next;
  1275. }
  1276. tmp->prev->next = tmp->next;
  1277. tmp->next->prev = tmp->prev;
  1278. /* free what's to be freed */
  1279. if (l->attrs.copy_data && tmp->data != NULL)
  1280. ks_pool_free(&tmp->data);
  1281. if (l->spareelsnum < SIMCLIST_MAX_SPARE_ELEMS) {
  1282. l->spareels[l->spareelsnum++] = tmp;
  1283. }
  1284. else {
  1285. ks_pool_free(&tmp);
  1286. }
  1287. return 0;
  1288. }
  1289. /* ready-made comparators and meters */
  1290. #define SIMCLIST_NUMBER_COMPARATOR(type) int ks_list_comparator_##type(const void *a, const void *b) { return( *(type *)a < *(type *)b) - (*(type *)a > *(type *)b); }
  1291. SIMCLIST_NUMBER_COMPARATOR(int8_t)
  1292. SIMCLIST_NUMBER_COMPARATOR(int16_t)
  1293. SIMCLIST_NUMBER_COMPARATOR(int32_t)
  1294. SIMCLIST_NUMBER_COMPARATOR(int64_t)
  1295. SIMCLIST_NUMBER_COMPARATOR(uint8_t)
  1296. SIMCLIST_NUMBER_COMPARATOR(uint16_t)
  1297. SIMCLIST_NUMBER_COMPARATOR(uint32_t)
  1298. SIMCLIST_NUMBER_COMPARATOR(uint64_t)
  1299. SIMCLIST_NUMBER_COMPARATOR(float)
  1300. SIMCLIST_NUMBER_COMPARATOR(double)
  1301. int ks_list_comparator_string(const void *a, const void *b) { return strcmp((const char *)b, (const char *)a); }
  1302. /* ready-made metric functions */
  1303. #define SIMCLIST_METER(type) ks_size_t ks_list_meter_##type(const void *el) { if (el) { /* kill compiler whinge */ } return sizeof(type); }
  1304. SIMCLIST_METER(int8_t)
  1305. SIMCLIST_METER(int16_t)
  1306. SIMCLIST_METER(int32_t)
  1307. SIMCLIST_METER(int64_t)
  1308. SIMCLIST_METER(uint8_t)
  1309. SIMCLIST_METER(uint16_t)
  1310. SIMCLIST_METER(uint32_t)
  1311. SIMCLIST_METER(uint64_t)
  1312. SIMCLIST_METER(float)
  1313. SIMCLIST_METER(double)
  1314. ks_size_t ks_list_meter_string(const void *el) { return strlen((const char *)el) + 1; }
  1315. /* ready-made hashing functions */
  1316. #define SIMCLIST_HASHCOMPUTER(type) ks_list_hash_t ks_list_hashcomputer_##type(const void *el) { return (ks_list_hash_t)(*(type *)el); }
  1317. SIMCLIST_HASHCOMPUTER(int8_t)
  1318. SIMCLIST_HASHCOMPUTER(int16_t)
  1319. SIMCLIST_HASHCOMPUTER(int32_t)
  1320. SIMCLIST_HASHCOMPUTER(int64_t)
  1321. SIMCLIST_HASHCOMPUTER(uint8_t)
  1322. SIMCLIST_HASHCOMPUTER(uint16_t)
  1323. SIMCLIST_HASHCOMPUTER(uint32_t)
  1324. SIMCLIST_HASHCOMPUTER(uint64_t)
  1325. SIMCLIST_HASHCOMPUTER(float)
  1326. SIMCLIST_HASHCOMPUTER(double)
  1327. ks_list_hash_t ks_list_hashcomputer_string(const void *el) {
  1328. ks_size_t l;
  1329. ks_list_hash_t hash = 123;
  1330. const char *str = (const char *)el;
  1331. char plus;
  1332. for (l = 0; str[l] != '\0'; l++) {
  1333. if (l) plus = (char)(hash ^ str[l]);
  1334. else plus = (char)(hash ^ (str[l] - str[0]));
  1335. hash += (plus << (CHAR_BIT * (l % sizeof(ks_list_hash_t))));
  1336. }
  1337. return hash;
  1338. }
  1339. static int ks_list_repOk(const ks_list_t *restrict l) {
  1340. int ok, i;
  1341. struct ks_list_entry_s *s;
  1342. ok = (l != NULL) && (
  1343. /* head/tail checks */
  1344. (l->head_sentinel != NULL && l->tail_sentinel != NULL) &&
  1345. (l->head_sentinel != l->tail_sentinel) && (l->head_sentinel->prev == NULL && l->tail_sentinel->next == NULL) &&
  1346. /* empty list */
  1347. (l->numels > 0 || (l->mid == NULL && l->head_sentinel->next == l->tail_sentinel && l->tail_sentinel->prev == l->head_sentinel)) &&
  1348. /* spare elements checks */
  1349. l->spareelsnum <= SIMCLIST_MAX_SPARE_ELEMS
  1350. );
  1351. if (!ok) return 0;
  1352. if (l->numels >= 1) {
  1353. /* correct referencing */
  1354. for (i = -1, s = l->head_sentinel; i < (int)(l->numels - 1) / 2 && s->next != NULL; i++, s = s->next) {
  1355. if (s->next->prev != s) break;
  1356. }
  1357. ok = (i == (int)(l->numels - 1) / 2 && l->mid == s);
  1358. if (!ok) return 0;
  1359. for (; s->next != NULL; i++, s = s->next) {
  1360. if (s->next->prev != s) break;
  1361. }
  1362. ok = (i == (int)l->numels && s == l->tail_sentinel);
  1363. }
  1364. return ok;
  1365. }
  1366. static int ks_list_attrOk(const ks_list_t *restrict l) {
  1367. int ok;
  1368. ok = (l->attrs.copy_data == 0 || l->attrs.meter != NULL);
  1369. return ok;
  1370. }
  1371. /* For Emacs:
  1372. * Local Variables:
  1373. * mode:c
  1374. * indent-tabs-mode:t
  1375. * tab-width:4
  1376. * c-basic-offset:4
  1377. * End:
  1378. * For VIM:
  1379. * vim:set softtabstop=4 shiftwidth=4 tabstop=4 noet:
  1380. */