container.c 42 KB

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