container.c 34 KB

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