container.c 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2011, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file container.c
  7. * \brief Implements a smartlist (a resizable array) along
  8. * with helper functions to use smartlists. Also includes
  9. * hash table implementations of a string-to-void* map, and of
  10. * a digest-to-void* map.
  11. **/
  12. #include "compat.h"
  13. #include "util.h"
  14. #include "torlog.h"
  15. #include "container.h"
  16. #include "crypto.h"
  17. #include <stdlib.h>
  18. #include <string.h>
  19. #include <assert.h>
  20. #include "ht.h"
  21. /** All newly allocated smartlists have this capacity. */
  22. #define SMARTLIST_DEFAULT_CAPACITY 16
  23. /** Allocate and return an empty smartlist.
  24. */
  25. smartlist_t *
  26. smartlist_create(void)
  27. {
  28. smartlist_t *sl = tor_malloc(sizeof(smartlist_t));
  29. sl->num_used = 0;
  30. sl->capacity = SMARTLIST_DEFAULT_CAPACITY;
  31. sl->list = tor_malloc(sizeof(void *) * sl->capacity);
  32. return sl;
  33. }
  34. /** Deallocate a smartlist. Does not release storage associated with the
  35. * list's elements.
  36. */
  37. void
  38. smartlist_free(smartlist_t *sl)
  39. {
  40. if (!sl)
  41. return;
  42. tor_free(sl->list);
  43. tor_free(sl);
  44. }
  45. /** Remove all elements from the list.
  46. */
  47. void
  48. smartlist_clear(smartlist_t *sl)
  49. {
  50. sl->num_used = 0;
  51. }
  52. /** Make sure that <b>sl</b> can hold at least <b>size</b> entries. */
  53. static INLINE void
  54. smartlist_ensure_capacity(smartlist_t *sl, int size)
  55. {
  56. if (size > sl->capacity) {
  57. int higher = sl->capacity * 2;
  58. while (size > higher)
  59. higher *= 2;
  60. tor_assert(higher > 0); /* detect overflow */
  61. sl->capacity = higher;
  62. sl->list = tor_realloc(sl->list, sizeof(void*)*sl->capacity);
  63. }
  64. }
  65. /** Append element to the end of the list. */
  66. void
  67. smartlist_add(smartlist_t *sl, void *element)
  68. {
  69. smartlist_ensure_capacity(sl, sl->num_used+1);
  70. sl->list[sl->num_used++] = element;
  71. }
  72. /** Append each element from S2 to the end of S1. */
  73. void
  74. smartlist_add_all(smartlist_t *s1, const smartlist_t *s2)
  75. {
  76. int new_size = s1->num_used + s2->num_used;
  77. tor_assert(new_size >= s1->num_used); /* check for overflow. */
  78. smartlist_ensure_capacity(s1, new_size);
  79. memcpy(s1->list + s1->num_used, s2->list, s2->num_used*sizeof(void*));
  80. s1->num_used = new_size;
  81. }
  82. /** Remove all elements E from sl such that E==element. Preserve
  83. * the order of any elements before E, but elements after E can be
  84. * rearranged.
  85. */
  86. void
  87. smartlist_remove(smartlist_t *sl, const void *element)
  88. {
  89. int i;
  90. if (element == NULL)
  91. return;
  92. for (i=0; i < sl->num_used; i++)
  93. if (sl->list[i] == element) {
  94. sl->list[i] = sl->list[--sl->num_used]; /* swap with the end */
  95. i--; /* so we process the new i'th element */
  96. }
  97. }
  98. /** If <b>sl</b> is nonempty, remove and return the final element. Otherwise,
  99. * return NULL. */
  100. void *
  101. smartlist_pop_last(smartlist_t *sl)
  102. {
  103. tor_assert(sl);
  104. if (sl->num_used)
  105. return sl->list[--sl->num_used];
  106. else
  107. return NULL;
  108. }
  109. /** Reverse the order of the items in <b>sl</b>. */
  110. void
  111. smartlist_reverse(smartlist_t *sl)
  112. {
  113. int i, j;
  114. void *tmp;
  115. tor_assert(sl);
  116. for (i = 0, j = sl->num_used-1; i < j; ++i, --j) {
  117. tmp = sl->list[i];
  118. sl->list[i] = sl->list[j];
  119. sl->list[j] = tmp;
  120. }
  121. }
  122. /** If there are any strings in sl equal to element, remove and free them.
  123. * Does not preserve order. */
  124. void
  125. smartlist_string_remove(smartlist_t *sl, const char *element)
  126. {
  127. int i;
  128. tor_assert(sl);
  129. tor_assert(element);
  130. for (i = 0; i < sl->num_used; ++i) {
  131. if (!strcmp(element, sl->list[i])) {
  132. tor_free(sl->list[i]);
  133. sl->list[i] = sl->list[--sl->num_used]; /* swap with the end */
  134. i--; /* so we process the new i'th element */
  135. }
  136. }
  137. }
  138. /** Return true iff some element E of sl has E==element.
  139. */
  140. int
  141. smartlist_isin(const smartlist_t *sl, const void *element)
  142. {
  143. int i;
  144. for (i=0; i < sl->num_used; i++)
  145. if (sl->list[i] == element)
  146. return 1;
  147. return 0;
  148. }
  149. /** Return true iff <b>sl</b> has some element E such that
  150. * !strcmp(E,<b>element</b>)
  151. */
  152. int
  153. smartlist_string_isin(const smartlist_t *sl, const char *element)
  154. {
  155. int i;
  156. if (!sl) return 0;
  157. for (i=0; i < sl->num_used; i++)
  158. if (strcmp((const char*)sl->list[i],element)==0)
  159. return 1;
  160. return 0;
  161. }
  162. /** If <b>element</b> is equal to an element of <b>sl</b>, return that
  163. * element's index. Otherwise, return -1. */
  164. int
  165. smartlist_string_pos(const smartlist_t *sl, const char *element)
  166. {
  167. int i;
  168. if (!sl) return -1;
  169. for (i=0; i < sl->num_used; i++)
  170. if (strcmp((const char*)sl->list[i],element)==0)
  171. return i;
  172. return -1;
  173. }
  174. /** Return true iff <b>sl</b> has some element E such that
  175. * !strcasecmp(E,<b>element</b>)
  176. */
  177. int
  178. smartlist_string_isin_case(const smartlist_t *sl, const char *element)
  179. {
  180. int i;
  181. if (!sl) return 0;
  182. for (i=0; i < sl->num_used; i++)
  183. if (strcasecmp((const char*)sl->list[i],element)==0)
  184. return 1;
  185. return 0;
  186. }
  187. /** Return true iff <b>sl</b> has some element E such that E is equal
  188. * to the decimal encoding of <b>num</b>.
  189. */
  190. int
  191. smartlist_string_num_isin(const smartlist_t *sl, int num)
  192. {
  193. char buf[16];
  194. tor_snprintf(buf,sizeof(buf),"%d", num);
  195. return smartlist_string_isin(sl, buf);
  196. }
  197. /** Return true iff <b>sl</b> has some element E such that
  198. * !memcmp(E,<b>element</b>,DIGEST_LEN)
  199. */
  200. int
  201. smartlist_digest_isin(const smartlist_t *sl, const char *element)
  202. {
  203. int i;
  204. if (!sl) return 0;
  205. for (i=0; i < sl->num_used; i++)
  206. if (memcmp((const char*)sl->list[i],element,DIGEST_LEN)==0)
  207. return 1;
  208. return 0;
  209. }
  210. /** Return true iff some element E of sl2 has smartlist_isin(sl1,E).
  211. */
  212. int
  213. smartlist_overlap(const smartlist_t *sl1, const smartlist_t *sl2)
  214. {
  215. int i;
  216. for (i=0; i < sl2->num_used; i++)
  217. if (smartlist_isin(sl1, sl2->list[i]))
  218. return 1;
  219. return 0;
  220. }
  221. /** Remove every element E of sl1 such that !smartlist_isin(sl2,E).
  222. * Does not preserve the order of sl1.
  223. */
  224. void
  225. smartlist_intersect(smartlist_t *sl1, const smartlist_t *sl2)
  226. {
  227. int i;
  228. for (i=0; i < sl1->num_used; i++)
  229. if (!smartlist_isin(sl2, sl1->list[i])) {
  230. sl1->list[i] = sl1->list[--sl1->num_used]; /* swap with the end */
  231. i--; /* so we process the new i'th element */
  232. }
  233. }
  234. /** Remove every element E of sl1 such that smartlist_isin(sl2,E).
  235. * Does not preserve the order of sl1.
  236. */
  237. void
  238. smartlist_subtract(smartlist_t *sl1, const smartlist_t *sl2)
  239. {
  240. int i;
  241. for (i=0; i < sl2->num_used; i++)
  242. smartlist_remove(sl1, sl2->list[i]);
  243. }
  244. /** Remove the <b>idx</b>th element of sl; if idx is not the last
  245. * element, swap the last element of sl into the <b>idx</b>th space.
  246. * Return the old value of the <b>idx</b>th element.
  247. */
  248. void
  249. smartlist_del(smartlist_t *sl, int idx)
  250. {
  251. tor_assert(sl);
  252. tor_assert(idx>=0);
  253. tor_assert(idx < sl->num_used);
  254. sl->list[idx] = sl->list[--sl->num_used];
  255. }
  256. /** Remove the <b>idx</b>th element of sl; if idx is not the last element,
  257. * moving all subsequent elements back one space. Return the old value
  258. * of the <b>idx</b>th element.
  259. */
  260. void
  261. smartlist_del_keeporder(smartlist_t *sl, int idx)
  262. {
  263. tor_assert(sl);
  264. tor_assert(idx>=0);
  265. tor_assert(idx < sl->num_used);
  266. --sl->num_used;
  267. if (idx < sl->num_used)
  268. memmove(sl->list+idx, sl->list+idx+1, sizeof(void*)*(sl->num_used-idx));
  269. }
  270. /** Insert the value <b>val</b> as the new <b>idx</b>th element of
  271. * <b>sl</b>, moving all items previously at <b>idx</b> or later
  272. * forward one space.
  273. */
  274. void
  275. smartlist_insert(smartlist_t *sl, int idx, void *val)
  276. {
  277. tor_assert(sl);
  278. tor_assert(idx>=0);
  279. tor_assert(idx <= sl->num_used);
  280. if (idx == sl->num_used) {
  281. smartlist_add(sl, val);
  282. } else {
  283. smartlist_ensure_capacity(sl, sl->num_used+1);
  284. /* Move other elements away */
  285. if (idx < sl->num_used)
  286. memmove(sl->list + idx + 1, sl->list + idx,
  287. sizeof(void*)*(sl->num_used-idx));
  288. sl->num_used++;
  289. sl->list[idx] = val;
  290. }
  291. }
  292. /**
  293. * Split a string <b>str</b> along all occurrences of <b>sep</b>,
  294. * adding the split strings, in order, to <b>sl</b>.
  295. *
  296. * If <b>flags</b>&amp;SPLIT_SKIP_SPACE is true, remove initial and
  297. * trailing space from each entry.
  298. * If <b>flags</b>&amp;SPLIT_IGNORE_BLANK is true, remove any entries
  299. * of length 0.
  300. * If <b>flags</b>&amp;SPLIT_STRIP_SPACE is true, strip spaces from each
  301. * split string.
  302. *
  303. * If max>0, divide the string into no more than <b>max</b> pieces. If
  304. * <b>sep</b> is NULL, split on any sequence of horizontal space.
  305. */
  306. int
  307. smartlist_split_string(smartlist_t *sl, const char *str, const char *sep,
  308. int flags, int max)
  309. {
  310. const char *cp, *end, *next;
  311. int n = 0;
  312. tor_assert(sl);
  313. tor_assert(str);
  314. cp = str;
  315. while (1) {
  316. if (flags&SPLIT_SKIP_SPACE) {
  317. while (TOR_ISSPACE(*cp)) ++cp;
  318. }
  319. if (max>0 && n == max-1) {
  320. end = strchr(cp,'\0');
  321. } else if (sep) {
  322. end = strstr(cp,sep);
  323. if (!end)
  324. end = strchr(cp,'\0');
  325. } else {
  326. for (end = cp; *end && *end != '\t' && *end != ' '; ++end)
  327. ;
  328. }
  329. tor_assert(end);
  330. if (!*end) {
  331. next = NULL;
  332. } else if (sep) {
  333. next = end+strlen(sep);
  334. } else {
  335. next = end+1;
  336. while (*next == '\t' || *next == ' ')
  337. ++next;
  338. }
  339. if (flags&SPLIT_SKIP_SPACE) {
  340. while (end > cp && TOR_ISSPACE(*(end-1)))
  341. --end;
  342. }
  343. if (end != cp || !(flags&SPLIT_IGNORE_BLANK)) {
  344. char *string = tor_strndup(cp, end-cp);
  345. if (flags&SPLIT_STRIP_SPACE)
  346. tor_strstrip(string, " ");
  347. smartlist_add(sl, string);
  348. ++n;
  349. }
  350. if (!next)
  351. break;
  352. cp = next;
  353. }
  354. return n;
  355. }
  356. /** Allocate and return a new string containing the concatenation of
  357. * the elements of <b>sl</b>, in order, separated by <b>join</b>. If
  358. * <b>terminate</b> is true, also terminate the string with <b>join</b>.
  359. * If <b>len_out</b> is not NULL, set <b>len_out</b> to the length of
  360. * the returned string. Requires that every element of <b>sl</b> is
  361. * NUL-terminated string.
  362. */
  363. char *
  364. smartlist_join_strings(smartlist_t *sl, const char *join,
  365. int terminate, size_t *len_out)
  366. {
  367. return smartlist_join_strings2(sl,join,strlen(join),terminate,len_out);
  368. }
  369. /** As smartlist_join_strings, but instead of separating/terminated with a
  370. * NUL-terminated string <b>join</b>, uses the <b>join_len</b>-byte sequence
  371. * at <b>join</b>. (Useful for generating a sequence of NUL-terminated
  372. * strings.)
  373. */
  374. char *
  375. smartlist_join_strings2(smartlist_t *sl, const char *join,
  376. size_t join_len, int terminate, size_t *len_out)
  377. {
  378. int i;
  379. size_t n = 0;
  380. char *r = NULL, *dst, *src;
  381. tor_assert(sl);
  382. tor_assert(join);
  383. if (terminate)
  384. n = join_len;
  385. for (i = 0; i < sl->num_used; ++i) {
  386. n += strlen(sl->list[i]);
  387. if (i+1 < sl->num_used) /* avoid double-counting the last one */
  388. n += join_len;
  389. }
  390. dst = r = tor_malloc(n+1);
  391. for (i = 0; i < sl->num_used; ) {
  392. for (src = sl->list[i]; *src; )
  393. *dst++ = *src++;
  394. if (++i < sl->num_used) {
  395. memcpy(dst, join, join_len);
  396. dst += join_len;
  397. }
  398. }
  399. if (terminate) {
  400. memcpy(dst, join, join_len);
  401. dst += join_len;
  402. }
  403. *dst = '\0';
  404. if (len_out)
  405. *len_out = dst-r;
  406. return r;
  407. }
  408. /** Sort the members of <b>sl</b> into an order defined by
  409. * the ordering function <b>compare</b>, which returns less then 0 if a
  410. * precedes b, greater than 0 if b precedes a, and 0 if a 'equals' b.
  411. */
  412. void
  413. smartlist_sort(smartlist_t *sl, int (*compare)(const void **a, const void **b))
  414. {
  415. if (!sl->num_used)
  416. return;
  417. qsort(sl->list, sl->num_used, sizeof(void*),
  418. (int (*)(const void *,const void*))compare);
  419. }
  420. /** Given a smartlist <b>sl</b> sorted with the function <b>compare</b>,
  421. * return the most frequent member in the list. Break ties in favor of
  422. * later elements. If the list is empty, return NULL.
  423. */
  424. void *
  425. smartlist_get_most_frequent(const smartlist_t *sl,
  426. int (*compare)(const void **a, const void **b))
  427. {
  428. const void *most_frequent = NULL;
  429. int most_frequent_count = 0;
  430. const void *cur = NULL;
  431. int i, count=0;
  432. if (!sl->num_used)
  433. return NULL;
  434. for (i = 0; i < sl->num_used; ++i) {
  435. const void *item = sl->list[i];
  436. if (cur && 0 == compare(&cur, &item)) {
  437. ++count;
  438. } else {
  439. if (cur && count >= most_frequent_count) {
  440. most_frequent = cur;
  441. most_frequent_count = count;
  442. }
  443. cur = item;
  444. count = 1;
  445. }
  446. }
  447. if (cur && count >= most_frequent_count) {
  448. most_frequent = cur;
  449. most_frequent_count = count;
  450. }
  451. return (void*)most_frequent;
  452. }
  453. /** Given a sorted smartlist <b>sl</b> and the comparison function used to
  454. * sort it, remove all duplicate members. If free_fn is provided, calls
  455. * free_fn on each duplicate. Otherwise, just removes them. Preserves order.
  456. */
  457. void
  458. smartlist_uniq(smartlist_t *sl,
  459. int (*compare)(const void **a, const void **b),
  460. void (*free_fn)(void *a))
  461. {
  462. int i;
  463. for (i=1; i < sl->num_used; ++i) {
  464. if (compare((const void **)&(sl->list[i-1]),
  465. (const void **)&(sl->list[i])) == 0) {
  466. if (free_fn)
  467. free_fn(sl->list[i]);
  468. smartlist_del_keeporder(sl, i--);
  469. }
  470. }
  471. }
  472. /** Assuming the members of <b>sl</b> are in order, return a pointer to the
  473. * member that matches <b>key</b>. Ordering and matching are defined by a
  474. * <b>compare</b> function that returns 0 on a match; less than 0 if key is
  475. * less than member, and greater than 0 if key is greater then member.
  476. */
  477. void *
  478. smartlist_bsearch(smartlist_t *sl, const void *key,
  479. int (*compare)(const void *key, const void **member))
  480. {
  481. int found, idx;
  482. idx = smartlist_bsearch_idx(sl, key, compare, &found);
  483. return found ? smartlist_get(sl, idx) : NULL;
  484. }
  485. /** Assuming the members of <b>sl</b> are in order, return the index of the
  486. * member that matches <b>key</b>. If no member matches, return the index of
  487. * the first member greater than <b>key</b>, or smartlist_len(sl) if no member
  488. * is greater than <b>key</b>. Set <b>found_out</b> to true on a match, to
  489. * false otherwise. Ordering and matching are defined by a <b>compare</b>
  490. * function that returns 0 on a match; less than 0 if key is less than member,
  491. * and greater than 0 if key is greater then member.
  492. */
  493. int
  494. smartlist_bsearch_idx(const smartlist_t *sl, const void *key,
  495. int (*compare)(const void *key, const void **member),
  496. int *found_out)
  497. {
  498. int hi = smartlist_len(sl) - 1, lo = 0, cmp, mid;
  499. while (lo <= hi) {
  500. mid = (lo + hi) / 2;
  501. cmp = compare(key, (const void**) &(sl->list[mid]));
  502. if (cmp>0) { /* key > sl[mid] */
  503. lo = mid+1;
  504. } else if (cmp<0) { /* key < sl[mid] */
  505. hi = mid-1;
  506. } else { /* key == sl[mid] */
  507. *found_out = 1;
  508. return mid;
  509. }
  510. }
  511. /* lo > hi. */
  512. {
  513. tor_assert(lo >= 0);
  514. if (lo < smartlist_len(sl)) {
  515. cmp = compare(key, (const void**) &(sl->list[lo]));
  516. tor_assert(cmp < 0);
  517. } else if (smartlist_len(sl)) {
  518. cmp = compare(key, (const void**) &(sl->list[smartlist_len(sl)-1]));
  519. tor_assert(cmp > 0);
  520. }
  521. }
  522. *found_out = 0;
  523. return lo;
  524. }
  525. /** Helper: compare two const char **s. */
  526. static int
  527. _compare_string_ptrs(const void **_a, const void **_b)
  528. {
  529. return strcmp((const char*)*_a, (const char*)*_b);
  530. }
  531. /** Sort a smartlist <b>sl</b> containing strings into lexically ascending
  532. * order. */
  533. void
  534. smartlist_sort_strings(smartlist_t *sl)
  535. {
  536. smartlist_sort(sl, _compare_string_ptrs);
  537. }
  538. /** Return the most frequent string in the sorted list <b>sl</b> */
  539. char *
  540. smartlist_get_most_frequent_string(smartlist_t *sl)
  541. {
  542. return smartlist_get_most_frequent(sl, _compare_string_ptrs);
  543. }
  544. /** Remove duplicate strings from a sorted list, and free them with tor_free().
  545. */
  546. void
  547. smartlist_uniq_strings(smartlist_t *sl)
  548. {
  549. smartlist_uniq(sl, _compare_string_ptrs, _tor_free);
  550. }
  551. /* Heap-based priority queue implementation for O(lg N) insert and remove.
  552. * Recall that the heap property is that, for every index I, h[I] <
  553. * H[LEFT_CHILD[I]] and h[I] < H[RIGHT_CHILD[I]].
  554. *
  555. * For us to remove items other than the topmost item, each item must store
  556. * its own index within the heap. When calling the pqueue functions, tell
  557. * them about the offset of the field that stores the index within the item.
  558. *
  559. * Example:
  560. *
  561. * typedef struct timer_t {
  562. * struct timeval tv;
  563. * int heap_index;
  564. * } timer_t;
  565. *
  566. * static int compare(const void *p1, const void *p2) {
  567. * const timer_t *t1 = p1, *t2 = p2;
  568. * if (t1->tv.tv_sec < t2->tv.tv_sec) {
  569. * return -1;
  570. * } else if (t1->tv.tv_sec > t2->tv.tv_sec) {
  571. * return 1;
  572. * } else {
  573. * return t1->tv.tv_usec - t2->tv_usec;
  574. * }
  575. * }
  576. *
  577. * void timer_heap_insert(smartlist_t *heap, timer_t *timer) {
  578. * smartlist_pqueue_add(heap, compare, STRUCT_OFFSET(timer_t, heap_index),
  579. * timer);
  580. * }
  581. *
  582. * void timer_heap_pop(smartlist_t *heap) {
  583. * return smartlist_pqueue_pop(heap, compare,
  584. * STRUCT_OFFSET(timer_t, heap_index));
  585. * }
  586. */
  587. /** @{ */
  588. /** Functions to manipulate heap indices to find a node's parent and children.
  589. *
  590. * For a 1-indexed array, we would use LEFT_CHILD[x] = 2*x and RIGHT_CHILD[x]
  591. * = 2*x + 1. But this is C, so we have to adjust a little. */
  592. //#define LEFT_CHILD(i) ( ((i)+1)*2 - 1)
  593. //#define RIGHT_CHILD(i) ( ((i)+1)*2 )
  594. //#define PARENT(i) ( ((i)+1)/2 - 1)
  595. #define LEFT_CHILD(i) ( 2*(i) + 1 )
  596. #define RIGHT_CHILD(i) ( 2*(i) + 2 )
  597. #define PARENT(i) ( ((i)-1) / 2 )
  598. /** }@ */
  599. /** @{ */
  600. /** Helper macros for heaps: Given a local variable <b>idx_field_offset</b>
  601. * set to the offset of an integer index within the heap element structure,
  602. * IDX_OF_ITEM(p) gives you the index of p, and IDXP(p) gives you a pointer to
  603. * where p's index is stored. Given additionally a local smartlist <b>sl</b>,
  604. * UPDATE_IDX(i) sets the index of the element at <b>i</b> to the correct
  605. * value (that is, to <b>i</b>).
  606. */
  607. #define IDXP(p) ((int*)STRUCT_VAR_P(p, idx_field_offset))
  608. #define UPDATE_IDX(i) do { \
  609. void *updated = sl->list[i]; \
  610. *IDXP(updated) = i; \
  611. } while (0)
  612. #define IDX_OF_ITEM(p) (*IDXP(p))
  613. /** @} */
  614. /** Helper. <b>sl</b> may have at most one violation of the heap property:
  615. * the item at <b>idx</b> may be greater than one or both of its children.
  616. * Restore the heap property. */
  617. static INLINE void
  618. smartlist_heapify(smartlist_t *sl,
  619. int (*compare)(const void *a, const void *b),
  620. int idx_field_offset,
  621. int idx)
  622. {
  623. while (1) {
  624. int left_idx = LEFT_CHILD(idx);
  625. int best_idx;
  626. if (left_idx >= sl->num_used)
  627. return;
  628. if (compare(sl->list[idx],sl->list[left_idx]) < 0)
  629. best_idx = idx;
  630. else
  631. best_idx = left_idx;
  632. if (left_idx+1 < sl->num_used &&
  633. compare(sl->list[left_idx+1],sl->list[best_idx]) < 0)
  634. best_idx = left_idx + 1;
  635. if (best_idx == idx) {
  636. return;
  637. } else {
  638. void *tmp = sl->list[idx];
  639. sl->list[idx] = sl->list[best_idx];
  640. sl->list[best_idx] = tmp;
  641. UPDATE_IDX(idx);
  642. UPDATE_IDX(best_idx);
  643. idx = best_idx;
  644. }
  645. }
  646. }
  647. /** Insert <b>item</b> into the heap stored in <b>sl</b>, where order is
  648. * determined by <b>compare</b> and the offset of the item in the heap is
  649. * stored in an int-typed field at position <b>idx_field_offset</b> within
  650. * item.
  651. */
  652. void
  653. smartlist_pqueue_add(smartlist_t *sl,
  654. int (*compare)(const void *a, const void *b),
  655. int idx_field_offset,
  656. void *item)
  657. {
  658. int idx;
  659. smartlist_add(sl,item);
  660. UPDATE_IDX(sl->num_used-1);
  661. for (idx = sl->num_used - 1; idx; ) {
  662. int parent = PARENT(idx);
  663. if (compare(sl->list[idx], sl->list[parent]) < 0) {
  664. void *tmp = sl->list[parent];
  665. sl->list[parent] = sl->list[idx];
  666. sl->list[idx] = tmp;
  667. UPDATE_IDX(parent);
  668. UPDATE_IDX(idx);
  669. idx = parent;
  670. } else {
  671. return;
  672. }
  673. }
  674. }
  675. /** Remove and return the top-priority item from the heap stored in <b>sl</b>,
  676. * where order is determined by <b>compare</b> and the item's position is
  677. * stored at position <b>idx_field_offset</b> within the item. <b>sl</b> must
  678. * not be empty. */
  679. void *
  680. smartlist_pqueue_pop(smartlist_t *sl,
  681. int (*compare)(const void *a, const void *b),
  682. int idx_field_offset)
  683. {
  684. void *top;
  685. tor_assert(sl->num_used);
  686. top = sl->list[0];
  687. *IDXP(top)=-1;
  688. if (--sl->num_used) {
  689. sl->list[0] = sl->list[sl->num_used];
  690. UPDATE_IDX(0);
  691. smartlist_heapify(sl, compare, idx_field_offset, 0);
  692. }
  693. return top;
  694. }
  695. /** Remove the item <b>item</b> from the heap stored in <b>sl</b>,
  696. * where order is determined by <b>compare</b> and the item's position is
  697. * stored at position <b>idx_field_offset</b> within the item. <b>sl</b> must
  698. * not be empty. */
  699. void
  700. smartlist_pqueue_remove(smartlist_t *sl,
  701. int (*compare)(const void *a, const void *b),
  702. int idx_field_offset,
  703. void *item)
  704. {
  705. int idx = IDX_OF_ITEM(item);
  706. tor_assert(idx >= 0);
  707. tor_assert(sl->list[idx] == item);
  708. --sl->num_used;
  709. *IDXP(item) = -1;
  710. if (idx == sl->num_used) {
  711. return;
  712. } else {
  713. sl->list[idx] = sl->list[sl->num_used];
  714. UPDATE_IDX(idx);
  715. smartlist_heapify(sl, compare, idx_field_offset, idx);
  716. }
  717. }
  718. /** Assert that the heap property is correctly maintained by the heap stored
  719. * in <b>sl</b>, where order is determined by <b>compare</b>. */
  720. void
  721. smartlist_pqueue_assert_ok(smartlist_t *sl,
  722. int (*compare)(const void *a, const void *b),
  723. int idx_field_offset)
  724. {
  725. int i;
  726. for (i = sl->num_used - 1; i >= 0; --i) {
  727. if (i>0)
  728. tor_assert(compare(sl->list[PARENT(i)], sl->list[i]) <= 0);
  729. tor_assert(IDX_OF_ITEM(sl->list[i]) == i);
  730. }
  731. }
  732. /** Helper: compare two DIGEST_LEN digests. */
  733. static int
  734. _compare_digests(const void **_a, const void **_b)
  735. {
  736. return memcmp((const char*)*_a, (const char*)*_b, DIGEST_LEN);
  737. }
  738. /** Sort the list of DIGEST_LEN-byte digests into ascending order. */
  739. void
  740. smartlist_sort_digests(smartlist_t *sl)
  741. {
  742. smartlist_sort(sl, _compare_digests);
  743. }
  744. /** Remove duplicate digests from a sorted list, and free them with tor_free().
  745. */
  746. void
  747. smartlist_uniq_digests(smartlist_t *sl)
  748. {
  749. smartlist_uniq(sl, _compare_digests, _tor_free);
  750. }
  751. /** Helper: compare two DIGEST256_LEN digests. */
  752. static int
  753. _compare_digests256(const void **_a, const void **_b)
  754. {
  755. return memcmp((const char*)*_a, (const char*)*_b, DIGEST256_LEN);
  756. }
  757. /** Sort the list of DIGEST256_LEN-byte digests into ascending order. */
  758. void
  759. smartlist_sort_digests256(smartlist_t *sl)
  760. {
  761. smartlist_sort(sl, _compare_digests256);
  762. }
  763. /** Return the most frequent member of the sorted list of DIGEST256_LEN
  764. * digests in <b>sl</b> */
  765. char *
  766. smartlist_get_most_frequent_digest256(smartlist_t *sl)
  767. {
  768. return smartlist_get_most_frequent(sl, _compare_digests256);
  769. }
  770. /** Remove duplicate 256-bit digests from a sorted list, and free them with
  771. * tor_free().
  772. */
  773. void
  774. smartlist_uniq_digests256(smartlist_t *sl)
  775. {
  776. smartlist_uniq(sl, _compare_digests256, _tor_free);
  777. }
  778. /** Helper: Declare an entry type and a map type to implement a mapping using
  779. * ht.h. The map type will be called <b>maptype</b>. The key part of each
  780. * entry is declared using the C declaration <b>keydecl</b>. All functions
  781. * and types associated with the map get prefixed with <b>prefix</b> */
  782. #define DEFINE_MAP_STRUCTS(maptype, keydecl, prefix) \
  783. typedef struct prefix ## entry_t { \
  784. HT_ENTRY(prefix ## entry_t) node; \
  785. void *val; \
  786. keydecl; \
  787. } prefix ## entry_t; \
  788. struct maptype { \
  789. HT_HEAD(prefix ## impl, prefix ## entry_t) head; \
  790. }
  791. DEFINE_MAP_STRUCTS(strmap_t, char *key, strmap_);
  792. DEFINE_MAP_STRUCTS(digestmap_t, char key[DIGEST_LEN], digestmap_);
  793. /** Helper: compare strmap_entry_t objects by key value. */
  794. static INLINE int
  795. strmap_entries_eq(const strmap_entry_t *a, const strmap_entry_t *b)
  796. {
  797. return !strcmp(a->key, b->key);
  798. }
  799. /** Helper: return a hash value for a strmap_entry_t. */
  800. static INLINE unsigned int
  801. strmap_entry_hash(const strmap_entry_t *a)
  802. {
  803. return ht_string_hash(a->key);
  804. }
  805. /** Helper: compare digestmap_entry_t objects by key value. */
  806. static INLINE int
  807. digestmap_entries_eq(const digestmap_entry_t *a, const digestmap_entry_t *b)
  808. {
  809. return !memcmp(a->key, b->key, DIGEST_LEN);
  810. }
  811. /** Helper: return a hash value for a digest_map_t. */
  812. static INLINE unsigned int
  813. digestmap_entry_hash(const digestmap_entry_t *a)
  814. {
  815. #if SIZEOF_INT != 8
  816. const uint32_t *p = (const uint32_t*)a->key;
  817. return p[0] ^ p[1] ^ p[2] ^ p[3] ^ p[4];
  818. #else
  819. const uint64_t *p = (const uint64_t*)a->key;
  820. return p[0] ^ p[1];
  821. #endif
  822. }
  823. HT_PROTOTYPE(strmap_impl, strmap_entry_t, node, strmap_entry_hash,
  824. strmap_entries_eq)
  825. HT_GENERATE(strmap_impl, strmap_entry_t, node, strmap_entry_hash,
  826. strmap_entries_eq, 0.6, malloc, realloc, free)
  827. HT_PROTOTYPE(digestmap_impl, digestmap_entry_t, node, digestmap_entry_hash,
  828. digestmap_entries_eq)
  829. HT_GENERATE(digestmap_impl, digestmap_entry_t, node, digestmap_entry_hash,
  830. digestmap_entries_eq, 0.6, malloc, realloc, free)
  831. /** Constructor to create a new empty map from strings to void*'s.
  832. */
  833. strmap_t *
  834. strmap_new(void)
  835. {
  836. strmap_t *result;
  837. result = tor_malloc(sizeof(strmap_t));
  838. HT_INIT(strmap_impl, &result->head);
  839. return result;
  840. }
  841. /** Constructor to create a new empty map from digests to void*'s.
  842. */
  843. digestmap_t *
  844. digestmap_new(void)
  845. {
  846. digestmap_t *result;
  847. result = tor_malloc(sizeof(digestmap_t));
  848. HT_INIT(digestmap_impl, &result->head);
  849. return result;
  850. }
  851. /** Set the current value for <b>key</b> to <b>val</b>. Returns the previous
  852. * value for <b>key</b> if one was set, or NULL if one was not.
  853. *
  854. * This function makes a copy of <b>key</b> if necessary, but not of
  855. * <b>val</b>.
  856. */
  857. void *
  858. strmap_set(strmap_t *map, const char *key, void *val)
  859. {
  860. strmap_entry_t *resolve;
  861. strmap_entry_t search;
  862. void *oldval;
  863. tor_assert(map);
  864. tor_assert(key);
  865. tor_assert(val);
  866. search.key = (char*)key;
  867. resolve = HT_FIND(strmap_impl, &map->head, &search);
  868. if (resolve) {
  869. oldval = resolve->val;
  870. resolve->val = val;
  871. return oldval;
  872. } else {
  873. resolve = tor_malloc_zero(sizeof(strmap_entry_t));
  874. resolve->key = tor_strdup(key);
  875. resolve->val = val;
  876. tor_assert(!HT_FIND(strmap_impl, &map->head, resolve));
  877. HT_INSERT(strmap_impl, &map->head, resolve);
  878. return NULL;
  879. }
  880. }
  881. #define OPTIMIZED_DIGESTMAP_SET
  882. /** Like strmap_set() above but for digestmaps. */
  883. void *
  884. digestmap_set(digestmap_t *map, const char *key, void *val)
  885. {
  886. #ifndef OPTIMIZED_DIGESTMAP_SET
  887. digestmap_entry_t *resolve;
  888. #endif
  889. digestmap_entry_t search;
  890. void *oldval;
  891. tor_assert(map);
  892. tor_assert(key);
  893. tor_assert(val);
  894. memcpy(&search.key, key, DIGEST_LEN);
  895. #ifndef OPTIMIZED_DIGESTMAP_SET
  896. resolve = HT_FIND(digestmap_impl, &map->head, &search);
  897. if (resolve) {
  898. oldval = resolve->val;
  899. resolve->val = val;
  900. return oldval;
  901. } else {
  902. resolve = tor_malloc_zero(sizeof(digestmap_entry_t));
  903. memcpy(resolve->key, key, DIGEST_LEN);
  904. resolve->val = val;
  905. HT_INSERT(digestmap_impl, &map->head, resolve);
  906. return NULL;
  907. }
  908. #else
  909. /* We spend up to 5% of our time in this function, so the code below is
  910. * meant to optimize the check/alloc/set cycle by avoiding the two trips to
  911. * the hash table that we do in the unoptimized code above. (Each of
  912. * HT_INSERT and HT_FIND calls HT_SET_HASH and HT_FIND_P.)
  913. */
  914. _HT_FIND_OR_INSERT(digestmap_impl, node, digestmap_entry_hash, &(map->head),
  915. digestmap_entry_t, &search, ptr,
  916. {
  917. /* we found an entry. */
  918. oldval = (*ptr)->val;
  919. (*ptr)->val = val;
  920. return oldval;
  921. },
  922. {
  923. /* We didn't find the entry. */
  924. digestmap_entry_t *newent =
  925. tor_malloc_zero(sizeof(digestmap_entry_t));
  926. memcpy(newent->key, key, DIGEST_LEN);
  927. newent->val = val;
  928. _HT_FOI_INSERT(node, &(map->head), &search, newent, ptr);
  929. return NULL;
  930. });
  931. #endif
  932. }
  933. /** Return the current value associated with <b>key</b>, or NULL if no
  934. * value is set.
  935. */
  936. void *
  937. strmap_get(const strmap_t *map, const char *key)
  938. {
  939. strmap_entry_t *resolve;
  940. strmap_entry_t search;
  941. tor_assert(map);
  942. tor_assert(key);
  943. search.key = (char*)key;
  944. resolve = HT_FIND(strmap_impl, &map->head, &search);
  945. if (resolve) {
  946. return resolve->val;
  947. } else {
  948. return NULL;
  949. }
  950. }
  951. /** Like strmap_get() above but for digestmaps. */
  952. void *
  953. digestmap_get(const digestmap_t *map, const char *key)
  954. {
  955. digestmap_entry_t *resolve;
  956. digestmap_entry_t search;
  957. tor_assert(map);
  958. tor_assert(key);
  959. memcpy(&search.key, key, DIGEST_LEN);
  960. resolve = HT_FIND(digestmap_impl, &map->head, &search);
  961. if (resolve) {
  962. return resolve->val;
  963. } else {
  964. return NULL;
  965. }
  966. }
  967. /** Remove the value currently associated with <b>key</b> from the map.
  968. * Return the value if one was set, or NULL if there was no entry for
  969. * <b>key</b>.
  970. *
  971. * Note: you must free any storage associated with the returned value.
  972. */
  973. void *
  974. strmap_remove(strmap_t *map, const char *key)
  975. {
  976. strmap_entry_t *resolve;
  977. strmap_entry_t search;
  978. void *oldval;
  979. tor_assert(map);
  980. tor_assert(key);
  981. search.key = (char*)key;
  982. resolve = HT_REMOVE(strmap_impl, &map->head, &search);
  983. if (resolve) {
  984. oldval = resolve->val;
  985. tor_free(resolve->key);
  986. tor_free(resolve);
  987. return oldval;
  988. } else {
  989. return NULL;
  990. }
  991. }
  992. /** Like strmap_remove() above but for digestmaps. */
  993. void *
  994. digestmap_remove(digestmap_t *map, const char *key)
  995. {
  996. digestmap_entry_t *resolve;
  997. digestmap_entry_t search;
  998. void *oldval;
  999. tor_assert(map);
  1000. tor_assert(key);
  1001. memcpy(&search.key, key, DIGEST_LEN);
  1002. resolve = HT_REMOVE(digestmap_impl, &map->head, &search);
  1003. if (resolve) {
  1004. oldval = resolve->val;
  1005. tor_free(resolve);
  1006. return oldval;
  1007. } else {
  1008. return NULL;
  1009. }
  1010. }
  1011. /** Same as strmap_set, but first converts <b>key</b> to lowercase. */
  1012. void *
  1013. strmap_set_lc(strmap_t *map, const char *key, void *val)
  1014. {
  1015. /* We could be a little faster by using strcasecmp instead, and a separate
  1016. * type, but I don't think it matters. */
  1017. void *v;
  1018. char *lc_key = tor_strdup(key);
  1019. tor_strlower(lc_key);
  1020. v = strmap_set(map,lc_key,val);
  1021. tor_free(lc_key);
  1022. return v;
  1023. }
  1024. /** Same as strmap_get, but first converts <b>key</b> to lowercase. */
  1025. void *
  1026. strmap_get_lc(const strmap_t *map, const char *key)
  1027. {
  1028. void *v;
  1029. char *lc_key = tor_strdup(key);
  1030. tor_strlower(lc_key);
  1031. v = strmap_get(map,lc_key);
  1032. tor_free(lc_key);
  1033. return v;
  1034. }
  1035. /** Same as strmap_remove, but first converts <b>key</b> to lowercase */
  1036. void *
  1037. strmap_remove_lc(strmap_t *map, const char *key)
  1038. {
  1039. void *v;
  1040. char *lc_key = tor_strdup(key);
  1041. tor_strlower(lc_key);
  1042. v = strmap_remove(map,lc_key);
  1043. tor_free(lc_key);
  1044. return v;
  1045. }
  1046. /** return an <b>iterator</b> pointer to the front of a map.
  1047. *
  1048. * Iterator example:
  1049. *
  1050. * \code
  1051. * // uppercase values in "map", removing empty values.
  1052. *
  1053. * strmap_iter_t *iter;
  1054. * const char *key;
  1055. * void *val;
  1056. * char *cp;
  1057. *
  1058. * for (iter = strmap_iter_init(map); !strmap_iter_done(iter); ) {
  1059. * strmap_iter_get(iter, &key, &val);
  1060. * cp = (char*)val;
  1061. * if (!*cp) {
  1062. * iter = strmap_iter_next_rmv(map,iter);
  1063. * free(val);
  1064. * } else {
  1065. * for (;*cp;cp++) *cp = TOR_TOUPPER(*cp);
  1066. * iter = strmap_iter_next(map,iter);
  1067. * }
  1068. * }
  1069. * \endcode
  1070. *
  1071. */
  1072. strmap_iter_t *
  1073. strmap_iter_init(strmap_t *map)
  1074. {
  1075. tor_assert(map);
  1076. return HT_START(strmap_impl, &map->head);
  1077. }
  1078. /** Start iterating through <b>map</b>. See strmap_iter_init() for example. */
  1079. digestmap_iter_t *
  1080. digestmap_iter_init(digestmap_t *map)
  1081. {
  1082. tor_assert(map);
  1083. return HT_START(digestmap_impl, &map->head);
  1084. }
  1085. /** Advance the iterator <b>iter</b> for <b>map</b> a single step to the next
  1086. * entry, and return its new value. */
  1087. strmap_iter_t *
  1088. strmap_iter_next(strmap_t *map, strmap_iter_t *iter)
  1089. {
  1090. tor_assert(map);
  1091. tor_assert(iter);
  1092. return HT_NEXT(strmap_impl, &map->head, iter);
  1093. }
  1094. /** Advance the iterator <b>iter</b> for map a single step to the next entry,
  1095. * and return its new value. */
  1096. digestmap_iter_t *
  1097. digestmap_iter_next(digestmap_t *map, digestmap_iter_t *iter)
  1098. {
  1099. tor_assert(map);
  1100. tor_assert(iter);
  1101. return HT_NEXT(digestmap_impl, &map->head, iter);
  1102. }
  1103. /** Advance the iterator <b>iter</b> a single step to the next entry, removing
  1104. * the current entry, and return its new value.
  1105. */
  1106. strmap_iter_t *
  1107. strmap_iter_next_rmv(strmap_t *map, strmap_iter_t *iter)
  1108. {
  1109. strmap_entry_t *rmv;
  1110. tor_assert(map);
  1111. tor_assert(iter);
  1112. tor_assert(*iter);
  1113. rmv = *iter;
  1114. iter = HT_NEXT_RMV(strmap_impl, &map->head, iter);
  1115. tor_free(rmv->key);
  1116. tor_free(rmv);
  1117. return iter;
  1118. }
  1119. /** Advance the iterator <b>iter</b> a single step to the next entry, removing
  1120. * the current entry, and return its new value.
  1121. */
  1122. digestmap_iter_t *
  1123. digestmap_iter_next_rmv(digestmap_t *map, digestmap_iter_t *iter)
  1124. {
  1125. digestmap_entry_t *rmv;
  1126. tor_assert(map);
  1127. tor_assert(iter);
  1128. tor_assert(*iter);
  1129. rmv = *iter;
  1130. iter = HT_NEXT_RMV(digestmap_impl, &map->head, iter);
  1131. tor_free(rmv);
  1132. return iter;
  1133. }
  1134. /** Set *<b>keyp</b> and *<b>valp</b> to the current entry pointed to by
  1135. * iter. */
  1136. void
  1137. strmap_iter_get(strmap_iter_t *iter, const char **keyp, void **valp)
  1138. {
  1139. tor_assert(iter);
  1140. tor_assert(*iter);
  1141. tor_assert(keyp);
  1142. tor_assert(valp);
  1143. *keyp = (*iter)->key;
  1144. *valp = (*iter)->val;
  1145. }
  1146. /** Set *<b>keyp</b> and *<b>valp</b> to the current entry pointed to by
  1147. * iter. */
  1148. void
  1149. digestmap_iter_get(digestmap_iter_t *iter, const char **keyp, void **valp)
  1150. {
  1151. tor_assert(iter);
  1152. tor_assert(*iter);
  1153. tor_assert(keyp);
  1154. tor_assert(valp);
  1155. *keyp = (*iter)->key;
  1156. *valp = (*iter)->val;
  1157. }
  1158. /** Return true iff <b>iter</b> has advanced past the last entry of
  1159. * <b>map</b>. */
  1160. int
  1161. strmap_iter_done(strmap_iter_t *iter)
  1162. {
  1163. return iter == NULL;
  1164. }
  1165. /** Return true iff <b>iter</b> has advanced past the last entry of
  1166. * <b>map</b>. */
  1167. int
  1168. digestmap_iter_done(digestmap_iter_t *iter)
  1169. {
  1170. return iter == NULL;
  1171. }
  1172. /** Remove all entries from <b>map</b>, and deallocate storage for those
  1173. * entries. If free_val is provided, it is invoked on every value in
  1174. * <b>map</b>.
  1175. */
  1176. void
  1177. strmap_free(strmap_t *map, void (*free_val)(void*))
  1178. {
  1179. strmap_entry_t **ent, **next, *this;
  1180. if (!map)
  1181. return;
  1182. for (ent = HT_START(strmap_impl, &map->head); ent != NULL; ent = next) {
  1183. this = *ent;
  1184. next = HT_NEXT_RMV(strmap_impl, &map->head, ent);
  1185. tor_free(this->key);
  1186. if (free_val)
  1187. free_val(this->val);
  1188. tor_free(this);
  1189. }
  1190. tor_assert(HT_EMPTY(&map->head));
  1191. HT_CLEAR(strmap_impl, &map->head);
  1192. tor_free(map);
  1193. }
  1194. /** Remove all entries from <b>map</b>, and deallocate storage for those
  1195. * entries. If free_val is provided, it is invoked on every value in
  1196. * <b>map</b>.
  1197. */
  1198. void
  1199. digestmap_free(digestmap_t *map, void (*free_val)(void*))
  1200. {
  1201. digestmap_entry_t **ent, **next, *this;
  1202. if (!map)
  1203. return;
  1204. for (ent = HT_START(digestmap_impl, &map->head); ent != NULL; ent = next) {
  1205. this = *ent;
  1206. next = HT_NEXT_RMV(digestmap_impl, &map->head, ent);
  1207. if (free_val)
  1208. free_val(this->val);
  1209. tor_free(this);
  1210. }
  1211. tor_assert(HT_EMPTY(&map->head));
  1212. HT_CLEAR(digestmap_impl, &map->head);
  1213. tor_free(map);
  1214. }
  1215. /** Fail with an assertion error if anything has gone wrong with the internal
  1216. * representation of <b>map</b>. */
  1217. void
  1218. strmap_assert_ok(const strmap_t *map)
  1219. {
  1220. tor_assert(!_strmap_impl_HT_REP_IS_BAD(&map->head));
  1221. }
  1222. /** Fail with an assertion error if anything has gone wrong with the internal
  1223. * representation of <b>map</b>. */
  1224. void
  1225. digestmap_assert_ok(const digestmap_t *map)
  1226. {
  1227. tor_assert(!_digestmap_impl_HT_REP_IS_BAD(&map->head));
  1228. }
  1229. /** Return true iff <b>map</b> has no entries. */
  1230. int
  1231. strmap_isempty(const strmap_t *map)
  1232. {
  1233. return HT_EMPTY(&map->head);
  1234. }
  1235. /** Return true iff <b>map</b> has no entries. */
  1236. int
  1237. digestmap_isempty(const digestmap_t *map)
  1238. {
  1239. return HT_EMPTY(&map->head);
  1240. }
  1241. /** Return the number of items in <b>map</b>. */
  1242. int
  1243. strmap_size(const strmap_t *map)
  1244. {
  1245. return HT_SIZE(&map->head);
  1246. }
  1247. /** Return the number of items in <b>map</b>. */
  1248. int
  1249. digestmap_size(const digestmap_t *map)
  1250. {
  1251. return HT_SIZE(&map->head);
  1252. }
  1253. /** Declare a function called <b>funcname</b> that acts as a find_nth_FOO
  1254. * function for an array of type <b>elt_t</b>*.
  1255. *
  1256. * NOTE: The implementation kind of sucks: It's O(n log n), whereas finding
  1257. * the kth element of an n-element list can be done in O(n). Then again, this
  1258. * implementation is not in critical path, and it is obviously correct. */
  1259. #define IMPLEMENT_ORDER_FUNC(funcname, elt_t) \
  1260. static int \
  1261. _cmp_ ## elt_t(const void *_a, const void *_b) \
  1262. { \
  1263. const elt_t *a = _a, *b = _b; \
  1264. if (*a<*b) \
  1265. return -1; \
  1266. else if (*a>*b) \
  1267. return 1; \
  1268. else \
  1269. return 0; \
  1270. } \
  1271. elt_t \
  1272. funcname(elt_t *array, int n_elements, int nth) \
  1273. { \
  1274. tor_assert(nth >= 0); \
  1275. tor_assert(nth < n_elements); \
  1276. qsort(array, n_elements, sizeof(elt_t), _cmp_ ##elt_t); \
  1277. return array[nth]; \
  1278. }
  1279. IMPLEMENT_ORDER_FUNC(find_nth_int, int)
  1280. IMPLEMENT_ORDER_FUNC(find_nth_time, time_t)
  1281. IMPLEMENT_ORDER_FUNC(find_nth_double, double)
  1282. IMPLEMENT_ORDER_FUNC(find_nth_uint32, uint32_t)
  1283. IMPLEMENT_ORDER_FUNC(find_nth_int32, int32_t)
  1284. IMPLEMENT_ORDER_FUNC(find_nth_long, long)
  1285. /** Return a newly allocated digestset_t, optimized to hold a total of
  1286. * <b>max_elements</b> digests with a reasonably low false positive weight. */
  1287. digestset_t *
  1288. digestset_new(int max_elements)
  1289. {
  1290. /* The probability of false positives is about P=(1 - exp(-kn/m))^k, where k
  1291. * is the number of hash functions per entry, m is the bits in the array,
  1292. * and n is the number of elements inserted. For us, k==4, n<=max_elements,
  1293. * and m==n_bits= approximately max_elements*32. This gives
  1294. * P<(1-exp(-4*n/(32*n)))^4 == (1-exp(1/-8))^4 == .00019
  1295. *
  1296. * It would be more optimal in space vs false positives to get this false
  1297. * positive rate by going for k==13, and m==18.5n, but we also want to
  1298. * conserve CPU, and k==13 is pretty big.
  1299. */
  1300. int n_bits = 1u << (tor_log2(max_elements)+5);
  1301. digestset_t *r = tor_malloc(sizeof(digestset_t));
  1302. r->mask = n_bits - 1;
  1303. r->ba = bitarray_init_zero(n_bits);
  1304. return r;
  1305. }
  1306. /** Free all storage held in <b>set</b>. */
  1307. void
  1308. digestset_free(digestset_t *set)
  1309. {
  1310. if (!set)
  1311. return;
  1312. bitarray_free(set->ba);
  1313. tor_free(set);
  1314. }