container.c 39 KB

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