container.c 53 KB

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