smartlist.c 30 KB

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