container.c 42 KB

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