container.c 36 KB

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