smartlist.c 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096
  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 "lib/malloc/util_malloc.h"
  13. #include "lib/container/smartlist.h"
  14. #include "lib/err/torerr.h"
  15. #include "lib/malloc/util_malloc.h"
  16. #include "lib/defs/digest_sizes.h"
  17. #include "lib/ctime/di_ops.h"
  18. #include "lib/string/util_string.h"
  19. #include <stdlib.h>
  20. #include <string.h>
  21. /** All newly allocated smartlists have this capacity. */
  22. #define SMARTLIST_DEFAULT_CAPACITY 16
  23. /** Allocate and return an empty smartlist.
  24. */
  25. MOCK_IMPL(smartlist_t *,
  26. smartlist_new,(void))
  27. {
  28. smartlist_t *sl = tor_malloc(sizeof(smartlist_t));
  29. sl->num_used = 0;
  30. sl->capacity = SMARTLIST_DEFAULT_CAPACITY;
  31. sl->list = tor_calloc(sizeof(void *), sl->capacity);
  32. return sl;
  33. }
  34. /** Deallocate a smartlist. Does not release storage associated with the
  35. * list's elements.
  36. */
  37. MOCK_IMPL(void,
  38. smartlist_free_,(smartlist_t *sl))
  39. {
  40. if (!sl)
  41. return;
  42. tor_free(sl->list);
  43. tor_free(sl);
  44. }
  45. /** Remove all elements from the list.
  46. */
  47. void
  48. smartlist_clear(smartlist_t *sl)
  49. {
  50. memset(sl->list, 0, sizeof(void *) * sl->num_used);
  51. sl->num_used = 0;
  52. }
  53. #if SIZE_MAX < INT_MAX
  54. #error "We don't support systems where size_t is smaller than int."
  55. #endif
  56. /** Make sure that <b>sl</b> can hold at least <b>size</b> entries. */
  57. static inline void
  58. smartlist_ensure_capacity(smartlist_t *sl, size_t size)
  59. {
  60. /* Set MAX_CAPACITY to MIN(INT_MAX, SIZE_MAX / sizeof(void*)) */
  61. #if (SIZE_MAX/SIZEOF_VOID_P) > INT_MAX
  62. #define MAX_CAPACITY (INT_MAX)
  63. #else
  64. #define MAX_CAPACITY (int)((SIZE_MAX / (sizeof(void*))))
  65. #endif
  66. raw_assert(size <= MAX_CAPACITY);
  67. if (size > (size_t) sl->capacity) {
  68. size_t higher = (size_t) sl->capacity;
  69. if (PREDICT_UNLIKELY(size > MAX_CAPACITY/2)) {
  70. higher = MAX_CAPACITY;
  71. } else {
  72. while (size > higher)
  73. higher *= 2;
  74. }
  75. sl->list = tor_reallocarray(sl->list, sizeof(void *),
  76. ((size_t)higher));
  77. memset(sl->list + sl->capacity, 0,
  78. sizeof(void *) * (higher - sl->capacity));
  79. sl->capacity = (int) higher;
  80. }
  81. #undef ASSERT_CAPACITY
  82. #undef MAX_CAPACITY
  83. }
  84. /** Append element to the end of the list. */
  85. void
  86. smartlist_add(smartlist_t *sl, void *element)
  87. {
  88. smartlist_ensure_capacity(sl, ((size_t) sl->num_used)+1);
  89. sl->list[sl->num_used++] = element;
  90. }
  91. /** Append each element from S2 to the end of S1. */
  92. void
  93. smartlist_add_all(smartlist_t *s1, const smartlist_t *s2)
  94. {
  95. size_t new_size = (size_t)s1->num_used + (size_t)s2->num_used;
  96. tor_assert(new_size >= (size_t) s1->num_used); /* check for overflow. */
  97. smartlist_ensure_capacity(s1, new_size);
  98. memcpy(s1->list + s1->num_used, s2->list, s2->num_used*sizeof(void*));
  99. tor_assert(new_size <= INT_MAX); /* redundant. */
  100. s1->num_used = (int) new_size;
  101. }
  102. /** Append a copy of string to sl */
  103. void
  104. smartlist_add_strdup(struct smartlist_t *sl, const char *string)
  105. {
  106. char *copy;
  107. copy = tor_strdup(string);
  108. smartlist_add(sl, copy);
  109. }
  110. /** Remove all elements E from sl such that E==element. Preserve
  111. * the order of any elements before E, but elements after E can be
  112. * rearranged.
  113. */
  114. void
  115. smartlist_remove(smartlist_t *sl, const void *element)
  116. {
  117. int i;
  118. if (element == NULL)
  119. return;
  120. for (i=0; i < sl->num_used; i++)
  121. if (sl->list[i] == element) {
  122. sl->list[i] = sl->list[--sl->num_used]; /* swap with the end */
  123. i--; /* so we process the new i'th element */
  124. sl->list[sl->num_used] = NULL;
  125. }
  126. }
  127. /** As <b>smartlist_remove</b>, but do not change the order of
  128. * any elements not removed */
  129. void
  130. smartlist_remove_keeporder(smartlist_t *sl, const void *element)
  131. {
  132. int i, j, num_used_orig = sl->num_used;
  133. if (element == NULL)
  134. return;
  135. for (i=j=0; j < num_used_orig; ++j) {
  136. if (sl->list[j] == element) {
  137. --sl->num_used;
  138. } else {
  139. sl->list[i++] = sl->list[j];
  140. }
  141. }
  142. }
  143. /** If <b>sl</b> is nonempty, remove and return the final element. Otherwise,
  144. * return NULL. */
  145. void *
  146. smartlist_pop_last(smartlist_t *sl)
  147. {
  148. tor_assert(sl);
  149. if (sl->num_used) {
  150. void *tmp = sl->list[--sl->num_used];
  151. sl->list[sl->num_used] = NULL;
  152. return tmp;
  153. } else
  154. return NULL;
  155. }
  156. /** Reverse the order of the items in <b>sl</b>. */
  157. void
  158. smartlist_reverse(smartlist_t *sl)
  159. {
  160. int i, j;
  161. void *tmp;
  162. tor_assert(sl);
  163. for (i = 0, j = sl->num_used-1; i < j; ++i, --j) {
  164. tmp = sl->list[i];
  165. sl->list[i] = sl->list[j];
  166. sl->list[j] = tmp;
  167. }
  168. }
  169. /** If there are any strings in sl equal to element, remove and free them.
  170. * Does not preserve order. */
  171. void
  172. smartlist_string_remove(smartlist_t *sl, const char *element)
  173. {
  174. int i;
  175. tor_assert(sl);
  176. tor_assert(element);
  177. for (i = 0; i < sl->num_used; ++i) {
  178. if (!strcmp(element, sl->list[i])) {
  179. tor_free(sl->list[i]);
  180. sl->list[i] = sl->list[--sl->num_used]; /* swap with the end */
  181. i--; /* so we process the new i'th element */
  182. sl->list[sl->num_used] = NULL;
  183. }
  184. }
  185. }
  186. /** Return true iff some element E of sl has E==element.
  187. */
  188. int
  189. smartlist_contains(const smartlist_t *sl, const void *element)
  190. {
  191. int i;
  192. for (i=0; i < sl->num_used; i++)
  193. if (sl->list[i] == element)
  194. return 1;
  195. return 0;
  196. }
  197. /** Return true iff <b>sl</b> has some element E such that
  198. * !strcmp(E,<b>element</b>)
  199. */
  200. int
  201. smartlist_contains_string(const smartlist_t *sl, const char *element)
  202. {
  203. int i;
  204. if (!sl) return 0;
  205. for (i=0; i < sl->num_used; i++)
  206. if (strcmp((const char*)sl->list[i],element)==0)
  207. return 1;
  208. return 0;
  209. }
  210. /** If <b>element</b> is equal to an element of <b>sl</b>, return that
  211. * element's index. Otherwise, return -1. */
  212. int
  213. smartlist_string_pos(const smartlist_t *sl, const char *element)
  214. {
  215. int i;
  216. if (!sl) return -1;
  217. for (i=0; i < sl->num_used; i++)
  218. if (strcmp((const char*)sl->list[i],element)==0)
  219. return i;
  220. return -1;
  221. }
  222. /** If <b>element</b> is the same pointer as an element of <b>sl</b>, return
  223. * that element's index. Otherwise, return -1. */
  224. int
  225. smartlist_pos(const smartlist_t *sl, const void *element)
  226. {
  227. int i;
  228. if (!sl) return -1;
  229. for (i=0; i < sl->num_used; i++)
  230. if (element == sl->list[i])
  231. return i;
  232. return -1;
  233. }
  234. /** Return true iff <b>sl</b> has some element E such that
  235. * !strcasecmp(E,<b>element</b>)
  236. */
  237. int
  238. smartlist_contains_string_case(const smartlist_t *sl, const char *element)
  239. {
  240. int i;
  241. if (!sl) return 0;
  242. for (i=0; i < sl->num_used; i++)
  243. if (strcasecmp((const char*)sl->list[i],element)==0)
  244. return 1;
  245. return 0;
  246. }
  247. /** Return true iff <b>sl</b> has some element E such that E is equal
  248. * to the decimal encoding of <b>num</b>.
  249. */
  250. int
  251. smartlist_contains_int_as_string(const smartlist_t *sl, int num)
  252. {
  253. char buf[32]; /* long enough for 64-bit int, and then some. */
  254. tor_snprintf(buf,sizeof(buf),"%d", num);
  255. return smartlist_contains_string(sl, buf);
  256. }
  257. /** Return true iff the two lists contain the same strings in the same
  258. * order, or if they are both NULL. */
  259. int
  260. smartlist_strings_eq(const smartlist_t *sl1, const smartlist_t *sl2)
  261. {
  262. if (sl1 == NULL)
  263. return sl2 == NULL;
  264. if (sl2 == NULL)
  265. return 0;
  266. if (smartlist_len(sl1) != smartlist_len(sl2))
  267. return 0;
  268. SMARTLIST_FOREACH(sl1, const char *, cp1, {
  269. const char *cp2 = smartlist_get(sl2, cp1_sl_idx);
  270. if (strcmp(cp1, cp2))
  271. return 0;
  272. });
  273. return 1;
  274. }
  275. /** Return true iff the two lists contain the same int pointer values in
  276. * the same order, or if they are both NULL. */
  277. int
  278. smartlist_ints_eq(const smartlist_t *sl1, const smartlist_t *sl2)
  279. {
  280. if (sl1 == NULL)
  281. return sl2 == NULL;
  282. if (sl2 == NULL)
  283. return 0;
  284. if (smartlist_len(sl1) != smartlist_len(sl2))
  285. return 0;
  286. SMARTLIST_FOREACH(sl1, int *, cp1, {
  287. int *cp2 = smartlist_get(sl2, cp1_sl_idx);
  288. if (*cp1 != *cp2)
  289. return 0;
  290. });
  291. return 1;
  292. }
  293. /** Return true iff <b>sl</b> has some element E such that
  294. * tor_memeq(E,<b>element</b>,DIGEST_LEN)
  295. */
  296. int
  297. smartlist_contains_digest(const smartlist_t *sl, const char *element)
  298. {
  299. int i;
  300. if (!sl) return 0;
  301. for (i=0; i < sl->num_used; i++)
  302. if (tor_memeq((const char*)sl->list[i],element,DIGEST_LEN))
  303. return 1;
  304. return 0;
  305. }
  306. /** Return true iff some element E of sl2 has smartlist_contains(sl1,E).
  307. */
  308. int
  309. smartlist_overlap(const smartlist_t *sl1, const smartlist_t *sl2)
  310. {
  311. int i;
  312. for (i=0; i < sl2->num_used; i++)
  313. if (smartlist_contains(sl1, sl2->list[i]))
  314. return 1;
  315. return 0;
  316. }
  317. /** Remove every element E of sl1 such that !smartlist_contains(sl2,E).
  318. * Does not preserve the order of sl1.
  319. */
  320. void
  321. smartlist_intersect(smartlist_t *sl1, const smartlist_t *sl2)
  322. {
  323. int i;
  324. for (i=0; i < sl1->num_used; i++)
  325. if (!smartlist_contains(sl2, sl1->list[i])) {
  326. sl1->list[i] = sl1->list[--sl1->num_used]; /* swap with the end */
  327. i--; /* so we process the new i'th element */
  328. sl1->list[sl1->num_used] = NULL;
  329. }
  330. }
  331. /** Remove every element E of sl1 such that smartlist_contains(sl2,E).
  332. * Does not preserve the order of sl1.
  333. */
  334. void
  335. smartlist_subtract(smartlist_t *sl1, const smartlist_t *sl2)
  336. {
  337. int i;
  338. for (i=0; i < sl2->num_used; i++)
  339. smartlist_remove(sl1, sl2->list[i]);
  340. }
  341. /** Remove the <b>idx</b>th element of sl; if idx is not the last
  342. * element, swap the last element of sl into the <b>idx</b>th space.
  343. */
  344. void
  345. smartlist_del(smartlist_t *sl, int idx)
  346. {
  347. tor_assert(sl);
  348. tor_assert(idx>=0);
  349. tor_assert(idx < sl->num_used);
  350. sl->list[idx] = sl->list[--sl->num_used];
  351. sl->list[sl->num_used] = NULL;
  352. }
  353. /** Remove the <b>idx</b>th element of sl; if idx is not the last element,
  354. * moving all subsequent elements back one space. Return the old value
  355. * of the <b>idx</b>th element.
  356. */
  357. void
  358. smartlist_del_keeporder(smartlist_t *sl, int idx)
  359. {
  360. tor_assert(sl);
  361. tor_assert(idx>=0);
  362. tor_assert(idx < sl->num_used);
  363. --sl->num_used;
  364. if (idx < sl->num_used)
  365. memmove(sl->list+idx, sl->list+idx+1, sizeof(void*)*(sl->num_used-idx));
  366. sl->list[sl->num_used] = NULL;
  367. }
  368. /** Insert the value <b>val</b> as the new <b>idx</b>th element of
  369. * <b>sl</b>, moving all items previously at <b>idx</b> or later
  370. * forward one space.
  371. */
  372. void
  373. smartlist_insert(smartlist_t *sl, int idx, void *val)
  374. {
  375. tor_assert(sl);
  376. tor_assert(idx>=0);
  377. tor_assert(idx <= sl->num_used);
  378. if (idx == sl->num_used) {
  379. smartlist_add(sl, val);
  380. } else {
  381. smartlist_ensure_capacity(sl, ((size_t) sl->num_used)+1);
  382. /* Move other elements away */
  383. if (idx < sl->num_used)
  384. memmove(sl->list + idx + 1, sl->list + idx,
  385. sizeof(void*)*(sl->num_used-idx));
  386. sl->num_used++;
  387. sl->list[idx] = val;
  388. }
  389. }
  390. /**
  391. * Split a string <b>str</b> along all occurrences of <b>sep</b>,
  392. * appending the (newly allocated) split strings, in order, to
  393. * <b>sl</b>. Return the number of strings added to <b>sl</b>.
  394. *
  395. * If <b>flags</b>&amp;SPLIT_SKIP_SPACE is true, remove initial and
  396. * trailing space from each entry.
  397. * If <b>flags</b>&amp;SPLIT_IGNORE_BLANK is true, remove any entries
  398. * of length 0.
  399. * If <b>flags</b>&amp;SPLIT_STRIP_SPACE is true, strip spaces from each
  400. * split string.
  401. *
  402. * If <b>max</b>\>0, divide the string into no more than <b>max</b> pieces. If
  403. * <b>sep</b> is NULL, split on any sequence of horizontal space.
  404. */
  405. int
  406. smartlist_split_string(smartlist_t *sl, const char *str, const char *sep,
  407. int flags, int max)
  408. {
  409. const char *cp, *end, *next;
  410. int n = 0;
  411. tor_assert(sl);
  412. tor_assert(str);
  413. cp = str;
  414. while (1) {
  415. if (flags&SPLIT_SKIP_SPACE) {
  416. while (TOR_ISSPACE(*cp)) ++cp;
  417. }
  418. if (max>0 && n == max-1) {
  419. end = strchr(cp,'\0');
  420. } else if (sep) {
  421. end = strstr(cp,sep);
  422. if (!end)
  423. end = strchr(cp,'\0');
  424. } else {
  425. for (end = cp; *end && *end != '\t' && *end != ' '; ++end)
  426. ;
  427. }
  428. tor_assert(end);
  429. if (!*end) {
  430. next = NULL;
  431. } else if (sep) {
  432. next = end+strlen(sep);
  433. } else {
  434. next = end+1;
  435. while (*next == '\t' || *next == ' ')
  436. ++next;
  437. }
  438. if (flags&SPLIT_SKIP_SPACE) {
  439. while (end > cp && TOR_ISSPACE(*(end-1)))
  440. --end;
  441. }
  442. if (end != cp || !(flags&SPLIT_IGNORE_BLANK)) {
  443. char *string = tor_strndup(cp, end-cp);
  444. if (flags&SPLIT_STRIP_SPACE)
  445. tor_strstrip(string, " ");
  446. smartlist_add(sl, string);
  447. ++n;
  448. }
  449. if (!next)
  450. break;
  451. cp = next;
  452. }
  453. return n;
  454. }
  455. /** Allocate and return a new string containing the concatenation of
  456. * the elements of <b>sl</b>, in order, separated by <b>join</b>. If
  457. * <b>terminate</b> is true, also terminate the string with <b>join</b>.
  458. * If <b>len_out</b> is not NULL, set <b>len_out</b> to the length of
  459. * the returned string. Requires that every element of <b>sl</b> is
  460. * NUL-terminated string.
  461. */
  462. char *
  463. smartlist_join_strings(smartlist_t *sl, const char *join,
  464. int terminate, size_t *len_out)
  465. {
  466. return smartlist_join_strings2(sl,join,strlen(join),terminate,len_out);
  467. }
  468. /** As smartlist_join_strings, but instead of separating/terminated with a
  469. * NUL-terminated string <b>join</b>, uses the <b>join_len</b>-byte sequence
  470. * at <b>join</b>. (Useful for generating a sequence of NUL-terminated
  471. * strings.)
  472. */
  473. char *
  474. smartlist_join_strings2(smartlist_t *sl, const char *join,
  475. size_t join_len, int terminate, size_t *len_out)
  476. {
  477. int i;
  478. size_t n = 0;
  479. char *r = NULL, *dst, *src;
  480. tor_assert(sl);
  481. tor_assert(join);
  482. if (terminate)
  483. n = join_len;
  484. for (i = 0; i < sl->num_used; ++i) {
  485. n += strlen(sl->list[i]);
  486. if (i+1 < sl->num_used) /* avoid double-counting the last one */
  487. n += join_len;
  488. }
  489. dst = r = tor_malloc(n+1);
  490. for (i = 0; i < sl->num_used; ) {
  491. for (src = sl->list[i]; *src; )
  492. *dst++ = *src++;
  493. if (++i < sl->num_used) {
  494. memcpy(dst, join, join_len);
  495. dst += join_len;
  496. }
  497. }
  498. if (terminate) {
  499. memcpy(dst, join, join_len);
  500. dst += join_len;
  501. }
  502. *dst = '\0';
  503. if (len_out)
  504. *len_out = dst-r;
  505. return r;
  506. }
  507. /** Sort the members of <b>sl</b> into an order defined by
  508. * the ordering function <b>compare</b>, which returns less then 0 if a
  509. * precedes b, greater than 0 if b precedes a, and 0 if a 'equals' b.
  510. */
  511. void
  512. smartlist_sort(smartlist_t *sl, int (*compare)(const void **a, const void **b))
  513. {
  514. if (!sl->num_used)
  515. return;
  516. qsort(sl->list, sl->num_used, sizeof(void*),
  517. (int (*)(const void *,const void*))compare);
  518. }
  519. /** Given a smartlist <b>sl</b> sorted with the function <b>compare</b>,
  520. * return the most frequent member in the list. Break ties in favor of
  521. * later elements. If the list is empty, return NULL. If count_out is
  522. * non-null, set it to the count of the most frequent member.
  523. */
  524. void *
  525. smartlist_get_most_frequent_(const smartlist_t *sl,
  526. int (*compare)(const void **a, const void **b),
  527. int *count_out)
  528. {
  529. const void *most_frequent = NULL;
  530. int most_frequent_count = 0;
  531. const void *cur = NULL;
  532. int i, count=0;
  533. if (!sl->num_used) {
  534. if (count_out)
  535. *count_out = 0;
  536. return NULL;
  537. }
  538. for (i = 0; i < sl->num_used; ++i) {
  539. const void *item = sl->list[i];
  540. if (cur && 0 == compare(&cur, &item)) {
  541. ++count;
  542. } else {
  543. if (cur && count >= most_frequent_count) {
  544. most_frequent = cur;
  545. most_frequent_count = count;
  546. }
  547. cur = item;
  548. count = 1;
  549. }
  550. }
  551. if (cur && count >= most_frequent_count) {
  552. most_frequent = cur;
  553. most_frequent_count = count;
  554. }
  555. if (count_out)
  556. *count_out = most_frequent_count;
  557. return (void*)most_frequent;
  558. }
  559. /** Given a sorted smartlist <b>sl</b> and the comparison function used to
  560. * sort it, remove all duplicate members. If free_fn is provided, calls
  561. * free_fn on each duplicate. Otherwise, just removes them. Preserves order.
  562. */
  563. void
  564. smartlist_uniq(smartlist_t *sl,
  565. int (*compare)(const void **a, const void **b),
  566. void (*free_fn)(void *a))
  567. {
  568. int i;
  569. for (i=1; i < sl->num_used; ++i) {
  570. if (compare((const void **)&(sl->list[i-1]),
  571. (const void **)&(sl->list[i])) == 0) {
  572. if (free_fn)
  573. free_fn(sl->list[i]);
  574. smartlist_del_keeporder(sl, i--);
  575. }
  576. }
  577. }
  578. /** Assuming the members of <b>sl</b> are in order, return a pointer to the
  579. * member that matches <b>key</b>. Ordering and matching are defined by a
  580. * <b>compare</b> function that returns 0 on a match; less than 0 if key is
  581. * less than member, and greater than 0 if key is greater then member.
  582. */
  583. void *
  584. smartlist_bsearch(smartlist_t *sl, const void *key,
  585. int (*compare)(const void *key, const void **member))
  586. {
  587. int found, idx;
  588. idx = smartlist_bsearch_idx(sl, key, compare, &found);
  589. return found ? smartlist_get(sl, idx) : NULL;
  590. }
  591. /** Assuming the members of <b>sl</b> are in order, return the index of the
  592. * member that matches <b>key</b>. If no member matches, return the index of
  593. * the first member greater than <b>key</b>, or smartlist_len(sl) if no member
  594. * is greater than <b>key</b>. Set <b>found_out</b> to true on a match, to
  595. * false otherwise. Ordering and matching are defined by a <b>compare</b>
  596. * function that returns 0 on a match; less than 0 if key is less than member,
  597. * and greater than 0 if key is greater then member.
  598. */
  599. int
  600. smartlist_bsearch_idx(const smartlist_t *sl, const void *key,
  601. int (*compare)(const void *key, const void **member),
  602. int *found_out)
  603. {
  604. int hi, lo, cmp, mid, len, diff;
  605. tor_assert(sl);
  606. tor_assert(compare);
  607. tor_assert(found_out);
  608. len = smartlist_len(sl);
  609. /* Check for the trivial case of a zero-length list */
  610. if (len == 0) {
  611. *found_out = 0;
  612. /* We already know smartlist_len(sl) is 0 in this case */
  613. return 0;
  614. }
  615. /* Okay, we have a real search to do */
  616. tor_assert(len > 0);
  617. lo = 0;
  618. hi = len - 1;
  619. /*
  620. * These invariants are always true:
  621. *
  622. * For all i such that 0 <= i < lo, sl[i] < key
  623. * For all i such that hi < i <= len, sl[i] > key
  624. */
  625. while (lo <= hi) {
  626. diff = hi - lo;
  627. /*
  628. * We want mid = (lo + hi) / 2, but that could lead to overflow, so
  629. * instead diff = hi - lo (non-negative because of loop condition), and
  630. * then hi = lo + diff, mid = (lo + lo + diff) / 2 = lo + (diff / 2).
  631. */
  632. mid = lo + (diff / 2);
  633. cmp = compare(key, (const void**) &(sl->list[mid]));
  634. if (cmp == 0) {
  635. /* sl[mid] == key; we found it */
  636. *found_out = 1;
  637. return mid;
  638. } else if (cmp > 0) {
  639. /*
  640. * key > sl[mid] and an index i such that sl[i] == key must
  641. * have i > mid if it exists.
  642. */
  643. /*
  644. * Since lo <= mid <= hi, hi can only decrease on each iteration (by
  645. * being set to mid - 1) and hi is initially len - 1, mid < len should
  646. * always hold, and this is not symmetric with the left end of list
  647. * mid > 0 test below. A key greater than the right end of the list
  648. * should eventually lead to lo == hi == mid == len - 1, and then
  649. * we set lo to len below and fall out to the same exit we hit for
  650. * a key in the middle of the list but not matching. Thus, we just
  651. * assert for consistency here rather than handle a mid == len case.
  652. */
  653. tor_assert(mid < len);
  654. /* Move lo to the element immediately after sl[mid] */
  655. lo = mid + 1;
  656. } else {
  657. /* This should always be true in this case */
  658. tor_assert(cmp < 0);
  659. /*
  660. * key < sl[mid] and an index i such that sl[i] == key must
  661. * have i < mid if it exists.
  662. */
  663. if (mid > 0) {
  664. /* Normal case, move hi to the element immediately before sl[mid] */
  665. hi = mid - 1;
  666. } else {
  667. /* These should always be true in this case */
  668. tor_assert(mid == lo);
  669. tor_assert(mid == 0);
  670. /*
  671. * We were at the beginning of the list and concluded that every
  672. * element e compares e > key.
  673. */
  674. *found_out = 0;
  675. return 0;
  676. }
  677. }
  678. }
  679. /*
  680. * lo > hi; we have no element matching key but we have elements falling
  681. * on both sides of it. The lo index points to the first element > key.
  682. */
  683. tor_assert(lo == hi + 1); /* All other cases should have been handled */
  684. tor_assert(lo >= 0);
  685. tor_assert(lo <= len);
  686. tor_assert(hi >= 0);
  687. tor_assert(hi <= len);
  688. if (lo < len) {
  689. cmp = compare(key, (const void **) &(sl->list[lo]));
  690. tor_assert(cmp < 0);
  691. } else {
  692. cmp = compare(key, (const void **) &(sl->list[len-1]));
  693. tor_assert(cmp > 0);
  694. }
  695. *found_out = 0;
  696. return lo;
  697. }
  698. /** Helper: compare two const char **s. */
  699. static int
  700. compare_string_ptrs_(const void **_a, const void **_b)
  701. {
  702. return strcmp((const char*)*_a, (const char*)*_b);
  703. }
  704. /** Sort a smartlist <b>sl</b> containing strings into lexically ascending
  705. * order. */
  706. void
  707. smartlist_sort_strings(smartlist_t *sl)
  708. {
  709. smartlist_sort(sl, compare_string_ptrs_);
  710. }
  711. /** Return the most frequent string in the sorted list <b>sl</b> */
  712. const char *
  713. smartlist_get_most_frequent_string(smartlist_t *sl)
  714. {
  715. return smartlist_get_most_frequent(sl, compare_string_ptrs_);
  716. }
  717. /** Return the most frequent string in the sorted list <b>sl</b>.
  718. * If <b>count_out</b> is provided, set <b>count_out</b> to the
  719. * number of times that string appears.
  720. */
  721. const char *
  722. smartlist_get_most_frequent_string_(smartlist_t *sl, int *count_out)
  723. {
  724. return smartlist_get_most_frequent_(sl, compare_string_ptrs_, count_out);
  725. }
  726. /** Remove duplicate strings from a sorted list, and free them with tor_free().
  727. */
  728. void
  729. smartlist_uniq_strings(smartlist_t *sl)
  730. {
  731. smartlist_uniq(sl, compare_string_ptrs_, tor_free_);
  732. }
  733. /** Helper: compare two pointers. */
  734. static int
  735. compare_ptrs_(const void **_a, const void **_b)
  736. {
  737. const void *a = *_a, *b = *_b;
  738. if (a<b)
  739. return -1;
  740. else if (a==b)
  741. return 0;
  742. else
  743. return 1;
  744. }
  745. /** Sort <b>sl</b> in ascending order of the pointers it contains. */
  746. void
  747. smartlist_sort_pointers(smartlist_t *sl)
  748. {
  749. smartlist_sort(sl, compare_ptrs_);
  750. }
  751. /* Heap-based priority queue implementation for O(lg N) insert and remove.
  752. * Recall that the heap property is that, for every index I, h[I] <
  753. * H[LEFT_CHILD[I]] and h[I] < H[RIGHT_CHILD[I]].
  754. *
  755. * For us to remove items other than the topmost item, each item must store
  756. * its own index within the heap. When calling the pqueue functions, tell
  757. * them about the offset of the field that stores the index within the item.
  758. *
  759. * Example:
  760. *
  761. * typedef struct timer_t {
  762. * struct timeval tv;
  763. * int heap_index;
  764. * } timer_t;
  765. *
  766. * static int compare(const void *p1, const void *p2) {
  767. * const timer_t *t1 = p1, *t2 = p2;
  768. * if (t1->tv.tv_sec < t2->tv.tv_sec) {
  769. * return -1;
  770. * } else if (t1->tv.tv_sec > t2->tv.tv_sec) {
  771. * return 1;
  772. * } else {
  773. * return t1->tv.tv_usec - t2->tv_usec;
  774. * }
  775. * }
  776. *
  777. * void timer_heap_insert(smartlist_t *heap, timer_t *timer) {
  778. * smartlist_pqueue_add(heap, compare, offsetof(timer_t, heap_index),
  779. * timer);
  780. * }
  781. *
  782. * void timer_heap_pop(smartlist_t *heap) {
  783. * return smartlist_pqueue_pop(heap, compare,
  784. * offsetof(timer_t, heap_index));
  785. * }
  786. */
  787. /** @{ */
  788. /** Functions to manipulate heap indices to find a node's parent and children.
  789. *
  790. * For a 1-indexed array, we would use LEFT_CHILD[x] = 2*x and RIGHT_CHILD[x]
  791. * = 2*x + 1. But this is C, so we have to adjust a little. */
  792. /* MAX_PARENT_IDX is the largest IDX in the smartlist which might have
  793. * children whose indices fit inside an int.
  794. * LEFT_CHILD(MAX_PARENT_IDX) == INT_MAX-2;
  795. * RIGHT_CHILD(MAX_PARENT_IDX) == INT_MAX-1;
  796. * LEFT_CHILD(MAX_PARENT_IDX + 1) == INT_MAX // impossible, see max list size.
  797. */
  798. #define MAX_PARENT_IDX ((INT_MAX - 2) / 2)
  799. /* If this is true, then i is small enough to potentially have children
  800. * in the smartlist, and it is save to use LEFT_CHILD/RIGHT_CHILD on it. */
  801. #define IDX_MAY_HAVE_CHILDREN(i) ((i) <= MAX_PARENT_IDX)
  802. #define LEFT_CHILD(i) ( 2*(i) + 1 )
  803. #define RIGHT_CHILD(i) ( 2*(i) + 2 )
  804. #define PARENT(i) ( ((i)-1) / 2 )
  805. /** }@ */
  806. /** @{ */
  807. /** Helper macros for heaps: Given a local variable <b>idx_field_offset</b>
  808. * set to the offset of an integer index within the heap element structure,
  809. * IDX_OF_ITEM(p) gives you the index of p, and IDXP(p) gives you a pointer to
  810. * where p's index is stored. Given additionally a local smartlist <b>sl</b>,
  811. * UPDATE_IDX(i) sets the index of the element at <b>i</b> to the correct
  812. * value (that is, to <b>i</b>).
  813. */
  814. #define IDXP(p) ((int*)STRUCT_VAR_P(p, idx_field_offset))
  815. #define UPDATE_IDX(i) do { \
  816. void *updated = sl->list[i]; \
  817. *IDXP(updated) = i; \
  818. } while (0)
  819. #define IDX_OF_ITEM(p) (*IDXP(p))
  820. /** @} */
  821. /** Helper. <b>sl</b> may have at most one violation of the heap property:
  822. * the item at <b>idx</b> may be greater than one or both of its children.
  823. * Restore the heap property. */
  824. static inline void
  825. smartlist_heapify(smartlist_t *sl,
  826. int (*compare)(const void *a, const void *b),
  827. int idx_field_offset,
  828. int idx)
  829. {
  830. while (1) {
  831. if (! IDX_MAY_HAVE_CHILDREN(idx)) {
  832. /* idx is so large that it cannot have any children, since doing so
  833. * would mean the smartlist was over-capacity. Therefore it cannot
  834. * violate the heap property by being greater than a child (since it
  835. * doesn't have any). */
  836. return;
  837. }
  838. int left_idx = LEFT_CHILD(idx);
  839. int best_idx;
  840. if (left_idx >= sl->num_used)
  841. return;
  842. if (compare(sl->list[idx],sl->list[left_idx]) < 0)
  843. best_idx = idx;
  844. else
  845. best_idx = left_idx;
  846. if (left_idx+1 < sl->num_used &&
  847. compare(sl->list[left_idx+1],sl->list[best_idx]) < 0)
  848. best_idx = left_idx + 1;
  849. if (best_idx == idx) {
  850. return;
  851. } else {
  852. void *tmp = sl->list[idx];
  853. sl->list[idx] = sl->list[best_idx];
  854. sl->list[best_idx] = tmp;
  855. UPDATE_IDX(idx);
  856. UPDATE_IDX(best_idx);
  857. idx = best_idx;
  858. }
  859. }
  860. }
  861. /** Insert <b>item</b> into the heap stored in <b>sl</b>, where order is
  862. * determined by <b>compare</b> and the offset of the item in the heap is
  863. * stored in an int-typed field at position <b>idx_field_offset</b> within
  864. * item.
  865. */
  866. void
  867. smartlist_pqueue_add(smartlist_t *sl,
  868. int (*compare)(const void *a, const void *b),
  869. int idx_field_offset,
  870. void *item)
  871. {
  872. int idx;
  873. smartlist_add(sl,item);
  874. UPDATE_IDX(sl->num_used-1);
  875. for (idx = sl->num_used - 1; idx; ) {
  876. int parent = PARENT(idx);
  877. if (compare(sl->list[idx], sl->list[parent]) < 0) {
  878. void *tmp = sl->list[parent];
  879. sl->list[parent] = sl->list[idx];
  880. sl->list[idx] = tmp;
  881. UPDATE_IDX(parent);
  882. UPDATE_IDX(idx);
  883. idx = parent;
  884. } else {
  885. return;
  886. }
  887. }
  888. }
  889. /** Remove and return the top-priority item from the heap stored in <b>sl</b>,
  890. * where order is determined by <b>compare</b> and the item's position is
  891. * stored at position <b>idx_field_offset</b> within the item. <b>sl</b> must
  892. * not be empty. */
  893. void *
  894. smartlist_pqueue_pop(smartlist_t *sl,
  895. int (*compare)(const void *a, const void *b),
  896. int idx_field_offset)
  897. {
  898. void *top;
  899. tor_assert(sl->num_used);
  900. top = sl->list[0];
  901. *IDXP(top)=-1;
  902. if (--sl->num_used) {
  903. sl->list[0] = sl->list[sl->num_used];
  904. sl->list[sl->num_used] = NULL;
  905. UPDATE_IDX(0);
  906. smartlist_heapify(sl, compare, idx_field_offset, 0);
  907. }
  908. sl->list[sl->num_used] = NULL;
  909. return top;
  910. }
  911. /** Remove the item <b>item</b> from the heap stored in <b>sl</b>,
  912. * where order is determined by <b>compare</b> and the item's position is
  913. * stored at position <b>idx_field_offset</b> within the item. <b>sl</b> must
  914. * not be empty. */
  915. void
  916. smartlist_pqueue_remove(smartlist_t *sl,
  917. int (*compare)(const void *a, const void *b),
  918. int idx_field_offset,
  919. void *item)
  920. {
  921. int idx = IDX_OF_ITEM(item);
  922. tor_assert(idx >= 0);
  923. tor_assert(sl->list[idx] == item);
  924. --sl->num_used;
  925. *IDXP(item) = -1;
  926. if (idx == sl->num_used) {
  927. sl->list[sl->num_used] = NULL;
  928. return;
  929. } else {
  930. sl->list[idx] = sl->list[sl->num_used];
  931. sl->list[sl->num_used] = NULL;
  932. UPDATE_IDX(idx);
  933. smartlist_heapify(sl, compare, idx_field_offset, idx);
  934. }
  935. }
  936. /** Assert that the heap property is correctly maintained by the heap stored
  937. * in <b>sl</b>, where order is determined by <b>compare</b>. */
  938. void
  939. smartlist_pqueue_assert_ok(smartlist_t *sl,
  940. int (*compare)(const void *a, const void *b),
  941. int idx_field_offset)
  942. {
  943. int i;
  944. for (i = sl->num_used - 1; i >= 0; --i) {
  945. if (i>0)
  946. tor_assert(compare(sl->list[PARENT(i)], sl->list[i]) <= 0);
  947. tor_assert(IDX_OF_ITEM(sl->list[i]) == i);
  948. }
  949. }
  950. /** Helper: compare two DIGEST_LEN digests. */
  951. static int
  952. compare_digests_(const void **_a, const void **_b)
  953. {
  954. return tor_memcmp((const char*)*_a, (const char*)*_b, DIGEST_LEN);
  955. }
  956. /** Sort the list of DIGEST_LEN-byte digests into ascending order. */
  957. void
  958. smartlist_sort_digests(smartlist_t *sl)
  959. {
  960. smartlist_sort(sl, compare_digests_);
  961. }
  962. /** Remove duplicate digests from a sorted list, and free them with tor_free().
  963. */
  964. void
  965. smartlist_uniq_digests(smartlist_t *sl)
  966. {
  967. smartlist_uniq(sl, compare_digests_, tor_free_);
  968. }
  969. /** Helper: compare two DIGEST256_LEN digests. */
  970. static int
  971. compare_digests256_(const void **_a, const void **_b)
  972. {
  973. return tor_memcmp((const char*)*_a, (const char*)*_b, DIGEST256_LEN);
  974. }
  975. /** Sort the list of DIGEST256_LEN-byte digests into ascending order. */
  976. void
  977. smartlist_sort_digests256(smartlist_t *sl)
  978. {
  979. smartlist_sort(sl, compare_digests256_);
  980. }
  981. /** Return the most frequent member of the sorted list of DIGEST256_LEN
  982. * digests in <b>sl</b> */
  983. const uint8_t *
  984. smartlist_get_most_frequent_digest256(smartlist_t *sl)
  985. {
  986. return smartlist_get_most_frequent(sl, compare_digests256_);
  987. }
  988. /** Remove duplicate 256-bit digests from a sorted list, and free them with
  989. * tor_free().
  990. */
  991. void
  992. smartlist_uniq_digests256(smartlist_t *sl)
  993. {
  994. smartlist_uniq(sl, compare_digests256_, tor_free_);
  995. }