container.c 52 KB

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