container.c 42 KB

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