smartlist.c 30 KB

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