container.c 43 KB

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