container.c 42 KB

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