smartlist.c 31 KB

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