container.c 38 KB

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