container.c 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419
  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. /* For a 1-indexed array, we would use LEFT_CHILD[x] = 2*x and RIGHT_CHILD[x]
  588. * = 2*x + 1. But this is C, so we have to adjust a little. */
  589. //#define LEFT_CHILD(i) ( ((i)+1)*2 - 1)
  590. //#define RIGHT_CHILD(i) ( ((i)+1)*2 )
  591. //#define PARENT(i) ( ((i)+1)/2 - 1)
  592. #define LEFT_CHILD(i) ( 2*(i) + 1 )
  593. #define RIGHT_CHILD(i) ( 2*(i) + 2 )
  594. #define PARENT(i) ( ((i)-1) / 2 )
  595. #define IDXP(p) ((int*)STRUCT_VAR_P(p, idx_field_offset))
  596. #define UPDATE_IDX(i) do { \
  597. void *updated = sl->list[i]; \
  598. *IDXP(updated) = i; \
  599. } while (0)
  600. #define IDX_OF_ITEM(p) (*IDXP(p))
  601. /** Helper. <b>sl</b> may have at most one violation of the heap property:
  602. * the item at <b>idx</b> may be greater than one or both of its children.
  603. * Restore the heap property. */
  604. static INLINE void
  605. smartlist_heapify(smartlist_t *sl,
  606. int (*compare)(const void *a, const void *b),
  607. int idx_field_offset,
  608. int idx)
  609. {
  610. while (1) {
  611. int left_idx = LEFT_CHILD(idx);
  612. int best_idx;
  613. if (left_idx >= sl->num_used)
  614. return;
  615. if (compare(sl->list[idx],sl->list[left_idx]) < 0)
  616. best_idx = idx;
  617. else
  618. best_idx = left_idx;
  619. if (left_idx+1 < sl->num_used &&
  620. compare(sl->list[left_idx+1],sl->list[best_idx]) < 0)
  621. best_idx = left_idx + 1;
  622. if (best_idx == idx) {
  623. return;
  624. } else {
  625. void *tmp = sl->list[idx];
  626. sl->list[idx] = sl->list[best_idx];
  627. sl->list[best_idx] = tmp;
  628. UPDATE_IDX(idx);
  629. UPDATE_IDX(best_idx);
  630. idx = best_idx;
  631. }
  632. }
  633. }
  634. /** Insert <b>item</b> into the heap stored in <b>sl</b>, where order is
  635. * determined by <b>compare</b> and the offset of the item in the heap is
  636. * stored in an int-typed field at position <b>idx_field_offset</b> within
  637. * item.
  638. */
  639. void
  640. smartlist_pqueue_add(smartlist_t *sl,
  641. int (*compare)(const void *a, const void *b),
  642. int idx_field_offset,
  643. void *item)
  644. {
  645. int idx;
  646. smartlist_add(sl,item);
  647. UPDATE_IDX(sl->num_used-1);
  648. for (idx = sl->num_used - 1; idx; ) {
  649. int parent = PARENT(idx);
  650. if (compare(sl->list[idx], sl->list[parent]) < 0) {
  651. void *tmp = sl->list[parent];
  652. sl->list[parent] = sl->list[idx];
  653. sl->list[idx] = tmp;
  654. UPDATE_IDX(parent);
  655. UPDATE_IDX(idx);
  656. idx = parent;
  657. } else {
  658. return;
  659. }
  660. }
  661. }
  662. /** Remove and return the top-priority item from the heap stored in <b>sl</b>,
  663. * where order is determined by <b>compare</b> and the item's position is
  664. * stored at position <b>idx_field_offset</b> within the item. <b>sl</b> must
  665. * not be empty. */
  666. void *
  667. smartlist_pqueue_pop(smartlist_t *sl,
  668. int (*compare)(const void *a, const void *b),
  669. int idx_field_offset)
  670. {
  671. void *top;
  672. tor_assert(sl->num_used);
  673. top = sl->list[0];
  674. *IDXP(top)=-1;
  675. if (--sl->num_used) {
  676. sl->list[0] = sl->list[sl->num_used];
  677. UPDATE_IDX(0);
  678. smartlist_heapify(sl, compare, idx_field_offset, 0);
  679. }
  680. return top;
  681. }
  682. /** Remove the item <b>item</b> from the heap stored in <b>sl</b>,
  683. * where order is determined by <b>compare</b> and the item's position is
  684. * stored at position <b>idx_field_offset</b> within the item. <b>sl</b> must
  685. * not be empty. */
  686. void
  687. smartlist_pqueue_remove(smartlist_t *sl,
  688. int (*compare)(const void *a, const void *b),
  689. int idx_field_offset,
  690. void *item)
  691. {
  692. int idx = IDX_OF_ITEM(item);
  693. tor_assert(idx >= 0);
  694. tor_assert(sl->list[idx] == item);
  695. --sl->num_used;
  696. *IDXP(item) = -1;
  697. if (idx == sl->num_used) {
  698. return;
  699. } else {
  700. sl->list[idx] = sl->list[sl->num_used];
  701. UPDATE_IDX(idx);
  702. smartlist_heapify(sl, compare, idx_field_offset, idx);
  703. }
  704. }
  705. /** Assert that the heap property is correctly maintained by the heap stored
  706. * in <b>sl</b>, where order is determined by <b>compare</b>. */
  707. void
  708. smartlist_pqueue_assert_ok(smartlist_t *sl,
  709. int (*compare)(const void *a, const void *b),
  710. int idx_field_offset)
  711. {
  712. int i;
  713. for (i = sl->num_used - 1; i >= 0; --i) {
  714. if (i>0)
  715. tor_assert(compare(sl->list[PARENT(i)], sl->list[i]) <= 0);
  716. tor_assert(IDX_OF_ITEM(sl->list[i]) == i);
  717. }
  718. }
  719. /** Helper: compare two DIGEST_LEN digests. */
  720. static int
  721. _compare_digests(const void **_a, const void **_b)
  722. {
  723. return memcmp((const char*)*_a, (const char*)*_b, DIGEST_LEN);
  724. }
  725. /** Sort the list of DIGEST_LEN-byte digests into ascending order. */
  726. void
  727. smartlist_sort_digests(smartlist_t *sl)
  728. {
  729. smartlist_sort(sl, _compare_digests);
  730. }
  731. /** Remove duplicate digests from a sorted list, and free them with tor_free().
  732. */
  733. void
  734. smartlist_uniq_digests(smartlist_t *sl)
  735. {
  736. smartlist_uniq(sl, _compare_digests, _tor_free);
  737. }
  738. /** Helper: compare two DIGEST256_LEN digests. */
  739. static int
  740. _compare_digests256(const void **_a, const void **_b)
  741. {
  742. return memcmp((const char*)*_a, (const char*)*_b, DIGEST256_LEN);
  743. }
  744. /** Sort the list of DIGEST256_LEN-byte digests into ascending order. */
  745. void
  746. smartlist_sort_digests256(smartlist_t *sl)
  747. {
  748. smartlist_sort(sl, _compare_digests256);
  749. }
  750. /** Return the most frequent member of the sorted list of DIGEST256_LEN
  751. * digests in <b>sl</b> */
  752. char *
  753. smartlist_get_most_frequent_digest256(smartlist_t *sl)
  754. {
  755. return smartlist_get_most_frequent(sl, _compare_digests256);
  756. }
  757. /** Remove duplicate 256-bit digests from a sorted list, and free them with
  758. * tor_free().
  759. */
  760. void
  761. smartlist_uniq_digests256(smartlist_t *sl)
  762. {
  763. smartlist_uniq(sl, _compare_digests256, _tor_free);
  764. }
  765. /** Helper: Declare an entry type and a map type to implement a mapping using
  766. * ht.h. The map type will be called <b>maptype</b>. The key part of each
  767. * entry is declared using the C declaration <b>keydecl</b>. All functions
  768. * and types associated with the map get prefixed with <b>prefix</b> */
  769. #define DEFINE_MAP_STRUCTS(maptype, keydecl, prefix) \
  770. typedef struct prefix ## entry_t { \
  771. HT_ENTRY(prefix ## entry_t) node; \
  772. void *val; \
  773. keydecl; \
  774. } prefix ## entry_t; \
  775. struct maptype { \
  776. HT_HEAD(prefix ## impl, prefix ## entry_t) head; \
  777. }
  778. DEFINE_MAP_STRUCTS(strmap_t, char *key, strmap_);
  779. DEFINE_MAP_STRUCTS(digestmap_t, char key[DIGEST_LEN], digestmap_);
  780. /** Helper: compare strmap_entry_t objects by key value. */
  781. static INLINE int
  782. strmap_entries_eq(const strmap_entry_t *a, const strmap_entry_t *b)
  783. {
  784. return !strcmp(a->key, b->key);
  785. }
  786. /** Helper: return a hash value for a strmap_entry_t. */
  787. static INLINE unsigned int
  788. strmap_entry_hash(const strmap_entry_t *a)
  789. {
  790. return ht_string_hash(a->key);
  791. }
  792. /** Helper: compare digestmap_entry_t objects by key value. */
  793. static INLINE int
  794. digestmap_entries_eq(const digestmap_entry_t *a, const digestmap_entry_t *b)
  795. {
  796. return !memcmp(a->key, b->key, DIGEST_LEN);
  797. }
  798. /** Helper: return a hash value for a digest_map_t. */
  799. static INLINE unsigned int
  800. digestmap_entry_hash(const digestmap_entry_t *a)
  801. {
  802. #if SIZEOF_INT != 8
  803. const uint32_t *p = (const uint32_t*)a->key;
  804. return p[0] ^ p[1] ^ p[2] ^ p[3] ^ p[4];
  805. #else
  806. const uint64_t *p = (const uint64_t*)a->key;
  807. return p[0] ^ p[1];
  808. #endif
  809. }
  810. HT_PROTOTYPE(strmap_impl, strmap_entry_t, node, strmap_entry_hash,
  811. strmap_entries_eq)
  812. HT_GENERATE(strmap_impl, strmap_entry_t, node, strmap_entry_hash,
  813. strmap_entries_eq, 0.6, malloc, realloc, free)
  814. HT_PROTOTYPE(digestmap_impl, digestmap_entry_t, node, digestmap_entry_hash,
  815. digestmap_entries_eq)
  816. HT_GENERATE(digestmap_impl, digestmap_entry_t, node, digestmap_entry_hash,
  817. digestmap_entries_eq, 0.6, malloc, realloc, free)
  818. /** Constructor to create a new empty map from strings to void*'s.
  819. */
  820. strmap_t *
  821. strmap_new(void)
  822. {
  823. strmap_t *result;
  824. result = tor_malloc(sizeof(strmap_t));
  825. HT_INIT(strmap_impl, &result->head);
  826. return result;
  827. }
  828. /** Constructor to create a new empty map from digests to void*'s.
  829. */
  830. digestmap_t *
  831. digestmap_new(void)
  832. {
  833. digestmap_t *result;
  834. result = tor_malloc(sizeof(digestmap_t));
  835. HT_INIT(digestmap_impl, &result->head);
  836. return result;
  837. }
  838. /** Set the current value for <b>key</b> to <b>val</b>. Returns the previous
  839. * value for <b>key</b> if one was set, or NULL if one was not.
  840. *
  841. * This function makes a copy of <b>key</b> if necessary, but not of
  842. * <b>val</b>.
  843. */
  844. void *
  845. strmap_set(strmap_t *map, const char *key, void *val)
  846. {
  847. strmap_entry_t *resolve;
  848. strmap_entry_t search;
  849. void *oldval;
  850. tor_assert(map);
  851. tor_assert(key);
  852. tor_assert(val);
  853. search.key = (char*)key;
  854. resolve = HT_FIND(strmap_impl, &map->head, &search);
  855. if (resolve) {
  856. oldval = resolve->val;
  857. resolve->val = val;
  858. return oldval;
  859. } else {
  860. resolve = tor_malloc_zero(sizeof(strmap_entry_t));
  861. resolve->key = tor_strdup(key);
  862. resolve->val = val;
  863. tor_assert(!HT_FIND(strmap_impl, &map->head, resolve));
  864. HT_INSERT(strmap_impl, &map->head, resolve);
  865. return NULL;
  866. }
  867. }
  868. #define OPTIMIZED_DIGESTMAP_SET
  869. /** Like strmap_set() above but for digestmaps. */
  870. void *
  871. digestmap_set(digestmap_t *map, const char *key, void *val)
  872. {
  873. #ifndef OPTIMIZED_DIGESTMAP_SET
  874. digestmap_entry_t *resolve;
  875. #endif
  876. digestmap_entry_t search;
  877. void *oldval;
  878. tor_assert(map);
  879. tor_assert(key);
  880. tor_assert(val);
  881. memcpy(&search.key, key, DIGEST_LEN);
  882. #ifndef OPTIMIZED_DIGESTMAP_SET
  883. resolve = HT_FIND(digestmap_impl, &map->head, &search);
  884. if (resolve) {
  885. oldval = resolve->val;
  886. resolve->val = val;
  887. return oldval;
  888. } else {
  889. resolve = tor_malloc_zero(sizeof(digestmap_entry_t));
  890. memcpy(resolve->key, key, DIGEST_LEN);
  891. resolve->val = val;
  892. HT_INSERT(digestmap_impl, &map->head, resolve);
  893. return NULL;
  894. }
  895. #else
  896. /* We spend up to 5% of our time in this function, so the code below is
  897. * meant to optimize the check/alloc/set cycle by avoiding the two trips to
  898. * the hash table that we do in the unoptimized code above. (Each of
  899. * HT_INSERT and HT_FIND calls HT_SET_HASH and HT_FIND_P.)
  900. */
  901. _HT_FIND_OR_INSERT(digestmap_impl, node, digestmap_entry_hash, &(map->head),
  902. digestmap_entry_t, &search, ptr,
  903. {
  904. /* we found an entry. */
  905. oldval = (*ptr)->val;
  906. (*ptr)->val = val;
  907. return oldval;
  908. },
  909. {
  910. /* We didn't find the entry. */
  911. digestmap_entry_t *newent =
  912. tor_malloc_zero(sizeof(digestmap_entry_t));
  913. memcpy(newent->key, key, DIGEST_LEN);
  914. newent->val = val;
  915. _HT_FOI_INSERT(node, &(map->head), &search, newent, ptr);
  916. return NULL;
  917. });
  918. #endif
  919. }
  920. /** Return the current value associated with <b>key</b>, or NULL if no
  921. * value is set.
  922. */
  923. void *
  924. strmap_get(const strmap_t *map, const char *key)
  925. {
  926. strmap_entry_t *resolve;
  927. strmap_entry_t search;
  928. tor_assert(map);
  929. tor_assert(key);
  930. search.key = (char*)key;
  931. resolve = HT_FIND(strmap_impl, &map->head, &search);
  932. if (resolve) {
  933. return resolve->val;
  934. } else {
  935. return NULL;
  936. }
  937. }
  938. /** Like strmap_get() above but for digestmaps. */
  939. void *
  940. digestmap_get(const digestmap_t *map, const char *key)
  941. {
  942. digestmap_entry_t *resolve;
  943. digestmap_entry_t search;
  944. tor_assert(map);
  945. tor_assert(key);
  946. memcpy(&search.key, key, DIGEST_LEN);
  947. resolve = HT_FIND(digestmap_impl, &map->head, &search);
  948. if (resolve) {
  949. return resolve->val;
  950. } else {
  951. return NULL;
  952. }
  953. }
  954. /** Remove the value currently associated with <b>key</b> from the map.
  955. * Return the value if one was set, or NULL if there was no entry for
  956. * <b>key</b>.
  957. *
  958. * Note: you must free any storage associated with the returned value.
  959. */
  960. void *
  961. strmap_remove(strmap_t *map, const char *key)
  962. {
  963. strmap_entry_t *resolve;
  964. strmap_entry_t search;
  965. void *oldval;
  966. tor_assert(map);
  967. tor_assert(key);
  968. search.key = (char*)key;
  969. resolve = HT_REMOVE(strmap_impl, &map->head, &search);
  970. if (resolve) {
  971. oldval = resolve->val;
  972. tor_free(resolve->key);
  973. tor_free(resolve);
  974. return oldval;
  975. } else {
  976. return NULL;
  977. }
  978. }
  979. /** Like strmap_remove() above but for digestmaps. */
  980. void *
  981. digestmap_remove(digestmap_t *map, const char *key)
  982. {
  983. digestmap_entry_t *resolve;
  984. digestmap_entry_t search;
  985. void *oldval;
  986. tor_assert(map);
  987. tor_assert(key);
  988. memcpy(&search.key, key, DIGEST_LEN);
  989. resolve = HT_REMOVE(digestmap_impl, &map->head, &search);
  990. if (resolve) {
  991. oldval = resolve->val;
  992. tor_free(resolve);
  993. return oldval;
  994. } else {
  995. return NULL;
  996. }
  997. }
  998. /** Same as strmap_set, but first converts <b>key</b> to lowercase. */
  999. void *
  1000. strmap_set_lc(strmap_t *map, const char *key, void *val)
  1001. {
  1002. /* We could be a little faster by using strcasecmp instead, and a separate
  1003. * type, but I don't think it matters. */
  1004. void *v;
  1005. char *lc_key = tor_strdup(key);
  1006. tor_strlower(lc_key);
  1007. v = strmap_set(map,lc_key,val);
  1008. tor_free(lc_key);
  1009. return v;
  1010. }
  1011. /** Same as strmap_get, but first converts <b>key</b> to lowercase. */
  1012. void *
  1013. strmap_get_lc(const strmap_t *map, const char *key)
  1014. {
  1015. void *v;
  1016. char *lc_key = tor_strdup(key);
  1017. tor_strlower(lc_key);
  1018. v = strmap_get(map,lc_key);
  1019. tor_free(lc_key);
  1020. return v;
  1021. }
  1022. /** Same as strmap_remove, but first converts <b>key</b> to lowercase */
  1023. void *
  1024. strmap_remove_lc(strmap_t *map, const char *key)
  1025. {
  1026. void *v;
  1027. char *lc_key = tor_strdup(key);
  1028. tor_strlower(lc_key);
  1029. v = strmap_remove(map,lc_key);
  1030. tor_free(lc_key);
  1031. return v;
  1032. }
  1033. /** return an <b>iterator</b> pointer to the front of a map.
  1034. *
  1035. * Iterator example:
  1036. *
  1037. * \code
  1038. * // uppercase values in "map", removing empty values.
  1039. *
  1040. * strmap_iter_t *iter;
  1041. * const char *key;
  1042. * void *val;
  1043. * char *cp;
  1044. *
  1045. * for (iter = strmap_iter_init(map); !strmap_iter_done(iter); ) {
  1046. * strmap_iter_get(iter, &key, &val);
  1047. * cp = (char*)val;
  1048. * if (!*cp) {
  1049. * iter = strmap_iter_next_rmv(map,iter);
  1050. * free(val);
  1051. * } else {
  1052. * for (;*cp;cp++) *cp = TOR_TOUPPER(*cp);
  1053. * iter = strmap_iter_next(map,iter);
  1054. * }
  1055. * }
  1056. * \endcode
  1057. *
  1058. */
  1059. strmap_iter_t *
  1060. strmap_iter_init(strmap_t *map)
  1061. {
  1062. tor_assert(map);
  1063. return HT_START(strmap_impl, &map->head);
  1064. }
  1065. /** Start iterating through <b>map</b>. See strmap_iter_init() for example. */
  1066. digestmap_iter_t *
  1067. digestmap_iter_init(digestmap_t *map)
  1068. {
  1069. tor_assert(map);
  1070. return HT_START(digestmap_impl, &map->head);
  1071. }
  1072. /** Advance the iterator <b>iter</b> for <b>map</b> a single step to the next
  1073. * entry, and return its new value. */
  1074. strmap_iter_t *
  1075. strmap_iter_next(strmap_t *map, strmap_iter_t *iter)
  1076. {
  1077. tor_assert(map);
  1078. tor_assert(iter);
  1079. return HT_NEXT(strmap_impl, &map->head, iter);
  1080. }
  1081. /** Advance the iterator <b>iter</b> for map a single step to the next entry,
  1082. * and return its new value. */
  1083. digestmap_iter_t *
  1084. digestmap_iter_next(digestmap_t *map, digestmap_iter_t *iter)
  1085. {
  1086. tor_assert(map);
  1087. tor_assert(iter);
  1088. return HT_NEXT(digestmap_impl, &map->head, iter);
  1089. }
  1090. /** Advance the iterator <b>iter</b> a single step to the next entry, removing
  1091. * the current entry, and return its new value.
  1092. */
  1093. strmap_iter_t *
  1094. strmap_iter_next_rmv(strmap_t *map, strmap_iter_t *iter)
  1095. {
  1096. strmap_entry_t *rmv;
  1097. tor_assert(map);
  1098. tor_assert(iter);
  1099. tor_assert(*iter);
  1100. rmv = *iter;
  1101. iter = HT_NEXT_RMV(strmap_impl, &map->head, iter);
  1102. tor_free(rmv->key);
  1103. tor_free(rmv);
  1104. return iter;
  1105. }
  1106. /** Advance the iterator <b>iter</b> a single step to the next entry, removing
  1107. * the current entry, and return its new value.
  1108. */
  1109. digestmap_iter_t *
  1110. digestmap_iter_next_rmv(digestmap_t *map, digestmap_iter_t *iter)
  1111. {
  1112. digestmap_entry_t *rmv;
  1113. tor_assert(map);
  1114. tor_assert(iter);
  1115. tor_assert(*iter);
  1116. rmv = *iter;
  1117. iter = HT_NEXT_RMV(digestmap_impl, &map->head, iter);
  1118. tor_free(rmv);
  1119. return iter;
  1120. }
  1121. /** Set *<b>keyp</b> and *<b>valp</b> to the current entry pointed to by
  1122. * iter. */
  1123. void
  1124. strmap_iter_get(strmap_iter_t *iter, const char **keyp, void **valp)
  1125. {
  1126. tor_assert(iter);
  1127. tor_assert(*iter);
  1128. tor_assert(keyp);
  1129. tor_assert(valp);
  1130. *keyp = (*iter)->key;
  1131. *valp = (*iter)->val;
  1132. }
  1133. /** Set *<b>keyp</b> and *<b>valp</b> to the current entry pointed to by
  1134. * iter. */
  1135. void
  1136. digestmap_iter_get(digestmap_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. /** Return true iff <b>iter</b> has advanced past the last entry of
  1146. * <b>map</b>. */
  1147. int
  1148. strmap_iter_done(strmap_iter_t *iter)
  1149. {
  1150. return iter == NULL;
  1151. }
  1152. /** Return true iff <b>iter</b> has advanced past the last entry of
  1153. * <b>map</b>. */
  1154. int
  1155. digestmap_iter_done(digestmap_iter_t *iter)
  1156. {
  1157. return iter == NULL;
  1158. }
  1159. /** Remove all entries from <b>map</b>, and deallocate storage for those
  1160. * entries. If free_val is provided, it is invoked on every value in
  1161. * <b>map</b>.
  1162. */
  1163. void
  1164. strmap_free(strmap_t *map, void (*free_val)(void*))
  1165. {
  1166. strmap_entry_t **ent, **next, *this;
  1167. if (!map)
  1168. return;
  1169. for (ent = HT_START(strmap_impl, &map->head); ent != NULL; ent = next) {
  1170. this = *ent;
  1171. next = HT_NEXT_RMV(strmap_impl, &map->head, ent);
  1172. tor_free(this->key);
  1173. if (free_val)
  1174. free_val(this->val);
  1175. tor_free(this);
  1176. }
  1177. tor_assert(HT_EMPTY(&map->head));
  1178. HT_CLEAR(strmap_impl, &map->head);
  1179. tor_free(map);
  1180. }
  1181. /** Remove all entries from <b>map</b>, and deallocate storage for those
  1182. * entries. If free_val is provided, it is invoked on every value in
  1183. * <b>map</b>.
  1184. */
  1185. void
  1186. digestmap_free(digestmap_t *map, void (*free_val)(void*))
  1187. {
  1188. digestmap_entry_t **ent, **next, *this;
  1189. if (!map)
  1190. return;
  1191. for (ent = HT_START(digestmap_impl, &map->head); ent != NULL; ent = next) {
  1192. this = *ent;
  1193. next = HT_NEXT_RMV(digestmap_impl, &map->head, ent);
  1194. if (free_val)
  1195. free_val(this->val);
  1196. tor_free(this);
  1197. }
  1198. tor_assert(HT_EMPTY(&map->head));
  1199. HT_CLEAR(digestmap_impl, &map->head);
  1200. tor_free(map);
  1201. }
  1202. /** Fail with an assertion error if anything has gone wrong with the internal
  1203. * representation of <b>map</b>. */
  1204. void
  1205. strmap_assert_ok(const strmap_t *map)
  1206. {
  1207. tor_assert(!_strmap_impl_HT_REP_IS_BAD(&map->head));
  1208. }
  1209. /** Fail with an assertion error if anything has gone wrong with the internal
  1210. * representation of <b>map</b>. */
  1211. void
  1212. digestmap_assert_ok(const digestmap_t *map)
  1213. {
  1214. tor_assert(!_digestmap_impl_HT_REP_IS_BAD(&map->head));
  1215. }
  1216. /** Return true iff <b>map</b> has no entries. */
  1217. int
  1218. strmap_isempty(const strmap_t *map)
  1219. {
  1220. return HT_EMPTY(&map->head);
  1221. }
  1222. /** Return true iff <b>map</b> has no entries. */
  1223. int
  1224. digestmap_isempty(const digestmap_t *map)
  1225. {
  1226. return HT_EMPTY(&map->head);
  1227. }
  1228. /** Return the number of items in <b>map</b>. */
  1229. int
  1230. strmap_size(const strmap_t *map)
  1231. {
  1232. return HT_SIZE(&map->head);
  1233. }
  1234. /** Return the number of items in <b>map</b>. */
  1235. int
  1236. digestmap_size(const digestmap_t *map)
  1237. {
  1238. return HT_SIZE(&map->head);
  1239. }
  1240. /** Declare a function called <b>funcname</b> that acts as a find_nth_FOO
  1241. * function for an array of type <b>elt_t</b>*.
  1242. *
  1243. * NOTE: The implementation kind of sucks: It's O(n log n), whereas finding
  1244. * the kth element of an n-element list can be done in O(n). Then again, this
  1245. * implementation is not in critical path, and it is obviously correct. */
  1246. #define IMPLEMENT_ORDER_FUNC(funcname, elt_t) \
  1247. static int \
  1248. _cmp_ ## elt_t(const void *_a, const void *_b) \
  1249. { \
  1250. const elt_t *a = _a, *b = _b; \
  1251. if (*a<*b) \
  1252. return -1; \
  1253. else if (*a>*b) \
  1254. return 1; \
  1255. else \
  1256. return 0; \
  1257. } \
  1258. elt_t \
  1259. funcname(elt_t *array, int n_elements, int nth) \
  1260. { \
  1261. tor_assert(nth >= 0); \
  1262. tor_assert(nth < n_elements); \
  1263. qsort(array, n_elements, sizeof(elt_t), _cmp_ ##elt_t); \
  1264. return array[nth]; \
  1265. }
  1266. IMPLEMENT_ORDER_FUNC(find_nth_int, int)
  1267. IMPLEMENT_ORDER_FUNC(find_nth_time, time_t)
  1268. IMPLEMENT_ORDER_FUNC(find_nth_double, double)
  1269. IMPLEMENT_ORDER_FUNC(find_nth_uint32, uint32_t)
  1270. IMPLEMENT_ORDER_FUNC(find_nth_int32, int32_t)
  1271. IMPLEMENT_ORDER_FUNC(find_nth_long, long)
  1272. /** Return a newly allocated digestset_t, optimized to hold a total of
  1273. * <b>max_elements</b> digests with a reasonably low false positive weight. */
  1274. digestset_t *
  1275. digestset_new(int max_elements)
  1276. {
  1277. /* The probability of false positives is about P=(1 - exp(-kn/m))^k, where k
  1278. * is the number of hash functions per entry, m is the bits in the array,
  1279. * and n is the number of elements inserted. For us, k==4, n<=max_elements,
  1280. * and m==n_bits= approximately max_elements*32. This gives
  1281. * P<(1-exp(-4*n/(32*n)))^4 == (1-exp(1/-8))^4 == .00019
  1282. *
  1283. * It would be more optimal in space vs false positives to get this false
  1284. * positive rate by going for k==13, and m==18.5n, but we also want to
  1285. * conserve CPU, and k==13 is pretty big.
  1286. */
  1287. int n_bits = 1u << (tor_log2(max_elements)+5);
  1288. digestset_t *r = tor_malloc(sizeof(digestset_t));
  1289. r->mask = n_bits - 1;
  1290. r->ba = bitarray_init_zero(n_bits);
  1291. return r;
  1292. }
  1293. /** Free all storage held in <b>set</b>. */
  1294. void
  1295. digestset_free(digestset_t *set)
  1296. {
  1297. if (!set)
  1298. return;
  1299. bitarray_free(set->ba);
  1300. tor_free(set);
  1301. }