smartlist.c 31 KB

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