container.c 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135
  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, frees them with tor_free(), which
  432. * may not be what you want.. 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. else
  446. tor_free(sl->list[i]);
  447. smartlist_del_keeporder(sl, i--);
  448. }
  449. }
  450. }
  451. /** Assuming the members of <b>sl</b> are in order, return a pointer to the
  452. * member which matches <b>key</b>. Ordering and matching are defined by a
  453. * <b>compare</b> function, which returns 0 on a match; less than 0 if key is
  454. * less than member, and greater than 0 if key is greater then member.
  455. */
  456. void *
  457. smartlist_bsearch(smartlist_t *sl, const void *key,
  458. int (*compare)(const void *key, const void **member))
  459. {
  460. void ** r;
  461. if (!sl->num_used)
  462. return NULL;
  463. r = bsearch(key, sl->list, sl->num_used, sizeof(void*),
  464. (int (*)(const void *, const void *))compare);
  465. return r ? *r : NULL;
  466. }
  467. /** Helper: compare two const char **s. */
  468. static int
  469. _compare_string_ptrs(const void **_a, const void **_b)
  470. {
  471. return strcmp((const char*)*_a, (const char*)*_b);
  472. }
  473. /** Sort a smartlist <b>sl</b> containing strings into lexically ascending
  474. * order. */
  475. void
  476. smartlist_sort_strings(smartlist_t *sl)
  477. {
  478. smartlist_sort(sl, _compare_string_ptrs);
  479. }
  480. /** Remove duplicate strings from a sorted list, and free them with tor_free().
  481. */
  482. void
  483. smartlist_uniq_strings(smartlist_t *sl)
  484. {
  485. smartlist_uniq(sl, _compare_string_ptrs, NULL);
  486. }
  487. /* Heap-based priority queue implementation for O(lg N) insert and remove.
  488. * Recall that the heap property is that, for every index I, h[I] <
  489. * H[LEFT_CHILD[I]] and h[I] < H[RIGHT_CHILD[I]].
  490. */
  491. /* For a 1-indexed array, we would use LEFT_CHILD[x] = 2*x and RIGHT_CHILD[x]
  492. * = 2*x + 1. But this is C, so we have to adjust a little. */
  493. //#define LEFT_CHILD(i) ( ((i)+1)*2 - 1)
  494. //#define RIGHT_CHILD(i) ( ((i)+1)*2 )
  495. //#define PARENT(i) ( ((i)+1)/2 - 1)
  496. #define LEFT_CHILD(i) ( 2*(i) + 1 )
  497. #define RIGHT_CHILD(i) ( 2*(i) + 2 )
  498. #define PARENT(i) ( ((i)-1) / 2 )
  499. /** Helper. <b>sl</b> may have at most one violation of the heap property:
  500. * the item at <b>idx</b> may be greater than one or both of its children.
  501. * Restore the heap property. */
  502. static INLINE void
  503. smartlist_heapify(smartlist_t *sl,
  504. int (*compare)(const void *a, const void *b),
  505. int idx)
  506. {
  507. while (1) {
  508. int left_idx = LEFT_CHILD(idx);
  509. int best_idx;
  510. if (left_idx >= sl->num_used)
  511. return;
  512. if (compare(sl->list[idx],sl->list[left_idx]) < 0)
  513. best_idx = idx;
  514. else
  515. best_idx = left_idx;
  516. if (left_idx+1 < sl->num_used &&
  517. compare(sl->list[left_idx+1],sl->list[best_idx]) < 0)
  518. best_idx = left_idx + 1;
  519. if (best_idx == idx) {
  520. return;
  521. } else {
  522. void *tmp = sl->list[idx];
  523. sl->list[idx] = sl->list[best_idx];
  524. sl->list[best_idx] = tmp;
  525. idx = best_idx;
  526. }
  527. }
  528. }
  529. /** Insert <b>item</b> into the heap stored in <b>sl</b>, where order
  530. * is determined by <b>compare</b>. */
  531. void
  532. smartlist_pqueue_add(smartlist_t *sl,
  533. int (*compare)(const void *a, const void *b),
  534. void *item)
  535. {
  536. int idx;
  537. smartlist_add(sl,item);
  538. for (idx = sl->num_used - 1; idx; ) {
  539. int parent = PARENT(idx);
  540. if (compare(sl->list[idx], sl->list[parent]) < 0) {
  541. void *tmp = sl->list[parent];
  542. sl->list[parent] = sl->list[idx];
  543. sl->list[idx] = tmp;
  544. idx = parent;
  545. } else {
  546. return;
  547. }
  548. }
  549. }
  550. /** Remove and return the top-priority item from the heap stored in <b>sl</b>,
  551. * where order is determined by <b>compare</b>. <b>sl</b> must not be
  552. * empty. */
  553. void *
  554. smartlist_pqueue_pop(smartlist_t *sl,
  555. int (*compare)(const void *a, const void *b))
  556. {
  557. void *top;
  558. tor_assert(sl->num_used);
  559. top = sl->list[0];
  560. if (--sl->num_used) {
  561. sl->list[0] = sl->list[sl->num_used];
  562. smartlist_heapify(sl, compare, 0);
  563. }
  564. return top;
  565. }
  566. /** Assert that the heap property is correctly maintained by the heap stored
  567. * in <b>sl</b>, where order is determined by <b>compare</b>. */
  568. void
  569. smartlist_pqueue_assert_ok(smartlist_t *sl,
  570. int (*compare)(const void *a, const void *b))
  571. {
  572. int i;
  573. for (i = sl->num_used - 1; i > 0; --i) {
  574. tor_assert(compare(sl->list[PARENT(i)], sl->list[i]) <= 0);
  575. }
  576. }
  577. /** Helper: compare two DIGEST_LEN digests. */
  578. static int
  579. _compare_digests(const void **_a, const void **_b)
  580. {
  581. return memcmp((const char*)*_a, (const char*)*_b, DIGEST_LEN);
  582. }
  583. /** Sort the list of DIGEST_LEN-byte digests into ascending order. */
  584. void
  585. smartlist_sort_digests(smartlist_t *sl)
  586. {
  587. smartlist_sort(sl, _compare_digests);
  588. }
  589. /** Remove duplicate digests from a sorted list, and free them with tor_free().
  590. */
  591. void
  592. smartlist_uniq_digests(smartlist_t *sl)
  593. {
  594. smartlist_uniq(sl, _compare_digests, NULL);
  595. }
  596. #define DEFINE_MAP_STRUCTS(maptype, keydecl, prefix) \
  597. typedef struct prefix ## entry_t { \
  598. HT_ENTRY(prefix ## entry_t) node; \
  599. void *val; \
  600. keydecl; \
  601. } prefix ## entry_t; \
  602. struct maptype { \
  603. HT_HEAD(prefix ## impl, prefix ## entry_t) head; \
  604. }
  605. DEFINE_MAP_STRUCTS(strmap_t, char *key, strmap_);
  606. DEFINE_MAP_STRUCTS(digestmap_t, char key[DIGEST_LEN], digestmap_);
  607. /** Helper: compare strmap_entry_t objects by key value. */
  608. static INLINE int
  609. strmap_entries_eq(const strmap_entry_t *a, const strmap_entry_t *b)
  610. {
  611. return !strcmp(a->key, b->key);
  612. }
  613. /** Helper: return a hash value for a strmap_entry_t. */
  614. static INLINE unsigned int
  615. strmap_entry_hash(const strmap_entry_t *a)
  616. {
  617. return ht_string_hash(a->key);
  618. }
  619. /** Helper: compare digestmap_entry_t objects by key value. */
  620. static INLINE int
  621. digestmap_entries_eq(const digestmap_entry_t *a, const digestmap_entry_t *b)
  622. {
  623. return !memcmp(a->key, b->key, DIGEST_LEN);
  624. }
  625. /** Helper: return a hash value for a digest_map_t. */
  626. static INLINE unsigned int
  627. digestmap_entry_hash(const digestmap_entry_t *a)
  628. {
  629. uint32_t *p = (uint32_t*)a->key;
  630. return ht_improve_hash(p[0] ^ p[1] ^ p[2] ^ p[3] ^ p[4]);
  631. }
  632. HT_PROTOTYPE(strmap_impl, strmap_entry_t, node, strmap_entry_hash,
  633. strmap_entries_eq)
  634. HT_GENERATE(strmap_impl, strmap_entry_t, node, strmap_entry_hash,
  635. strmap_entries_eq, 0.6, malloc, realloc, free)
  636. HT_PROTOTYPE(digestmap_impl, digestmap_entry_t, node, digestmap_entry_hash,
  637. digestmap_entries_eq)
  638. HT_GENERATE(digestmap_impl, digestmap_entry_t, node, digestmap_entry_hash,
  639. digestmap_entries_eq, 0.6, malloc, realloc, free)
  640. /** Constructor to create a new empty map from strings to void*'s.
  641. */
  642. strmap_t *
  643. strmap_new(void)
  644. {
  645. strmap_t *result;
  646. result = tor_malloc(sizeof(strmap_t));
  647. HT_INIT(strmap_impl, &result->head);
  648. return result;
  649. }
  650. /** Constructor to create a new empty map from digests to void*'s.
  651. */
  652. digestmap_t *
  653. digestmap_new(void)
  654. {
  655. digestmap_t *result;
  656. result = tor_malloc(sizeof(digestmap_t));
  657. HT_INIT(digestmap_impl, &result->head);
  658. return result;
  659. }
  660. /** Set the current value for <b>key</b> to <b>val</b>. Returns the previous
  661. * value for <b>key</b> if one was set, or NULL if one was not.
  662. *
  663. * This function makes a copy of <b>key</b> if necessary, but not of
  664. * <b>val</b>.
  665. */
  666. void *
  667. strmap_set(strmap_t *map, const char *key, void *val)
  668. {
  669. strmap_entry_t *resolve;
  670. strmap_entry_t search;
  671. void *oldval;
  672. tor_assert(map);
  673. tor_assert(key);
  674. tor_assert(val);
  675. search.key = (char*)key;
  676. resolve = HT_FIND(strmap_impl, &map->head, &search);
  677. if (resolve) {
  678. oldval = resolve->val;
  679. resolve->val = val;
  680. return oldval;
  681. } else {
  682. resolve = tor_malloc_zero(sizeof(strmap_entry_t));
  683. resolve->key = tor_strdup(key);
  684. resolve->val = val;
  685. tor_assert(!HT_FIND(strmap_impl, &map->head, resolve));
  686. HT_INSERT(strmap_impl, &map->head, resolve);
  687. return NULL;
  688. }
  689. }
  690. #define OPTIMIZED_DIGESTMAP_SET
  691. /** Like strmap_set() above but for digestmaps. */
  692. void *
  693. digestmap_set(digestmap_t *map, const char *key, void *val)
  694. {
  695. #ifndef OPTIMIZED_DIGESTMAP_SET
  696. digestmap_entry_t *resolve;
  697. #endif
  698. digestmap_entry_t search;
  699. void *oldval;
  700. tor_assert(map);
  701. tor_assert(key);
  702. tor_assert(val);
  703. memcpy(&search.key, key, DIGEST_LEN);
  704. #ifndef OPTIMIZED_DIGESTMAP_SET
  705. resolve = HT_FIND(digestmap_impl, &map->head, &search);
  706. if (resolve) {
  707. oldval = resolve->val;
  708. resolve->val = val;
  709. return oldval;
  710. } else {
  711. resolve = tor_malloc_zero(sizeof(digestmap_entry_t));
  712. memcpy(resolve->key, key, DIGEST_LEN);
  713. resolve->val = val;
  714. HT_INSERT(digestmap_impl, &map->head, resolve);
  715. return NULL;
  716. }
  717. #else
  718. /* We spend up to 5% of our time in this function, so the code below is
  719. * meant to optimize the check/alloc/set cycle by avoiding the two trips to
  720. * the hash table that we do in the unoptimized code above. (Each of
  721. * HT_INSERT and HT_FIND calls HT_SET_HASH and HT_FIND_P.)
  722. */
  723. _HT_FIND_OR_INSERT(digestmap_impl, node, digestmap_entry_hash, &(map->head),
  724. digestmap_entry_t, &search, ptr,
  725. {
  726. /* we found an entry. */
  727. oldval = (*ptr)->val;
  728. (*ptr)->val = val;
  729. return oldval;
  730. },
  731. {
  732. /* We didn't find the entry. */
  733. digestmap_entry_t *newent =
  734. tor_malloc_zero(sizeof(digestmap_entry_t));
  735. memcpy(newent->key, key, DIGEST_LEN);
  736. newent->val = val;
  737. _HT_FOI_INSERT(node, &(map->head), &search, newent, ptr);
  738. return NULL;
  739. });
  740. #endif
  741. }
  742. /** Return the current value associated with <b>key</b>, or NULL if no
  743. * value is set.
  744. */
  745. void *
  746. strmap_get(const strmap_t *map, const char *key)
  747. {
  748. strmap_entry_t *resolve;
  749. strmap_entry_t search;
  750. tor_assert(map);
  751. tor_assert(key);
  752. search.key = (char*)key;
  753. resolve = HT_FIND(strmap_impl, &map->head, &search);
  754. if (resolve) {
  755. return resolve->val;
  756. } else {
  757. return NULL;
  758. }
  759. }
  760. /** Like strmap_get() above but for digestmaps. */
  761. void *
  762. digestmap_get(const digestmap_t *map, const char *key)
  763. {
  764. digestmap_entry_t *resolve;
  765. digestmap_entry_t search;
  766. tor_assert(map);
  767. tor_assert(key);
  768. memcpy(&search.key, key, DIGEST_LEN);
  769. resolve = HT_FIND(digestmap_impl, &map->head, &search);
  770. if (resolve) {
  771. return resolve->val;
  772. } else {
  773. return NULL;
  774. }
  775. }
  776. /** Remove the value currently associated with <b>key</b> from the map.
  777. * Return the value if one was set, or NULL if there was no entry for
  778. * <b>key</b>.
  779. *
  780. * Note: you must free any storage associated with the returned value.
  781. */
  782. void *
  783. strmap_remove(strmap_t *map, const char *key)
  784. {
  785. strmap_entry_t *resolve;
  786. strmap_entry_t search;
  787. void *oldval;
  788. tor_assert(map);
  789. tor_assert(key);
  790. search.key = (char*)key;
  791. resolve = HT_REMOVE(strmap_impl, &map->head, &search);
  792. if (resolve) {
  793. oldval = resolve->val;
  794. tor_free(resolve->key);
  795. tor_free(resolve);
  796. return oldval;
  797. } else {
  798. return NULL;
  799. }
  800. }
  801. /** Like strmap_remove() above but for digestmaps. */
  802. void *
  803. digestmap_remove(digestmap_t *map, const char *key)
  804. {
  805. digestmap_entry_t *resolve;
  806. digestmap_entry_t search;
  807. void *oldval;
  808. tor_assert(map);
  809. tor_assert(key);
  810. memcpy(&search.key, key, DIGEST_LEN);
  811. resolve = HT_REMOVE(digestmap_impl, &map->head, &search);
  812. if (resolve) {
  813. oldval = resolve->val;
  814. tor_free(resolve);
  815. return oldval;
  816. } else {
  817. return NULL;
  818. }
  819. }
  820. /** Same as strmap_set, but first converts <b>key</b> to lowercase. */
  821. void *
  822. strmap_set_lc(strmap_t *map, const char *key, void *val)
  823. {
  824. /* We could be a little faster by using strcasecmp instead, and a separate
  825. * type, but I don't think it matters. */
  826. void *v;
  827. char *lc_key = tor_strdup(key);
  828. tor_strlower(lc_key);
  829. v = strmap_set(map,lc_key,val);
  830. tor_free(lc_key);
  831. return v;
  832. }
  833. /** Same as strmap_get, but first converts <b>key</b> to lowercase. */
  834. void *
  835. strmap_get_lc(const strmap_t *map, const char *key)
  836. {
  837. void *v;
  838. char *lc_key = tor_strdup(key);
  839. tor_strlower(lc_key);
  840. v = strmap_get(map,lc_key);
  841. tor_free(lc_key);
  842. return v;
  843. }
  844. /** Same as strmap_remove, but first converts <b>key</b> to lowercase */
  845. void *
  846. strmap_remove_lc(strmap_t *map, const char *key)
  847. {
  848. void *v;
  849. char *lc_key = tor_strdup(key);
  850. tor_strlower(lc_key);
  851. v = strmap_remove(map,lc_key);
  852. tor_free(lc_key);
  853. return v;
  854. }
  855. /** return an <b>iterator</b> pointer to the front of a map.
  856. *
  857. * Iterator example:
  858. *
  859. * \code
  860. * // uppercase values in "map", removing empty values.
  861. *
  862. * strmap_iter_t *iter;
  863. * const char *key;
  864. * void *val;
  865. * char *cp;
  866. *
  867. * for (iter = strmap_iter_init(map); !strmap_iter_done(iter); ) {
  868. * strmap_iter_get(iter, &key, &val);
  869. * cp = (char*)val;
  870. * if (!*cp) {
  871. * iter = strmap_iter_next_rmv(iter);
  872. * free(val);
  873. * } else {
  874. * for (;*cp;cp++) *cp = TOR_TOUPPER(*cp);
  875. * iter = strmap_iter_next(iter);
  876. * }
  877. * }
  878. * \endcode
  879. *
  880. */
  881. strmap_iter_t *
  882. strmap_iter_init(strmap_t *map)
  883. {
  884. tor_assert(map);
  885. return HT_START(strmap_impl, &map->head);
  886. }
  887. digestmap_iter_t *
  888. digestmap_iter_init(digestmap_t *map)
  889. {
  890. tor_assert(map);
  891. return HT_START(digestmap_impl, &map->head);
  892. }
  893. /** Advance the iterator <b>iter</b> for map a single step to the next entry.
  894. */
  895. strmap_iter_t *
  896. strmap_iter_next(strmap_t *map, strmap_iter_t *iter)
  897. {
  898. tor_assert(map);
  899. tor_assert(iter);
  900. return HT_NEXT(strmap_impl, &map->head, iter);
  901. }
  902. digestmap_iter_t *
  903. digestmap_iter_next(digestmap_t *map, digestmap_iter_t *iter)
  904. {
  905. tor_assert(map);
  906. tor_assert(iter);
  907. return HT_NEXT(digestmap_impl, &map->head, iter);
  908. }
  909. /** Advance the iterator <b>iter</b> a single step to the next entry, removing
  910. * the current entry.
  911. */
  912. strmap_iter_t *
  913. strmap_iter_next_rmv(strmap_t *map, strmap_iter_t *iter)
  914. {
  915. strmap_entry_t *rmv;
  916. tor_assert(map);
  917. tor_assert(iter);
  918. tor_assert(*iter);
  919. rmv = *iter;
  920. iter = HT_NEXT_RMV(strmap_impl, &map->head, iter);
  921. tor_free(rmv->key);
  922. tor_free(rmv);
  923. return iter;
  924. }
  925. digestmap_iter_t *
  926. digestmap_iter_next_rmv(digestmap_t *map, digestmap_iter_t *iter)
  927. {
  928. digestmap_entry_t *rmv;
  929. tor_assert(map);
  930. tor_assert(iter);
  931. tor_assert(*iter);
  932. rmv = *iter;
  933. iter = HT_NEXT_RMV(digestmap_impl, &map->head, iter);
  934. tor_free(rmv);
  935. return iter;
  936. }
  937. /** Set *keyp and *valp to the current entry pointed to by iter.
  938. */
  939. void
  940. strmap_iter_get(strmap_iter_t *iter, const char **keyp, void **valp)
  941. {
  942. tor_assert(iter);
  943. tor_assert(*iter);
  944. tor_assert(keyp);
  945. tor_assert(valp);
  946. *keyp = (*iter)->key;
  947. *valp = (*iter)->val;
  948. }
  949. void
  950. digestmap_iter_get(digestmap_iter_t *iter, const char **keyp, void **valp)
  951. {
  952. tor_assert(iter);
  953. tor_assert(*iter);
  954. tor_assert(keyp);
  955. tor_assert(valp);
  956. *keyp = (*iter)->key;
  957. *valp = (*iter)->val;
  958. }
  959. /** Return true iff iter has advanced past the last entry of map.
  960. */
  961. int
  962. strmap_iter_done(strmap_iter_t *iter)
  963. {
  964. return iter == NULL;
  965. }
  966. int
  967. digestmap_iter_done(digestmap_iter_t *iter)
  968. {
  969. return iter == NULL;
  970. }
  971. /** Remove all entries from <b>map</b>, and deallocate storage for those
  972. * entries. If free_val is provided, it is invoked on every value in
  973. * <b>map</b>.
  974. */
  975. void
  976. strmap_free(strmap_t *map, void (*free_val)(void*))
  977. {
  978. strmap_entry_t **ent, **next, *this;
  979. for (ent = HT_START(strmap_impl, &map->head); ent != NULL; ent = next) {
  980. this = *ent;
  981. next = HT_NEXT_RMV(strmap_impl, &map->head, ent);
  982. tor_free(this->key);
  983. if (free_val)
  984. free_val(this->val);
  985. tor_free(this);
  986. }
  987. tor_assert(HT_EMPTY(&map->head));
  988. HT_CLEAR(strmap_impl, &map->head);
  989. tor_free(map);
  990. }
  991. void
  992. digestmap_free(digestmap_t *map, void (*free_val)(void*))
  993. {
  994. digestmap_entry_t **ent, **next, *this;
  995. for (ent = HT_START(digestmap_impl, &map->head); ent != NULL; ent = next) {
  996. this = *ent;
  997. next = HT_NEXT_RMV(digestmap_impl, &map->head, ent);
  998. if (free_val)
  999. free_val(this->val);
  1000. tor_free(this);
  1001. }
  1002. tor_assert(HT_EMPTY(&map->head));
  1003. HT_CLEAR(digestmap_impl, &map->head);
  1004. tor_free(map);
  1005. }
  1006. void
  1007. strmap_assert_ok(const strmap_t *map)
  1008. {
  1009. tor_assert(!_strmap_impl_HT_REP_IS_BAD(&map->head));
  1010. }
  1011. void
  1012. digestmap_assert_ok(const digestmap_t *map)
  1013. {
  1014. tor_assert(!_digestmap_impl_HT_REP_IS_BAD(&map->head));
  1015. }
  1016. /** Return true iff <b>map</b> has no entries. */
  1017. int
  1018. strmap_isempty(const strmap_t *map)
  1019. {
  1020. return HT_EMPTY(&map->head);
  1021. }
  1022. int
  1023. digestmap_isempty(const digestmap_t *map)
  1024. {
  1025. return HT_EMPTY(&map->head);
  1026. }
  1027. /** Return the number of items in <b>map</b>. */
  1028. int
  1029. strmap_size(const strmap_t *map)
  1030. {
  1031. return HT_SIZE(&map->head);
  1032. }
  1033. int
  1034. digestmap_size(const digestmap_t *map)
  1035. {
  1036. return HT_SIZE(&map->head);
  1037. }