container.c 53 KB

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