container.c 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2008, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char container_c_id[] =
  7. "$Id$";
  8. /**
  9. * \file container.c
  10. * \brief Implements a smartlist (a resizable array) along
  11. * with helper functions to use smartlists. Also includes
  12. * hash table implementations of a string-to-void* map, and of
  13. * a digest-to-void* map.
  14. **/
  15. #include "compat.h"
  16. #include "util.h"
  17. #include "log.h"
  18. #include "container.h"
  19. #include "crypto.h"
  20. #ifdef HAVE_CTYPE_H
  21. #include <ctype.h>
  22. #endif
  23. #include <stdlib.h>
  24. #include <string.h>
  25. #include <assert.h>
  26. #include "ht.h"
  27. /** All newly allocated smartlists have this capacity. */
  28. #define SMARTLIST_DEFAULT_CAPACITY 32
  29. /** Allocate and return an empty smartlist.
  30. */
  31. smartlist_t *
  32. smartlist_create(void)
  33. {
  34. smartlist_t *sl = tor_malloc(sizeof(smartlist_t));
  35. sl->num_used = 0;
  36. sl->capacity = SMARTLIST_DEFAULT_CAPACITY;
  37. sl->list = tor_malloc(sizeof(void *) * sl->capacity);
  38. return sl;
  39. }
  40. /** Deallocate a smartlist. Does not release storage associated with the
  41. * list's elements.
  42. */
  43. void
  44. smartlist_free(smartlist_t *sl)
  45. {
  46. tor_assert(sl != NULL);
  47. tor_free(sl->list);
  48. tor_free(sl);
  49. }
  50. /** Change the capacity of the smartlist to <b>n</b>, so that we can grow
  51. * the list up to <b>n</b> elements with no further reallocation or wasted
  52. * space. If <b>n</b> is less than or equal to the number of elements
  53. * currently in the list, reduce the list's capacity as much as
  54. * possible without losing elements.
  55. */
  56. void
  57. smartlist_set_capacity(smartlist_t *sl, int n)
  58. {
  59. if (n < sl->num_used)
  60. n = sl->num_used;
  61. if (n < 1)
  62. n = 1;
  63. if (sl->capacity != n) {
  64. sl->capacity = n;
  65. sl->list = tor_realloc(sl->list, sizeof(void*)*sl->capacity);
  66. }
  67. }
  68. /** Remove all elements from the list.
  69. */
  70. void
  71. smartlist_clear(smartlist_t *sl)
  72. {
  73. sl->num_used = 0;
  74. }
  75. /** Make sure that <b>sl</b> can hold at least <b>size</b> entries. */
  76. static INLINE void
  77. smartlist_ensure_capacity(smartlist_t *sl, int size)
  78. {
  79. if (size > sl->capacity) {
  80. int higher = sl->capacity * 2;
  81. while (size > higher)
  82. higher *= 2;
  83. tor_assert(higher > 0); /* detect overflow */
  84. sl->capacity = higher;
  85. sl->list = tor_realloc(sl->list, sizeof(void*)*sl->capacity);
  86. }
  87. }
  88. /** Append element to the end of the list. */
  89. void
  90. smartlist_add(smartlist_t *sl, void *element)
  91. {
  92. smartlist_ensure_capacity(sl, sl->num_used+1);
  93. sl->list[sl->num_used++] = element;
  94. }
  95. /** Append each element from S2 to the end of S1. */
  96. void
  97. smartlist_add_all(smartlist_t *s1, const smartlist_t *s2)
  98. {
  99. smartlist_ensure_capacity(s1, s1->num_used + s2->num_used);
  100. memcpy(s1->list + s1->num_used, s2->list, s2->num_used*sizeof(void*));
  101. s1->num_used += s2->num_used;
  102. }
  103. /** Remove all elements E from sl such that E==element. Preserve
  104. * the order of any elements before E, but elements after E can be
  105. * rearranged.
  106. */
  107. void
  108. smartlist_remove(smartlist_t *sl, const void *element)
  109. {
  110. int i;
  111. if (element == NULL)
  112. return;
  113. for (i=0; i < sl->num_used; i++)
  114. if (sl->list[i] == element) {
  115. sl->list[i] = sl->list[--sl->num_used]; /* swap with the end */
  116. i--; /* so we process the new i'th element */
  117. }
  118. }
  119. /** If <b>sl</b> is nonempty, remove and return the final element. Otherwise,
  120. * return NULL. */
  121. void *
  122. smartlist_pop_last(smartlist_t *sl)
  123. {
  124. tor_assert(sl);
  125. if (sl->num_used)
  126. return sl->list[--sl->num_used];
  127. else
  128. return NULL;
  129. }
  130. /** Reverse the order of the items in <b>sl</b>. */
  131. void
  132. smartlist_reverse(smartlist_t *sl)
  133. {
  134. int i, j;
  135. void *tmp;
  136. tor_assert(sl);
  137. for (i = 0, j = sl->num_used-1; i < j; ++i, --j) {
  138. tmp = sl->list[i];
  139. sl->list[i] = sl->list[j];
  140. sl->list[j] = tmp;
  141. }
  142. }
  143. /** If there are any strings in sl equal to element, remove and free them.
  144. * Does not preserve order. */
  145. void
  146. smartlist_string_remove(smartlist_t *sl, const char *element)
  147. {
  148. int i;
  149. tor_assert(sl);
  150. tor_assert(element);
  151. for (i = 0; i < sl->num_used; ++i) {
  152. if (!strcmp(element, sl->list[i])) {
  153. tor_free(sl->list[i]);
  154. sl->list[i] = sl->list[--sl->num_used]; /* swap with the end */
  155. i--; /* so we process the new i'th element */
  156. }
  157. }
  158. }
  159. /** Return true iff some element E of sl has E==element.
  160. */
  161. int
  162. smartlist_isin(const smartlist_t *sl, const void *element)
  163. {
  164. int i;
  165. for (i=0; i < sl->num_used; i++)
  166. if (sl->list[i] == element)
  167. return 1;
  168. return 0;
  169. }
  170. /** Return true iff <b>sl</b> has some element E such that
  171. * !strcmp(E,<b>element</b>)
  172. */
  173. int
  174. smartlist_string_isin(const smartlist_t *sl, const char *element)
  175. {
  176. int i;
  177. if (!sl) return 0;
  178. for (i=0; i < sl->num_used; i++)
  179. if (strcmp((const char*)sl->list[i],element)==0)
  180. return 1;
  181. return 0;
  182. }
  183. /** If <b>element</b> is equal to an element of <b>sl</b>, return that
  184. * element's index. Otherwise, return -1. */
  185. int
  186. smartlist_string_pos(const smartlist_t *sl, const char *element)
  187. {
  188. int i;
  189. if (!sl) return -1;
  190. for (i=0; i < sl->num_used; i++)
  191. if (strcmp((const char*)sl->list[i],element)==0)
  192. return i;
  193. return -1;
  194. }
  195. /** Return true iff <b>sl</b> has some element E such that
  196. * !strcasecmp(E,<b>element</b>)
  197. */
  198. int
  199. smartlist_string_isin_case(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 (strcasecmp((const char*)sl->list[i],element)==0)
  205. return 1;
  206. return 0;
  207. }
  208. /** Return true iff <b>sl</b> has some element E such that E is equal
  209. * to the decimal encoding of <b>num</b>.
  210. */
  211. int
  212. smartlist_string_num_isin(const smartlist_t *sl, int num)
  213. {
  214. char buf[16];
  215. tor_snprintf(buf,sizeof(buf),"%d", num);
  216. return smartlist_string_isin(sl, buf);
  217. }
  218. /** Return true iff <b>sl</b> has some element E such that
  219. * !memcmp(E,<b>element</b>,DIGEST_LEN)
  220. */
  221. int
  222. smartlist_digest_isin(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 (memcmp((const char*)sl->list[i],element,DIGEST_LEN)==0)
  228. return 1;
  229. return 0;
  230. }
  231. /** Return true iff some element E of sl2 has smartlist_isin(sl1,E).
  232. */
  233. int
  234. smartlist_overlap(const smartlist_t *sl1, const smartlist_t *sl2)
  235. {
  236. int i;
  237. for (i=0; i < sl2->num_used; i++)
  238. if (smartlist_isin(sl1, sl2->list[i]))
  239. return 1;
  240. return 0;
  241. }
  242. /** Remove every element E of sl1 such that !smartlist_isin(sl2,E).
  243. * Does not preserve the order of sl1.
  244. */
  245. void
  246. smartlist_intersect(smartlist_t *sl1, const smartlist_t *sl2)
  247. {
  248. int i;
  249. for (i=0; i < sl1->num_used; i++)
  250. if (!smartlist_isin(sl2, sl1->list[i])) {
  251. sl1->list[i] = sl1->list[--sl1->num_used]; /* swap with the end */
  252. i--; /* so we process the new i'th element */
  253. }
  254. }
  255. /** Remove every element E of sl1 such that smartlist_isin(sl2,E).
  256. * Does not preserve the order of sl1.
  257. */
  258. void
  259. smartlist_subtract(smartlist_t *sl1, const smartlist_t *sl2)
  260. {
  261. int i;
  262. for (i=0; i < sl2->num_used; i++)
  263. smartlist_remove(sl1, sl2->list[i]);
  264. }
  265. /** Remove the <b>idx</b>th element of sl; if idx is not the last
  266. * element, swap the last element of sl into the <b>idx</b>th space.
  267. * Return the old value of the <b>idx</b>th element.
  268. */
  269. void
  270. smartlist_del(smartlist_t *sl, int idx)
  271. {
  272. tor_assert(sl);
  273. tor_assert(idx>=0);
  274. tor_assert(idx < sl->num_used);
  275. sl->list[idx] = sl->list[--sl->num_used];
  276. }
  277. /** Remove the <b>idx</b>th element of sl; if idx is not the last element,
  278. * moving all subsequent elements back one space. Return the old value
  279. * of the <b>idx</b>th element.
  280. */
  281. void
  282. smartlist_del_keeporder(smartlist_t *sl, int idx)
  283. {
  284. tor_assert(sl);
  285. tor_assert(idx>=0);
  286. tor_assert(idx < sl->num_used);
  287. --sl->num_used;
  288. if (idx < sl->num_used)
  289. memmove(sl->list+idx, sl->list+idx+1, sizeof(void*)*(sl->num_used-idx));
  290. }
  291. /** Insert the value <b>val</b> as the new <b>idx</b>th element of
  292. * <b>sl</b>, moving all items previously at <b>idx</b> or later
  293. * forward one space.
  294. */
  295. void
  296. smartlist_insert(smartlist_t *sl, int idx, void *val)
  297. {
  298. tor_assert(sl);
  299. tor_assert(idx>=0);
  300. tor_assert(idx <= sl->num_used);
  301. if (idx == sl->num_used) {
  302. smartlist_add(sl, val);
  303. } else {
  304. smartlist_ensure_capacity(sl, sl->num_used+1);
  305. /* Move other elements away */
  306. if (idx < sl->num_used)
  307. memmove(sl->list + idx + 1, sl->list + idx,
  308. sizeof(void*)*(sl->num_used-idx));
  309. sl->num_used++;
  310. sl->list[idx] = val;
  311. }
  312. }
  313. /**
  314. * Split a string <b>str</b> along all occurrences of <b>sep</b>,
  315. * adding the split strings, in order, to <b>sl</b>. If
  316. * <b>flags</b>&amp;SPLIT_SKIP_SPACE is true, remove initial and
  317. * trailing space from each entry. If
  318. * <b>flags</b>&amp;SPLIT_IGNORE_BLANK is true, remove any entries of
  319. * length 0. If max>0, divide the string into no more than <b>max</b>
  320. * pieces. If <b>sep</b> is NULL, split on any sequence of horizontal space.
  321. */
  322. int
  323. smartlist_split_string(smartlist_t *sl, const char *str, const char *sep,
  324. int flags, int max)
  325. {
  326. const char *cp, *end, *next;
  327. int n = 0;
  328. tor_assert(sl);
  329. tor_assert(str);
  330. cp = str;
  331. while (1) {
  332. if (flags&SPLIT_SKIP_SPACE) {
  333. while (TOR_ISSPACE(*cp)) ++cp;
  334. }
  335. if (max>0 && n == max-1) {
  336. end = strchr(cp,'\0');
  337. } else if (sep) {
  338. end = strstr(cp,sep);
  339. if (!end)
  340. end = strchr(cp,'\0');
  341. } else {
  342. for (end = cp; *end && *end != '\t' && *end != ' '; ++end)
  343. ;
  344. }
  345. if (!*end) {
  346. next = NULL;
  347. } else if (sep) {
  348. next = end+strlen(sep);
  349. } else {
  350. next = end+1;
  351. while (*next == '\t' || *next == ' ')
  352. ++next;
  353. }
  354. if (flags&SPLIT_SKIP_SPACE) {
  355. while (end > cp && TOR_ISSPACE(*(end-1)))
  356. --end;
  357. }
  358. if (end != cp || !(flags&SPLIT_IGNORE_BLANK)) {
  359. smartlist_add(sl, tor_strndup(cp, end-cp));
  360. ++n;
  361. }
  362. if (!next)
  363. break;
  364. cp = next;
  365. }
  366. return n;
  367. }
  368. /** Allocate and return a new string containing the concatenation of
  369. * the elements of <b>sl</b>, in order, separated by <b>join</b>. If
  370. * <b>terminate</b> is true, also terminate the string with <b>join</b>.
  371. * If <b>len_out</b> is not NULL, set <b>len_out</b> to the length of
  372. * the returned string. Requires that every element of <b>sl</b> is
  373. * NUL-terminated string.
  374. */
  375. char *
  376. smartlist_join_strings(smartlist_t *sl, const char *join,
  377. int terminate, size_t *len_out)
  378. {
  379. return smartlist_join_strings2(sl,join,strlen(join),terminate,len_out);
  380. }
  381. /** As smartlist_join_strings, but instead of separating/terminated with a
  382. * NUL-terminated string <b>join</b>, uses the <b>join_len</b>-byte sequence
  383. * at <b>join</b>. (Useful for generating a sequence of NUL-terminated
  384. * strings.)
  385. */
  386. char *
  387. smartlist_join_strings2(smartlist_t *sl, const char *join,
  388. size_t join_len, int terminate, size_t *len_out)
  389. {
  390. int i;
  391. size_t n = 0;
  392. char *r = NULL, *dst, *src;
  393. tor_assert(sl);
  394. tor_assert(join);
  395. if (terminate)
  396. n = join_len;
  397. for (i = 0; i < sl->num_used; ++i) {
  398. n += strlen(sl->list[i]);
  399. if (i+1 < sl->num_used) /* avoid double-counting the last one */
  400. n += join_len;
  401. }
  402. dst = r = tor_malloc(n+1);
  403. for (i = 0; i < sl->num_used; ) {
  404. for (src = sl->list[i]; *src; )
  405. *dst++ = *src++;
  406. if (++i < sl->num_used) {
  407. memcpy(dst, join, join_len);
  408. dst += join_len;
  409. }
  410. }
  411. if (terminate) {
  412. memcpy(dst, join, join_len);
  413. dst += join_len;
  414. }
  415. *dst = '\0';
  416. if (len_out)
  417. *len_out = dst-r;
  418. return r;
  419. }
  420. /** Sort the members of <b>sl</b> into an order defined by
  421. * the ordering function <b>compare</b>, which returns less then 0 if a
  422. * precedes b, greater than 0 if b precedes a, and 0 if a 'equals' b.
  423. */
  424. void
  425. smartlist_sort(smartlist_t *sl, int (*compare)(const void **a, const void **b))
  426. {
  427. if (!sl->num_used)
  428. return;
  429. qsort(sl->list, sl->num_used, sizeof(void*),
  430. (int (*)(const void *,const void*))compare);
  431. }
  432. /** Given a sorted smartlist <b>sl</b> and the comparison function used to
  433. * sort it, remove all duplicate members. If free_fn is provided, calls
  434. * free_fn on each duplicate. Otherwise, just removes them. Preserves order.
  435. */
  436. void
  437. smartlist_uniq(smartlist_t *sl,
  438. int (*compare)(const void **a, const void **b),
  439. void (*free_fn)(void *a))
  440. {
  441. int i;
  442. for (i=1; i < sl->num_used; ++i) {
  443. if (compare((const void **)&(sl->list[i-1]),
  444. (const void **)&(sl->list[i])) == 0) {
  445. if (free_fn)
  446. free_fn(sl->list[i]);
  447. smartlist_del_keeporder(sl, i--);
  448. }
  449. }
  450. }
  451. /** Assuming the members of <b>sl</b> are in order, return a pointer to the
  452. * member that matches <b>key</b>. Ordering and matching are defined by a
  453. * <b>compare</b> function that returns 0 on a match; less than 0 if key is
  454. * less than member, and greater than 0 if key is greater then member.
  455. */
  456. void *
  457. smartlist_bsearch(smartlist_t *sl, const void *key,
  458. int (*compare)(const void *key, const void **member))
  459. {
  460. int found, idx;
  461. idx = smartlist_bsearch_idx(sl, key, compare, &found);
  462. return found ? smartlist_get(sl, idx) : NULL;
  463. }
  464. /** Assuming the members of <b>sl</b> are in order, return the index of the
  465. * member that matches <b>key</b>. If no member matches, return the index of
  466. * the first member greater than <b>key</b>, or smartlist_len(sl) if no member
  467. * is greater than <b>key</b>. Set <b>found_out</b> to true on a match, to
  468. * false otherwise. Ordering and matching are defined by a <b>compare</b>
  469. * function that returns 0 on a match; less than 0 if key is less than member,
  470. * and greater than 0 if key is greater then member.
  471. */
  472. int
  473. smartlist_bsearch_idx(const smartlist_t *sl, const void *key,
  474. int (*compare)(const void *key, const void **member),
  475. int *found_out)
  476. {
  477. int hi = smartlist_len(sl) - 1, lo = 0, cmp, mid;
  478. while (lo <= hi) {
  479. mid = (lo + hi) / 2;
  480. cmp = compare(key, (const void**) &(sl->list[mid]));
  481. if (cmp>0) { /* key > sl[mid] */
  482. lo = mid+1;
  483. } else if (cmp<0) { /* key < sl[mid] */
  484. hi = mid-1;
  485. } else { /* key == sl[mid] */
  486. *found_out = 1;
  487. return mid;
  488. }
  489. }
  490. /* lo > hi. */
  491. {
  492. tor_assert(lo >= 0);
  493. if (lo < smartlist_len(sl)) {
  494. cmp = compare(key, (const void**) &(sl->list[lo]));
  495. tor_assert(cmp < 0);
  496. } else if (smartlist_len(sl)) {
  497. cmp = compare(key, (const void**) &(sl->list[smartlist_len(sl)-1]));
  498. tor_assert(cmp > 0);
  499. }
  500. }
  501. *found_out = 0;
  502. return lo;
  503. }
  504. /** Helper: compare two const char **s. */
  505. static int
  506. _compare_string_ptrs(const void **_a, const void **_b)
  507. {
  508. return strcmp((const char*)*_a, (const char*)*_b);
  509. }
  510. /** Sort a smartlist <b>sl</b> containing strings into lexically ascending
  511. * order. */
  512. void
  513. smartlist_sort_strings(smartlist_t *sl)
  514. {
  515. smartlist_sort(sl, _compare_string_ptrs);
  516. }
  517. /** Remove duplicate strings from a sorted list, and free them with tor_free().
  518. */
  519. void
  520. smartlist_uniq_strings(smartlist_t *sl)
  521. {
  522. smartlist_uniq(sl, _compare_string_ptrs, _tor_free);
  523. }
  524. /* Heap-based priority queue implementation for O(lg N) insert and remove.
  525. * Recall that the heap property is that, for every index I, h[I] <
  526. * H[LEFT_CHILD[I]] and h[I] < H[RIGHT_CHILD[I]].
  527. */
  528. /* For a 1-indexed array, we would use LEFT_CHILD[x] = 2*x and RIGHT_CHILD[x]
  529. * = 2*x + 1. But this is C, so we have to adjust a little. */
  530. //#define LEFT_CHILD(i) ( ((i)+1)*2 - 1)
  531. //#define RIGHT_CHILD(i) ( ((i)+1)*2 )
  532. //#define PARENT(i) ( ((i)+1)/2 - 1)
  533. #define LEFT_CHILD(i) ( 2*(i) + 1 )
  534. #define RIGHT_CHILD(i) ( 2*(i) + 2 )
  535. #define PARENT(i) ( ((i)-1) / 2 )
  536. /** Helper. <b>sl</b> may have at most one violation of the heap property:
  537. * the item at <b>idx</b> may be greater than one or both of its children.
  538. * Restore the heap property. */
  539. static INLINE void
  540. smartlist_heapify(smartlist_t *sl,
  541. int (*compare)(const void *a, const void *b),
  542. int idx)
  543. {
  544. while (1) {
  545. int left_idx = LEFT_CHILD(idx);
  546. int best_idx;
  547. if (left_idx >= sl->num_used)
  548. return;
  549. if (compare(sl->list[idx],sl->list[left_idx]) < 0)
  550. best_idx = idx;
  551. else
  552. best_idx = left_idx;
  553. if (left_idx+1 < sl->num_used &&
  554. compare(sl->list[left_idx+1],sl->list[best_idx]) < 0)
  555. best_idx = left_idx + 1;
  556. if (best_idx == idx) {
  557. return;
  558. } else {
  559. void *tmp = sl->list[idx];
  560. sl->list[idx] = sl->list[best_idx];
  561. sl->list[best_idx] = tmp;
  562. idx = best_idx;
  563. }
  564. }
  565. }
  566. /** Insert <b>item</b> into the heap stored in <b>sl</b>, where order
  567. * is determined by <b>compare</b>. */
  568. void
  569. smartlist_pqueue_add(smartlist_t *sl,
  570. int (*compare)(const void *a, const void *b),
  571. void *item)
  572. {
  573. int idx;
  574. smartlist_add(sl,item);
  575. for (idx = sl->num_used - 1; idx; ) {
  576. int parent = PARENT(idx);
  577. if (compare(sl->list[idx], sl->list[parent]) < 0) {
  578. void *tmp = sl->list[parent];
  579. sl->list[parent] = sl->list[idx];
  580. sl->list[idx] = tmp;
  581. idx = parent;
  582. } else {
  583. return;
  584. }
  585. }
  586. }
  587. /** Remove and return the top-priority item from the heap stored in <b>sl</b>,
  588. * where order is determined by <b>compare</b>. <b>sl</b> must not be
  589. * empty. */
  590. void *
  591. smartlist_pqueue_pop(smartlist_t *sl,
  592. int (*compare)(const void *a, const void *b))
  593. {
  594. void *top;
  595. tor_assert(sl->num_used);
  596. top = sl->list[0];
  597. if (--sl->num_used) {
  598. sl->list[0] = sl->list[sl->num_used];
  599. smartlist_heapify(sl, compare, 0);
  600. }
  601. return top;
  602. }
  603. /** Assert that the heap property is correctly maintained by the heap stored
  604. * in <b>sl</b>, where order is determined by <b>compare</b>. */
  605. void
  606. smartlist_pqueue_assert_ok(smartlist_t *sl,
  607. int (*compare)(const void *a, const void *b))
  608. {
  609. int i;
  610. for (i = sl->num_used - 1; i > 0; --i) {
  611. tor_assert(compare(sl->list[PARENT(i)], sl->list[i]) <= 0);
  612. }
  613. }
  614. /** Helper: compare two DIGEST_LEN digests. */
  615. static int
  616. _compare_digests(const void **_a, const void **_b)
  617. {
  618. return memcmp((const char*)*_a, (const char*)*_b, DIGEST_LEN);
  619. }
  620. /** Sort the list of DIGEST_LEN-byte digests into ascending order. */
  621. void
  622. smartlist_sort_digests(smartlist_t *sl)
  623. {
  624. smartlist_sort(sl, _compare_digests);
  625. }
  626. /** Remove duplicate digests from a sorted list, and free them with tor_free().
  627. */
  628. void
  629. smartlist_uniq_digests(smartlist_t *sl)
  630. {
  631. smartlist_uniq(sl, _compare_digests, _tor_free);
  632. }
  633. #define DEFINE_MAP_STRUCTS(maptype, keydecl, prefix) \
  634. typedef struct prefix ## entry_t { \
  635. HT_ENTRY(prefix ## entry_t) node; \
  636. void *val; \
  637. keydecl; \
  638. } prefix ## entry_t; \
  639. struct maptype { \
  640. HT_HEAD(prefix ## impl, prefix ## entry_t) head; \
  641. }
  642. DEFINE_MAP_STRUCTS(strmap_t, char *key, strmap_);
  643. DEFINE_MAP_STRUCTS(digestmap_t, char key[DIGEST_LEN], digestmap_);
  644. /** Helper: compare strmap_entry_t objects by key value. */
  645. static INLINE int
  646. strmap_entries_eq(const strmap_entry_t *a, const strmap_entry_t *b)
  647. {
  648. return !strcmp(a->key, b->key);
  649. }
  650. /** Helper: return a hash value for a strmap_entry_t. */
  651. static INLINE unsigned int
  652. strmap_entry_hash(const strmap_entry_t *a)
  653. {
  654. return ht_string_hash(a->key);
  655. }
  656. /** Helper: compare digestmap_entry_t objects by key value. */
  657. static INLINE int
  658. digestmap_entries_eq(const digestmap_entry_t *a, const digestmap_entry_t *b)
  659. {
  660. return !memcmp(a->key, b->key, DIGEST_LEN);
  661. }
  662. /** Helper: return a hash value for a digest_map_t. */
  663. static INLINE unsigned int
  664. digestmap_entry_hash(const digestmap_entry_t *a)
  665. {
  666. #if SIZEOF_INT != 8
  667. const uint32_t *p = (const uint32_t*)a->key;
  668. return p[0] ^ p[1] ^ p[2] ^ p[3] ^ p[4];
  669. #else
  670. const uint64_t *p = (const uint64_t*)a->key;
  671. return p[0] ^ p[1];
  672. #endif
  673. }
  674. HT_PROTOTYPE(strmap_impl, strmap_entry_t, node, strmap_entry_hash,
  675. strmap_entries_eq)
  676. HT_GENERATE(strmap_impl, strmap_entry_t, node, strmap_entry_hash,
  677. strmap_entries_eq, 0.6, malloc, realloc, free)
  678. HT_PROTOTYPE(digestmap_impl, digestmap_entry_t, node, digestmap_entry_hash,
  679. digestmap_entries_eq)
  680. HT_GENERATE(digestmap_impl, digestmap_entry_t, node, digestmap_entry_hash,
  681. digestmap_entries_eq, 0.6, malloc, realloc, free)
  682. /** Constructor to create a new empty map from strings to void*'s.
  683. */
  684. strmap_t *
  685. strmap_new(void)
  686. {
  687. strmap_t *result;
  688. result = tor_malloc(sizeof(strmap_t));
  689. HT_INIT(strmap_impl, &result->head);
  690. return result;
  691. }
  692. /** Constructor to create a new empty map from digests to void*'s.
  693. */
  694. digestmap_t *
  695. digestmap_new(void)
  696. {
  697. digestmap_t *result;
  698. result = tor_malloc(sizeof(digestmap_t));
  699. HT_INIT(digestmap_impl, &result->head);
  700. return result;
  701. }
  702. /** Set the current value for <b>key</b> to <b>val</b>. Returns the previous
  703. * value for <b>key</b> if one was set, or NULL if one was not.
  704. *
  705. * This function makes a copy of <b>key</b> if necessary, but not of
  706. * <b>val</b>.
  707. */
  708. void *
  709. strmap_set(strmap_t *map, const char *key, void *val)
  710. {
  711. strmap_entry_t *resolve;
  712. strmap_entry_t search;
  713. void *oldval;
  714. tor_assert(map);
  715. tor_assert(key);
  716. tor_assert(val);
  717. search.key = (char*)key;
  718. resolve = HT_FIND(strmap_impl, &map->head, &search);
  719. if (resolve) {
  720. oldval = resolve->val;
  721. resolve->val = val;
  722. return oldval;
  723. } else {
  724. resolve = tor_malloc_zero(sizeof(strmap_entry_t));
  725. resolve->key = tor_strdup(key);
  726. resolve->val = val;
  727. tor_assert(!HT_FIND(strmap_impl, &map->head, resolve));
  728. HT_INSERT(strmap_impl, &map->head, resolve);
  729. return NULL;
  730. }
  731. }
  732. #define OPTIMIZED_DIGESTMAP_SET
  733. /** Like strmap_set() above but for digestmaps. */
  734. void *
  735. digestmap_set(digestmap_t *map, const char *key, void *val)
  736. {
  737. #ifndef OPTIMIZED_DIGESTMAP_SET
  738. digestmap_entry_t *resolve;
  739. #endif
  740. digestmap_entry_t search;
  741. void *oldval;
  742. tor_assert(map);
  743. tor_assert(key);
  744. tor_assert(val);
  745. memcpy(&search.key, key, DIGEST_LEN);
  746. #ifndef OPTIMIZED_DIGESTMAP_SET
  747. resolve = HT_FIND(digestmap_impl, &map->head, &search);
  748. if (resolve) {
  749. oldval = resolve->val;
  750. resolve->val = val;
  751. return oldval;
  752. } else {
  753. resolve = tor_malloc_zero(sizeof(digestmap_entry_t));
  754. memcpy(resolve->key, key, DIGEST_LEN);
  755. resolve->val = val;
  756. HT_INSERT(digestmap_impl, &map->head, resolve);
  757. return NULL;
  758. }
  759. #else
  760. /* We spend up to 5% of our time in this function, so the code below is
  761. * meant to optimize the check/alloc/set cycle by avoiding the two trips to
  762. * the hash table that we do in the unoptimized code above. (Each of
  763. * HT_INSERT and HT_FIND calls HT_SET_HASH and HT_FIND_P.)
  764. */
  765. _HT_FIND_OR_INSERT(digestmap_impl, node, digestmap_entry_hash, &(map->head),
  766. digestmap_entry_t, &search, ptr,
  767. {
  768. /* we found an entry. */
  769. oldval = (*ptr)->val;
  770. (*ptr)->val = val;
  771. return oldval;
  772. },
  773. {
  774. /* We didn't find the entry. */
  775. digestmap_entry_t *newent =
  776. tor_malloc_zero(sizeof(digestmap_entry_t));
  777. memcpy(newent->key, key, DIGEST_LEN);
  778. newent->val = val;
  779. _HT_FOI_INSERT(node, &(map->head), &search, newent, ptr);
  780. return NULL;
  781. });
  782. #endif
  783. }
  784. /** Return the current value associated with <b>key</b>, or NULL if no
  785. * value is set.
  786. */
  787. void *
  788. strmap_get(const strmap_t *map, const char *key)
  789. {
  790. strmap_entry_t *resolve;
  791. strmap_entry_t search;
  792. tor_assert(map);
  793. tor_assert(key);
  794. search.key = (char*)key;
  795. resolve = HT_FIND(strmap_impl, &map->head, &search);
  796. if (resolve) {
  797. return resolve->val;
  798. } else {
  799. return NULL;
  800. }
  801. }
  802. /** Like strmap_get() above but for digestmaps. */
  803. void *
  804. digestmap_get(const digestmap_t *map, const char *key)
  805. {
  806. digestmap_entry_t *resolve;
  807. digestmap_entry_t search;
  808. tor_assert(map);
  809. tor_assert(key);
  810. memcpy(&search.key, key, DIGEST_LEN);
  811. resolve = HT_FIND(digestmap_impl, &map->head, &search);
  812. if (resolve) {
  813. return resolve->val;
  814. } else {
  815. return NULL;
  816. }
  817. }
  818. /** Remove the value currently associated with <b>key</b> from the map.
  819. * Return the value if one was set, or NULL if there was no entry for
  820. * <b>key</b>.
  821. *
  822. * Note: you must free any storage associated with the returned value.
  823. */
  824. void *
  825. strmap_remove(strmap_t *map, const char *key)
  826. {
  827. strmap_entry_t *resolve;
  828. strmap_entry_t search;
  829. void *oldval;
  830. tor_assert(map);
  831. tor_assert(key);
  832. search.key = (char*)key;
  833. resolve = HT_REMOVE(strmap_impl, &map->head, &search);
  834. if (resolve) {
  835. oldval = resolve->val;
  836. tor_free(resolve->key);
  837. tor_free(resolve);
  838. return oldval;
  839. } else {
  840. return NULL;
  841. }
  842. }
  843. /** Like strmap_remove() above but for digestmaps. */
  844. void *
  845. digestmap_remove(digestmap_t *map, const char *key)
  846. {
  847. digestmap_entry_t *resolve;
  848. digestmap_entry_t search;
  849. void *oldval;
  850. tor_assert(map);
  851. tor_assert(key);
  852. memcpy(&search.key, key, DIGEST_LEN);
  853. resolve = HT_REMOVE(digestmap_impl, &map->head, &search);
  854. if (resolve) {
  855. oldval = resolve->val;
  856. tor_free(resolve);
  857. return oldval;
  858. } else {
  859. return NULL;
  860. }
  861. }
  862. /** Same as strmap_set, but first converts <b>key</b> to lowercase. */
  863. void *
  864. strmap_set_lc(strmap_t *map, const char *key, void *val)
  865. {
  866. /* We could be a little faster by using strcasecmp instead, and a separate
  867. * type, but I don't think it matters. */
  868. void *v;
  869. char *lc_key = tor_strdup(key);
  870. tor_strlower(lc_key);
  871. v = strmap_set(map,lc_key,val);
  872. tor_free(lc_key);
  873. return v;
  874. }
  875. /** Same as strmap_get, but first converts <b>key</b> to lowercase. */
  876. void *
  877. strmap_get_lc(const strmap_t *map, const char *key)
  878. {
  879. void *v;
  880. char *lc_key = tor_strdup(key);
  881. tor_strlower(lc_key);
  882. v = strmap_get(map,lc_key);
  883. tor_free(lc_key);
  884. return v;
  885. }
  886. /** Same as strmap_remove, but first converts <b>key</b> to lowercase */
  887. void *
  888. strmap_remove_lc(strmap_t *map, const char *key)
  889. {
  890. void *v;
  891. char *lc_key = tor_strdup(key);
  892. tor_strlower(lc_key);
  893. v = strmap_remove(map,lc_key);
  894. tor_free(lc_key);
  895. return v;
  896. }
  897. /** return an <b>iterator</b> pointer to the front of a map.
  898. *
  899. * Iterator example:
  900. *
  901. * \code
  902. * // uppercase values in "map", removing empty values.
  903. *
  904. * strmap_iter_t *iter;
  905. * const char *key;
  906. * void *val;
  907. * char *cp;
  908. *
  909. * for (iter = strmap_iter_init(map); !strmap_iter_done(iter); ) {
  910. * strmap_iter_get(iter, &key, &val);
  911. * cp = (char*)val;
  912. * if (!*cp) {
  913. * iter = strmap_iter_next_rmv(map,iter);
  914. * free(val);
  915. * } else {
  916. * for (;*cp;cp++) *cp = TOR_TOUPPER(*cp);
  917. * iter = strmap_iter_next(map,iter);
  918. * }
  919. * }
  920. * \endcode
  921. *
  922. */
  923. strmap_iter_t *
  924. strmap_iter_init(strmap_t *map)
  925. {
  926. tor_assert(map);
  927. return HT_START(strmap_impl, &map->head);
  928. }
  929. digestmap_iter_t *
  930. digestmap_iter_init(digestmap_t *map)
  931. {
  932. tor_assert(map);
  933. return HT_START(digestmap_impl, &map->head);
  934. }
  935. /** Advance the iterator <b>iter</b> for map a single step to the next entry.
  936. */
  937. strmap_iter_t *
  938. strmap_iter_next(strmap_t *map, strmap_iter_t *iter)
  939. {
  940. tor_assert(map);
  941. tor_assert(iter);
  942. return HT_NEXT(strmap_impl, &map->head, iter);
  943. }
  944. digestmap_iter_t *
  945. digestmap_iter_next(digestmap_t *map, digestmap_iter_t *iter)
  946. {
  947. tor_assert(map);
  948. tor_assert(iter);
  949. return HT_NEXT(digestmap_impl, &map->head, iter);
  950. }
  951. /** Advance the iterator <b>iter</b> a single step to the next entry, removing
  952. * the current entry.
  953. */
  954. strmap_iter_t *
  955. strmap_iter_next_rmv(strmap_t *map, strmap_iter_t *iter)
  956. {
  957. strmap_entry_t *rmv;
  958. tor_assert(map);
  959. tor_assert(iter);
  960. tor_assert(*iter);
  961. rmv = *iter;
  962. iter = HT_NEXT_RMV(strmap_impl, &map->head, iter);
  963. tor_free(rmv->key);
  964. tor_free(rmv);
  965. return iter;
  966. }
  967. digestmap_iter_t *
  968. digestmap_iter_next_rmv(digestmap_t *map, digestmap_iter_t *iter)
  969. {
  970. digestmap_entry_t *rmv;
  971. tor_assert(map);
  972. tor_assert(iter);
  973. tor_assert(*iter);
  974. rmv = *iter;
  975. iter = HT_NEXT_RMV(digestmap_impl, &map->head, iter);
  976. tor_free(rmv);
  977. return iter;
  978. }
  979. /** Set *keyp and *valp to the current entry pointed to by iter.
  980. */
  981. void
  982. strmap_iter_get(strmap_iter_t *iter, const char **keyp, void **valp)
  983. {
  984. tor_assert(iter);
  985. tor_assert(*iter);
  986. tor_assert(keyp);
  987. tor_assert(valp);
  988. *keyp = (*iter)->key;
  989. *valp = (*iter)->val;
  990. }
  991. void
  992. digestmap_iter_get(digestmap_iter_t *iter, const char **keyp, void **valp)
  993. {
  994. tor_assert(iter);
  995. tor_assert(*iter);
  996. tor_assert(keyp);
  997. tor_assert(valp);
  998. *keyp = (*iter)->key;
  999. *valp = (*iter)->val;
  1000. }
  1001. /** Return true iff iter has advanced past the last entry of map.
  1002. */
  1003. int
  1004. strmap_iter_done(strmap_iter_t *iter)
  1005. {
  1006. return iter == NULL;
  1007. }
  1008. int
  1009. digestmap_iter_done(digestmap_iter_t *iter)
  1010. {
  1011. return iter == NULL;
  1012. }
  1013. /** Remove all entries from <b>map</b>, and deallocate storage for those
  1014. * entries. If free_val is provided, it is invoked on every value in
  1015. * <b>map</b>.
  1016. */
  1017. void
  1018. strmap_free(strmap_t *map, void (*free_val)(void*))
  1019. {
  1020. strmap_entry_t **ent, **next, *this;
  1021. for (ent = HT_START(strmap_impl, &map->head); ent != NULL; ent = next) {
  1022. this = *ent;
  1023. next = HT_NEXT_RMV(strmap_impl, &map->head, ent);
  1024. tor_free(this->key);
  1025. if (free_val)
  1026. free_val(this->val);
  1027. tor_free(this);
  1028. }
  1029. tor_assert(HT_EMPTY(&map->head));
  1030. HT_CLEAR(strmap_impl, &map->head);
  1031. tor_free(map);
  1032. }
  1033. void
  1034. digestmap_free(digestmap_t *map, void (*free_val)(void*))
  1035. {
  1036. digestmap_entry_t **ent, **next, *this;
  1037. for (ent = HT_START(digestmap_impl, &map->head); ent != NULL; ent = next) {
  1038. this = *ent;
  1039. next = HT_NEXT_RMV(digestmap_impl, &map->head, ent);
  1040. if (free_val)
  1041. free_val(this->val);
  1042. tor_free(this);
  1043. }
  1044. tor_assert(HT_EMPTY(&map->head));
  1045. HT_CLEAR(digestmap_impl, &map->head);
  1046. tor_free(map);
  1047. }
  1048. void
  1049. strmap_assert_ok(const strmap_t *map)
  1050. {
  1051. tor_assert(!_strmap_impl_HT_REP_IS_BAD(&map->head));
  1052. }
  1053. void
  1054. digestmap_assert_ok(const digestmap_t *map)
  1055. {
  1056. tor_assert(!_digestmap_impl_HT_REP_IS_BAD(&map->head));
  1057. }
  1058. /** Return true iff <b>map</b> has no entries. */
  1059. int
  1060. strmap_isempty(const strmap_t *map)
  1061. {
  1062. return HT_EMPTY(&map->head);
  1063. }
  1064. int
  1065. digestmap_isempty(const digestmap_t *map)
  1066. {
  1067. return HT_EMPTY(&map->head);
  1068. }
  1069. /** Return the number of items in <b>map</b>. */
  1070. int
  1071. strmap_size(const strmap_t *map)
  1072. {
  1073. return HT_SIZE(&map->head);
  1074. }
  1075. int
  1076. digestmap_size(const digestmap_t *map)
  1077. {
  1078. return HT_SIZE(&map->head);
  1079. }
  1080. /** Declare a function called <b>funcname</b> that acts as a find_nth_FOO
  1081. * function for an array of type <b>elt_t</b>*.
  1082. *
  1083. * NOTE: The implementation kind of sucks: It's O(n log n), whereas finding
  1084. * the nth element of a list can be done in O(n). Then again, this
  1085. * implementation is not in critical path, and it is obviously correct. */
  1086. #define IMPLEMENT_ORDER_FUNC(funcname, elt_t) \
  1087. static int \
  1088. _cmp_ ## elt_t(const void *_a, const void *_b) \
  1089. { \
  1090. const elt_t *a = _a, *b = _b; \
  1091. if (*a<*b) \
  1092. return -1; \
  1093. else if (*a>*b) \
  1094. return 1; \
  1095. else \
  1096. return 0; \
  1097. } \
  1098. elt_t \
  1099. funcname(elt_t *array, int n_elements, int nth) \
  1100. { \
  1101. tor_assert(nth >= 0); \
  1102. tor_assert(nth < n_elements); \
  1103. qsort(array, n_elements, sizeof(elt_t), _cmp_ ##elt_t); \
  1104. return array[nth]; \
  1105. }
  1106. IMPLEMENT_ORDER_FUNC(find_nth_int, int)
  1107. IMPLEMENT_ORDER_FUNC(find_nth_time, time_t)
  1108. IMPLEMENT_ORDER_FUNC(find_nth_double, double)
  1109. IMPLEMENT_ORDER_FUNC(find_nth_uint32, uint32_t)
  1110. IMPLEMENT_ORDER_FUNC(find_nth_long, long)