container.c 32 KB

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