container.c 39 KB

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