container.c 39 KB

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