container.c 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2009, 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 "log.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. tor_assert(sl != NULL);
  41. tor_free(sl->list);
  42. tor_free(sl);
  43. }
  44. /** Remove all elements from the list.
  45. */
  46. void
  47. smartlist_clear(smartlist_t *sl)
  48. {
  49. sl->num_used = 0;
  50. }
  51. /** Make sure that <b>sl</b> can hold at least <b>size</b> entries. */
  52. static INLINE void
  53. smartlist_ensure_capacity(smartlist_t *sl, int size)
  54. {
  55. if (size > sl->capacity) {
  56. int higher = sl->capacity * 2;
  57. while (size > higher)
  58. higher *= 2;
  59. tor_assert(higher > 0); /* detect overflow */
  60. sl->capacity = higher;
  61. sl->list = tor_realloc(sl->list, sizeof(void*)*sl->capacity);
  62. }
  63. }
  64. /** Append element to the end of the list. */
  65. void
  66. smartlist_add(smartlist_t *sl, void *element)
  67. {
  68. smartlist_ensure_capacity(sl, sl->num_used+1);
  69. sl->list[sl->num_used++] = element;
  70. }
  71. /** Append each element from S2 to the end of S1. */
  72. void
  73. smartlist_add_all(smartlist_t *s1, const smartlist_t *s2)
  74. {
  75. int new_size = s1->num_used + s2->num_used;
  76. tor_assert(new_size >= s1->num_used); /* check for overflow. */
  77. smartlist_ensure_capacity(s1, new_size);
  78. memcpy(s1->list + s1->num_used, s2->list, s2->num_used*sizeof(void*));
  79. s1->num_used = new_size;
  80. }
  81. /** Remove all elements E from sl such that E==element. Preserve
  82. * the order of any elements before E, but elements after E can be
  83. * rearranged.
  84. */
  85. void
  86. smartlist_remove(smartlist_t *sl, const void *element)
  87. {
  88. int i;
  89. if (element == NULL)
  90. return;
  91. for (i=0; i < sl->num_used; i++)
  92. if (sl->list[i] == element) {
  93. sl->list[i] = sl->list[--sl->num_used]; /* swap with the end */
  94. i--; /* so we process the new i'th element */
  95. }
  96. }
  97. /** If <b>sl</b> is nonempty, remove and return the final element. Otherwise,
  98. * return NULL. */
  99. void *
  100. smartlist_pop_last(smartlist_t *sl)
  101. {
  102. tor_assert(sl);
  103. if (sl->num_used)
  104. return sl->list[--sl->num_used];
  105. else
  106. return NULL;
  107. }
  108. /** Reverse the order of the items in <b>sl</b>. */
  109. void
  110. smartlist_reverse(smartlist_t *sl)
  111. {
  112. int i, j;
  113. void *tmp;
  114. tor_assert(sl);
  115. for (i = 0, j = sl->num_used-1; i < j; ++i, --j) {
  116. tmp = sl->list[i];
  117. sl->list[i] = sl->list[j];
  118. sl->list[j] = tmp;
  119. }
  120. }
  121. /** If there are any strings in sl equal to element, remove and free them.
  122. * Does not preserve order. */
  123. void
  124. smartlist_string_remove(smartlist_t *sl, const char *element)
  125. {
  126. int i;
  127. tor_assert(sl);
  128. tor_assert(element);
  129. for (i = 0; i < sl->num_used; ++i) {
  130. if (!strcmp(element, sl->list[i])) {
  131. tor_free(sl->list[i]);
  132. sl->list[i] = sl->list[--sl->num_used]; /* swap with the end */
  133. i--; /* so we process the new i'th element */
  134. }
  135. }
  136. }
  137. /** Return true iff some element E of sl has E==element.
  138. */
  139. int
  140. smartlist_isin(const smartlist_t *sl, const void *element)
  141. {
  142. int i;
  143. for (i=0; i < sl->num_used; i++)
  144. if (sl->list[i] == element)
  145. return 1;
  146. return 0;
  147. }
  148. /** Return true iff <b>sl</b> has some element E such that
  149. * !strcmp(E,<b>element</b>)
  150. */
  151. int
  152. smartlist_string_isin(const smartlist_t *sl, const char *element)
  153. {
  154. int i;
  155. if (!sl) return 0;
  156. for (i=0; i < sl->num_used; i++)
  157. if (strcmp((const char*)sl->list[i],element)==0)
  158. return 1;
  159. return 0;
  160. }
  161. /** If <b>element</b> is equal to an element of <b>sl</b>, return that
  162. * element's index. Otherwise, return -1. */
  163. int
  164. smartlist_string_pos(const smartlist_t *sl, const char *element)
  165. {
  166. int i;
  167. if (!sl) return -1;
  168. for (i=0; i < sl->num_used; i++)
  169. if (strcmp((const char*)sl->list[i],element)==0)
  170. return i;
  171. return -1;
  172. }
  173. /** Return true iff <b>sl</b> has some element E such that
  174. * !strcasecmp(E,<b>element</b>)
  175. */
  176. int
  177. smartlist_string_isin_case(const smartlist_t *sl, const char *element)
  178. {
  179. int i;
  180. if (!sl) return 0;
  181. for (i=0; i < sl->num_used; i++)
  182. if (strcasecmp((const char*)sl->list[i],element)==0)
  183. return 1;
  184. return 0;
  185. }
  186. /** Return true iff <b>sl</b> has some element E such that E is equal
  187. * to the decimal encoding of <b>num</b>.
  188. */
  189. int
  190. smartlist_string_num_isin(const smartlist_t *sl, int num)
  191. {
  192. char buf[16];
  193. tor_snprintf(buf,sizeof(buf),"%d", num);
  194. return smartlist_string_isin(sl, buf);
  195. }
  196. /** Return true iff <b>sl</b> has some element E such that
  197. * !memcmp(E,<b>element</b>,DIGEST_LEN)
  198. */
  199. int
  200. smartlist_digest_isin(const smartlist_t *sl, const char *element)
  201. {
  202. int i;
  203. if (!sl) return 0;
  204. for (i=0; i < sl->num_used; i++)
  205. if (memcmp((const char*)sl->list[i],element,DIGEST_LEN)==0)
  206. return 1;
  207. return 0;
  208. }
  209. /** Return true iff some element E of sl2 has smartlist_isin(sl1,E).
  210. */
  211. int
  212. smartlist_overlap(const smartlist_t *sl1, const smartlist_t *sl2)
  213. {
  214. int i;
  215. for (i=0; i < sl2->num_used; i++)
  216. if (smartlist_isin(sl1, sl2->list[i]))
  217. return 1;
  218. return 0;
  219. }
  220. /** Remove every element E of sl1 such that !smartlist_isin(sl2,E).
  221. * Does not preserve the order of sl1.
  222. */
  223. void
  224. smartlist_intersect(smartlist_t *sl1, const smartlist_t *sl2)
  225. {
  226. int i;
  227. for (i=0; i < sl1->num_used; i++)
  228. if (!smartlist_isin(sl2, sl1->list[i])) {
  229. sl1->list[i] = sl1->list[--sl1->num_used]; /* swap with the end */
  230. i--; /* so we process the new i'th element */
  231. }
  232. }
  233. /** Remove every element E of sl1 such that smartlist_isin(sl2,E).
  234. * Does not preserve the order of sl1.
  235. */
  236. void
  237. smartlist_subtract(smartlist_t *sl1, const smartlist_t *sl2)
  238. {
  239. int i;
  240. for (i=0; i < sl2->num_used; i++)
  241. smartlist_remove(sl1, sl2->list[i]);
  242. }
  243. /** Remove the <b>idx</b>th element of sl; if idx is not the last
  244. * element, swap the last element of sl into the <b>idx</b>th space.
  245. * Return the old value of the <b>idx</b>th element.
  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 a 1-indexed array, we would use LEFT_CHILD[x] = 2*x and RIGHT_CHILD[x]
  555. * = 2*x + 1. But this is C, so we have to adjust a little. */
  556. //#define LEFT_CHILD(i) ( ((i)+1)*2 - 1)
  557. //#define RIGHT_CHILD(i) ( ((i)+1)*2 )
  558. //#define PARENT(i) ( ((i)+1)/2 - 1)
  559. #define LEFT_CHILD(i) ( 2*(i) + 1 )
  560. #define RIGHT_CHILD(i) ( 2*(i) + 2 )
  561. #define PARENT(i) ( ((i)-1) / 2 )
  562. /** Helper. <b>sl</b> may have at most one violation of the heap property:
  563. * the item at <b>idx</b> may be greater than one or both of its children.
  564. * Restore the heap property. */
  565. static INLINE void
  566. smartlist_heapify(smartlist_t *sl,
  567. int (*compare)(const void *a, const void *b),
  568. int idx)
  569. {
  570. while (1) {
  571. int left_idx = LEFT_CHILD(idx);
  572. int best_idx;
  573. if (left_idx >= sl->num_used)
  574. return;
  575. if (compare(sl->list[idx],sl->list[left_idx]) < 0)
  576. best_idx = idx;
  577. else
  578. best_idx = left_idx;
  579. if (left_idx+1 < sl->num_used &&
  580. compare(sl->list[left_idx+1],sl->list[best_idx]) < 0)
  581. best_idx = left_idx + 1;
  582. if (best_idx == idx) {
  583. return;
  584. } else {
  585. void *tmp = sl->list[idx];
  586. sl->list[idx] = sl->list[best_idx];
  587. sl->list[best_idx] = tmp;
  588. idx = best_idx;
  589. }
  590. }
  591. }
  592. /** Insert <b>item</b> into the heap stored in <b>sl</b>, where order
  593. * is determined by <b>compare</b>. */
  594. void
  595. smartlist_pqueue_add(smartlist_t *sl,
  596. int (*compare)(const void *a, const void *b),
  597. void *item)
  598. {
  599. int idx;
  600. smartlist_add(sl,item);
  601. for (idx = sl->num_used - 1; idx; ) {
  602. int parent = PARENT(idx);
  603. if (compare(sl->list[idx], sl->list[parent]) < 0) {
  604. void *tmp = sl->list[parent];
  605. sl->list[parent] = sl->list[idx];
  606. sl->list[idx] = tmp;
  607. idx = parent;
  608. } else {
  609. return;
  610. }
  611. }
  612. }
  613. /** Remove and return the top-priority item from the heap stored in <b>sl</b>,
  614. * where order is determined by <b>compare</b>. <b>sl</b> must not be
  615. * empty. */
  616. void *
  617. smartlist_pqueue_pop(smartlist_t *sl,
  618. int (*compare)(const void *a, const void *b))
  619. {
  620. void *top;
  621. tor_assert(sl->num_used);
  622. top = sl->list[0];
  623. if (--sl->num_used) {
  624. sl->list[0] = sl->list[sl->num_used];
  625. smartlist_heapify(sl, compare, 0);
  626. }
  627. return top;
  628. }
  629. /** Assert that the heap property is correctly maintained by the heap stored
  630. * in <b>sl</b>, where order is determined by <b>compare</b>. */
  631. void
  632. smartlist_pqueue_assert_ok(smartlist_t *sl,
  633. int (*compare)(const void *a, const void *b))
  634. {
  635. int i;
  636. for (i = sl->num_used - 1; i > 0; --i) {
  637. tor_assert(compare(sl->list[PARENT(i)], sl->list[i]) <= 0);
  638. }
  639. }
  640. /** Helper: compare two DIGEST_LEN digests. */
  641. static int
  642. _compare_digests(const void **_a, const void **_b)
  643. {
  644. return memcmp((const char*)*_a, (const char*)*_b, DIGEST_LEN);
  645. }
  646. /** Sort the list of DIGEST_LEN-byte digests into ascending order. */
  647. void
  648. smartlist_sort_digests(smartlist_t *sl)
  649. {
  650. smartlist_sort(sl, _compare_digests);
  651. }
  652. /** Remove duplicate digests from a sorted list, and free them with tor_free().
  653. */
  654. void
  655. smartlist_uniq_digests(smartlist_t *sl)
  656. {
  657. smartlist_uniq(sl, _compare_digests, _tor_free);
  658. }
  659. /** Helper: compare two DIGEST256_LEN digests. */
  660. static int
  661. _compare_digests256(const void **_a, const void **_b)
  662. {
  663. return memcmp((const char*)*_a, (const char*)*_b, DIGEST256_LEN);
  664. }
  665. /** Sort the list of DIGEST256_LEN-byte digests into ascending order. */
  666. void
  667. smartlist_sort_digests256(smartlist_t *sl)
  668. {
  669. smartlist_sort(sl, _compare_digests256);
  670. }
  671. /** Return the most frequent member of the sorted list of DIGEST256_LEN
  672. * digests in <b>sl</b> */
  673. char *
  674. smartlist_get_most_frequent_digest256(smartlist_t *sl)
  675. {
  676. return smartlist_get_most_frequent(sl, _compare_digests256);
  677. }
  678. /** Remove duplicate 256-bit digests from a sorted list, and free them with
  679. * tor_free().
  680. */
  681. void
  682. smartlist_uniq_digests256(smartlist_t *sl)
  683. {
  684. smartlist_uniq(sl, _compare_digests256, _tor_free);
  685. }
  686. /** Helper: Declare an entry type and a map type to implement a mapping using
  687. * ht.h. The map type will be called <b>maptype</b>. The key part of each
  688. * entry is declared using the C declaration <b>keydecl</b>. All functions
  689. * and types associated with the map get prefixed with <b>prefix</b> */
  690. #define DEFINE_MAP_STRUCTS(maptype, keydecl, prefix) \
  691. typedef struct prefix ## entry_t { \
  692. HT_ENTRY(prefix ## entry_t) node; \
  693. void *val; \
  694. keydecl; \
  695. } prefix ## entry_t; \
  696. struct maptype { \
  697. HT_HEAD(prefix ## impl, prefix ## entry_t) head; \
  698. }
  699. DEFINE_MAP_STRUCTS(strmap_t, char *key, strmap_);
  700. DEFINE_MAP_STRUCTS(digestmap_t, char key[DIGEST_LEN], digestmap_);
  701. /** Helper: compare strmap_entry_t objects by key value. */
  702. static INLINE int
  703. strmap_entries_eq(const strmap_entry_t *a, const strmap_entry_t *b)
  704. {
  705. return !strcmp(a->key, b->key);
  706. }
  707. /** Helper: return a hash value for a strmap_entry_t. */
  708. static INLINE unsigned int
  709. strmap_entry_hash(const strmap_entry_t *a)
  710. {
  711. return ht_string_hash(a->key);
  712. }
  713. /** Helper: compare digestmap_entry_t objects by key value. */
  714. static INLINE int
  715. digestmap_entries_eq(const digestmap_entry_t *a, const digestmap_entry_t *b)
  716. {
  717. return !memcmp(a->key, b->key, DIGEST_LEN);
  718. }
  719. /** Helper: return a hash value for a digest_map_t. */
  720. static INLINE unsigned int
  721. digestmap_entry_hash(const digestmap_entry_t *a)
  722. {
  723. #if SIZEOF_INT != 8
  724. const uint32_t *p = (const uint32_t*)a->key;
  725. return p[0] ^ p[1] ^ p[2] ^ p[3] ^ p[4];
  726. #else
  727. const uint64_t *p = (const uint64_t*)a->key;
  728. return p[0] ^ p[1];
  729. #endif
  730. }
  731. HT_PROTOTYPE(strmap_impl, strmap_entry_t, node, strmap_entry_hash,
  732. strmap_entries_eq)
  733. HT_GENERATE(strmap_impl, strmap_entry_t, node, strmap_entry_hash,
  734. strmap_entries_eq, 0.6, malloc, realloc, free)
  735. HT_PROTOTYPE(digestmap_impl, digestmap_entry_t, node, digestmap_entry_hash,
  736. digestmap_entries_eq)
  737. HT_GENERATE(digestmap_impl, digestmap_entry_t, node, digestmap_entry_hash,
  738. digestmap_entries_eq, 0.6, malloc, realloc, free)
  739. /** Constructor to create a new empty map from strings to void*'s.
  740. */
  741. strmap_t *
  742. strmap_new(void)
  743. {
  744. strmap_t *result;
  745. result = tor_malloc(sizeof(strmap_t));
  746. HT_INIT(strmap_impl, &result->head);
  747. return result;
  748. }
  749. /** Constructor to create a new empty map from digests to void*'s.
  750. */
  751. digestmap_t *
  752. digestmap_new(void)
  753. {
  754. digestmap_t *result;
  755. result = tor_malloc(sizeof(digestmap_t));
  756. HT_INIT(digestmap_impl, &result->head);
  757. return result;
  758. }
  759. /** Set the current value for <b>key</b> to <b>val</b>. Returns the previous
  760. * value for <b>key</b> if one was set, or NULL if one was not.
  761. *
  762. * This function makes a copy of <b>key</b> if necessary, but not of
  763. * <b>val</b>.
  764. */
  765. void *
  766. strmap_set(strmap_t *map, const char *key, void *val)
  767. {
  768. strmap_entry_t *resolve;
  769. strmap_entry_t search;
  770. void *oldval;
  771. tor_assert(map);
  772. tor_assert(key);
  773. tor_assert(val);
  774. search.key = (char*)key;
  775. resolve = HT_FIND(strmap_impl, &map->head, &search);
  776. if (resolve) {
  777. oldval = resolve->val;
  778. resolve->val = val;
  779. return oldval;
  780. } else {
  781. resolve = tor_malloc_zero(sizeof(strmap_entry_t));
  782. resolve->key = tor_strdup(key);
  783. resolve->val = val;
  784. tor_assert(!HT_FIND(strmap_impl, &map->head, resolve));
  785. HT_INSERT(strmap_impl, &map->head, resolve);
  786. return NULL;
  787. }
  788. }
  789. #define OPTIMIZED_DIGESTMAP_SET
  790. /** Like strmap_set() above but for digestmaps. */
  791. void *
  792. digestmap_set(digestmap_t *map, const char *key, void *val)
  793. {
  794. #ifndef OPTIMIZED_DIGESTMAP_SET
  795. digestmap_entry_t *resolve;
  796. #endif
  797. digestmap_entry_t search;
  798. void *oldval;
  799. tor_assert(map);
  800. tor_assert(key);
  801. tor_assert(val);
  802. memcpy(&search.key, key, DIGEST_LEN);
  803. #ifndef OPTIMIZED_DIGESTMAP_SET
  804. resolve = HT_FIND(digestmap_impl, &map->head, &search);
  805. if (resolve) {
  806. oldval = resolve->val;
  807. resolve->val = val;
  808. return oldval;
  809. } else {
  810. resolve = tor_malloc_zero(sizeof(digestmap_entry_t));
  811. memcpy(resolve->key, key, DIGEST_LEN);
  812. resolve->val = val;
  813. HT_INSERT(digestmap_impl, &map->head, resolve);
  814. return NULL;
  815. }
  816. #else
  817. /* We spend up to 5% of our time in this function, so the code below is
  818. * meant to optimize the check/alloc/set cycle by avoiding the two trips to
  819. * the hash table that we do in the unoptimized code above. (Each of
  820. * HT_INSERT and HT_FIND calls HT_SET_HASH and HT_FIND_P.)
  821. */
  822. _HT_FIND_OR_INSERT(digestmap_impl, node, digestmap_entry_hash, &(map->head),
  823. digestmap_entry_t, &search, ptr,
  824. {
  825. /* we found an entry. */
  826. oldval = (*ptr)->val;
  827. (*ptr)->val = val;
  828. return oldval;
  829. },
  830. {
  831. /* We didn't find the entry. */
  832. digestmap_entry_t *newent =
  833. tor_malloc_zero(sizeof(digestmap_entry_t));
  834. memcpy(newent->key, key, DIGEST_LEN);
  835. newent->val = val;
  836. _HT_FOI_INSERT(node, &(map->head), &search, newent, ptr);
  837. return NULL;
  838. });
  839. #endif
  840. }
  841. /** Return the current value associated with <b>key</b>, or NULL if no
  842. * value is set.
  843. */
  844. void *
  845. strmap_get(const strmap_t *map, const char *key)
  846. {
  847. strmap_entry_t *resolve;
  848. strmap_entry_t search;
  849. tor_assert(map);
  850. tor_assert(key);
  851. search.key = (char*)key;
  852. resolve = HT_FIND(strmap_impl, &map->head, &search);
  853. if (resolve) {
  854. return resolve->val;
  855. } else {
  856. return NULL;
  857. }
  858. }
  859. /** Like strmap_get() above but for digestmaps. */
  860. void *
  861. digestmap_get(const digestmap_t *map, const char *key)
  862. {
  863. digestmap_entry_t *resolve;
  864. digestmap_entry_t search;
  865. tor_assert(map);
  866. tor_assert(key);
  867. memcpy(&search.key, key, DIGEST_LEN);
  868. resolve = HT_FIND(digestmap_impl, &map->head, &search);
  869. if (resolve) {
  870. return resolve->val;
  871. } else {
  872. return NULL;
  873. }
  874. }
  875. /** Remove the value currently associated with <b>key</b> from the map.
  876. * Return the value if one was set, or NULL if there was no entry for
  877. * <b>key</b>.
  878. *
  879. * Note: you must free any storage associated with the returned value.
  880. */
  881. void *
  882. strmap_remove(strmap_t *map, const char *key)
  883. {
  884. strmap_entry_t *resolve;
  885. strmap_entry_t search;
  886. void *oldval;
  887. tor_assert(map);
  888. tor_assert(key);
  889. search.key = (char*)key;
  890. resolve = HT_REMOVE(strmap_impl, &map->head, &search);
  891. if (resolve) {
  892. oldval = resolve->val;
  893. tor_free(resolve->key);
  894. tor_free(resolve);
  895. return oldval;
  896. } else {
  897. return NULL;
  898. }
  899. }
  900. /** Like strmap_remove() above but for digestmaps. */
  901. void *
  902. digestmap_remove(digestmap_t *map, const char *key)
  903. {
  904. digestmap_entry_t *resolve;
  905. digestmap_entry_t search;
  906. void *oldval;
  907. tor_assert(map);
  908. tor_assert(key);
  909. memcpy(&search.key, key, DIGEST_LEN);
  910. resolve = HT_REMOVE(digestmap_impl, &map->head, &search);
  911. if (resolve) {
  912. oldval = resolve->val;
  913. tor_free(resolve);
  914. return oldval;
  915. } else {
  916. return NULL;
  917. }
  918. }
  919. /** Same as strmap_set, but first converts <b>key</b> to lowercase. */
  920. void *
  921. strmap_set_lc(strmap_t *map, const char *key, void *val)
  922. {
  923. /* We could be a little faster by using strcasecmp instead, and a separate
  924. * type, but I don't think it matters. */
  925. void *v;
  926. char *lc_key = tor_strdup(key);
  927. tor_strlower(lc_key);
  928. v = strmap_set(map,lc_key,val);
  929. tor_free(lc_key);
  930. return v;
  931. }
  932. /** Same as strmap_get, but first converts <b>key</b> to lowercase. */
  933. void *
  934. strmap_get_lc(const strmap_t *map, const char *key)
  935. {
  936. void *v;
  937. char *lc_key = tor_strdup(key);
  938. tor_strlower(lc_key);
  939. v = strmap_get(map,lc_key);
  940. tor_free(lc_key);
  941. return v;
  942. }
  943. /** Same as strmap_remove, but first converts <b>key</b> to lowercase */
  944. void *
  945. strmap_remove_lc(strmap_t *map, const char *key)
  946. {
  947. void *v;
  948. char *lc_key = tor_strdup(key);
  949. tor_strlower(lc_key);
  950. v = strmap_remove(map,lc_key);
  951. tor_free(lc_key);
  952. return v;
  953. }
  954. /** return an <b>iterator</b> pointer to the front of a map.
  955. *
  956. * Iterator example:
  957. *
  958. * \code
  959. * // uppercase values in "map", removing empty values.
  960. *
  961. * strmap_iter_t *iter;
  962. * const char *key;
  963. * void *val;
  964. * char *cp;
  965. *
  966. * for (iter = strmap_iter_init(map); !strmap_iter_done(iter); ) {
  967. * strmap_iter_get(iter, &key, &val);
  968. * cp = (char*)val;
  969. * if (!*cp) {
  970. * iter = strmap_iter_next_rmv(map,iter);
  971. * free(val);
  972. * } else {
  973. * for (;*cp;cp++) *cp = TOR_TOUPPER(*cp);
  974. * iter = strmap_iter_next(map,iter);
  975. * }
  976. * }
  977. * \endcode
  978. *
  979. */
  980. strmap_iter_t *
  981. strmap_iter_init(strmap_t *map)
  982. {
  983. tor_assert(map);
  984. return HT_START(strmap_impl, &map->head);
  985. }
  986. /** Start iterating through <b>map</b>. See strmap_iter_init() for example. */
  987. digestmap_iter_t *
  988. digestmap_iter_init(digestmap_t *map)
  989. {
  990. tor_assert(map);
  991. return HT_START(digestmap_impl, &map->head);
  992. }
  993. /** Advance the iterator <b>iter</b> for <b>map</b> a single step to the next
  994. * entry, and return its new value. */
  995. strmap_iter_t *
  996. strmap_iter_next(strmap_t *map, strmap_iter_t *iter)
  997. {
  998. tor_assert(map);
  999. tor_assert(iter);
  1000. return HT_NEXT(strmap_impl, &map->head, iter);
  1001. }
  1002. /** Advance the iterator <b>iter</b> for map a single step to the next entry,
  1003. * and return its new value. */
  1004. digestmap_iter_t *
  1005. digestmap_iter_next(digestmap_t *map, digestmap_iter_t *iter)
  1006. {
  1007. tor_assert(map);
  1008. tor_assert(iter);
  1009. return HT_NEXT(digestmap_impl, &map->head, iter);
  1010. }
  1011. /** Advance the iterator <b>iter</b> a single step to the next entry, removing
  1012. * the current entry, and return its new value.
  1013. */
  1014. strmap_iter_t *
  1015. strmap_iter_next_rmv(strmap_t *map, strmap_iter_t *iter)
  1016. {
  1017. strmap_entry_t *rmv;
  1018. tor_assert(map);
  1019. tor_assert(iter);
  1020. tor_assert(*iter);
  1021. rmv = *iter;
  1022. iter = HT_NEXT_RMV(strmap_impl, &map->head, iter);
  1023. tor_free(rmv->key);
  1024. tor_free(rmv);
  1025. return iter;
  1026. }
  1027. /** Advance the iterator <b>iter</b> a single step to the next entry, removing
  1028. * the current entry, and return its new value.
  1029. */
  1030. digestmap_iter_t *
  1031. digestmap_iter_next_rmv(digestmap_t *map, digestmap_iter_t *iter)
  1032. {
  1033. digestmap_entry_t *rmv;
  1034. tor_assert(map);
  1035. tor_assert(iter);
  1036. tor_assert(*iter);
  1037. rmv = *iter;
  1038. iter = HT_NEXT_RMV(digestmap_impl, &map->head, iter);
  1039. tor_free(rmv);
  1040. return iter;
  1041. }
  1042. /** Set *<b>keyp</b> and *<b>valp</b> to the current entry pointed to by
  1043. * iter. */
  1044. void
  1045. strmap_iter_get(strmap_iter_t *iter, const char **keyp, void **valp)
  1046. {
  1047. tor_assert(iter);
  1048. tor_assert(*iter);
  1049. tor_assert(keyp);
  1050. tor_assert(valp);
  1051. *keyp = (*iter)->key;
  1052. *valp = (*iter)->val;
  1053. }
  1054. /** Set *<b>keyp</b> and *<b>valp</b> to the current entry pointed to by
  1055. * iter. */
  1056. void
  1057. digestmap_iter_get(digestmap_iter_t *iter, const char **keyp, void **valp)
  1058. {
  1059. tor_assert(iter);
  1060. tor_assert(*iter);
  1061. tor_assert(keyp);
  1062. tor_assert(valp);
  1063. *keyp = (*iter)->key;
  1064. *valp = (*iter)->val;
  1065. }
  1066. /** Return true iff <b>iter</b> has advanced past the last entry of
  1067. * <b>map</b>. */
  1068. int
  1069. strmap_iter_done(strmap_iter_t *iter)
  1070. {
  1071. return iter == NULL;
  1072. }
  1073. /** Return true iff <b>iter</b> has advanced past the last entry of
  1074. * <b>map</b>. */
  1075. int
  1076. digestmap_iter_done(digestmap_iter_t *iter)
  1077. {
  1078. return iter == NULL;
  1079. }
  1080. /** Remove all entries from <b>map</b>, and deallocate storage for those
  1081. * entries. If free_val is provided, it is invoked on every value in
  1082. * <b>map</b>.
  1083. */
  1084. void
  1085. strmap_free(strmap_t *map, void (*free_val)(void*))
  1086. {
  1087. strmap_entry_t **ent, **next, *this;
  1088. for (ent = HT_START(strmap_impl, &map->head); ent != NULL; ent = next) {
  1089. this = *ent;
  1090. next = HT_NEXT_RMV(strmap_impl, &map->head, ent);
  1091. tor_free(this->key);
  1092. if (free_val)
  1093. free_val(this->val);
  1094. tor_free(this);
  1095. }
  1096. tor_assert(HT_EMPTY(&map->head));
  1097. HT_CLEAR(strmap_impl, &map->head);
  1098. tor_free(map);
  1099. }
  1100. /** Remove all entries from <b>map</b>, and deallocate storage for those
  1101. * entries. If free_val is provided, it is invoked on every value in
  1102. * <b>map</b>.
  1103. */
  1104. void
  1105. digestmap_free(digestmap_t *map, void (*free_val)(void*))
  1106. {
  1107. digestmap_entry_t **ent, **next, *this;
  1108. for (ent = HT_START(digestmap_impl, &map->head); ent != NULL; ent = next) {
  1109. this = *ent;
  1110. next = HT_NEXT_RMV(digestmap_impl, &map->head, ent);
  1111. if (free_val)
  1112. free_val(this->val);
  1113. tor_free(this);
  1114. }
  1115. tor_assert(HT_EMPTY(&map->head));
  1116. HT_CLEAR(digestmap_impl, &map->head);
  1117. tor_free(map);
  1118. }
  1119. /** Fail with an assertion error if anything has gone wrong with the internal
  1120. * representation of <b>map</b>. */
  1121. void
  1122. strmap_assert_ok(const strmap_t *map)
  1123. {
  1124. tor_assert(!_strmap_impl_HT_REP_IS_BAD(&map->head));
  1125. }
  1126. /** Fail with an assertion error if anything has gone wrong with the internal
  1127. * representation of <b>map</b>. */
  1128. void
  1129. digestmap_assert_ok(const digestmap_t *map)
  1130. {
  1131. tor_assert(!_digestmap_impl_HT_REP_IS_BAD(&map->head));
  1132. }
  1133. /** Return true iff <b>map</b> has no entries. */
  1134. int
  1135. strmap_isempty(const strmap_t *map)
  1136. {
  1137. return HT_EMPTY(&map->head);
  1138. }
  1139. /** Return true iff <b>map</b> has no entries. */
  1140. int
  1141. digestmap_isempty(const digestmap_t *map)
  1142. {
  1143. return HT_EMPTY(&map->head);
  1144. }
  1145. /** Return the number of items in <b>map</b>. */
  1146. int
  1147. strmap_size(const strmap_t *map)
  1148. {
  1149. return HT_SIZE(&map->head);
  1150. }
  1151. /** Return the number of items in <b>map</b>. */
  1152. int
  1153. digestmap_size(const digestmap_t *map)
  1154. {
  1155. return HT_SIZE(&map->head);
  1156. }
  1157. /** Declare a function called <b>funcname</b> that acts as a find_nth_FOO
  1158. * function for an array of type <b>elt_t</b>*.
  1159. *
  1160. * NOTE: The implementation kind of sucks: It's O(n log n), whereas finding
  1161. * the kth element of an n-element list can be done in O(n). Then again, this
  1162. * implementation is not in critical path, and it is obviously correct. */
  1163. #define IMPLEMENT_ORDER_FUNC(funcname, elt_t) \
  1164. static int \
  1165. _cmp_ ## elt_t(const void *_a, const void *_b) \
  1166. { \
  1167. const elt_t *a = _a, *b = _b; \
  1168. if (*a<*b) \
  1169. return -1; \
  1170. else if (*a>*b) \
  1171. return 1; \
  1172. else \
  1173. return 0; \
  1174. } \
  1175. elt_t \
  1176. funcname(elt_t *array, int n_elements, int nth) \
  1177. { \
  1178. tor_assert(nth >= 0); \
  1179. tor_assert(nth < n_elements); \
  1180. qsort(array, n_elements, sizeof(elt_t), _cmp_ ##elt_t); \
  1181. return array[nth]; \
  1182. }
  1183. IMPLEMENT_ORDER_FUNC(find_nth_int, int)
  1184. IMPLEMENT_ORDER_FUNC(find_nth_time, time_t)
  1185. IMPLEMENT_ORDER_FUNC(find_nth_double, double)
  1186. IMPLEMENT_ORDER_FUNC(find_nth_uint32, uint32_t)
  1187. IMPLEMENT_ORDER_FUNC(find_nth_int32, int32_t)
  1188. IMPLEMENT_ORDER_FUNC(find_nth_long, long)
  1189. /** Return a newly allocated digestset_t, optimized to hold a total of
  1190. * <b>max_elements</b> digests with a reasonably low false positive weight. */
  1191. digestset_t *
  1192. digestset_new(int max_elements)
  1193. {
  1194. /* The probability of false positives is about P=(1 - exp(-kn/m))^k, where k
  1195. * is the number of hash functions per entry, m is the bits in the array,
  1196. * and n is the number of elements inserted. For us, k==4, n<=max_elements,
  1197. * and m==n_bits= approximately max_elements*32. This gives
  1198. * P<(1-exp(-4*n/(32*n)))^4 == (1-exp(1/-8))^4 == .00019
  1199. *
  1200. * It would be more optimal in space vs false positives to get this false
  1201. * positive rate by going for k==13, and m==18.5n, but we also want to
  1202. * conserve CPU, and k==13 is pretty big.
  1203. */
  1204. int n_bits = 1u << (tor_log2(max_elements)+5);
  1205. digestset_t *r = tor_malloc(sizeof(digestset_t));
  1206. r->mask = n_bits - 1;
  1207. r->ba = bitarray_init_zero(n_bits);
  1208. return r;
  1209. }
  1210. /** Free all storage held in <b>set</b>. */
  1211. void
  1212. digestset_free(digestset_t *set)
  1213. {
  1214. bitarray_free(set->ba);
  1215. tor_free(set);
  1216. }