container.c 32 KB

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