container.c 29 KB

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