container.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2008, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char container_c_id[] =
  7. "$Id$";
  8. /**
  9. * \file container.c
  10. * \brief Implements a smartlist (a resizable array) along
  11. * with helper functions to use smartlists. Also includes
  12. * hash table implementations of a string-to-void* map, and of
  13. * a digest-to-void* map.
  14. **/
  15. #include "compat.h"
  16. #include "util.h"
  17. #include "log.h"
  18. #include "container.h"
  19. #include "crypto.h"
  20. #ifdef HAVE_CTYPE_H
  21. #include <ctype.h>
  22. #endif
  23. #include <stdlib.h>
  24. #include <string.h>
  25. #include <assert.h>
  26. #include "ht.h"
  27. /** All newly allocated smartlists have this capacity. */
  28. #define SMARTLIST_DEFAULT_CAPACITY 16
  29. /** Allocate and return an empty smartlist.
  30. */
  31. smartlist_t *
  32. smartlist_create(void)
  33. {
  34. smartlist_t *sl = tor_malloc(sizeof(smartlist_t));
  35. sl->num_used = 0;
  36. sl->capacity = SMARTLIST_DEFAULT_CAPACITY;
  37. sl->list = tor_malloc(sizeof(void *) * sl->capacity);
  38. return sl;
  39. }
  40. /** Deallocate a smartlist. Does not release storage associated with the
  41. * list's elements.
  42. */
  43. void
  44. smartlist_free(smartlist_t *sl)
  45. {
  46. tor_assert(sl != NULL);
  47. tor_free(sl->list);
  48. tor_free(sl);
  49. }
  50. /** Remove all elements from the list.
  51. */
  52. void
  53. smartlist_clear(smartlist_t *sl)
  54. {
  55. sl->num_used = 0;
  56. }
  57. /** Make sure that <b>sl</b> can hold at least <b>size</b> entries. */
  58. static INLINE void
  59. smartlist_ensure_capacity(smartlist_t *sl, int size)
  60. {
  61. if (size > sl->capacity) {
  62. int higher = sl->capacity * 2;
  63. while (size > higher)
  64. higher *= 2;
  65. tor_assert(higher > 0); /* detect overflow */
  66. sl->capacity = higher;
  67. sl->list = tor_realloc(sl->list, sizeof(void*)*sl->capacity);
  68. }
  69. }
  70. /** Append element to the end of the list. */
  71. void
  72. smartlist_add(smartlist_t *sl, void *element)
  73. {
  74. smartlist_ensure_capacity(sl, sl->num_used+1);
  75. sl->list[sl->num_used++] = element;
  76. }
  77. /** Append each element from S2 to the end of S1. */
  78. void
  79. smartlist_add_all(smartlist_t *s1, const smartlist_t *s2)
  80. {
  81. int new_size = s1->num_used + s2->num_used;
  82. tor_assert(new_size >= s1->num_used); /* check for overflow. */
  83. smartlist_ensure_capacity(s1, new_size);
  84. memcpy(s1->list + s1->num_used, s2->list, s2->num_used*sizeof(void*));
  85. s1->num_used = new_size;
  86. }
  87. /** Remove all elements E from sl such that E==element. Preserve
  88. * the order of any elements before E, but elements after E can be
  89. * rearranged.
  90. */
  91. void
  92. smartlist_remove(smartlist_t *sl, const void *element)
  93. {
  94. int i;
  95. if (element == NULL)
  96. return;
  97. for (i=0; i < sl->num_used; i++)
  98. if (sl->list[i] == element) {
  99. sl->list[i] = sl->list[--sl->num_used]; /* swap with the end */
  100. i--; /* so we process the new i'th element */
  101. }
  102. }
  103. /** If <b>sl</b> is nonempty, remove and return the final element. Otherwise,
  104. * return NULL. */
  105. void *
  106. smartlist_pop_last(smartlist_t *sl)
  107. {
  108. tor_assert(sl);
  109. if (sl->num_used)
  110. return sl->list[--sl->num_used];
  111. else
  112. return NULL;
  113. }
  114. /** Reverse the order of the items in <b>sl</b>. */
  115. void
  116. smartlist_reverse(smartlist_t *sl)
  117. {
  118. int i, j;
  119. void *tmp;
  120. tor_assert(sl);
  121. for (i = 0, j = sl->num_used-1; i < j; ++i, --j) {
  122. tmp = sl->list[i];
  123. sl->list[i] = sl->list[j];
  124. sl->list[j] = tmp;
  125. }
  126. }
  127. /** If there are any strings in sl equal to element, remove and free them.
  128. * Does not preserve order. */
  129. void
  130. smartlist_string_remove(smartlist_t *sl, const char *element)
  131. {
  132. int i;
  133. tor_assert(sl);
  134. tor_assert(element);
  135. for (i = 0; i < sl->num_used; ++i) {
  136. if (!strcmp(element, sl->list[i])) {
  137. tor_free(sl->list[i]);
  138. sl->list[i] = sl->list[--sl->num_used]; /* swap with the end */
  139. i--; /* so we process the new i'th element */
  140. }
  141. }
  142. }
  143. /** Return true iff some element E of sl has E==element.
  144. */
  145. int
  146. smartlist_isin(const smartlist_t *sl, const void *element)
  147. {
  148. int i;
  149. for (i=0; i < sl->num_used; i++)
  150. if (sl->list[i] == element)
  151. return 1;
  152. return 0;
  153. }
  154. /** Return true iff <b>sl</b> has some element E such that
  155. * !strcmp(E,<b>element</b>)
  156. */
  157. int
  158. smartlist_string_isin(const smartlist_t *sl, const char *element)
  159. {
  160. int i;
  161. if (!sl) return 0;
  162. for (i=0; i < sl->num_used; i++)
  163. if (strcmp((const char*)sl->list[i],element)==0)
  164. return 1;
  165. return 0;
  166. }
  167. /** If <b>element</b> is equal to an element of <b>sl</b>, return that
  168. * element's index. Otherwise, return -1. */
  169. int
  170. smartlist_string_pos(const smartlist_t *sl, const char *element)
  171. {
  172. int i;
  173. if (!sl) return -1;
  174. for (i=0; i < sl->num_used; i++)
  175. if (strcmp((const char*)sl->list[i],element)==0)
  176. return i;
  177. return -1;
  178. }
  179. /** Return true iff <b>sl</b> has some element E such that
  180. * !strcasecmp(E,<b>element</b>)
  181. */
  182. int
  183. smartlist_string_isin_case(const smartlist_t *sl, const char *element)
  184. {
  185. int i;
  186. if (!sl) return 0;
  187. for (i=0; i < sl->num_used; i++)
  188. if (strcasecmp((const char*)sl->list[i],element)==0)
  189. return 1;
  190. return 0;
  191. }
  192. /** Return true iff <b>sl</b> has some element E such that E is equal
  193. * to the decimal encoding of <b>num</b>.
  194. */
  195. int
  196. smartlist_string_num_isin(const smartlist_t *sl, int num)
  197. {
  198. char buf[16];
  199. tor_snprintf(buf,sizeof(buf),"%d", num);
  200. return smartlist_string_isin(sl, buf);
  201. }
  202. /** Return true iff <b>sl</b> has some element E such that
  203. * !memcmp(E,<b>element</b>,DIGEST_LEN)
  204. */
  205. int
  206. smartlist_digest_isin(const smartlist_t *sl, const char *element)
  207. {
  208. int i;
  209. if (!sl) return 0;
  210. for (i=0; i < sl->num_used; i++)
  211. if (memcmp((const char*)sl->list[i],element,DIGEST_LEN)==0)
  212. return 1;
  213. return 0;
  214. }
  215. /** Return true iff some element E of sl2 has smartlist_isin(sl1,E).
  216. */
  217. int
  218. smartlist_overlap(const smartlist_t *sl1, const smartlist_t *sl2)
  219. {
  220. int i;
  221. for (i=0; i < sl2->num_used; i++)
  222. if (smartlist_isin(sl1, sl2->list[i]))
  223. return 1;
  224. return 0;
  225. }
  226. /** Remove every element E of sl1 such that !smartlist_isin(sl2,E).
  227. * Does not preserve the order of sl1.
  228. */
  229. void
  230. smartlist_intersect(smartlist_t *sl1, const smartlist_t *sl2)
  231. {
  232. int i;
  233. for (i=0; i < sl1->num_used; i++)
  234. if (!smartlist_isin(sl2, sl1->list[i])) {
  235. sl1->list[i] = sl1->list[--sl1->num_used]; /* swap with the end */
  236. i--; /* so we process the new i'th element */
  237. }
  238. }
  239. /** Remove every element E of sl1 such that smartlist_isin(sl2,E).
  240. * Does not preserve the order of sl1.
  241. */
  242. void
  243. smartlist_subtract(smartlist_t *sl1, const smartlist_t *sl2)
  244. {
  245. int i;
  246. for (i=0; i < sl2->num_used; i++)
  247. smartlist_remove(sl1, sl2->list[i]);
  248. }
  249. /** Remove the <b>idx</b>th element of sl; if idx is not the last
  250. * element, swap the last element of sl into the <b>idx</b>th space.
  251. * Return the old value of the <b>idx</b>th element.
  252. */
  253. void
  254. smartlist_del(smartlist_t *sl, int idx)
  255. {
  256. tor_assert(sl);
  257. tor_assert(idx>=0);
  258. tor_assert(idx < sl->num_used);
  259. sl->list[idx] = sl->list[--sl->num_used];
  260. }
  261. /** Remove the <b>idx</b>th element of sl; if idx is not the last element,
  262. * moving all subsequent elements back one space. Return the old value
  263. * of the <b>idx</b>th element.
  264. */
  265. void
  266. smartlist_del_keeporder(smartlist_t *sl, int idx)
  267. {
  268. tor_assert(sl);
  269. tor_assert(idx>=0);
  270. tor_assert(idx < sl->num_used);
  271. --sl->num_used;
  272. if (idx < sl->num_used)
  273. memmove(sl->list+idx, sl->list+idx+1, sizeof(void*)*(sl->num_used-idx));
  274. }
  275. /** Insert the value <b>val</b> as the new <b>idx</b>th element of
  276. * <b>sl</b>, moving all items previously at <b>idx</b> or later
  277. * forward one space.
  278. */
  279. void
  280. smartlist_insert(smartlist_t *sl, int idx, void *val)
  281. {
  282. tor_assert(sl);
  283. tor_assert(idx>=0);
  284. tor_assert(idx <= sl->num_used);
  285. if (idx == sl->num_used) {
  286. smartlist_add(sl, val);
  287. } else {
  288. smartlist_ensure_capacity(sl, sl->num_used+1);
  289. /* Move other elements away */
  290. if (idx < sl->num_used)
  291. memmove(sl->list + idx + 1, sl->list + idx,
  292. sizeof(void*)*(sl->num_used-idx));
  293. sl->num_used++;
  294. sl->list[idx] = val;
  295. }
  296. }
  297. /**
  298. * Split a string <b>str</b> along all occurrences of <b>sep</b>,
  299. * adding the split strings, in order, to <b>sl</b>.
  300. *
  301. * If <b>flags</b>&amp;SPLIT_SKIP_SPACE is true, remove initial and
  302. * trailing space from each entry.
  303. * If <b>flags</b>&amp;SPLIT_IGNORE_BLANK is true, remove any entries
  304. * of length 0.
  305. * If <b>flags</b>&amp;SPLIT_STRIP_SPACE is true, strip spaces from each
  306. * split string.
  307. *
  308. * If max>0, divide the string into no more than <b>max</b> pieces. If
  309. * <b>sep</b> is NULL, split on any sequence of horizontal space.
  310. */
  311. int
  312. smartlist_split_string(smartlist_t *sl, const char *str, const char *sep,
  313. int flags, int max)
  314. {
  315. const char *cp, *end, *next;
  316. int n = 0;
  317. tor_assert(sl);
  318. tor_assert(str);
  319. cp = str;
  320. while (1) {
  321. if (flags&SPLIT_SKIP_SPACE) {
  322. while (TOR_ISSPACE(*cp)) ++cp;
  323. }
  324. if (max>0 && n == max-1) {
  325. end = strchr(cp,'\0');
  326. } else if (sep) {
  327. end = strstr(cp,sep);
  328. if (!end)
  329. end = strchr(cp,'\0');
  330. } else {
  331. for (end = cp; *end && *end != '\t' && *end != ' '; ++end)
  332. ;
  333. }
  334. tor_assert(end);
  335. if (!*end) {
  336. next = NULL;
  337. } else if (sep) {
  338. next = end+strlen(sep);
  339. } else {
  340. next = end+1;
  341. while (*next == '\t' || *next == ' ')
  342. ++next;
  343. }
  344. if (flags&SPLIT_SKIP_SPACE) {
  345. while (end > cp && TOR_ISSPACE(*(end-1)))
  346. --end;
  347. }
  348. if (end != cp || !(flags&SPLIT_IGNORE_BLANK)) {
  349. char *string = tor_strndup(cp, end-cp);
  350. if (flags&SPLIT_STRIP_SPACE)
  351. tor_strstrip(string, " ");
  352. smartlist_add(sl, string);
  353. ++n;
  354. }
  355. if (!next)
  356. break;
  357. cp = next;
  358. }
  359. return n;
  360. }
  361. /** Allocate and return a new string containing the concatenation of
  362. * the elements of <b>sl</b>, in order, separated by <b>join</b>. If
  363. * <b>terminate</b> is true, also terminate the string with <b>join</b>.
  364. * If <b>len_out</b> is not NULL, set <b>len_out</b> to the length of
  365. * the returned string. Requires that every element of <b>sl</b> is
  366. * NUL-terminated string.
  367. */
  368. char *
  369. smartlist_join_strings(smartlist_t *sl, const char *join,
  370. int terminate, size_t *len_out)
  371. {
  372. return smartlist_join_strings2(sl,join,strlen(join),terminate,len_out);
  373. }
  374. /** As smartlist_join_strings, but instead of separating/terminated with a
  375. * NUL-terminated string <b>join</b>, uses the <b>join_len</b>-byte sequence
  376. * at <b>join</b>. (Useful for generating a sequence of NUL-terminated
  377. * strings.)
  378. */
  379. char *
  380. smartlist_join_strings2(smartlist_t *sl, const char *join,
  381. size_t join_len, int terminate, size_t *len_out)
  382. {
  383. int i;
  384. size_t n = 0;
  385. char *r = NULL, *dst, *src;
  386. tor_assert(sl);
  387. tor_assert(join);
  388. if (terminate)
  389. n = join_len;
  390. for (i = 0; i < sl->num_used; ++i) {
  391. n += strlen(sl->list[i]);
  392. if (i+1 < sl->num_used) /* avoid double-counting the last one */
  393. n += join_len;
  394. }
  395. dst = r = tor_malloc(n+1);
  396. for (i = 0; i < sl->num_used; ) {
  397. for (src = sl->list[i]; *src; )
  398. *dst++ = *src++;
  399. if (++i < sl->num_used) {
  400. memcpy(dst, join, join_len);
  401. dst += join_len;
  402. }
  403. }
  404. if (terminate) {
  405. memcpy(dst, join, join_len);
  406. dst += join_len;
  407. }
  408. *dst = '\0';
  409. if (len_out)
  410. *len_out = dst-r;
  411. return r;
  412. }
  413. /** Sort the members of <b>sl</b> into an order defined by
  414. * the ordering function <b>compare</b>, which returns less then 0 if a
  415. * precedes b, greater than 0 if b precedes a, and 0 if a 'equals' b.
  416. */
  417. void
  418. smartlist_sort(smartlist_t *sl, int (*compare)(const void **a, const void **b))
  419. {
  420. if (!sl->num_used)
  421. return;
  422. qsort(sl->list, sl->num_used, sizeof(void*),
  423. (int (*)(const void *,const void*))compare);
  424. }
  425. /** Given a sorted smartlist <b>sl</b> and the comparison function used to
  426. * sort it, remove all duplicate members. If free_fn is provided, calls
  427. * free_fn on each duplicate. Otherwise, just removes them. Preserves order.
  428. */
  429. void
  430. smartlist_uniq(smartlist_t *sl,
  431. int (*compare)(const void **a, const void **b),
  432. void (*free_fn)(void *a))
  433. {
  434. int i;
  435. for (i=1; i < sl->num_used; ++i) {
  436. if (compare((const void **)&(sl->list[i-1]),
  437. (const void **)&(sl->list[i])) == 0) {
  438. if (free_fn)
  439. free_fn(sl->list[i]);
  440. smartlist_del_keeporder(sl, i--);
  441. }
  442. }
  443. }
  444. /** Assuming the members of <b>sl</b> are in order, return a pointer to the
  445. * member that matches <b>key</b>. Ordering and matching are defined by a
  446. * <b>compare</b> function that returns 0 on a match; less than 0 if key is
  447. * less than member, and greater than 0 if key is greater then member.
  448. */
  449. void *
  450. smartlist_bsearch(smartlist_t *sl, const void *key,
  451. int (*compare)(const void *key, const void **member))
  452. {
  453. int found=0, idx;
  454. idx = smartlist_bsearch_idx(sl, key, compare, &found);
  455. return found ? smartlist_get(sl, idx) : NULL;
  456. }
  457. /** Assuming the members of <b>sl</b> are in order, return the index of the
  458. * member that matches <b>key</b>. If no member matches, return the index of
  459. * the first member greater than <b>key</b>, or smartlist_len(sl) if no member
  460. * is greater than <b>key</b>. Set <b>found_out</b> to true on a match, to
  461. * false otherwise. Ordering and matching are defined by a <b>compare</b>
  462. * function that returns 0 on a match; less than 0 if key is less than member,
  463. * and greater than 0 if key is greater then member.
  464. */
  465. int
  466. smartlist_bsearch_idx(const smartlist_t *sl, const void *key,
  467. int (*compare)(const void *key, const void **member),
  468. int *found_out)
  469. {
  470. int hi = smartlist_len(sl) - 1, lo = 0, cmp, mid;
  471. while (lo <= hi) {
  472. mid = (lo + hi) / 2;
  473. cmp = compare(key, (const void**) &(sl->list[mid]));
  474. if (cmp>0) { /* key > sl[mid] */
  475. lo = mid+1;
  476. } else if (cmp<0) { /* key < sl[mid] */
  477. hi = mid-1;
  478. } else { /* key == sl[mid] */
  479. *found_out = 1;
  480. return mid;
  481. }
  482. }
  483. /* lo > hi. */
  484. {
  485. tor_assert(lo >= 0);
  486. if (lo < smartlist_len(sl)) {
  487. cmp = compare(key, (const void**) &(sl->list[lo]));
  488. tor_assert(cmp < 0);
  489. } else if (smartlist_len(sl)) {
  490. cmp = compare(key, (const void**) &(sl->list[smartlist_len(sl)-1]));
  491. tor_assert(cmp > 0);
  492. }
  493. }
  494. *found_out = 0;
  495. return lo;
  496. }
  497. /** Helper: compare two const char **s. */
  498. static int
  499. _compare_string_ptrs(const void **_a, const void **_b)
  500. {
  501. return strcmp((const char*)*_a, (const char*)*_b);
  502. }
  503. /** Sort a smartlist <b>sl</b> containing strings into lexically ascending
  504. * order. */
  505. void
  506. smartlist_sort_strings(smartlist_t *sl)
  507. {
  508. smartlist_sort(sl, _compare_string_ptrs);
  509. }
  510. /** Remove duplicate strings from a sorted list, and free them with tor_free().
  511. */
  512. void
  513. smartlist_uniq_strings(smartlist_t *sl)
  514. {
  515. smartlist_uniq(sl, _compare_string_ptrs, _tor_free);
  516. }
  517. /* Heap-based priority queue implementation for O(lg N) insert and remove.
  518. * Recall that the heap property is that, for every index I, h[I] <
  519. * H[LEFT_CHILD[I]] and h[I] < H[RIGHT_CHILD[I]].
  520. */
  521. /* For a 1-indexed array, we would use LEFT_CHILD[x] = 2*x and RIGHT_CHILD[x]
  522. * = 2*x + 1. But this is C, so we have to adjust a little. */
  523. //#define LEFT_CHILD(i) ( ((i)+1)*2 - 1)
  524. //#define RIGHT_CHILD(i) ( ((i)+1)*2 )
  525. //#define PARENT(i) ( ((i)+1)/2 - 1)
  526. #define LEFT_CHILD(i) ( 2*(i) + 1 )
  527. #define RIGHT_CHILD(i) ( 2*(i) + 2 )
  528. #define PARENT(i) ( ((i)-1) / 2 )
  529. /** Helper. <b>sl</b> may have at most one violation of the heap property:
  530. * the item at <b>idx</b> may be greater than one or both of its children.
  531. * Restore the heap property. */
  532. static INLINE void
  533. smartlist_heapify(smartlist_t *sl,
  534. int (*compare)(const void *a, const void *b),
  535. int idx)
  536. {
  537. while (1) {
  538. int left_idx = LEFT_CHILD(idx);
  539. int best_idx;
  540. if (left_idx >= sl->num_used)
  541. return;
  542. if (compare(sl->list[idx],sl->list[left_idx]) < 0)
  543. best_idx = idx;
  544. else
  545. best_idx = left_idx;
  546. if (left_idx+1 < sl->num_used &&
  547. compare(sl->list[left_idx+1],sl->list[best_idx]) < 0)
  548. best_idx = left_idx + 1;
  549. if (best_idx == idx) {
  550. return;
  551. } else {
  552. void *tmp = sl->list[idx];
  553. sl->list[idx] = sl->list[best_idx];
  554. sl->list[best_idx] = tmp;
  555. idx = best_idx;
  556. }
  557. }
  558. }
  559. /** Insert <b>item</b> into the heap stored in <b>sl</b>, where order
  560. * is determined by <b>compare</b>. */
  561. void
  562. smartlist_pqueue_add(smartlist_t *sl,
  563. int (*compare)(const void *a, const void *b),
  564. void *item)
  565. {
  566. int idx;
  567. smartlist_add(sl,item);
  568. for (idx = sl->num_used - 1; idx; ) {
  569. int parent = PARENT(idx);
  570. if (compare(sl->list[idx], sl->list[parent]) < 0) {
  571. void *tmp = sl->list[parent];
  572. sl->list[parent] = sl->list[idx];
  573. sl->list[idx] = tmp;
  574. idx = parent;
  575. } else {
  576. return;
  577. }
  578. }
  579. }
  580. /** Remove and return the top-priority item from the heap stored in <b>sl</b>,
  581. * where order is determined by <b>compare</b>. <b>sl</b> must not be
  582. * empty. */
  583. void *
  584. smartlist_pqueue_pop(smartlist_t *sl,
  585. int (*compare)(const void *a, const void *b))
  586. {
  587. void *top;
  588. tor_assert(sl->num_used);
  589. top = sl->list[0];
  590. if (--sl->num_used) {
  591. sl->list[0] = sl->list[sl->num_used];
  592. smartlist_heapify(sl, compare, 0);
  593. }
  594. return top;
  595. }
  596. /** Assert that the heap property is correctly maintained by the heap stored
  597. * in <b>sl</b>, where order is determined by <b>compare</b>. */
  598. void
  599. smartlist_pqueue_assert_ok(smartlist_t *sl,
  600. int (*compare)(const void *a, const void *b))
  601. {
  602. int i;
  603. for (i = sl->num_used - 1; i > 0; --i) {
  604. tor_assert(compare(sl->list[PARENT(i)], sl->list[i]) <= 0);
  605. }
  606. }
  607. /** Helper: compare two DIGEST_LEN digests. */
  608. static int
  609. _compare_digests(const void **_a, const void **_b)
  610. {
  611. return memcmp((const char*)*_a, (const char*)*_b, DIGEST_LEN);
  612. }
  613. /** Sort the list of DIGEST_LEN-byte digests into ascending order. */
  614. void
  615. smartlist_sort_digests(smartlist_t *sl)
  616. {
  617. smartlist_sort(sl, _compare_digests);
  618. }
  619. /** Remove duplicate digests from a sorted list, and free them with tor_free().
  620. */
  621. void
  622. smartlist_uniq_digests(smartlist_t *sl)
  623. {
  624. smartlist_uniq(sl, _compare_digests, _tor_free);
  625. }
  626. #define DEFINE_MAP_STRUCTS(maptype, keydecl, prefix) \
  627. typedef struct prefix ## entry_t { \
  628. HT_ENTRY(prefix ## entry_t) node; \
  629. void *val; \
  630. keydecl; \
  631. } prefix ## entry_t; \
  632. struct maptype { \
  633. HT_HEAD(prefix ## impl, prefix ## entry_t) head; \
  634. }
  635. DEFINE_MAP_STRUCTS(strmap_t, char *key, strmap_);
  636. DEFINE_MAP_STRUCTS(digestmap_t, char key[DIGEST_LEN], digestmap_);
  637. /** Helper: compare strmap_entry_t objects by key value. */
  638. static INLINE int
  639. strmap_entries_eq(const strmap_entry_t *a, const strmap_entry_t *b)
  640. {
  641. return !strcmp(a->key, b->key);
  642. }
  643. /** Helper: return a hash value for a strmap_entry_t. */
  644. static INLINE unsigned int
  645. strmap_entry_hash(const strmap_entry_t *a)
  646. {
  647. return ht_string_hash(a->key);
  648. }
  649. /** Helper: compare digestmap_entry_t objects by key value. */
  650. static INLINE int
  651. digestmap_entries_eq(const digestmap_entry_t *a, const digestmap_entry_t *b)
  652. {
  653. return !memcmp(a->key, b->key, DIGEST_LEN);
  654. }
  655. /** Helper: return a hash value for a digest_map_t. */
  656. static INLINE unsigned int
  657. digestmap_entry_hash(const digestmap_entry_t *a)
  658. {
  659. #if SIZEOF_INT != 8
  660. const uint32_t *p = (const uint32_t*)a->key;
  661. return p[0] ^ p[1] ^ p[2] ^ p[3] ^ p[4];
  662. #else
  663. const uint64_t *p = (const uint64_t*)a->key;
  664. return p[0] ^ p[1];
  665. #endif
  666. }
  667. HT_PROTOTYPE(strmap_impl, strmap_entry_t, node, strmap_entry_hash,
  668. strmap_entries_eq)
  669. HT_GENERATE(strmap_impl, strmap_entry_t, node, strmap_entry_hash,
  670. strmap_entries_eq, 0.6, malloc, realloc, free)
  671. HT_PROTOTYPE(digestmap_impl, digestmap_entry_t, node, digestmap_entry_hash,
  672. digestmap_entries_eq)
  673. HT_GENERATE(digestmap_impl, digestmap_entry_t, node, digestmap_entry_hash,
  674. digestmap_entries_eq, 0.6, malloc, realloc, free)
  675. /** Constructor to create a new empty map from strings to void*'s.
  676. */
  677. strmap_t *
  678. strmap_new(void)
  679. {
  680. strmap_t *result;
  681. result = tor_malloc(sizeof(strmap_t));
  682. HT_INIT(strmap_impl, &result->head);
  683. return result;
  684. }
  685. /** Constructor to create a new empty map from digests to void*'s.
  686. */
  687. digestmap_t *
  688. digestmap_new(void)
  689. {
  690. digestmap_t *result;
  691. result = tor_malloc(sizeof(digestmap_t));
  692. HT_INIT(digestmap_impl, &result->head);
  693. return result;
  694. }
  695. /** Set the current value for <b>key</b> to <b>val</b>. Returns the previous
  696. * value for <b>key</b> if one was set, or NULL if one was not.
  697. *
  698. * This function makes a copy of <b>key</b> if necessary, but not of
  699. * <b>val</b>.
  700. */
  701. void *
  702. strmap_set(strmap_t *map, const char *key, void *val)
  703. {
  704. strmap_entry_t *resolve;
  705. strmap_entry_t search;
  706. void *oldval;
  707. tor_assert(map);
  708. tor_assert(key);
  709. tor_assert(val);
  710. search.key = (char*)key;
  711. resolve = HT_FIND(strmap_impl, &map->head, &search);
  712. if (resolve) {
  713. oldval = resolve->val;
  714. resolve->val = val;
  715. return oldval;
  716. } else {
  717. resolve = tor_malloc_zero(sizeof(strmap_entry_t));
  718. resolve->key = tor_strdup(key);
  719. resolve->val = val;
  720. tor_assert(!HT_FIND(strmap_impl, &map->head, resolve));
  721. HT_INSERT(strmap_impl, &map->head, resolve);
  722. return NULL;
  723. }
  724. }
  725. #define OPTIMIZED_DIGESTMAP_SET
  726. /** Like strmap_set() above but for digestmaps. */
  727. void *
  728. digestmap_set(digestmap_t *map, const char *key, void *val)
  729. {
  730. #ifndef OPTIMIZED_DIGESTMAP_SET
  731. digestmap_entry_t *resolve;
  732. #endif
  733. digestmap_entry_t search;
  734. void *oldval;
  735. tor_assert(map);
  736. tor_assert(key);
  737. tor_assert(val);
  738. memcpy(&search.key, key, DIGEST_LEN);
  739. #ifndef OPTIMIZED_DIGESTMAP_SET
  740. resolve = HT_FIND(digestmap_impl, &map->head, &search);
  741. if (resolve) {
  742. oldval = resolve->val;
  743. resolve->val = val;
  744. return oldval;
  745. } else {
  746. resolve = tor_malloc_zero(sizeof(digestmap_entry_t));
  747. memcpy(resolve->key, key, DIGEST_LEN);
  748. resolve->val = val;
  749. HT_INSERT(digestmap_impl, &map->head, resolve);
  750. return NULL;
  751. }
  752. #else
  753. /* We spend up to 5% of our time in this function, so the code below is
  754. * meant to optimize the check/alloc/set cycle by avoiding the two trips to
  755. * the hash table that we do in the unoptimized code above. (Each of
  756. * HT_INSERT and HT_FIND calls HT_SET_HASH and HT_FIND_P.)
  757. */
  758. _HT_FIND_OR_INSERT(digestmap_impl, node, digestmap_entry_hash, &(map->head),
  759. digestmap_entry_t, &search, ptr,
  760. {
  761. /* we found an entry. */
  762. oldval = (*ptr)->val;
  763. (*ptr)->val = val;
  764. return oldval;
  765. },
  766. {
  767. /* We didn't find the entry. */
  768. digestmap_entry_t *newent =
  769. tor_malloc_zero(sizeof(digestmap_entry_t));
  770. memcpy(newent->key, key, DIGEST_LEN);
  771. newent->val = val;
  772. _HT_FOI_INSERT(node, &(map->head), &search, newent, ptr);
  773. return NULL;
  774. });
  775. #endif
  776. }
  777. /** Return the current value associated with <b>key</b>, or NULL if no
  778. * value is set.
  779. */
  780. void *
  781. strmap_get(const strmap_t *map, const char *key)
  782. {
  783. strmap_entry_t *resolve;
  784. strmap_entry_t search;
  785. tor_assert(map);
  786. tor_assert(key);
  787. search.key = (char*)key;
  788. resolve = HT_FIND(strmap_impl, &map->head, &search);
  789. if (resolve) {
  790. return resolve->val;
  791. } else {
  792. return NULL;
  793. }
  794. }
  795. /** Like strmap_get() above but for digestmaps. */
  796. void *
  797. digestmap_get(const digestmap_t *map, const char *key)
  798. {
  799. digestmap_entry_t *resolve;
  800. digestmap_entry_t search;
  801. tor_assert(map);
  802. tor_assert(key);
  803. memcpy(&search.key, key, DIGEST_LEN);
  804. resolve = HT_FIND(digestmap_impl, &map->head, &search);
  805. if (resolve) {
  806. return resolve->val;
  807. } else {
  808. return NULL;
  809. }
  810. }
  811. /** Remove the value currently associated with <b>key</b> from the map.
  812. * Return the value if one was set, or NULL if there was no entry for
  813. * <b>key</b>.
  814. *
  815. * Note: you must free any storage associated with the returned value.
  816. */
  817. void *
  818. strmap_remove(strmap_t *map, const char *key)
  819. {
  820. strmap_entry_t *resolve;
  821. strmap_entry_t search;
  822. void *oldval;
  823. tor_assert(map);
  824. tor_assert(key);
  825. search.key = (char*)key;
  826. resolve = HT_REMOVE(strmap_impl, &map->head, &search);
  827. if (resolve) {
  828. oldval = resolve->val;
  829. tor_free(resolve->key);
  830. tor_free(resolve);
  831. return oldval;
  832. } else {
  833. return NULL;
  834. }
  835. }
  836. /** Like strmap_remove() above but for digestmaps. */
  837. void *
  838. digestmap_remove(digestmap_t *map, const char *key)
  839. {
  840. digestmap_entry_t *resolve;
  841. digestmap_entry_t search;
  842. void *oldval;
  843. tor_assert(map);
  844. tor_assert(key);
  845. memcpy(&search.key, key, DIGEST_LEN);
  846. resolve = HT_REMOVE(digestmap_impl, &map->head, &search);
  847. if (resolve) {
  848. oldval = resolve->val;
  849. tor_free(resolve);
  850. return oldval;
  851. } else {
  852. return NULL;
  853. }
  854. }
  855. /** Same as strmap_set, but first converts <b>key</b> to lowercase. */
  856. void *
  857. strmap_set_lc(strmap_t *map, const char *key, void *val)
  858. {
  859. /* We could be a little faster by using strcasecmp instead, and a separate
  860. * type, but I don't think it matters. */
  861. void *v;
  862. char *lc_key = tor_strdup(key);
  863. tor_strlower(lc_key);
  864. v = strmap_set(map,lc_key,val);
  865. tor_free(lc_key);
  866. return v;
  867. }
  868. /** Same as strmap_get, but first converts <b>key</b> to lowercase. */
  869. void *
  870. strmap_get_lc(const strmap_t *map, const char *key)
  871. {
  872. void *v;
  873. char *lc_key = tor_strdup(key);
  874. tor_strlower(lc_key);
  875. v = strmap_get(map,lc_key);
  876. tor_free(lc_key);
  877. return v;
  878. }
  879. /** Same as strmap_remove, but first converts <b>key</b> to lowercase */
  880. void *
  881. strmap_remove_lc(strmap_t *map, const char *key)
  882. {
  883. void *v;
  884. char *lc_key = tor_strdup(key);
  885. tor_strlower(lc_key);
  886. v = strmap_remove(map,lc_key);
  887. tor_free(lc_key);
  888. return v;
  889. }
  890. /** return an <b>iterator</b> pointer to the front of a map.
  891. *
  892. * Iterator example:
  893. *
  894. * \code
  895. * // uppercase values in "map", removing empty values.
  896. *
  897. * strmap_iter_t *iter;
  898. * const char *key;
  899. * void *val;
  900. * char *cp;
  901. *
  902. * for (iter = strmap_iter_init(map); !strmap_iter_done(iter); ) {
  903. * strmap_iter_get(iter, &key, &val);
  904. * cp = (char*)val;
  905. * if (!*cp) {
  906. * iter = strmap_iter_next_rmv(map,iter);
  907. * free(val);
  908. * } else {
  909. * for (;*cp;cp++) *cp = TOR_TOUPPER(*cp);
  910. * iter = strmap_iter_next(map,iter);
  911. * }
  912. * }
  913. * \endcode
  914. *
  915. */
  916. strmap_iter_t *
  917. strmap_iter_init(strmap_t *map)
  918. {
  919. tor_assert(map);
  920. return HT_START(strmap_impl, &map->head);
  921. }
  922. digestmap_iter_t *
  923. digestmap_iter_init(digestmap_t *map)
  924. {
  925. tor_assert(map);
  926. return HT_START(digestmap_impl, &map->head);
  927. }
  928. /** Advance the iterator <b>iter</b> for map a single step to the next entry.
  929. */
  930. strmap_iter_t *
  931. strmap_iter_next(strmap_t *map, strmap_iter_t *iter)
  932. {
  933. tor_assert(map);
  934. tor_assert(iter);
  935. return HT_NEXT(strmap_impl, &map->head, iter);
  936. }
  937. digestmap_iter_t *
  938. digestmap_iter_next(digestmap_t *map, digestmap_iter_t *iter)
  939. {
  940. tor_assert(map);
  941. tor_assert(iter);
  942. return HT_NEXT(digestmap_impl, &map->head, iter);
  943. }
  944. /** Advance the iterator <b>iter</b> a single step to the next entry, removing
  945. * the current entry.
  946. */
  947. strmap_iter_t *
  948. strmap_iter_next_rmv(strmap_t *map, strmap_iter_t *iter)
  949. {
  950. strmap_entry_t *rmv;
  951. tor_assert(map);
  952. tor_assert(iter);
  953. tor_assert(*iter);
  954. rmv = *iter;
  955. iter = HT_NEXT_RMV(strmap_impl, &map->head, iter);
  956. tor_free(rmv->key);
  957. tor_free(rmv);
  958. return iter;
  959. }
  960. digestmap_iter_t *
  961. digestmap_iter_next_rmv(digestmap_t *map, digestmap_iter_t *iter)
  962. {
  963. digestmap_entry_t *rmv;
  964. tor_assert(map);
  965. tor_assert(iter);
  966. tor_assert(*iter);
  967. rmv = *iter;
  968. iter = HT_NEXT_RMV(digestmap_impl, &map->head, iter);
  969. tor_free(rmv);
  970. return iter;
  971. }
  972. /** Set *keyp and *valp to the current entry pointed to by iter.
  973. */
  974. void
  975. strmap_iter_get(strmap_iter_t *iter, const char **keyp, void **valp)
  976. {
  977. tor_assert(iter);
  978. tor_assert(*iter);
  979. tor_assert(keyp);
  980. tor_assert(valp);
  981. *keyp = (*iter)->key;
  982. *valp = (*iter)->val;
  983. }
  984. void
  985. digestmap_iter_get(digestmap_iter_t *iter, const char **keyp, void **valp)
  986. {
  987. tor_assert(iter);
  988. tor_assert(*iter);
  989. tor_assert(keyp);
  990. tor_assert(valp);
  991. *keyp = (*iter)->key;
  992. *valp = (*iter)->val;
  993. }
  994. /** Return true iff iter has advanced past the last entry of map.
  995. */
  996. int
  997. strmap_iter_done(strmap_iter_t *iter)
  998. {
  999. return iter == NULL;
  1000. }
  1001. int
  1002. digestmap_iter_done(digestmap_iter_t *iter)
  1003. {
  1004. return iter == NULL;
  1005. }
  1006. /** Remove all entries from <b>map</b>, and deallocate storage for those
  1007. * entries. If free_val is provided, it is invoked on every value in
  1008. * <b>map</b>.
  1009. */
  1010. void
  1011. strmap_free(strmap_t *map, void (*free_val)(void*))
  1012. {
  1013. strmap_entry_t **ent, **next, *this;
  1014. for (ent = HT_START(strmap_impl, &map->head); ent != NULL; ent = next) {
  1015. this = *ent;
  1016. next = HT_NEXT_RMV(strmap_impl, &map->head, ent);
  1017. tor_free(this->key);
  1018. if (free_val)
  1019. free_val(this->val);
  1020. tor_free(this);
  1021. }
  1022. tor_assert(HT_EMPTY(&map->head));
  1023. HT_CLEAR(strmap_impl, &map->head);
  1024. tor_free(map);
  1025. }
  1026. void
  1027. digestmap_free(digestmap_t *map, void (*free_val)(void*))
  1028. {
  1029. digestmap_entry_t **ent, **next, *this;
  1030. for (ent = HT_START(digestmap_impl, &map->head); ent != NULL; ent = next) {
  1031. this = *ent;
  1032. next = HT_NEXT_RMV(digestmap_impl, &map->head, ent);
  1033. if (free_val)
  1034. free_val(this->val);
  1035. tor_free(this);
  1036. }
  1037. tor_assert(HT_EMPTY(&map->head));
  1038. HT_CLEAR(digestmap_impl, &map->head);
  1039. tor_free(map);
  1040. }
  1041. void
  1042. strmap_assert_ok(const strmap_t *map)
  1043. {
  1044. tor_assert(!_strmap_impl_HT_REP_IS_BAD(&map->head));
  1045. }
  1046. void
  1047. digestmap_assert_ok(const digestmap_t *map)
  1048. {
  1049. tor_assert(!_digestmap_impl_HT_REP_IS_BAD(&map->head));
  1050. }
  1051. /** Return true iff <b>map</b> has no entries. */
  1052. int
  1053. strmap_isempty(const strmap_t *map)
  1054. {
  1055. return HT_EMPTY(&map->head);
  1056. }
  1057. int
  1058. digestmap_isempty(const digestmap_t *map)
  1059. {
  1060. return HT_EMPTY(&map->head);
  1061. }
  1062. /** Return the number of items in <b>map</b>. */
  1063. int
  1064. strmap_size(const strmap_t *map)
  1065. {
  1066. return HT_SIZE(&map->head);
  1067. }
  1068. int
  1069. digestmap_size(const digestmap_t *map)
  1070. {
  1071. return HT_SIZE(&map->head);
  1072. }
  1073. /** Declare a function called <b>funcname</b> that acts as a find_nth_FOO
  1074. * function for an array of type <b>elt_t</b>*.
  1075. *
  1076. * NOTE: The implementation kind of sucks: It's O(n log n), whereas finding
  1077. * the nth element of a list can be done in O(n). Then again, this
  1078. * implementation is not in critical path, and it is obviously correct. */
  1079. #define IMPLEMENT_ORDER_FUNC(funcname, elt_t) \
  1080. static int \
  1081. _cmp_ ## elt_t(const void *_a, const void *_b) \
  1082. { \
  1083. const elt_t *a = _a, *b = _b; \
  1084. if (*a<*b) \
  1085. return -1; \
  1086. else if (*a>*b) \
  1087. return 1; \
  1088. else \
  1089. return 0; \
  1090. } \
  1091. elt_t \
  1092. funcname(elt_t *array, int n_elements, int nth) \
  1093. { \
  1094. tor_assert(nth >= 0); \
  1095. tor_assert(nth < n_elements); \
  1096. qsort(array, n_elements, sizeof(elt_t), _cmp_ ##elt_t); \
  1097. return array[nth]; \
  1098. }
  1099. IMPLEMENT_ORDER_FUNC(find_nth_int, int)
  1100. IMPLEMENT_ORDER_FUNC(find_nth_time, time_t)
  1101. IMPLEMENT_ORDER_FUNC(find_nth_double, double)
  1102. IMPLEMENT_ORDER_FUNC(find_nth_uint32, uint32_t)
  1103. IMPLEMENT_ORDER_FUNC(find_nth_long, long)
  1104. /** Return a newly allocated digestset_t, optimized to hold a total of
  1105. * <b>max_elements</b> digests with a reasonably low false positive weight. */
  1106. digestset_t *
  1107. digestset_new(int max_elements)
  1108. {
  1109. int n_bits = 1u << (tor_log2(max_elements)+5);
  1110. digestset_t *r = tor_malloc(sizeof(digestset_t));
  1111. r->mask = n_bits - 1;
  1112. r->ba = bitarray_init_zero(n_bits);
  1113. return r;
  1114. }
  1115. /** Free all storage held in <b>set</b>. */
  1116. void
  1117. digestset_free(digestset_t *set)
  1118. {
  1119. bitarray_free(set->ba);
  1120. tor_free(set);
  1121. }