container.c 50 KB

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