container.c 51 KB

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