container.c 51 KB

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