fix typo
[tor.git] / src / common / container.c
blob689e7e55e93b6bc5a30e24342b7d08f005eca8cc
1 /* Copyright (c) 2003-2004, Roger Dingledine
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2017, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
6 /**
7 * \file container.c
8 * \brief Implements a smartlist (a resizable array) along
9 * with helper functions to use smartlists. Also includes
10 * hash table implementations of a string-to-void* map, and of
11 * a digest-to-void* map.
12 **/
14 #include "compat.h"
15 #include "util.h"
16 #include "torlog.h"
17 #include "container.h"
18 #include "crypto.h"
20 #include <stdlib.h>
21 #include <string.h>
22 #include <assert.h>
24 #include "ht.h"
26 /** All newly allocated smartlists have this capacity. */
27 #define SMARTLIST_DEFAULT_CAPACITY 16
29 /** Allocate and return an empty smartlist.
31 MOCK_IMPL(smartlist_t *,
32 smartlist_new,(void))
34 smartlist_t *sl = tor_malloc(sizeof(smartlist_t));
35 sl->num_used = 0;
36 sl->capacity = SMARTLIST_DEFAULT_CAPACITY;
37 sl->list = tor_calloc(sizeof(void *), sl->capacity);
38 return sl;
41 /** Deallocate a smartlist. Does not release storage associated with the
42 * list's elements.
44 MOCK_IMPL(void,
45 smartlist_free,(smartlist_t *sl))
47 if (!sl)
48 return;
49 tor_free(sl->list);
50 tor_free(sl);
53 /** Remove all elements from the list.
55 void
56 smartlist_clear(smartlist_t *sl)
58 memset(sl->list, 0, sizeof(void *) * sl->num_used);
59 sl->num_used = 0;
62 #if SIZE_MAX < INT_MAX
63 #error "We don't support systems where size_t is smaller than int."
64 #endif
66 /** Make sure that <b>sl</b> can hold at least <b>size</b> entries. */
67 static inline void
68 smartlist_ensure_capacity(smartlist_t *sl, size_t size)
70 /* Set MAX_CAPACITY to MIN(INT_MAX, SIZE_MAX / sizeof(void*)) */
71 #if (SIZE_MAX/SIZEOF_VOID_P) > INT_MAX
72 #define MAX_CAPACITY (INT_MAX)
73 #else
74 #define MAX_CAPACITY (int)((SIZE_MAX / (sizeof(void*))))
75 #endif
77 tor_assert(size <= MAX_CAPACITY);
79 if (size > (size_t) sl->capacity) {
80 size_t higher = (size_t) sl->capacity;
81 if (PREDICT_UNLIKELY(size > MAX_CAPACITY/2)) {
82 higher = MAX_CAPACITY;
83 } else {
84 while (size > higher)
85 higher *= 2;
87 sl->list = tor_reallocarray(sl->list, sizeof(void *),
88 ((size_t)higher));
89 memset(sl->list + sl->capacity, 0,
90 sizeof(void *) * (higher - sl->capacity));
91 sl->capacity = (int) higher;
93 #undef ASSERT_CAPACITY
94 #undef MAX_CAPACITY
97 /** Append element to the end of the list. */
98 void
99 smartlist_add(smartlist_t *sl, void *element)
101 smartlist_ensure_capacity(sl, ((size_t) sl->num_used)+1);
102 sl->list[sl->num_used++] = element;
105 /** Append each element from S2 to the end of S1. */
106 void
107 smartlist_add_all(smartlist_t *s1, const smartlist_t *s2)
109 size_t new_size = (size_t)s1->num_used + (size_t)s2->num_used;
110 tor_assert(new_size >= (size_t) s1->num_used); /* check for overflow. */
111 smartlist_ensure_capacity(s1, new_size);
112 memcpy(s1->list + s1->num_used, s2->list, s2->num_used*sizeof(void*));
113 tor_assert(new_size <= INT_MAX); /* redundant. */
114 s1->num_used = (int) new_size;
117 /** Remove all elements E from sl such that E==element. Preserve
118 * the order of any elements before E, but elements after E can be
119 * rearranged.
121 void
122 smartlist_remove(smartlist_t *sl, const void *element)
124 int i;
125 if (element == NULL)
126 return;
127 for (i=0; i < sl->num_used; i++)
128 if (sl->list[i] == element) {
129 sl->list[i] = sl->list[--sl->num_used]; /* swap with the end */
130 i--; /* so we process the new i'th element */
131 sl->list[sl->num_used] = NULL;
135 /** As <b>smartlist_remove</b>, but do not change the order of
136 * any elements not removed */
137 void
138 smartlist_remove_keeporder(smartlist_t *sl, const void *element)
140 int i, j, num_used_orig = sl->num_used;
141 if (element == NULL)
142 return;
144 for (i=j=0; j < num_used_orig; ++j) {
145 if (sl->list[j] == element) {
146 --sl->num_used;
147 } else {
148 sl->list[i++] = sl->list[j];
153 /** If <b>sl</b> is nonempty, remove and return the final element. Otherwise,
154 * return NULL. */
155 void *
156 smartlist_pop_last(smartlist_t *sl)
158 tor_assert(sl);
159 if (sl->num_used) {
160 void *tmp = sl->list[--sl->num_used];
161 sl->list[sl->num_used] = NULL;
162 return tmp;
163 } else
164 return NULL;
167 /** Reverse the order of the items in <b>sl</b>. */
168 void
169 smartlist_reverse(smartlist_t *sl)
171 int i, j;
172 void *tmp;
173 tor_assert(sl);
174 for (i = 0, j = sl->num_used-1; i < j; ++i, --j) {
175 tmp = sl->list[i];
176 sl->list[i] = sl->list[j];
177 sl->list[j] = tmp;
181 /** If there are any strings in sl equal to element, remove and free them.
182 * Does not preserve order. */
183 void
184 smartlist_string_remove(smartlist_t *sl, const char *element)
186 int i;
187 tor_assert(sl);
188 tor_assert(element);
189 for (i = 0; i < sl->num_used; ++i) {
190 if (!strcmp(element, sl->list[i])) {
191 tor_free(sl->list[i]);
192 sl->list[i] = sl->list[--sl->num_used]; /* swap with the end */
193 i--; /* so we process the new i'th element */
194 sl->list[sl->num_used] = NULL;
199 /** Return true iff some element E of sl has E==element.
202 smartlist_contains(const smartlist_t *sl, const void *element)
204 int i;
205 for (i=0; i < sl->num_used; i++)
206 if (sl->list[i] == element)
207 return 1;
208 return 0;
211 /** Return true iff <b>sl</b> has some element E such that
212 * !strcmp(E,<b>element</b>)
215 smartlist_contains_string(const smartlist_t *sl, const char *element)
217 int i;
218 if (!sl) return 0;
219 for (i=0; i < sl->num_used; i++)
220 if (strcmp((const char*)sl->list[i],element)==0)
221 return 1;
222 return 0;
225 /** If <b>element</b> is equal to an element of <b>sl</b>, return that
226 * element's index. Otherwise, return -1. */
228 smartlist_string_pos(const smartlist_t *sl, const char *element)
230 int i;
231 if (!sl) return -1;
232 for (i=0; i < sl->num_used; i++)
233 if (strcmp((const char*)sl->list[i],element)==0)
234 return i;
235 return -1;
238 /** If <b>element</b> is the same pointer as an element of <b>sl</b>, return
239 * that element's index. Otherwise, return -1. */
241 smartlist_pos(const smartlist_t *sl, const void *element)
243 int i;
244 if (!sl) return -1;
245 for (i=0; i < sl->num_used; i++)
246 if (element == sl->list[i])
247 return i;
248 return -1;
251 /** Return true iff <b>sl</b> has some element E such that
252 * !strcasecmp(E,<b>element</b>)
255 smartlist_contains_string_case(const smartlist_t *sl, const char *element)
257 int i;
258 if (!sl) return 0;
259 for (i=0; i < sl->num_used; i++)
260 if (strcasecmp((const char*)sl->list[i],element)==0)
261 return 1;
262 return 0;
265 /** Return true iff <b>sl</b> has some element E such that E is equal
266 * to the decimal encoding of <b>num</b>.
269 smartlist_contains_int_as_string(const smartlist_t *sl, int num)
271 char buf[32]; /* long enough for 64-bit int, and then some. */
272 tor_snprintf(buf,sizeof(buf),"%d", num);
273 return smartlist_contains_string(sl, buf);
276 /** Return true iff the two lists contain the same strings in the same
277 * order, or if they are both NULL. */
279 smartlist_strings_eq(const smartlist_t *sl1, const smartlist_t *sl2)
281 if (sl1 == NULL)
282 return sl2 == NULL;
283 if (sl2 == NULL)
284 return 0;
285 if (smartlist_len(sl1) != smartlist_len(sl2))
286 return 0;
287 SMARTLIST_FOREACH(sl1, const char *, cp1, {
288 const char *cp2 = smartlist_get(sl2, cp1_sl_idx);
289 if (strcmp(cp1, cp2))
290 return 0;
292 return 1;
295 /** Return true iff the two lists contain the same int pointer values in
296 * the same order, or if they are both NULL. */
298 smartlist_ints_eq(const smartlist_t *sl1, const smartlist_t *sl2)
300 if (sl1 == NULL)
301 return sl2 == NULL;
302 if (sl2 == NULL)
303 return 0;
304 if (smartlist_len(sl1) != smartlist_len(sl2))
305 return 0;
306 SMARTLIST_FOREACH(sl1, int *, cp1, {
307 int *cp2 = smartlist_get(sl2, cp1_sl_idx);
308 if (*cp1 != *cp2)
309 return 0;
311 return 1;
314 /** Return true iff <b>sl</b> has some element E such that
315 * tor_memeq(E,<b>element</b>,DIGEST_LEN)
318 smartlist_contains_digest(const smartlist_t *sl, const char *element)
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;
328 /** Return true iff some element E of sl2 has smartlist_contains(sl1,E).
331 smartlist_overlap(const smartlist_t *sl1, const smartlist_t *sl2)
333 int i;
334 for (i=0; i < sl2->num_used; i++)
335 if (smartlist_contains(sl1, sl2->list[i]))
336 return 1;
337 return 0;
340 /** Remove every element E of sl1 such that !smartlist_contains(sl2,E).
341 * Does not preserve the order of sl1.
343 void
344 smartlist_intersect(smartlist_t *sl1, const smartlist_t *sl2)
346 int i;
347 for (i=0; i < sl1->num_used; i++)
348 if (!smartlist_contains(sl2, sl1->list[i])) {
349 sl1->list[i] = sl1->list[--sl1->num_used]; /* swap with the end */
350 i--; /* so we process the new i'th element */
351 sl1->list[sl1->num_used] = NULL;
355 /** Remove every element E of sl1 such that smartlist_contains(sl2,E).
356 * Does not preserve the order of sl1.
358 void
359 smartlist_subtract(smartlist_t *sl1, const smartlist_t *sl2)
361 int i;
362 for (i=0; i < sl2->num_used; i++)
363 smartlist_remove(sl1, sl2->list[i]);
366 /** Remove the <b>idx</b>th element of sl; if idx is not the last
367 * element, swap the last element of sl into the <b>idx</b>th space.
369 void
370 smartlist_del(smartlist_t *sl, int idx)
372 tor_assert(sl);
373 tor_assert(idx>=0);
374 tor_assert(idx < sl->num_used);
375 sl->list[idx] = sl->list[--sl->num_used];
376 sl->list[sl->num_used] = NULL;
379 /** Remove the <b>idx</b>th element of sl; if idx is not the last element,
380 * moving all subsequent elements back one space. Return the old value
381 * of the <b>idx</b>th element.
383 void
384 smartlist_del_keeporder(smartlist_t *sl, int idx)
386 tor_assert(sl);
387 tor_assert(idx>=0);
388 tor_assert(idx < sl->num_used);
389 --sl->num_used;
390 if (idx < sl->num_used)
391 memmove(sl->list+idx, sl->list+idx+1, sizeof(void*)*(sl->num_used-idx));
392 sl->list[sl->num_used] = NULL;
395 /** Insert the value <b>val</b> as the new <b>idx</b>th element of
396 * <b>sl</b>, moving all items previously at <b>idx</b> or later
397 * forward one space.
399 void
400 smartlist_insert(smartlist_t *sl, int idx, void *val)
402 tor_assert(sl);
403 tor_assert(idx>=0);
404 tor_assert(idx <= sl->num_used);
405 if (idx == sl->num_used) {
406 smartlist_add(sl, val);
407 } else {
408 smartlist_ensure_capacity(sl, ((size_t) sl->num_used)+1);
409 /* Move other elements away */
410 if (idx < sl->num_used)
411 memmove(sl->list + idx + 1, sl->list + idx,
412 sizeof(void*)*(sl->num_used-idx));
413 sl->num_used++;
414 sl->list[idx] = val;
419 * Split a string <b>str</b> along all occurrences of <b>sep</b>,
420 * appending the (newly allocated) split strings, in order, to
421 * <b>sl</b>. Return the number of strings added to <b>sl</b>.
423 * If <b>flags</b>&amp;SPLIT_SKIP_SPACE is true, remove initial and
424 * trailing space from each entry.
425 * If <b>flags</b>&amp;SPLIT_IGNORE_BLANK is true, remove any entries
426 * of length 0.
427 * If <b>flags</b>&amp;SPLIT_STRIP_SPACE is true, strip spaces from each
428 * split string.
430 * If <b>max</b>\>0, divide the string into no more than <b>max</b> pieces. If
431 * <b>sep</b> is NULL, split on any sequence of horizontal space.
434 smartlist_split_string(smartlist_t *sl, const char *str, const char *sep,
435 int flags, int max)
437 const char *cp, *end, *next;
438 int n = 0;
440 tor_assert(sl);
441 tor_assert(str);
443 cp = str;
444 while (1) {
445 if (flags&SPLIT_SKIP_SPACE) {
446 while (TOR_ISSPACE(*cp)) ++cp;
449 if (max>0 && n == max-1) {
450 end = strchr(cp,'\0');
451 } else if (sep) {
452 end = strstr(cp,sep);
453 if (!end)
454 end = strchr(cp,'\0');
455 } else {
456 for (end = cp; *end && *end != '\t' && *end != ' '; ++end)
460 tor_assert(end);
462 if (!*end) {
463 next = NULL;
464 } else if (sep) {
465 next = end+strlen(sep);
466 } else {
467 next = end+1;
468 while (*next == '\t' || *next == ' ')
469 ++next;
472 if (flags&SPLIT_SKIP_SPACE) {
473 while (end > cp && TOR_ISSPACE(*(end-1)))
474 --end;
476 if (end != cp || !(flags&SPLIT_IGNORE_BLANK)) {
477 char *string = tor_strndup(cp, end-cp);
478 if (flags&SPLIT_STRIP_SPACE)
479 tor_strstrip(string, " ");
480 smartlist_add(sl, string);
481 ++n;
483 if (!next)
484 break;
485 cp = next;
488 return n;
491 /** Allocate and return a new string containing the concatenation of
492 * the elements of <b>sl</b>, in order, separated by <b>join</b>. If
493 * <b>terminate</b> is true, also terminate the string with <b>join</b>.
494 * If <b>len_out</b> is not NULL, set <b>len_out</b> to the length of
495 * the returned string. Requires that every element of <b>sl</b> is
496 * NUL-terminated string.
498 char *
499 smartlist_join_strings(smartlist_t *sl, const char *join,
500 int terminate, size_t *len_out)
502 return smartlist_join_strings2(sl,join,strlen(join),terminate,len_out);
505 /** As smartlist_join_strings, but instead of separating/terminated with a
506 * NUL-terminated string <b>join</b>, uses the <b>join_len</b>-byte sequence
507 * at <b>join</b>. (Useful for generating a sequence of NUL-terminated
508 * strings.)
510 char *
511 smartlist_join_strings2(smartlist_t *sl, const char *join,
512 size_t join_len, int terminate, size_t *len_out)
514 int i;
515 size_t n = 0;
516 char *r = NULL, *dst, *src;
518 tor_assert(sl);
519 tor_assert(join);
521 if (terminate)
522 n = join_len;
524 for (i = 0; i < sl->num_used; ++i) {
525 n += strlen(sl->list[i]);
526 if (i+1 < sl->num_used) /* avoid double-counting the last one */
527 n += join_len;
529 dst = r = tor_malloc(n+1);
530 for (i = 0; i < sl->num_used; ) {
531 for (src = sl->list[i]; *src; )
532 *dst++ = *src++;
533 if (++i < sl->num_used) {
534 memcpy(dst, join, join_len);
535 dst += join_len;
538 if (terminate) {
539 memcpy(dst, join, join_len);
540 dst += join_len;
542 *dst = '\0';
544 if (len_out)
545 *len_out = dst-r;
546 return r;
549 /** Sort the members of <b>sl</b> into an order defined by
550 * the ordering function <b>compare</b>, which returns less then 0 if a
551 * precedes b, greater than 0 if b precedes a, and 0 if a 'equals' b.
553 void
554 smartlist_sort(smartlist_t *sl, int (*compare)(const void **a, const void **b))
556 if (!sl->num_used)
557 return;
558 qsort(sl->list, sl->num_used, sizeof(void*),
559 (int (*)(const void *,const void*))compare);
562 /** Given a smartlist <b>sl</b> sorted with the function <b>compare</b>,
563 * return the most frequent member in the list. Break ties in favor of
564 * later elements. If the list is empty, return NULL. If count_out is
565 * non-null, set it to the count of the most frequent member.
567 void *
568 smartlist_get_most_frequent_(const smartlist_t *sl,
569 int (*compare)(const void **a, const void **b),
570 int *count_out)
572 const void *most_frequent = NULL;
573 int most_frequent_count = 0;
575 const void *cur = NULL;
576 int i, count=0;
578 if (!sl->num_used) {
579 if (count_out)
580 *count_out = 0;
581 return NULL;
583 for (i = 0; i < sl->num_used; ++i) {
584 const void *item = sl->list[i];
585 if (cur && 0 == compare(&cur, &item)) {
586 ++count;
587 } else {
588 if (cur && count >= most_frequent_count) {
589 most_frequent = cur;
590 most_frequent_count = count;
592 cur = item;
593 count = 1;
596 if (cur && count >= most_frequent_count) {
597 most_frequent = cur;
598 most_frequent_count = count;
600 if (count_out)
601 *count_out = most_frequent_count;
602 return (void*)most_frequent;
605 /** Given a sorted smartlist <b>sl</b> and the comparison function used to
606 * sort it, remove all duplicate members. If free_fn is provided, calls
607 * free_fn on each duplicate. Otherwise, just removes them. Preserves order.
609 void
610 smartlist_uniq(smartlist_t *sl,
611 int (*compare)(const void **a, const void **b),
612 void (*free_fn)(void *a))
614 int i;
615 for (i=1; i < sl->num_used; ++i) {
616 if (compare((const void **)&(sl->list[i-1]),
617 (const void **)&(sl->list[i])) == 0) {
618 if (free_fn)
619 free_fn(sl->list[i]);
620 smartlist_del_keeporder(sl, i--);
625 /** Assuming the members of <b>sl</b> are in order, return a pointer to the
626 * member that matches <b>key</b>. Ordering and matching are defined by a
627 * <b>compare</b> function that returns 0 on a match; less than 0 if key is
628 * less than member, and greater than 0 if key is greater then member.
630 void *
631 smartlist_bsearch(smartlist_t *sl, const void *key,
632 int (*compare)(const void *key, const void **member))
634 int found, idx;
635 idx = smartlist_bsearch_idx(sl, key, compare, &found);
636 return found ? smartlist_get(sl, idx) : NULL;
639 /** Assuming the members of <b>sl</b> are in order, return the index of the
640 * member that matches <b>key</b>. If no member matches, return the index of
641 * the first member greater than <b>key</b>, or smartlist_len(sl) if no member
642 * is greater than <b>key</b>. Set <b>found_out</b> to true on a match, to
643 * false otherwise. Ordering and matching are defined by a <b>compare</b>
644 * function that returns 0 on a match; less than 0 if key is less than member,
645 * and greater than 0 if key is greater then member.
648 smartlist_bsearch_idx(const smartlist_t *sl, const void *key,
649 int (*compare)(const void *key, const void **member),
650 int *found_out)
652 int hi, lo, cmp, mid, len, diff;
654 tor_assert(sl);
655 tor_assert(compare);
656 tor_assert(found_out);
658 len = smartlist_len(sl);
660 /* Check for the trivial case of a zero-length list */
661 if (len == 0) {
662 *found_out = 0;
663 /* We already know smartlist_len(sl) is 0 in this case */
664 return 0;
667 /* Okay, we have a real search to do */
668 tor_assert(len > 0);
669 lo = 0;
670 hi = len - 1;
673 * These invariants are always true:
675 * For all i such that 0 <= i < lo, sl[i] < key
676 * For all i such that hi < i <= len, sl[i] > key
679 while (lo <= hi) {
680 diff = hi - lo;
682 * We want mid = (lo + hi) / 2, but that could lead to overflow, so
683 * instead diff = hi - lo (non-negative because of loop condition), and
684 * then hi = lo + diff, mid = (lo + lo + diff) / 2 = lo + (diff / 2).
686 mid = lo + (diff / 2);
687 cmp = compare(key, (const void**) &(sl->list[mid]));
688 if (cmp == 0) {
689 /* sl[mid] == key; we found it */
690 *found_out = 1;
691 return mid;
692 } else if (cmp > 0) {
694 * key > sl[mid] and an index i such that sl[i] == key must
695 * have i > mid if it exists.
699 * Since lo <= mid <= hi, hi can only decrease on each iteration (by
700 * being set to mid - 1) and hi is initially len - 1, mid < len should
701 * always hold, and this is not symmetric with the left end of list
702 * mid > 0 test below. A key greater than the right end of the list
703 * should eventually lead to lo == hi == mid == len - 1, and then
704 * we set lo to len below and fall out to the same exit we hit for
705 * a key in the middle of the list but not matching. Thus, we just
706 * assert for consistency here rather than handle a mid == len case.
708 tor_assert(mid < len);
709 /* Move lo to the element immediately after sl[mid] */
710 lo = mid + 1;
711 } else {
712 /* This should always be true in this case */
713 tor_assert(cmp < 0);
716 * key < sl[mid] and an index i such that sl[i] == key must
717 * have i < mid if it exists.
720 if (mid > 0) {
721 /* Normal case, move hi to the element immediately before sl[mid] */
722 hi = mid - 1;
723 } else {
724 /* These should always be true in this case */
725 tor_assert(mid == lo);
726 tor_assert(mid == 0);
728 * We were at the beginning of the list and concluded that every
729 * element e compares e > key.
731 *found_out = 0;
732 return 0;
738 * lo > hi; we have no element matching key but we have elements falling
739 * on both sides of it. The lo index points to the first element > key.
741 tor_assert(lo == hi + 1); /* All other cases should have been handled */
742 tor_assert(lo >= 0);
743 tor_assert(lo <= len);
744 tor_assert(hi >= 0);
745 tor_assert(hi <= len);
747 if (lo < len) {
748 cmp = compare(key, (const void **) &(sl->list[lo]));
749 tor_assert(cmp < 0);
750 } else {
751 cmp = compare(key, (const void **) &(sl->list[len-1]));
752 tor_assert(cmp > 0);
755 *found_out = 0;
756 return lo;
759 /** Helper: compare two const char **s. */
760 static int
761 compare_string_ptrs_(const void **_a, const void **_b)
763 return strcmp((const char*)*_a, (const char*)*_b);
766 /** Sort a smartlist <b>sl</b> containing strings into lexically ascending
767 * order. */
768 void
769 smartlist_sort_strings(smartlist_t *sl)
771 smartlist_sort(sl, compare_string_ptrs_);
774 /** Return the most frequent string in the sorted list <b>sl</b> */
775 const char *
776 smartlist_get_most_frequent_string(smartlist_t *sl)
778 return smartlist_get_most_frequent(sl, compare_string_ptrs_);
781 /** Return the most frequent string in the sorted list <b>sl</b>.
782 * If <b>count_out</b> is provided, set <b>count_out</b> to the
783 * number of times that string appears.
785 const char *
786 smartlist_get_most_frequent_string_(smartlist_t *sl, int *count_out)
788 return smartlist_get_most_frequent_(sl, compare_string_ptrs_, count_out);
791 /** Remove duplicate strings from a sorted list, and free them with tor_free().
793 void
794 smartlist_uniq_strings(smartlist_t *sl)
796 smartlist_uniq(sl, compare_string_ptrs_, tor_free_);
799 /** Helper: compare two pointers. */
800 static int
801 compare_ptrs_(const void **_a, const void **_b)
803 const void *a = *_a, *b = *_b;
804 if (a<b)
805 return -1;
806 else if (a==b)
807 return 0;
808 else
809 return 1;
812 /** Sort <b>sl</b> in ascending order of the pointers it contains. */
813 void
814 smartlist_sort_pointers(smartlist_t *sl)
816 smartlist_sort(sl, compare_ptrs_);
819 /* Heap-based priority queue implementation for O(lg N) insert and remove.
820 * Recall that the heap property is that, for every index I, h[I] <
821 * H[LEFT_CHILD[I]] and h[I] < H[RIGHT_CHILD[I]].
823 * For us to remove items other than the topmost item, each item must store
824 * its own index within the heap. When calling the pqueue functions, tell
825 * them about the offset of the field that stores the index within the item.
827 * Example:
829 * typedef struct timer_t {
830 * struct timeval tv;
831 * int heap_index;
832 * } timer_t;
834 * static int compare(const void *p1, const void *p2) {
835 * const timer_t *t1 = p1, *t2 = p2;
836 * if (t1->tv.tv_sec < t2->tv.tv_sec) {
837 * return -1;
838 * } else if (t1->tv.tv_sec > t2->tv.tv_sec) {
839 * return 1;
840 * } else {
841 * return t1->tv.tv_usec - t2->tv_usec;
845 * void timer_heap_insert(smartlist_t *heap, timer_t *timer) {
846 * smartlist_pqueue_add(heap, compare, STRUCT_OFFSET(timer_t, heap_index),
847 * timer);
850 * void timer_heap_pop(smartlist_t *heap) {
851 * return smartlist_pqueue_pop(heap, compare,
852 * STRUCT_OFFSET(timer_t, heap_index));
856 /** @{ */
857 /** Functions to manipulate heap indices to find a node's parent and children.
859 * For a 1-indexed array, we would use LEFT_CHILD[x] = 2*x and RIGHT_CHILD[x]
860 * = 2*x + 1. But this is C, so we have to adjust a little. */
862 /* MAX_PARENT_IDX is the largest IDX in the smartlist which might have
863 * children whose indices fit inside an int.
864 * LEFT_CHILD(MAX_PARENT_IDX) == INT_MAX-2;
865 * RIGHT_CHILD(MAX_PARENT_IDX) == INT_MAX-1;
866 * LEFT_CHILD(MAX_PARENT_IDX + 1) == INT_MAX // impossible, see max list size.
868 #define MAX_PARENT_IDX ((INT_MAX - 2) / 2)
869 /* If this is true, then i is small enough to potentially have children
870 * in the smartlist, and it is save to use LEFT_CHILD/RIGHT_CHILD on it. */
871 #define IDX_MAY_HAVE_CHILDREN(i) ((i) <= MAX_PARENT_IDX)
872 #define LEFT_CHILD(i) ( 2*(i) + 1 )
873 #define RIGHT_CHILD(i) ( 2*(i) + 2 )
874 #define PARENT(i) ( ((i)-1) / 2 )
875 /** }@ */
877 /** @{ */
878 /** Helper macros for heaps: Given a local variable <b>idx_field_offset</b>
879 * set to the offset of an integer index within the heap element structure,
880 * IDX_OF_ITEM(p) gives you the index of p, and IDXP(p) gives you a pointer to
881 * where p's index is stored. Given additionally a local smartlist <b>sl</b>,
882 * UPDATE_IDX(i) sets the index of the element at <b>i</b> to the correct
883 * value (that is, to <b>i</b>).
885 #define IDXP(p) ((int*)STRUCT_VAR_P(p, idx_field_offset))
887 #define UPDATE_IDX(i) do { \
888 void *updated = sl->list[i]; \
889 *IDXP(updated) = i; \
890 } while (0)
892 #define IDX_OF_ITEM(p) (*IDXP(p))
893 /** @} */
895 /** Helper. <b>sl</b> may have at most one violation of the heap property:
896 * the item at <b>idx</b> may be greater than one or both of its children.
897 * Restore the heap property. */
898 static inline void
899 smartlist_heapify(smartlist_t *sl,
900 int (*compare)(const void *a, const void *b),
901 int idx_field_offset,
902 int idx)
904 while (1) {
905 if (! IDX_MAY_HAVE_CHILDREN(idx)) {
906 /* idx is so large that it cannot have any children, since doing so
907 * would mean the smartlist was over-capacity. Therefore it cannot
908 * violate the heap property by being greater than a child (since it
909 * doesn't have any). */
910 return;
913 int left_idx = LEFT_CHILD(idx);
914 int best_idx;
916 if (left_idx >= sl->num_used)
917 return;
918 if (compare(sl->list[idx],sl->list[left_idx]) < 0)
919 best_idx = idx;
920 else
921 best_idx = left_idx;
922 if (left_idx+1 < sl->num_used &&
923 compare(sl->list[left_idx+1],sl->list[best_idx]) < 0)
924 best_idx = left_idx + 1;
926 if (best_idx == idx) {
927 return;
928 } else {
929 void *tmp = sl->list[idx];
930 sl->list[idx] = sl->list[best_idx];
931 sl->list[best_idx] = tmp;
932 UPDATE_IDX(idx);
933 UPDATE_IDX(best_idx);
935 idx = best_idx;
940 /** Insert <b>item</b> into the heap stored in <b>sl</b>, where order is
941 * determined by <b>compare</b> and the offset of the item in the heap is
942 * stored in an int-typed field at position <b>idx_field_offset</b> within
943 * item.
945 void
946 smartlist_pqueue_add(smartlist_t *sl,
947 int (*compare)(const void *a, const void *b),
948 int idx_field_offset,
949 void *item)
951 int idx;
952 smartlist_add(sl,item);
953 UPDATE_IDX(sl->num_used-1);
955 for (idx = sl->num_used - 1; idx; ) {
956 int parent = PARENT(idx);
957 if (compare(sl->list[idx], sl->list[parent]) < 0) {
958 void *tmp = sl->list[parent];
959 sl->list[parent] = sl->list[idx];
960 sl->list[idx] = tmp;
961 UPDATE_IDX(parent);
962 UPDATE_IDX(idx);
963 idx = parent;
964 } else {
965 return;
970 /** Remove and return the top-priority item from the heap stored in <b>sl</b>,
971 * where order is determined by <b>compare</b> and the item's position is
972 * stored at position <b>idx_field_offset</b> within the item. <b>sl</b> must
973 * not be empty. */
974 void *
975 smartlist_pqueue_pop(smartlist_t *sl,
976 int (*compare)(const void *a, const void *b),
977 int idx_field_offset)
979 void *top;
980 tor_assert(sl->num_used);
982 top = sl->list[0];
983 *IDXP(top)=-1;
984 if (--sl->num_used) {
985 sl->list[0] = sl->list[sl->num_used];
986 sl->list[sl->num_used] = NULL;
987 UPDATE_IDX(0);
988 smartlist_heapify(sl, compare, idx_field_offset, 0);
990 sl->list[sl->num_used] = NULL;
991 return top;
994 /** Remove the item <b>item</b> from the heap stored in <b>sl</b>,
995 * where order is determined by <b>compare</b> and the item's position is
996 * stored at position <b>idx_field_offset</b> within the item. <b>sl</b> must
997 * not be empty. */
998 void
999 smartlist_pqueue_remove(smartlist_t *sl,
1000 int (*compare)(const void *a, const void *b),
1001 int idx_field_offset,
1002 void *item)
1004 int idx = IDX_OF_ITEM(item);
1005 tor_assert(idx >= 0);
1006 tor_assert(sl->list[idx] == item);
1007 --sl->num_used;
1008 *IDXP(item) = -1;
1009 if (idx == sl->num_used) {
1010 sl->list[sl->num_used] = NULL;
1011 return;
1012 } else {
1013 sl->list[idx] = sl->list[sl->num_used];
1014 sl->list[sl->num_used] = NULL;
1015 UPDATE_IDX(idx);
1016 smartlist_heapify(sl, compare, idx_field_offset, idx);
1020 /** Assert that the heap property is correctly maintained by the heap stored
1021 * in <b>sl</b>, where order is determined by <b>compare</b>. */
1022 void
1023 smartlist_pqueue_assert_ok(smartlist_t *sl,
1024 int (*compare)(const void *a, const void *b),
1025 int idx_field_offset)
1027 int i;
1028 for (i = sl->num_used - 1; i >= 0; --i) {
1029 if (i>0)
1030 tor_assert(compare(sl->list[PARENT(i)], sl->list[i]) <= 0);
1031 tor_assert(IDX_OF_ITEM(sl->list[i]) == i);
1035 /** Helper: compare two DIGEST_LEN digests. */
1036 static int
1037 compare_digests_(const void **_a, const void **_b)
1039 return tor_memcmp((const char*)*_a, (const char*)*_b, DIGEST_LEN);
1042 /** Sort the list of DIGEST_LEN-byte digests into ascending order. */
1043 void
1044 smartlist_sort_digests(smartlist_t *sl)
1046 smartlist_sort(sl, compare_digests_);
1049 /** Remove duplicate digests from a sorted list, and free them with tor_free().
1051 void
1052 smartlist_uniq_digests(smartlist_t *sl)
1054 smartlist_uniq(sl, compare_digests_, tor_free_);
1057 /** Helper: compare two DIGEST256_LEN digests. */
1058 static int
1059 compare_digests256_(const void **_a, const void **_b)
1061 return tor_memcmp((const char*)*_a, (const char*)*_b, DIGEST256_LEN);
1064 /** Sort the list of DIGEST256_LEN-byte digests into ascending order. */
1065 void
1066 smartlist_sort_digests256(smartlist_t *sl)
1068 smartlist_sort(sl, compare_digests256_);
1071 /** Return the most frequent member of the sorted list of DIGEST256_LEN
1072 * digests in <b>sl</b> */
1073 const uint8_t *
1074 smartlist_get_most_frequent_digest256(smartlist_t *sl)
1076 return smartlist_get_most_frequent(sl, compare_digests256_);
1079 /** Remove duplicate 256-bit digests from a sorted list, and free them with
1080 * tor_free().
1082 void
1083 smartlist_uniq_digests256(smartlist_t *sl)
1085 smartlist_uniq(sl, compare_digests256_, tor_free_);
1088 /** Helper: Declare an entry type and a map type to implement a mapping using
1089 * ht.h. The map type will be called <b>maptype</b>. The key part of each
1090 * entry is declared using the C declaration <b>keydecl</b>. All functions
1091 * and types associated with the map get prefixed with <b>prefix</b> */
1092 #define DEFINE_MAP_STRUCTS(maptype, keydecl, prefix) \
1093 typedef struct prefix ## entry_t { \
1094 HT_ENTRY(prefix ## entry_t) node; \
1095 void *val; \
1096 keydecl; \
1097 } prefix ## entry_t; \
1098 struct maptype { \
1099 HT_HEAD(prefix ## impl, prefix ## entry_t) head; \
1102 DEFINE_MAP_STRUCTS(strmap_t, char *key, strmap_);
1103 DEFINE_MAP_STRUCTS(digestmap_t, char key[DIGEST_LEN], digestmap_);
1104 DEFINE_MAP_STRUCTS(digest256map_t, uint8_t key[DIGEST256_LEN], digest256map_);
1106 /** Helper: compare strmap_entry_t objects by key value. */
1107 static inline int
1108 strmap_entries_eq(const strmap_entry_t *a, const strmap_entry_t *b)
1110 return !strcmp(a->key, b->key);
1113 /** Helper: return a hash value for a strmap_entry_t. */
1114 static inline unsigned int
1115 strmap_entry_hash(const strmap_entry_t *a)
1117 return (unsigned) siphash24g(a->key, strlen(a->key));
1120 /** Helper: compare digestmap_entry_t objects by key value. */
1121 static inline int
1122 digestmap_entries_eq(const digestmap_entry_t *a, const digestmap_entry_t *b)
1124 return tor_memeq(a->key, b->key, DIGEST_LEN);
1127 /** Helper: return a hash value for a digest_map_t. */
1128 static inline unsigned int
1129 digestmap_entry_hash(const digestmap_entry_t *a)
1131 return (unsigned) siphash24g(a->key, DIGEST_LEN);
1134 /** Helper: compare digestmap_entry_t objects by key value. */
1135 static inline int
1136 digest256map_entries_eq(const digest256map_entry_t *a,
1137 const digest256map_entry_t *b)
1139 return tor_memeq(a->key, b->key, DIGEST256_LEN);
1142 /** Helper: return a hash value for a digest_map_t. */
1143 static inline unsigned int
1144 digest256map_entry_hash(const digest256map_entry_t *a)
1146 return (unsigned) siphash24g(a->key, DIGEST256_LEN);
1149 HT_PROTOTYPE(strmap_impl, strmap_entry_t, node, strmap_entry_hash,
1150 strmap_entries_eq)
1151 HT_GENERATE2(strmap_impl, strmap_entry_t, node, strmap_entry_hash,
1152 strmap_entries_eq, 0.6, tor_reallocarray_, tor_free_)
1154 HT_PROTOTYPE(digestmap_impl, digestmap_entry_t, node, digestmap_entry_hash,
1155 digestmap_entries_eq)
1156 HT_GENERATE2(digestmap_impl, digestmap_entry_t, node, digestmap_entry_hash,
1157 digestmap_entries_eq, 0.6, tor_reallocarray_, tor_free_)
1159 HT_PROTOTYPE(digest256map_impl, digest256map_entry_t, node,
1160 digest256map_entry_hash,
1161 digest256map_entries_eq)
1162 HT_GENERATE2(digest256map_impl, digest256map_entry_t, node,
1163 digest256map_entry_hash,
1164 digest256map_entries_eq, 0.6, tor_reallocarray_, tor_free_)
1166 static inline void
1167 strmap_entry_free(strmap_entry_t *ent)
1169 tor_free(ent->key);
1170 tor_free(ent);
1172 static inline void
1173 digestmap_entry_free(digestmap_entry_t *ent)
1175 tor_free(ent);
1177 static inline void
1178 digest256map_entry_free(digest256map_entry_t *ent)
1180 tor_free(ent);
1183 static inline void
1184 strmap_assign_tmp_key(strmap_entry_t *ent, const char *key)
1186 ent->key = (char*)key;
1188 static inline void
1189 digestmap_assign_tmp_key(digestmap_entry_t *ent, const char *key)
1191 memcpy(ent->key, key, DIGEST_LEN);
1193 static inline void
1194 digest256map_assign_tmp_key(digest256map_entry_t *ent, const uint8_t *key)
1196 memcpy(ent->key, key, DIGEST256_LEN);
1198 static inline void
1199 strmap_assign_key(strmap_entry_t *ent, const char *key)
1201 ent->key = tor_strdup(key);
1203 static inline void
1204 digestmap_assign_key(digestmap_entry_t *ent, const char *key)
1206 memcpy(ent->key, key, DIGEST_LEN);
1208 static inline void
1209 digest256map_assign_key(digest256map_entry_t *ent, const uint8_t *key)
1211 memcpy(ent->key, key, DIGEST256_LEN);
1215 * Macro: implement all the functions for a map that are declared in
1216 * container.h by the DECLARE_MAP_FNS() macro. You must additionally define a
1217 * prefix_entry_free_() function to free entries (and their keys), a
1218 * prefix_assign_tmp_key() function to temporarily set a stack-allocated
1219 * entry to hold a key, and a prefix_assign_key() function to set a
1220 * heap-allocated entry to hold a key.
1222 #define IMPLEMENT_MAP_FNS(maptype, keytype, prefix) \
1223 /** Create and return a new empty map. */ \
1224 MOCK_IMPL(maptype *, \
1225 prefix##_new,(void)) \
1227 maptype *result; \
1228 result = tor_malloc(sizeof(maptype)); \
1229 HT_INIT(prefix##_impl, &result->head); \
1230 return result; \
1233 /** Return the item from <b>map</b> whose key matches <b>key</b>, or \
1234 * NULL if no such value exists. */ \
1235 void * \
1236 prefix##_get(const maptype *map, const keytype key) \
1238 prefix ##_entry_t *resolve; \
1239 prefix ##_entry_t search; \
1240 tor_assert(map); \
1241 tor_assert(key); \
1242 prefix ##_assign_tmp_key(&search, key); \
1243 resolve = HT_FIND(prefix ##_impl, &map->head, &search); \
1244 if (resolve) { \
1245 return resolve->val; \
1246 } else { \
1247 return NULL; \
1251 /** Add an entry to <b>map</b> mapping <b>key</b> to <b>val</b>; \
1252 * return the previous value, or NULL if no such value existed. */ \
1253 void * \
1254 prefix##_set(maptype *map, const keytype key, void *val) \
1256 prefix##_entry_t search; \
1257 void *oldval; \
1258 tor_assert(map); \
1259 tor_assert(key); \
1260 tor_assert(val); \
1261 prefix##_assign_tmp_key(&search, key); \
1262 /* We a lot of our time in this function, so the code below is */ \
1263 /* meant to optimize the check/alloc/set cycle by avoiding the two */\
1264 /* trips to the hash table that we would do in the unoptimized */ \
1265 /* version of this code. (Each of HT_INSERT and HT_FIND calls */ \
1266 /* HT_SET_HASH and HT_FIND_P.) */ \
1267 HT_FIND_OR_INSERT_(prefix##_impl, node, prefix##_entry_hash, \
1268 &(map->head), \
1269 prefix##_entry_t, &search, ptr, \
1271 /* we found an entry. */ \
1272 oldval = (*ptr)->val; \
1273 (*ptr)->val = val; \
1274 return oldval; \
1275 }, \
1277 /* We didn't find the entry. */ \
1278 prefix##_entry_t *newent = \
1279 tor_malloc_zero(sizeof(prefix##_entry_t)); \
1280 prefix##_assign_key(newent, key); \
1281 newent->val = val; \
1282 HT_FOI_INSERT_(node, &(map->head), \
1283 &search, newent, ptr); \
1284 return NULL; \
1285 }); \
1288 /** Remove the value currently associated with <b>key</b> from the map. \
1289 * Return the value if one was set, or NULL if there was no entry for \
1290 * <b>key</b>. \
1292 * Note: you must free any storage associated with the returned value. \
1293 */ \
1294 void * \
1295 prefix##_remove(maptype *map, const keytype key) \
1297 prefix##_entry_t *resolve; \
1298 prefix##_entry_t search; \
1299 void *oldval; \
1300 tor_assert(map); \
1301 tor_assert(key); \
1302 prefix##_assign_tmp_key(&search, key); \
1303 resolve = HT_REMOVE(prefix##_impl, &map->head, &search); \
1304 if (resolve) { \
1305 oldval = resolve->val; \
1306 prefix##_entry_free(resolve); \
1307 return oldval; \
1308 } else { \
1309 return NULL; \
1313 /** Return the number of elements in <b>map</b>. */ \
1314 int \
1315 prefix##_size(const maptype *map) \
1317 return HT_SIZE(&map->head); \
1320 /** Return true iff <b>map</b> has no entries. */ \
1321 int \
1322 prefix##_isempty(const maptype *map) \
1324 return HT_EMPTY(&map->head); \
1327 /** Assert that <b>map</b> is not corrupt. */ \
1328 void \
1329 prefix##_assert_ok(const maptype *map) \
1331 tor_assert(!prefix##_impl_HT_REP_IS_BAD_(&map->head)); \
1334 /** Remove all entries from <b>map</b>, and deallocate storage for \
1335 * those entries. If free_val is provided, invoked it every value in \
1336 * <b>map</b>. */ \
1337 MOCK_IMPL(void, \
1338 prefix##_free, (maptype *map, void (*free_val)(void*))) \
1340 prefix##_entry_t **ent, **next, *this; \
1341 if (!map) \
1342 return; \
1343 for (ent = HT_START(prefix##_impl, &map->head); ent != NULL; \
1344 ent = next) { \
1345 this = *ent; \
1346 next = HT_NEXT_RMV(prefix##_impl, &map->head, ent); \
1347 if (free_val) \
1348 free_val(this->val); \
1349 prefix##_entry_free(this); \
1351 tor_assert(HT_EMPTY(&map->head)); \
1352 HT_CLEAR(prefix##_impl, &map->head); \
1353 tor_free(map); \
1356 /** return an <b>iterator</b> pointer to the front of a map. \
1358 * Iterator example: \
1360 * \code \
1361 * // uppercase values in "map", removing empty values. \
1363 * strmap_iter_t *iter; \
1364 * const char *key; \
1365 * void *val; \
1366 * char *cp; \
1368 * for (iter = strmap_iter_init(map); !strmap_iter_done(iter); ) { \
1369 * strmap_iter_get(iter, &key, &val); \
1370 * cp = (char*)val; \
1371 * if (!*cp) { \
1372 * iter = strmap_iter_next_rmv(map,iter); \
1373 * free(val); \
1374 * } else { \
1375 * for (;*cp;cp++) *cp = TOR_TOUPPER(*cp); \
1376 */ \
1377 prefix##_iter_t * \
1378 prefix##_iter_init(maptype *map) \
1380 tor_assert(map); \
1381 return HT_START(prefix##_impl, &map->head); \
1384 /** Advance <b>iter</b> a single step to the next entry, and return \
1385 * its new value. */ \
1386 prefix##_iter_t * \
1387 prefix##_iter_next(maptype *map, prefix##_iter_t *iter) \
1389 tor_assert(map); \
1390 tor_assert(iter); \
1391 return HT_NEXT(prefix##_impl, &map->head, iter); \
1393 /** Advance <b>iter</b> a single step to the next entry, removing the \
1394 * current entry, and return its new value. */ \
1395 prefix##_iter_t * \
1396 prefix##_iter_next_rmv(maptype *map, prefix##_iter_t *iter) \
1398 prefix##_entry_t *rmv; \
1399 tor_assert(map); \
1400 tor_assert(iter); \
1401 tor_assert(*iter); \
1402 rmv = *iter; \
1403 iter = HT_NEXT_RMV(prefix##_impl, &map->head, iter); \
1404 prefix##_entry_free(rmv); \
1405 return iter; \
1407 /** Set *<b>keyp</b> and *<b>valp</b> to the current entry pointed \
1408 * to by iter. */ \
1409 void \
1410 prefix##_iter_get(prefix##_iter_t *iter, const keytype *keyp, \
1411 void **valp) \
1413 tor_assert(iter); \
1414 tor_assert(*iter); \
1415 tor_assert(keyp); \
1416 tor_assert(valp); \
1417 *keyp = (*iter)->key; \
1418 *valp = (*iter)->val; \
1420 /** Return true iff <b>iter</b> has advanced past the last entry of \
1421 * <b>map</b>. */ \
1422 int \
1423 prefix##_iter_done(prefix##_iter_t *iter) \
1425 return iter == NULL; \
1428 IMPLEMENT_MAP_FNS(strmap_t, char *, strmap)
1429 IMPLEMENT_MAP_FNS(digestmap_t, char *, digestmap)
1430 IMPLEMENT_MAP_FNS(digest256map_t, uint8_t *, digest256map)
1432 /** Same as strmap_set, but first converts <b>key</b> to lowercase. */
1433 void *
1434 strmap_set_lc(strmap_t *map, const char *key, void *val)
1436 /* We could be a little faster by using strcasecmp instead, and a separate
1437 * type, but I don't think it matters. */
1438 void *v;
1439 char *lc_key = tor_strdup(key);
1440 tor_strlower(lc_key);
1441 v = strmap_set(map,lc_key,val);
1442 tor_free(lc_key);
1443 return v;
1446 /** Same as strmap_get, but first converts <b>key</b> to lowercase. */
1447 void *
1448 strmap_get_lc(const strmap_t *map, const char *key)
1450 void *v;
1451 char *lc_key = tor_strdup(key);
1452 tor_strlower(lc_key);
1453 v = strmap_get(map,lc_key);
1454 tor_free(lc_key);
1455 return v;
1458 /** Same as strmap_remove, but first converts <b>key</b> to lowercase */
1459 void *
1460 strmap_remove_lc(strmap_t *map, const char *key)
1462 void *v;
1463 char *lc_key = tor_strdup(key);
1464 tor_strlower(lc_key);
1465 v = strmap_remove(map,lc_key);
1466 tor_free(lc_key);
1467 return v;
1470 /** Declare a function called <b>funcname</b> that acts as a find_nth_FOO
1471 * function for an array of type <b>elt_t</b>*.
1473 * NOTE: The implementation kind of sucks: It's O(n log n), whereas finding
1474 * the kth element of an n-element list can be done in O(n). Then again, this
1475 * implementation is not in critical path, and it is obviously correct. */
1476 #define IMPLEMENT_ORDER_FUNC(funcname, elt_t) \
1477 static int \
1478 _cmp_ ## elt_t(const void *_a, const void *_b) \
1480 const elt_t *a = _a, *b = _b; \
1481 if (*a<*b) \
1482 return -1; \
1483 else if (*a>*b) \
1484 return 1; \
1485 else \
1486 return 0; \
1488 elt_t \
1489 funcname(elt_t *array, int n_elements, int nth) \
1491 tor_assert(nth >= 0); \
1492 tor_assert(nth < n_elements); \
1493 qsort(array, n_elements, sizeof(elt_t), _cmp_ ##elt_t); \
1494 return array[nth]; \
1497 IMPLEMENT_ORDER_FUNC(find_nth_int, int)
1498 IMPLEMENT_ORDER_FUNC(find_nth_time, time_t)
1499 IMPLEMENT_ORDER_FUNC(find_nth_double, double)
1500 IMPLEMENT_ORDER_FUNC(find_nth_uint32, uint32_t)
1501 IMPLEMENT_ORDER_FUNC(find_nth_int32, int32_t)
1502 IMPLEMENT_ORDER_FUNC(find_nth_long, long)
1504 /** Return a newly allocated digestset_t, optimized to hold a total of
1505 * <b>max_elements</b> digests with a reasonably low false positive weight. */
1506 digestset_t *
1507 digestset_new(int max_elements)
1509 /* The probability of false positives is about P=(1 - exp(-kn/m))^k, where k
1510 * is the number of hash functions per entry, m is the bits in the array,
1511 * and n is the number of elements inserted. For us, k==4, n<=max_elements,
1512 * and m==n_bits= approximately max_elements*32. This gives
1513 * P<(1-exp(-4*n/(32*n)))^4 == (1-exp(1/-8))^4 == .00019
1515 * It would be more optimal in space vs false positives to get this false
1516 * positive rate by going for k==13, and m==18.5n, but we also want to
1517 * conserve CPU, and k==13 is pretty big.
1519 int n_bits = 1u << (tor_log2(max_elements)+5);
1520 digestset_t *r = tor_malloc(sizeof(digestset_t));
1521 r->mask = n_bits - 1;
1522 r->ba = bitarray_init_zero(n_bits);
1523 return r;
1526 /** Free all storage held in <b>set</b>. */
1527 void
1528 digestset_free(digestset_t *set)
1530 if (!set)
1531 return;
1532 bitarray_free(set->ba);
1533 tor_free(set);