container.c 28 KB

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