container.c 43 KB

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