container.c 32 KB

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